input
stringlengths
2.65k
237k
output
stringclasses
1 value
<gh_stars>1-10 from decimal import Decimal import uuid from xml.etree import ElementTree from couchdbkit.exceptions import ResourceNotFound from couchdbkit.ext.django.schema import * from django.db import transaction from django.utils.translation import ugettext as _ from casexml.apps.case.mock import CaseBlock from casexml.apps.case.models import CommCareCase from casexml.apps.stock import const as stockconst from casexml.apps.stock.consumption import (ConsumptionConfiguration, compute_default_monthly_consumption, compute_daily_consumption) from casexml.apps.stock.models import StockReport as DbStockReport, StockTransaction as DbStockTransaction, DocDomainMapping from casexml.apps.case.xml import V2 from corehq.apps.cachehq.mixins import CachedCouchDocumentMixin from corehq.apps.commtrack import const from corehq.apps.consumption.shortcuts import get_default_monthly_consumption from corehq.apps.hqcase.utils import submit_case_blocks from casexml.apps.stock.utils import months_of_stock_remaining, state_stock_category from corehq.apps.domain.models import Domain from couchforms.signals import xform_archived, xform_unarchived from dimagi.utils import parsing as dateparse from copy import copy from django.dispatch import receiver from corehq.apps.locations.signals import location_created, location_edited from corehq.apps.locations.models import Location, SQLLocation from corehq.apps.products.models import Product, SQLProduct from corehq.apps.commtrack.const import StockActions, RequisitionActions, RequisitionStatus, DAYS_IN_MONTH from corehq.apps.commtrack.xmlutil import XML from couchexport.models import register_column_type, ComplexExportColumn from dimagi.utils.dates import force_to_datetime from django.db import models from django.db.models.signals import post_save, post_delete from dimagi.utils.decorators.memoized import memoized STOCK_ACTION_ORDER = [ StockActions.RECEIPTS, StockActions.CONSUMPTION, StockActions.STOCKONHAND, StockActions.STOCKOUT, ] REQUISITION_ACTION_TYPES = [ # request a product RequisitionActions.REQUEST, # approve a requisition (it is allowed to be fulfilled) # this is optional and depends on app config RequisitionActions.APPROVAL, # fulfill a requisition (order is ready) RequisitionActions.FULFILL, # receive the sock (closes the requisition) # NOTE: it's not totally clear if this is necessary or # should be built into the regular receipt workflow. RequisitionActions.RECEIPTS, ] class CommtrackActionConfig(DocumentSchema): # one of the base stock action types (see StockActions enum) action = StringProperty() # (optional) to further distinguish different kinds of the base action # (i.e., separately tracking consumption as 'dispensed' or 'lost'). note that when the system # infers consumption/receipts from reported stock, it will be marked here as a subaction subaction = StringProperty() # sms code _keyword = StringProperty() # display title caption = StringProperty() @classmethod def wrap(cls, data): if 'action_type' in data: data['action'] = data['action_type'] del data['action_type'] if 'name' in data: if data['name'] == 'lost': data['subaction'] = 'loss' del data['name'] return super(CommtrackActionConfig, cls).wrap(data) def __repr__(self): return '{action} ({subaction}): {caption} ({_keyword})'.format(**self._doc) @property def keyword(self): return self._keyword @keyword.setter def keyword(self, val): self._keyword = val.lower() if val else None @property def name(self): return ':'.join(filter(None, [self.action, self.subaction])) @property def is_stock(self): return self.action in STOCK_ACTION_ORDER @property def is_requisition(self): return self.action in REQUISITION_ACTION_TYPES class CommtrackRequisitionConfig(DocumentSchema): # placeholder class for when this becomes fancier enabled = BooleanProperty(default=False) # requisitions have their own sets of actions actions = SchemaListProperty(CommtrackActionConfig) def get_sorted_actions(self): def _action_key(a): # intentionally fails hard if misconfigured. return const.ORDERED_REQUISITION_ACTIONS.index(a.action) return sorted(self.actions, key=_action_key) def get_next_action(self, previous_action_type): sorted_actions = self.get_sorted_actions() sorted_types = [a.action for a in sorted_actions] if previous_action_type in sorted_types: next_index = sorted_types.index(previous_action_type) + 1 return sorted_actions[next_index] if next_index < len(sorted_actions) else None else: return None class ConsumptionConfig(DocumentSchema): min_transactions = IntegerProperty(default=2) min_window = IntegerProperty(default=10) optimal_window = IntegerProperty() use_supply_point_type_default_consumption = BooleanProperty(default=False) class StockLevelsConfig(DocumentSchema): emergency_level = DecimalProperty(default=0.5) # in months understock_threshold = DecimalProperty(default=1.5) # in months overstock_threshold = DecimalProperty(default=3) # in months class OpenLMISConfig(DocumentSchema): # placeholder class for when this becomes fancier enabled = BooleanProperty(default=False) url = StringProperty() username = StringProperty() # we store passwords in cleartext right now, but in the future may want # to leverage something like oauth to manage this better password = StringProperty() using_requisitions = BooleanProperty(default=False) # whether openlmis handles our requisitions for us @property def is_configured(self): return True if self.enabled and self.url and self.password and self.username else False class AlertConfig(DocumentSchema): stock_out_facilities = BooleanProperty(default=False) stock_out_commodities = BooleanProperty(default=False) stock_out_rates = BooleanProperty(default=False) non_report = BooleanProperty(default=False) class StockRestoreConfig(DocumentSchema): section_to_consumption_types = DictProperty() force_consumption_case_types = ListProperty() use_dynamic_product_list = BooleanProperty(default=False) @classmethod def wrap(cls, obj): # todo: remove this cruft at some point if 'force_to_consumption_case_types' in obj: realval = obj['force_to_consumption_case_types'] oldval = obj.get('force_consumption_case_types') if realval and not oldval: obj['force_consumption_case_types'] = realval del obj['force_to_consumption_case_types'] return super(StockRestoreConfig, cls).wrap(obj) class CommtrackConfig(CachedCouchDocumentMixin, Document): domain = StringProperty() # supported stock actions for this commtrack domain # listed in the order they are processed -- TODO support for this custom ordering might go away actions = SchemaListProperty(CommtrackActionConfig) # TODO must catch ambiguous action lists (two action configs with the same 'name') multiaction_enabled = BooleanProperty() multiaction_keyword_ = StringProperty() requisition_config = SchemaProperty(CommtrackRequisitionConfig) openlmis_config = SchemaProperty(OpenLMISConfig) # configured on Advanced Settings page use_auto_emergency_levels = BooleanProperty(default=False) sync_location_fixtures = BooleanProperty(default=True) sync_consumption_fixtures = BooleanProperty(default=True) use_auto_consumption = BooleanProperty(default=False) consumption_config = SchemaProperty(ConsumptionConfig) stock_levels_config = SchemaProperty(StockLevelsConfig) ota_restore_config = SchemaProperty(StockRestoreConfig) individual_consumption_defaults = BooleanProperty(default=False) @property def multiaction_keyword(self): return self.multiaction_keyword_ @multiaction_keyword.setter def multiaction_keyword(self, val): self.multiaction_keyword_ = val.lower() if val else None # configured on Subscribe Sms page alert_config = SchemaProperty(AlertConfig) @classmethod def for_domain(cls, domain): result = cls.view("commtrack/domain_config", key=[domain], include_docs=True).first() return result @property def all_actions(self): return self.actions + (self.requisition_config.actions if self.requisitions_enabled else []) def action_by_keyword(self, keyword): def _action(action, type): action.type = type return action actions = [_action(a, 'stock') for a in self.actions] if self.requisitions_enabled: actions += [_action(a, 'req') for a in self.requisition_config.actions] return dict((a.keyword, a) for a in actions).get(keyword) def get_consumption_config(self): def _default_monthly_consumption(case_id, product_id): # note: for now as an optimization hack, per-supply point type is not supported # unless explicitly configured, because it will require looking up the case facility_type = None if self.consumption_config.use_supply_point_type_default_consumption: try: supply_point = SupplyPointCase.get(case_id) facility_type = supply_point.location.location_type except ResourceNotFound: pass return get_default_monthly_consumption(self.domain, product_id, facility_type, case_id) return ConsumptionConfiguration( min_periods=self.consumption_config.min_transactions, min_window=self.consumption_config.min_window, max_window=self.consumption_config.optimal_window, default_monthly_consumption_function=_default_monthly_consumption, ) def get_ota_restore_settings(self): # for some reason it doesn't like this import from casexml.apps.phone.restore import StockSettings default_product_ids = Product.ids_by_domain(self.domain) \ if self.ota_restore_config.use_dynamic_product_list else [] case_filter = lambda case: case.type in set(self.ota_restore_config.force_consumption_case_types) return StockSettings( section_to_consumption_types=self.ota_restore_config.section_to_consumption_types, consumption_config=self.get_consumption_config(), default_product_list=default_product_ids, force_consumption_case_filter=case_filter, ) @property def requisitions_enabled(self): return self.requisition_config.enabled @property def openlmis_enabled(self): return self.openlmis_config.enabled def _view_shared(view_name, domain, location_id=None, skip=0, limit=100): extras = {"limit": limit} if limit else {} startkey = [domain, location_id] if location_id else [domain] endkey = copy(startkey) + [{}] return CommCareCase.get_db().view( view_name, startkey=startkey, endkey=endkey, reduce=False, skip=skip, **extras) def force_int(value): if value is None: return None else: return int(value) def force_bool(value): if value is None: return None elif value is 'false': return False else: return bool(value) def force_empty_string_to_null(value): if value == '': return None else: return value class StringDataSchema(DocumentSchema): @classmethod def force_wrap(cls, data): data = copy(data) for property in cls.properties().values(): transform = { IntegerProperty: force_int, BooleanProperty: force_bool, DateProperty: force_empty_string_to_null, DateTimeProperty: force_empty_string_to_null, }.get(property.__class__, lambda x: x) data[property.name] = transform(data.get(property.name)) return super(StringDataSchema, cls).wrap(data) @classmethod def wrap(cls, data): raise NotImplementedError() class NewStockReport(object): """ Intermediate class for dealing with stock XML """ # todo: fix name, remove old stock report class def __init__(self, form, timestamp, tag, transactions): self._form = form self.form_id = form._id self.timestamp = timestamp self.tag = tag self.transactions = transactions @classmethod def from_xml(cls, form, config, elem): tag = elem.tag tag = tag[tag.find('}')+1:] # strip out ns timestamp = force_to_datetime(elem.attrib.get('date') or form.received_on).replace(tzinfo=None) products = elem.findall('./{%s}entry' % stockconst.COMMTRACK_REPORT_XMLNS) transactions = [t for prod_entry in products for t in StockTransaction.from_xml(config, timestamp, tag, elem, prod_entry)] return cls(form, timestamp, tag, transactions) @transaction.commit_on_success def create_models(self, domain=None): # todo: this function should probably move to somewhere in casexml.apps.stock if self.tag not in stockconst.VALID_REPORT_TYPES: return report = DbStockReport.objects.create( form_id=self.form_id, date=self.timestamp, type=self.tag, domain=self._form.domain, ) for txn in self.transactions: db_txn = DbStockTransaction( report=report, case_id=txn.case_id, section_id=txn.section_id, product_id=txn.product_id, ) if domain: # set this as a shortcut for post save signal receivers db_txn.domain = domain db_txn.type = txn.action db_txn.subtype = txn.subaction if self.tag == stockconst.REPORT_TYPE_BALANCE: db_txn.stock_on_hand = txn.quantity db_txn.quantity = 0 else: assert self.tag == stockconst.REPORT_TYPE_TRANSFER previous_transaction = db_txn.get_previous_transaction() db_txn.quantity = txn.relative_quantity db_txn.stock_on_hand = (previous_transaction.stock_on_hand if previous_transaction else 0) + db_txn.quantity db_txn.save() class StockTransaction(object): """ Helper class for transactions """ action = None subaction = None quantity = None location_id = None product = None timestamp = None def __init__(self, **kwargs): def _action_def(val): return { 'action': val.action, 'subaction': val.subaction, } def _product(val): # FIXME want to store product in memory object (but not persist to couch... # is this possible in jsonobject?) #self.product = val return { 'product_id': val._id, } def _inferred(val): return { 'subaction': stockconst.TRANSACTION_SUBTYPE_INFERRED, } def _config(val): ret = { 'processing_order': STOCK_ACTION_ORDER.index(kwargs['action']), } if not kwargs.get('domain'): ret['domain'] = val.domain return ret for name, var in locals().iteritems(): if hasattr(var, '__call__') and name.startswith('_'): attr = name[1:] if kwargs.get(attr): val = kwargs[attr] del kwargs[attr] kwargs.update(var(val)) for k, v in kwargs.items(): setattr(self, k, v) @property def relative_quantity(self): """ Gets the quantity of this transaction as a positive or negative number depending on the action/context """ if self.action == const.StockActions.CONSUMPTION: return -self.quantity else: return
== "r") or\ (padded_single_rule[i] == "\\" and padded_single_rule[i + 1] == "p" and padded_single_rule[i + 2] in "0123456789"): # capture the whole range j = i # Not the end ] while not (padded_single_rule[j] == "]" and padded_single_rule[j - 1] != "\\"): j += 1 groups_of_a_trans.append(padded_single_rule[i:j + 1]) i = j + 1 # A Range without prefix (\p, \r, \p#) # Just a range with no \p preceding. elif padded_single_rule[i] == "[" and padded_single_rule[ i - 1] != "\\": # capture the whole range j = i # Not the end ] while not (padded_single_rule[j] == "]" and padded_single_rule[j - 1] != "\\"): j += 1 groups_of_a_trans.append(padded_single_rule[i:j + 1]) i = j + 1 else: # Literal # If the litral is escape if padded_single_rule[i] == "\\": groups_of_a_trans.append(padded_single_rule[i + 1]) i = i + 2 else: groups_of_a_trans.append( padded_single_rule[i]) # else append itself i = i + 1 all_groups.append(groups_of_a_trans) # For each group transform into tokens self.tokenized = [[ RuleWrapper._process_group(group) for group in groups_of_a_trans ] for groups_of_a_trans in all_groups] # After tokenization, each component in a transformation can only be list/tuple/str. # And lists are in the form of [\p, tuple] #### Major Process For JtR Done #### # Step 3. Determine what parallel type it is. self.detect_parallelism() # Step 4. Unparallellize rules if necessary, and also convert tuples to sets for fast look-ups. self.get_subrules() @staticmethod def create_component_for_current_rule(sub_rules): """ Append empty component for each sub_rule. Used to break rules into sub rules, as we need to append the list for current single command """ if (sub_rules == [[]]): sub_rules[0].append([]) else: for sub_rule_idx in range(len(sub_rules)): # For each line of sub_rules, append it sub_rules[sub_rule_idx].append([]) return sub_rules @staticmethod def replicate_rules(rules, times): """Replicate the rules for some times Replicate the first rule # of times, then second rule, then third """ ret_val = [] for rule in rules: for _ in range(times): copy_rule = deepcopy(rule) ret_val.append(copy_rule) return ret_val @staticmethod def append_directly(sub_rules, the_thing): """Append a string to the current single rule (which is a list)""" for sub_rules_idx in range(len(sub_rules)): # This thing is line of rules, the last [] is for current single rule sub_rules[sub_rules_idx][-1].append(the_thing) return sub_rules @staticmethod def append_full_parallel(sub_rules, the_list): """ Expand Pure Parallel. The way we expand this is copy the first line of subrules, double it multiple times, then copy the second line, etc. """ sub_rules = RuleWrapper.replicate_rules( sub_rules, len(the_list)) # replicate previous sub_rules len(the_set) times for sub_rules_idx in range(len(sub_rules)): sub_rules[sub_rules_idx][-1].append( the_list[sub_rules_idx % len(the_list)]) return sub_rules @staticmethod def append_slash_parallel(sub_rules, comp, is_expanded_by_parallelism): r""" Expand \p and \r [something]. If the previous range specified in p# is expanded by some pure parallel, then we need to feed this range in a certain way (l l c c). Otherwise in another way (l c l c). """ if len( comp ) != 2: # List len error? it can only be something like [\p1, tuple()] raise FatalRuntimeError("Sorry List Length Error") else: parallel_preifx = comp[0] # Detect Command if parallel_preifx.startswith( "\\p") != True and parallel_preifx.startswith( "\\r") != True: # only be something like [\p1, tuple()] raise FatalRuntimeError( "Sorry Parrallel Command is not \p or \\r") if type(comp[1]) is not tuple or len(comp) != 2: # Detect Type # only be something like [\p1, set()] raise FatalRuntimeError("Sorry Comp Type Error") if parallel_preifx == "\\r": # \r only, it is actually pure parallel. the_tuple = comp[1] return RuleWrapper.append_full_parallel(sub_rules, the_tuple) parallel_preifx = parallel_preifx.replace("\\r", "") # get rid of \r if parallel_preifx == "\\p": # \p the_tuple = comp[1] for sub_rules_idx in range(len(sub_rules)): sub_rules[sub_rules_idx][-1].append( the_tuple[sub_rules_idx % len(the_tuple)]) # Put it one by one elif parallel_preifx.startswith("\\p"): # \p number # Get the number it parallels with parrallel_with = int(parallel_preifx[2]) # The previous is not expanded if is_expanded_by_parallelism[parrallel_with - 1] == False: the_tuple = comp[1] for sub_rules_idx in range(len(sub_rules)): sub_rules[sub_rules_idx][-1].append( the_tuple[sub_rules_idx % len(the_tuple)]) else: # The previous is expanded the_tuple = comp[1] each_rule_length = len(sub_rules) / len(the_tuple) for sub_rules_idx in range(len(sub_rules)): # size = 8 # Could overflow here sub_rules[sub_rules_idx][-1].append(the_tuple[int( sub_rules_idx / each_rule_length)]) return sub_rules def get_subrules(self): """ Create Subrules 1. We expand all tuples based on specification. If the tuple is the parameter str in ANStr or X in iNX/$X/^X, not expanded. 2. Transform tuples into sets for fast look-ups. """ if self.is_parallel == False: # Just return what we have # Transform tuples into sets. for i, transformation in enumerate(self.tokenized): for c, comp in enumerate(transformation): if type(comp) is tuple: transformation[c] = set(comp) if type(comp) is list: raise FatalRuntimeError( "Parallel Type Error for {}".format(self.raw)) self.tokenized[i] = transformation self.rules = [deepcopy(self.tokenized)] # just this one rule else: # Otherwise break it. sub_rules = [[]] # Start with a line of rules # Indicate the way it is organized, True: :, :, c, c. False: :, c, :, c is_expanded_by_parallelism = [] for transformation in self.tokenized: sub_rules = RuleWrapper.create_component_for_current_rule( sub_rules) # Initialize component for current single_rule for i, comp in enumerate(transformation): if type( comp ) is str: # The current comp of the single_rule is str, just append it sub_rules = RuleWrapper.append_directly(sub_rules, comp) # The current comp of the single_rule is tuple, pure parallel, double the size # Unless it is str in ANstr or X in iNX/$X/^X. elif (type(comp) is tuple): # don't expand, just append comp to every sub_rule. if (i >= 2 and transformation[0] in "Ai") or ( i == 1 and transformation[0] in "$^"): sub_rules = RuleWrapper.append_directly( sub_rules, set(comp)) else: # Reconstruct as the previous ranges are all expanded is_expanded_by_parallelism = [ True for _ in is_expanded_by_parallelism ] is_expanded_by_parallelism.append(False) sub_rules = RuleWrapper.append_full_parallel( sub_rules, comp) # In parallel with something (i.e. \p), add but dont change the size elif type(comp) is list: is_expanded_by_parallelism.append(False) sub_rules = RuleWrapper.append_slash_parallel( sub_rules, comp, is_expanded_by_parallelism) self.rules = sub_rules def detect_parallelism(self): """ Detect parallel type The component in a transformation right now can only be 3 types: 1. str 2. tuple 3. list, normally in the form of [\p, tuple] Set is_parallel to True if there is a tuple. The only exception is when there is a tuple, but the tuple is the parameter str in ANStr or X in iNX. We don't expand in this exception for efficiency reasons. """ self.is_parallel = False for transformation in self.tokenized: for i, comp in enumerate(transformation): if type(comp) == str: continue if type(comp) == list: for c in comp: if type(c) == tuple: self.is_parallel = True if type(comp) == tuple and not (i >= 2 and transformation[0] in "Ai"): self.is_parallel = True class RulelistReader(): """ A wrapper class that reads a rule list file, parses it and returns the list.""" @staticmethod def _read_raw_rules_from_file(rules_dir, filename): """ Read rules from file line by line, skip lines starting with "#" and "[List.", no parsing Specify a rules_dir and a filename, full_path = {rules_dir}/{filename}. full_path should exist. Args: rules_dir: directory where the file is stored filename: filename of the rule """ full_path = '{}/{}'.format(rules_dir, filename) if not os.path.isfile(full_path): raise FatalRuntimeError( "Rule List Address :{} Doesn't Exists! ".format(full_path)) with open(full_path, 'r') as infile: rules = infile.read().splitlines() return [ rule.strip("\r\n") for rule in rules if rule and not rule.startswith(("#", '[List.')) ] @staticmethod def read_and_parse_rule_list(filename, rules_dir="../data/rulelists/", safe_mode=True): """ Read rules from file, and parse it. Args: filename: filename of the rule rules_dir: directory where the file is stored safe_mode: ignore errors or not. """ parser = Elements.parser() raw_rules = RulelistReader._read_raw_rules_from_file( rules_dir, filename) parsed_rules = [] for rule in raw_rules: try: parsed_rules.append( RuleWrapper(rule, parser.parseString(rule).asList())) except: if safe_mode == True: print("Parsing rule: {} failed, discarded".format(rule)) else: print("Parsing rule: {} failed".format(rule)) raise return parsed_rules def jtr_only_func(func): """Decorator to check that the current program is running on JTR mode""" def wrapper(*args, **kwargs): if RUNTIME_CONFIG['running_style'] != RunningStyle.JTR: raise FatalRuntimeError( "Should Not Enter {} Function in non-JTR Mode".format( func.__name__)) return func(*args, **kwargs) return wrapper class Groups(): """ Helper class to parse rules These are not rule elements. These are constants that
!= 0: print('\n please provide vector(s) from R³ \n ') raise MTError(' !! ') if np.shape(vectors)[0] == 3: for ii in range(np.shape(vectors)[1]): lo_vectors.append(vectors[:, ii]) else: for ii in range(np.shape(vectors)[0]): lo_vectors.append(vectors[:, ii].transpose()) lo_vecs_to_show = [] for vec in lo_vectors: if system.upper() == 'NED': if fancy: lo_vecs_to_show.append(fancy_vector(vec)) else: lo_vecs_to_show.append(vec) elif system.upper() == 'USE': if fancy: lo_vecs_to_show.append(fancy_vector(NED2USE(vec))) else: lo_vecs_to_show.append(NED2USE(vec)) elif system.upper() == 'XYZ': if fancy: lo_vecs_to_show.append(fancy_vector(NED2XYZ(vec))) else: lo_vecs_to_show.append(NED2XYZ(vec)) elif system.upper() == 'NWU': if fancy: lo_vecs_to_show.append(fancy_vector(NED2NWU(vec))) else: lo_vecs_to_show.append(NED2NWU(vec)) if len(lo_vecs_to_show) == 1: return lo_vecs_to_show[0] else: if fancy: return ''.join(lo_vecs_to_show) else: return lo_vecs_to_show def get_M(self, system='NED', style='n'): """ Returns the moment tensor in matrix representation. Call with arguments to set ouput in other basis system or in fancy style (to be viewed with 'print') """ if style == 'f': print('\n Full moment tensor in %s-coordinates:' % (system)) return self._matrix_w_style_and_system(self._M, system, style) else: return self._matrix_w_style_and_system(self._M, system, style) def get_decomposition(self, in_system='NED', out_system='NED', style='n'): """ Returns a tuple of the decomposition results. Order: - 1 - basis of the provided input (string) - 2 - basis of the representation (string) - 3 - chosen decomposition type (integer) - 4 - full moment tensor (matrix) - 5 - isotropic part (matrix) - 6 - isotropic percentage (float) - 7 - deviatoric part (matrix) - 8 - deviatoric percentage (float) - 9 - DC part (matrix) -10 - DC percentage (float) -11 - DC2 part (matrix) -12 - DC2 percentage (float) -13 - DC3 part (matrix) -14 - DC3 percentage (float) -15 - CLVD part (matrix) -16 - CLVD percentage (matrix) -17 - seismic moment (float) -18 - moment magnitude (float) -19 - eigenvectors (3-array) -20 - eigenvalues (list) -21 - p-axis (3-array) -22 - neutral axis (3-array) -23 - t-axis (3-array) -24 - faultplanes (list of two 3-arrays) """ return [in_system, out_system, self.get_decomp_type(), self.get_M(system=out_system), self.get_iso(system=out_system), self.get_iso_percentage(), self.get_devi(system=out_system), self.get_devi_percentage(), self.get_DC(system=out_system), self.get_DC_percentage(), self.get_DC2(system=out_system), self.get_DC2_percentage(), self.get_DC3(system=out_system), self.get_DC3_percentage(), self.get_CLVD(system=out_system), self.get_CLVD_percentage(), self.get_moment(), self.get_mag(), self.get_eigvecs(system=out_system), self.get_eigvals(system=out_system), self.get_p_axis(system=out_system), self.get_null_axis(system=out_system), self.get_t_axis(system=out_system), self.get_fps()] def get_full_decomposition(self): """ Nice compilation of decomposition result to be viewed in the shell (call with 'print'). """ mexp = pow(10, np.ceil(np.log10(np.max(np.abs(self._M))))) m = self._M / mexp s = '\nScalar Moment: M0 = %g Nm (Mw = %3.1f)\n' s += 'Moment Tensor: Mnn = %6.3f, Mee = %6.3f, Mdd = %6.3f,\n' s += ' Mne = %6.3f, Mnd = %6.3f, Med = %6.3f ' s += '[ x %g ]\n\n' s = s % (self._seismic_moment, self._moment_magnitude, m[0, 0], m[1, 1], m[2, 2], m[0, 1], m[0, 2], m[1, 2], mexp) s += self._fault_planes_as_str() return s def _fault_planes_as_str(self): """ Internal setup of a nice string, containing information about the fault planes. """ s = '\n' for i, sdr in enumerate(self.get_fps()): s += 'Fault plane %i: ' % (i + 1) s += 'strike = %3.0f°, dip = %3.0f°, slip-rake = %4.0f°\n' % \ (sdr[0], sdr[1], sdr[2]) return s def get_input_system(self, style='n', **kwargs): """ Returns the basis system of the input. """ if style == 'f': print('\n Basis system of the input:\n ') return self._input_basis def get_output_system(self, style='n', **kwargs): """ Returns the basis system of the input. """ if style == 'f': print('\n Basis system of the output: \n ') return self._output_basis def get_decomp_type(self, style='n', **kwargs): """ Returns the decomposition type. """ decomp_dict = dict(zip(('20', '21', '31'), ('ISO + DC + CLVD', 'ISO + major DC + minor DC', 'ISO + DC1 + DC2 + DC3'))) if style == 'f': print('\n Decomposition type: \n ') return decomp_dict[str(self._decomposition_key)] return self._decomposition_key def get_iso(self, system='NED', style='n'): """ Returns the isotropic part of the moment tensor in matrix representation. Call with arguments to set ouput in other basis system or in fancy style (to be viewed with 'print') """ if style == 'f': print('\n Isotropic part in %s-coordinates: ' % (system)) return self._matrix_w_style_and_system(self._isotropic, system, style) def get_devi(self, system='NED', style='n'): """ Returns the deviatoric part of the moment tensor in matrix representation. Call with arguments to set ouput in other basis system or in fancy style (to be viewed with 'print') """ if style == 'f': print('\n Deviatoric part in %s-coordinates: ' % (system)) return self._matrix_w_style_and_system(self._deviatoric, system, style) def get_DC(self, system='NED', style='n'): """ Returns the Double Couple part of the moment tensor in matrix representation. Call with arguments to set ouput in other basis system or in fancy style (to be viewed with 'print') """ if style == 'f': print('\n Double Couple part in %s-coordinates:' % (system)) return self._matrix_w_style_and_system(self._DC, system, style) def get_DC2(self, system='NED', style='n'): """ Returns the second Double Couple part of the moment tensor in matrix representation. Call with arguments to set ouput in other basis system or in fancy style (to be viewed with 'print') """ if style == 'f': print('\n second Double Couple part in %s-coordinates:' % (system)) if self._DC2 is None: if style == 'f': print(' not available in this decomposition type ') return '' return self._matrix_w_style_and_system(self._DC2, system, style) def get_DC3(self, system='NED', style='n'): """ Returns the third Double Couple part of the moment tensor in matrix representation. Call with arguments to set ouput in other basis system or in fancy style (to be viewed with 'print') """ if style == 'f': print('\n third Double Couple part in %s-coordinates:' % (system)) if self._DC3 is None: if style == 'f': print(' not available in this decomposition type ') return '' return self._matrix_w_style_and_system(self._DC3, system, style) def get_CLVD(self, system='NED', style='n'): """ Returns the CLVD part of the moment tensor in matrix representation. Call with arguments to set ouput in other basis system or in fancy style (to be viewed with 'print') """ if style == 'f': print('\n CLVD part in %s-coordinates: \n' % (system)) if self._CLVD is None: if style == 'f': print(' not available in this decomposition type ') return '' return self._matrix_w_style_and_system(self._CLVD, system, style) def get_DC_percentage(self, system='NED', style='n'): """ Returns the percentage of the DC part of the moment tensor in matrix representation. """ if style == 'f': print('\n Double Couple percentage: \n') return self._DC_percentage def get_CLVD_percentage(self, system='NED', style='n'): """ Returns the percentage of the DC part of the moment tensor in matrix representation. """ if style == 'f': print('\n CLVD percentage: \n') if self._CLVD is None: if style == 'f': print(' not available in this decomposition type ') return '' return int(100 - self._DC_percentage - self._iso_percentage) def get_DC2_percentage(self, system='NED', style='n'): """ Returns the percentage of the second DC part of the moment tensor in matrix representation. """ if style == 'f': print("\n second Double Couple's percentage: \n") if self._DC2 is None: if style == 'f': print(' not available in this decomposition type ') return '' return self._DC2_percentage def get_DC3_percentage(self, system='NED', style='n'): """ Returns the percentage of the third DC part of the moment tensor in matrix representation. """ if style == 'f': print("\n third Double Couple percentage: \n") if self._DC3 is None: if style == 'f': print(' not available in this decomposition type ') return '' return int(100 - self._DC2_percentage - self._DC_percentage) def get_iso_percentage(self, system='NED', style='n'): """ Returns the percentage of the isotropic part of the moment tensor in matrix representation. """ if style == 'f': print('\n Isotropic percentage: \n') return self._iso_percentage def get_devi_percentage(self, system='NED', style='n'): """ Returns the percentage of the deviatoric part of the moment tensor in matrix representation. """ if style == 'f': print('\n Deviatoric percentage: \n') return int(100 - self._iso_percentage) def get_moment(self, system='NED', style='n'): """ Returns the seismic moment (in Nm) of the moment tensor. """ if style == 'f': print('\n Seismic moment (in Nm) : \n ') return self._seismic_moment def get_mag(self, system='NED', style='n'): """ Returns the moment magnitude M_w of the moment tensor. """ if style == 'f': print('\n Moment magnitude Mw: \n ') return self._moment_magnitude def get_decomposition_key(self, system='NED', style='n'): """ 10 = standard decomposition (Jost & Herrmann) """ if style == 'f': print('\n Decomposition key (standard = 10): \n ') return self._decomposition_key def get_eigvals(self, system='NED', style='n', **kwargs): """ Returns a list of the
""" DO NOT EDIT THIS FILE!! This file is automatically generated by the process_schemas.py program in the scripts directory. It is not intended to be edited directly. If you need to update the GEL protocol classes, please run the script on the appropriate schema version. """ from protocols.protocol import ProtocolElement from protocols.protocol import SearchRequest from protocols.protocol import SearchResponse from protocols.protocol import avro_parse import avro.schema version = '1.0.1' class ArrayConcordance(ProtocolElement): """ Array concordance with WGS data * `numberOfSites`: Number of sites considered * `numberOfDiscordantSites`: Number of sites discordant between WGS and Genotyping Array """ _schemaSource = """ {"type": "record", "name": "ArrayConcordance", "namespace": "org.gel.models.report.avro", "doc": "", "fields": [{"name": "numberOfSites", "type": "double"}, {"name": "numberOfDiscordantSites", "type": "double"}]} """ schema = avro_parse(_schemaSource) requiredFields = { "numberOfDiscordantSites", "numberOfSites", } @classmethod def isEmbeddedType(cls, fieldName): embeddedTypes = {} return fieldName in embeddedTypes @classmethod def getEmbeddedType(cls, fieldName): embeddedTypes = {} return embeddedTypes[fieldName] __slots__ = [ 'numberOfDiscordantSites', 'numberOfSites' ] def __init__(self, **kwargs): self.numberOfDiscordantSites = kwargs.get( 'numberOfDiscordantSites', None) self.numberOfSites = kwargs.get( 'numberOfSites', None) class ArrayGenotypingRate(ProtocolElement): """ Array genotyping rate for the sample * `IID` - Individual sample ID * `number_missing_genotypes`: The number of missing genotypes * `number_total_genotypes`: The number of total genotypes """ _schemaSource = """ {"type": "record", "name": "ArrayGenotypingRate", "namespace": "org.gel.models.report.avro", "doc": "", "fields": [{"name": "IID", "type": "string"}, {"name": "number_missing_genotypes", "type": "double"}, {"name": "number_total_genotypes", "type": "double"}]} """ schema = avro_parse(_schemaSource) requiredFields = { "IID", "number_missing_genotypes", "number_total_genotypes", } @classmethod def isEmbeddedType(cls, fieldName): embeddedTypes = {} return fieldName in embeddedTypes @classmethod def getEmbeddedType(cls, fieldName): embeddedTypes = {} return embeddedTypes[fieldName] __slots__ = [ 'IID', 'number_missing_genotypes', 'number_total_genotypes' ] def __init__(self, **kwargs): self.IID = kwargs.get( 'IID', None) self.number_missing_genotypes = kwargs.get( 'number_missing_genotypes', None) self.number_total_genotypes = kwargs.get( 'number_total_genotypes', None) class BamHeaderMachine(ProtocolElement): """ No documentation """ _schemaSource = """ {"type": "record", "name": "BamHeaderMachine", "namespace": "org.gel.models.report.avro", "fields": [{"name": "machines", "type": {"type": "array", "items": {"type": "record", "name": "Machine", "fields": [{"name": "DATE", "type": "double"}, {"name": "MACHINE", "type": "string"}, {"name": "FLOWCELL", "type": "string"}, {"name": "RUN", "type": "string"}]}}}]} """ schema = avro_parse(_schemaSource) requiredFields = { "machines", } @classmethod def isEmbeddedType(cls, fieldName): embeddedTypes = { 'machines': Machine, } return fieldName in embeddedTypes @classmethod def getEmbeddedType(cls, fieldName): embeddedTypes = { 'machines': Machine, } return embeddedTypes[fieldName] __slots__ = [ 'machines' ] def __init__(self, **kwargs): self.machines = kwargs.get( 'machines', None) class BamHeaderOther(ProtocolElement): """ No documentation """ _schemaSource = """ {"type": "record", "name": "BamHeaderOther", "namespace": "org.gel.models.report.avro", "fields": [{"name": "PIPELINE_ID", "type": "string"}, {"name": "PIPELINE_VERSION", "type": "string"}]} """ schema = avro_parse(_schemaSource) requiredFields = { "PIPELINE_ID", "PIPELINE_VERSION", } @classmethod def isEmbeddedType(cls, fieldName): embeddedTypes = {} return fieldName in embeddedTypes @classmethod def getEmbeddedType(cls, fieldName): embeddedTypes = {} return embeddedTypes[fieldName] __slots__ = [ 'PIPELINE_ID', 'PIPELINE_VERSION' ] def __init__(self, **kwargs): self.PIPELINE_ID = kwargs.get( 'PIPELINE_ID', None) self.PIPELINE_VERSION = kwargs.get( 'PIPELINE_VERSION', None) class CancerSummaryMetrics(ProtocolElement): """ No documentation """ _schemaSource = """ {"type": "record", "name": "CancerSummaryMetrics", "namespace": "org.gel.models.report.avro", "fields": [{"name": "samtools_reads_mapped", "type": "double"}, {"name": "samtools_reads_mapped_normal", "type": "double"}, {"name": "samtools_pairs_on_different_chromosomes", "type": "double"}, {"name": "samtools_pairs_on_different_chromosomes_normal", "type": "double"}, {"name": "samtools_insert_size_average", "type": "double"}, {"name": "samtools_insert_size_average_normal", "type": "double"}, {"name": "variantstats_total_snvs", "type": "int"}, {"name": "variantstats_total_indels", "type": "int"}, {"name": "variantstats_total_svs", "type": ["null", "int"]}, {"name": "tumor_contamination_cont_est", "type": "string"}, {"name": "tumor_contamination_con_pair", "type": "string"}, {"name": "mean", "type": "double"}, {"name": "mean_normal", "type": "double"}, {"name": "local_rmsd_normal", "type": "double"}, {"name": "local_rmsd", "type": "double"}, {"name": "cosmic_30x_cov", "type": "double"}]} """ schema = avro_parse(_schemaSource) requiredFields = { "cosmic_30x_cov", "local_rmsd", "local_rmsd_normal", "mean", "mean_normal", "samtools_insert_size_average", "samtools_insert_size_average_normal", "samtools_pairs_on_different_chromosomes", "samtools_pairs_on_different_chromosomes_normal", "samtools_reads_mapped", "samtools_reads_mapped_normal", "tumor_contamination_con_pair", "tumor_contamination_cont_est", "variantstats_total_indels", "variantstats_total_snvs", "variantstats_total_svs", } @classmethod def isEmbeddedType(cls, fieldName): embeddedTypes = {} return fieldName in embeddedTypes @classmethod def getEmbeddedType(cls, fieldName): embeddedTypes = {} return embeddedTypes[fieldName] __slots__ = [ 'cosmic_30x_cov', 'local_rmsd', 'local_rmsd_normal', 'mean', 'mean_normal', 'samtools_insert_size_average', 'samtools_insert_size_average_normal', 'samtools_pairs_on_different_chromosomes', 'samtools_pairs_on_different_chromosomes_normal', 'samtools_reads_mapped', 'samtools_reads_mapped_normal', 'tumor_contamination_con_pair', 'tumor_contamination_cont_est', 'variantstats_total_indels', 'variantstats_total_snvs', 'variantstats_total_svs' ] def __init__(self, **kwargs): self.cosmic_30x_cov = kwargs.get( 'cosmic_30x_cov', None) self.local_rmsd = kwargs.get( 'local_rmsd', None) self.local_rmsd_normal = kwargs.get( 'local_rmsd_normal', None) self.mean = kwargs.get( 'mean', None) self.mean_normal = kwargs.get( 'mean_normal', None) self.samtools_insert_size_average = kwargs.get( 'samtools_insert_size_average', None) self.samtools_insert_size_average_normal = kwargs.get( 'samtools_insert_size_average_normal', None) self.samtools_pairs_on_different_chromosomes = kwargs.get( 'samtools_pairs_on_different_chromosomes', None) self.samtools_pairs_on_different_chromosomes_normal = kwargs.get( 'samtools_pairs_on_different_chromosomes_normal', None) self.samtools_reads_mapped = kwargs.get( 'samtools_reads_mapped', None) self.samtools_reads_mapped_normal = kwargs.get( 'samtools_reads_mapped_normal', None) self.tumor_contamination_con_pair = kwargs.get( 'tumor_contamination_con_pair', None) self.tumor_contamination_cont_est = kwargs.get( 'tumor_contamination_cont_est', None) self.variantstats_total_indels = kwargs.get( 'variantstats_total_indels', None) self.variantstats_total_snvs = kwargs.get( 'variantstats_total_snvs', None) self.variantstats_total_svs = kwargs.get( 'variantstats_total_svs', None) class CoverageSummary(ProtocolElement): """ No documentation """ _schemaSource = """ {"type": "record", "name": "CoverageSummary", "namespace": "org.gel.models.report.avro", "fields": [{"name": "avg", "type": "double", "doc": ""}, {"name": "med", "type": "double", "doc": ""}, {"name": "bases", "type": "double", "doc": ""}, {"name": "pct25", "type": ["null", "double"], "doc": ""}, {"name": "pct75", "type": ["null", "double"], "doc": ""}, {"name": "lt15x", "type": ["null", "double"], "doc": ""}, {"name": "gte15x", "type": ["null", "double"], "doc": ""}, {"name": "gte30x", "type": ["null", "double"], "doc": ""}, {"name": "gte50x", "type": ["null", "double"], "doc": ""}, {"name": "sd", "type": ["null", "double"], "doc": ""}, {"name": "localRMSD", "type": ["null", "double"], "doc": ""}, {"name": "scope", "type": "string", "doc": ""}]} """ schema = avro_parse(_schemaSource) requiredFields = { "avg", "bases", "gte15x", "gte30x", "gte50x", "localRMSD", "lt15x", "med", "pct25", "pct75", "scope", "sd", } @classmethod def isEmbeddedType(cls, fieldName): embeddedTypes = {} return fieldName in embeddedTypes @classmethod def getEmbeddedType(cls, fieldName): embeddedTypes = {} return embeddedTypes[fieldName] __slots__ = [ 'avg', 'bases', 'gte15x', 'gte30x', 'gte50x', 'localRMSD', 'lt15x', 'med', 'pct25', 'pct75', 'scope', 'sd' ] def __init__(self, **kwargs): self.avg = kwargs.get( 'avg', None) self.bases = kwargs.get( 'bases', None) self.gte15x = kwargs.get( 'gte15x', None) self.gte30x = kwargs.get( 'gte30x', None) self.gte50x = kwargs.get( 'gte50x', None) self.localRMSD = kwargs.get( 'localRMSD', None) self.lt15x = kwargs.get( 'lt15x', None) self.med = kwargs.get( 'med', None) self.pct25 = kwargs.get( 'pct25', None) self.pct75 = kwargs.get( 'pct75', None) self.scope = kwargs.get( 'scope', None) self.sd = kwargs.get( 'sd', None) class CoverageSummaryCalculations(ProtocolElement): """ Stats calculated from values stored in CoverageSummary """ _schemaSource = """ {"type": "record", "name": "CoverageSummaryCalculations", "namespace": "org.gel.models.report.avro", "doc": "", "fields": [{"name": "lt30x_percent", "type": "double", "doc": ""}, {"name": "scope", "type": "string", "doc": ""}]} """ schema = avro_parse(_schemaSource) requiredFields = { "lt30x_percent", "scope", } @classmethod def isEmbeddedType(cls, fieldName): embeddedTypes = {} return fieldName in embeddedTypes @classmethod def getEmbeddedType(cls, fieldName): embeddedTypes = {} return embeddedTypes[fieldName] __slots__ = [ 'lt30x_percent', 'scope' ] def __init__(self, **kwargs): self.lt30x_percent = kwargs.get( 'lt30x_percent', None) self.scope = kwargs.get( 'scope', None) class ExomeCoverage(ProtocolElement): """ Renamed from ExonCoverage """ _schemaSource = """ {"type": "record", "name": "ExomeCoverage", "namespace": "org.gel.models.report.avro", "doc": "", "fields": [{"name": "coverageSummary", "type": {"type": "array", "items": {"type": "record", "name": "CoverageSummary", "fields": [{"name": "avg", "type": "double", "doc": ""}, {"name": "med", "type": "double", "doc": ""}, {"name": "bases", "type": "double", "doc": ""}, {"name": "pct25", "type": ["null", "double"], "doc": ""}, {"name": "pct75", "type": ["null", "double"], "doc": ""}, {"name": "lt15x", "type": ["null", "double"], "doc": ""}, {"name": "gte15x", "type": ["null", "double"], "doc": ""}, {"name": "gte30x", "type": ["null", "double"], "doc": ""}, {"name": "gte50x", "type": ["null", "double"], "doc": ""}, {"name": "sd", "type": ["null", "double"], "doc": ""}, {"name": "localRMSD", "type": ["null", "double"], "doc": ""}, {"name": "scope", "type": "string", "doc": ""}]}}}]} """ schema = avro_parse(_schemaSource) requiredFields = { "coverageSummary", } @classmethod def isEmbeddedType(cls, fieldName): embeddedTypes = { 'coverageSummary': CoverageSummary, } return fieldName in embeddedTypes @classmethod def getEmbeddedType(cls, fieldName): embeddedTypes = { 'coverageSummary': CoverageSummary, } return embeddedTypes[fieldName] __slots__ = [ 'coverageSummary' ] def __init__(self, **kwargs): self.coverageSummary = kwargs.get( 'coverageSummary', None) class File(ProtocolElement): """ This defines a file This Record is defined by the sampleID and a URI Currently SampleID can be a single String or an array of strings if multiple samples are associated with the same file * """ _schemaSource = """ {"type": "record", "name": "File", "namespace": "org.gel.models.metrics.avro", "doc": "", "fields": [{"name": "SampleId", "type": ["null", "string", {"type": "array", "items": "string"}], "doc": ""}, {"name": "URIFile", "type": "string", "doc": ""}, {"name": "fileType", "type": {"type": "enum", "name": "FileType", "symbols": ["BAM", "gVCF", "VCF_small", "VCF_somatic_small", "VCF_CNV", "VCF_somatic_CNV", "VCF_SV", "VCF_somatic_SV", "VCF_SV_CNV", "SVG", "ANN", "BigWig", "MD5Sum", "ROH", "OTHER"]}}, {"name": "md5Sum", "type": ["null", "string"]}]} """ schema = avro_parse(_schemaSource) requiredFields = { "SampleId", "URIFile", "fileType", "md5Sum", } @classmethod def isEmbeddedType(cls, fieldName): embeddedTypes = {} return fieldName in embeddedTypes @classmethod def getEmbeddedType(cls, fieldName): embeddedTypes = {} return embeddedTypes[fieldName] __slots__ = [ 'SampleId', 'URIFile', 'fileType', 'md5Sum' ] def __init__(self, **kwargs): self.SampleId = kwargs.get( 'SampleId', None) self.URIFile = kwargs.get( 'URIFile', None) self.fileType = kwargs.get( 'fileType', None) self.md5Sum = kwargs.get( 'md5Sum', None) class FileType(object): """ No documentation """ BAM = "BAM" gVCF = "gVCF" VCF_small = "VCF_small" VCF_somatic_small = "VCF_somatic_small" VCF_CNV = "VCF_CNV" VCF_somatic_CNV = "VCF_somatic_CNV" VCF_SV = "VCF_SV" VCF_somatic_SV = "VCF_somatic_SV" VCF_SV_CNV = "VCF_SV_CNV" SVG = "SVG" ANN = "ANN" BigWig = "BigWig" MD5Sum = "MD5Sum" ROH = "ROH" OTHER = "OTHER" def __hash__(self): return str(self).__hash__() class GelAtGcDrop(ProtocolElement): """ GEL AT/GC dropout calculation """ _schemaSource = """ {"type": "record", "name": "GelAtGcDrop", "namespace": "org.gel.models.report.avro", "doc": "", "fields": [{"name": "at_drop", "type": "double"}, {"name": "gc_drop", "type": "double"}]} """ schema
from __future__ import division, print_function import os, types import numpy as np import vtk from vtk.util.numpy_support import numpy_to_vtk from vtk.util.numpy_support import vtk_to_numpy import vtkplotter.colors as colors ############################################################################## vtkMV = vtk.vtkVersion().GetVTKMajorVersion() > 5 def add_actor(f): #decorator def wrapper(*args, **kwargs): actor = f(*args, **kwargs) args[0].actors.append(actor) return actor return wrapper def setInput(vtkobj, p, port=0): if isinstance(p, vtk.vtkAlgorithmOutput): vtkobj.SetInputConnection(port, p) # passing port return if vtkMV: vtkobj.SetInputData(p) else: vtkobj.SetInput(p) def isSequence(arg): if hasattr(arg, "strip"): return False if hasattr(arg, "__getslice__"): return True if hasattr(arg, "__iter__"): return True return False def arange(start,stop, step=1): return np.arange(start, stop, step) def vector(x, y=None, z=0.): if y is None: #assume x is already [x,y,z] return np.array(x, dtype=np.float64) return np.array([x,y,z], dtype=np.float64) def mag(z): if isinstance(z[0], np.ndarray): return np.array(list(map(np.linalg.norm, z))) else: return np.linalg.norm(z) def mag2(z): return np.dot(z,z) def norm(v): if isinstance(v[0], np.ndarray): return np.divide(v, mag(v)[:,None]) else: return v/mag(v) def to_precision(x, p): """ Returns a string representation of x formatted with a precision of p Based on the webkit javascript implementation taken from here: https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp Implemented in https://github.com/randlet/to-precision """ import math x = float(x) if x == 0.: return "0." + "0"*(p-1) out = [] if x < 0: out.append("-") x = -x e = int(math.log10(x)) tens = math.pow(10, e - p + 1) n = math.floor(x/tens) if n < math.pow(10, p - 1): e = e -1 tens = math.pow(10, e - p+1) n = math.floor(x / tens) if abs((n + 1.) * tens - x) <= abs(n * tens -x): n = n + 1 if n >= math.pow(10,p): n = n / 10. e = e + 1 m = "%.*g" % (p, n) if e < -2 or e >= p: out.append(m[0]) if p > 1: out.append(".") out.extend(m[1:p]) out.append('e') if e > 0: out.append("+") out.append(str(e)) elif e == (p -1): out.append(m) elif e >= 0: out.append(m[:e+1]) if e+1 < len(m): out.append(".") out.extend(m[e+1:]) else: out.append("0.") out.extend(["0"]*-(e+1)) out.append(m) return "".join(out) ######################################################################### def makeActor(poly, c='gold', alpha=0.5, wire=False, bc=None, edges=False, legend=None, texture=None): ''' Return a vtkActor from an input vtkPolyData, optional args: c, color in RGB format, hex, symbol or name alpha, transparency (0=invisible) wire, show surface as wireframe bc, backface color of internal surface edges, show edges as line on top of surface legend optional string texture jpg file name of surface texture, eg. 'metalfloor1' ''' clp = vtk.vtkCleanPolyData() setInput(clp, poly) clp.Update() pdnorm = vtk.vtkPolyDataNormals() setInput(pdnorm, clp.GetOutput()) pdnorm.ComputePointNormalsOn() pdnorm.ComputeCellNormalsOn() pdnorm.FlipNormalsOff() pdnorm.ConsistencyOn() pdnorm.Update() mapper = vtk.vtkPolyDataMapper() # check if color string contains a float, in this case ignore alpha if alpha is None: alpha=0.5 al = colors.getAlpha(c) if al: alpha = al setInput(mapper, pdnorm.GetOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper) prp = actor.GetProperty() ######################################################################### ### On some vtk versions/platforms points are redered as ugly squares ### in such a case uncomment this line: if vtk.vtkVersion().GetVTKMajorVersion()>6: prp.RenderPointsAsSpheresOn() ######################################################################### if c is None: mapper.ScalarVisibilityOn() else: mapper.ScalarVisibilityOff() c = colors.getColor(c) prp.SetColor(c) prp.SetOpacity(alpha) prp.SetSpecular(0.1) prp.SetSpecularColor(c) prp.SetSpecularPower(1) prp.SetAmbient(0.1) prp.SetAmbientColor(c) prp.SetDiffuse(1) prp.SetDiffuseColor(c) if edges: prp.EdgeVisibilityOn() if wire: prp.SetRepresentationToWireframe() if texture: mapper.ScalarVisibilityOff() assignTexture(actor, texture) if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) assignPhysicsMethods(actor) assignConvenienceMethods(actor, legend) return actor def makeAssembly(actors, legend=None): '''Group many actors as a single new actor''' assembly = vtk.vtkAssembly() for a in actors: assembly.AddPart(a) setattr(assembly, 'legend', legend) assignPhysicsMethods(assembly) assignConvenienceMethods(assembly, legend) if hasattr(actors[0], 'base'): setattr(assembly, 'base', actors[0].base) setattr(assembly, 'top', actors[0].top) return assembly def assignTexture(actor, name, scale=1, falsecolors=False, mapTo=1): '''Assign a texture to actor from file or name in /textures directory''' if mapTo == 1: tmapper = vtk.vtkTextureMapToCylinder() elif mapTo == 2: tmapper = vtk.vtkTextureMapToSphere() elif mapTo == 3: tmapper = vtk.vtkTextureMapToPlane() setInput(tmapper, polydata(actor)) if mapTo == 1: tmapper.PreventSeamOn() xform = vtk.vtkTransformTextureCoords() xform.SetInputConnection(tmapper.GetOutputPort()) xform.SetScale(scale,scale,scale) if mapTo == 1: xform.FlipSOn() xform.Update() mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(xform.GetOutputPort()) mapper.ScalarVisibilityOff() cdir = os.path.dirname(__file__) if cdir == '': cdir = '.' fn = cdir + '/textures/' + name + ".jpg" if os.path.exists(name): fn = name elif not os.path.exists(fn): colors.printc(('Texture', name, 'not found in', cdir+'/textures'), 'r') colors.printc('Available textures:', c='m', end=' ') for ff in os.listdir(cdir + '/textures'): colors.printc(ff.split('.')[0], end=' ', c='m') print() return jpgReader = vtk.vtkJPEGReader() jpgReader.SetFileName(fn) atext = vtk.vtkTexture() atext.RepeatOn() atext.EdgeClampOff() atext.InterpolateOn() if falsecolors: atext.MapColorScalarsThroughLookupTableOn() atext.SetInputConnection(jpgReader.GetOutputPort()) actor.GetProperty().SetColor(1,1,1) actor.SetMapper(mapper) actor.SetTexture(atext) # ########################################################################### def assignConvenienceMethods(actor, legend): if not hasattr(actor, 'legend'): setattr(actor, 'legend', legend) def _fclone(self, c=None, alpha=None, wire=False, bc=None, edges=False, legend=None, texture=None, rebuild=True): return clone(self, c, alpha, wire, bc, edges, legend, texture, rebuild) actor.clone = types.MethodType( _fclone, actor ) def _fpoint(self, i, p=None): if p is None : poly = polydata(self, True, 0) p = [0,0,0] poly.GetPoints().GetPoint(i, p) return np.array(p) else: poly = polydata(self, False, 0) poly.GetPoints().SetPoint(i, p) TI = vtk.vtkTransform() actor.SetUserMatrix(TI.GetMatrix()) # reset return self actor.point = types.MethodType( _fpoint, actor ) def _fN(self, index=0): return polydata(self, False, index).GetNumberOfPoints() actor.N = types.MethodType( _fN, actor ) def _fnormalize(self): return normalize(self) actor.normalize = types.MethodType( _fnormalize, actor ) def _fshrink(self, fraction=0.85): return shrink(self, fraction) actor.shrink = types.MethodType( _fshrink, actor ) def _fcutPlane(self, origin=(0,0,0), normal=(1,0,0), showcut=False): return cutPlane(self, origin, normal, showcut) actor.cutPlane = types.MethodType( _fcutPlane, actor ) def _fcutterw(self): return cutterWidget(self) actor.cutterWidget = types.MethodType( _fcutterw, actor ) def _fpolydata(self, rebuild=True, index=0): return polydata(self, rebuild, index) actor.polydata = types.MethodType( _fpolydata, actor ) def _fcoordinates(self, rebuild=True): return coordinates(self, rebuild) actor.coordinates = types.MethodType( _fcoordinates, actor ) def _fxbounds(self): b = polydata(actor, True).GetBounds() return (b[0],b[1]) actor.xbounds = types.MethodType( _fxbounds, actor ) def _fybounds(self): b = polydata(actor, True).GetBounds() return (b[2],b[3]) actor.ybounds = types.MethodType( _fybounds, actor ) def _fzbounds(self): b = polydata(actor, True).GetBounds() return (b[4],b[5]) actor.zbounds = types.MethodType( _fzbounds, actor ) def _fnormalAt(self, index): normals = polydata(self, True).GetPointData().GetNormals() return np.array(normals.GetTuple(index)) actor.normalAt = types.MethodType( _fnormalAt, actor ) def _fnormals(self): vtknormals = polydata(self, True).GetPointData().GetNormals() as_numpy = vtk_to_numpy(vtknormals) return as_numpy actor.normals = types.MethodType( _fnormals, actor ) def _fstretch(self, startpt, endpt): return stretch(self, startpt, endpt) actor.stretch = types.MethodType( _fstretch, actor) def _fsubdivide(self, N=1, method=0, legend=None): return subdivide(self, N, method, legend) actor.subdivide = types.MethodType( _fsubdivide, actor) def _fdecimate(self, fraction=0.5, N=None, verbose=True, boundaries=True): return decimate(self, fraction, N, verbose, boundaries) actor.decimate = types.MethodType( _fdecimate, actor) def _fcolor(self, c=None): if c is not None: self.GetProperty().SetColor(colors.getColor(c)) return self else: return np.array(self.GetProperty().GetColor()) actor.color = types.MethodType( _fcolor, actor) def _falpha(self, a=None): if a: self.GetProperty().SetOpacity(a) return self else: return self.GetProperty().GetOpacity() actor.alpha = types.MethodType( _falpha, actor) def _fwire(self, a=True): if a: self.GetProperty().SetRepresentationToWireframe() else: self.GetProperty().SetRepresentationToSurface() return self actor.wire = types.MethodType( _fwire, actor) def _fclosestPoint(self, pt, N=1, radius=None): return closestPoint(self, pt, N, radius) actor.closestPoint = types.MethodType( _fclosestPoint, actor) def _fintersectWithLine(self, p0, p1): return intersectWithLine(self, p0,p1) actor.intersectWithLine = types.MethodType(_fintersectWithLine , actor) def _fisInside(self, point, tol=0.0001): return isInside(self, point, tol) actor.isInside = types.MethodType(_fisInside , actor) def _finsidePoints(self, points, invert=False, tol=1e-05): return insidePoints(self, points, invert, tol) actor.insidePoints = types.MethodType(_finsidePoints , actor) def _fflipNormals(self): return flipNormals(self) actor.flipNormals = types.MethodType(_fflipNormals , actor) def _fcellCenters(self): return cellCenters(self) actor.cellCenters = types.MethodType(_fcellCenters, actor) def _fpointScalars(self, scalars, name): return pointScalars(self, scalars, name) actor.pointScalars = types.MethodType(_fpointScalars , actor) def _fpointColors(self, scalars, cmap='jet'): return pointColors(self, scalars, cmap) actor.pointColors = types.MethodType(_fpointColors , actor) def _fcellScalars(self, scalars, name): return cellScalars(self, scalars, name) actor.cellScalars = types.MethodType(_fcellScalars , actor) def _fcellColors(self, scalars, cmap='jet'): return cellColors(self, scalars, cmap) actor.cellColors = types.MethodType(_fcellColors , actor) def _fscalars(self, name): return scalars(self, name) actor.scalars = types.MethodType(_fscalars , actor) # ########################################################################### def assignPhysicsMethods(actor): def _fpos(self, p=None): if p is None: return np.array(self.GetPosition()) self.SetPosition(p) return self # return itself to concatenate methods actor.pos = types.MethodType( _fpos, actor ) def _faddpos(self, dp): self.SetPosition(np.array(self.GetPosition()) +dp ) return self actor.addpos = types.MethodType( _faddpos, actor ) def _fpx(self, px=None): # X _pos = self.GetPosition() if px is None: return _pos[0] newp = [px, _pos[1], _pos[2]] self.SetPosition(newp) return self actor.x = types.MethodType( _fpx, actor ) def _fpy(self, py=None): # Y _pos = self.GetPosition() if py is None: return _pos[1] newp = [_pos[0], py, _pos[2]] self.SetPosition(newp) return self actor.y = types.MethodType( _fpy, actor ) def _fpz(self, pz=None): #
<reponame>aerele/rpricemill from __future__ import unicode_literals import frappe from frappe import _ from frappe.model.document import Document from frappe.utils import comma_and,get_link_to_form from erpnext.accounts.utils import get_balance_on from erpnext.accounts.party import get_dashboard_info from frappe.model.naming import parse_naming_series from erpnext.accounts.utils import get_fiscal_year from datetime import datetime, timedelta from frappe.utils import get_link_to_form def rice_allert(doc,action): count = frappe.db.sql("""select count(*) from ( select sales.name, sales.posting_date, item.item_code, sales.customer, item.item_group from ( SELECT si.name, si.posting_date, sit.item_code, si.customer from `tabSales Invoice` as si inner join `tabSales Invoice Item` as sit on sit.parent = si.name ) as sales inner join `tabItem` as item on item.name = sales.item_code ) as grp inner join `tabItem Group` as igrp on grp.item_group = igrp.name WHERE grp.posting_date BETWEEN date_sub(curdate(), INTERVAL 10 DAY) and curdate() and grp.customer = %s and igrp.rp_item_group_primary like %s""",(doc.customer,"Rice")) if not count[0][0]: frappe.msgprint("Customer did not buy any item of group Rice") def pos_batch(doc,action): if(doc.pos_profile): branch = frappe.get_value("POS Profile",{"name" : doc.pos_profile},"branch") if branch: if not doc.branch: doc.branch = branch for item in doc.items: if not item.branch: item.branch = branch for tax in doc.taxes: if not tax.branch: tax.branch = branch else: frappe.throw("Branch Not Available in POS Profile") def contact_before_save(doc, action): nos = [] for num in doc.phone_nos: if frappe.db.exists('Contact Phone', {'phone': num.phone}): con_parent = frappe.db.get_value('Contact Phone', {'phone': num.phone}, 'parent') if con_parent == doc.name: if num.phone in nos: frappe.throw('Contact already in the list') else: nos.append(num.phone) else: link_name = frappe.db.get_value('Dynamic Link', {'link_doctype': 'Customer', 'parenttype': 'Contact', 'parent': con_parent}, 'link_name') if link_name: frappe.throw('Phone Number already linked to Customer: ' + get_link_to_form('Customer', link_name)) else: frappe.throw('Phone Number already linked to Contact: ' + get_link_to_form('Contact', link_name)) def update_loyality(doc,action): loyalty = frappe.get_doc("Customer", doc.customer) value = 0 if(loyalty.loyalty_program): if_loyalty = frappe.get_doc("Loyalty Program", loyalty.loyalty_program) if(if_loyalty.loyalty_program_based_on_item == 1): for ite in doc.items: if frappe.db.exists('Item', ite.item_code): item = frappe.get_doc("Item", ite.item_code) if(item.loyalty_points > 0): value += (float(item.loyalty_points) * float(item.loyalty_points_booster)) * int(ite.qty) point_entry = frappe.db.sql("select name from `tabLoyalty Point Entry` where invoice = %s and redeem_against is null",(doc.name)) if(len(point_entry)): val_point = frappe.get_doc("Loyalty Point Entry",point_entry[0][0]) val_point.loyalty_points = value val_point.save(ignore_permissions=True) new_customer = frappe.db.sql("""select count(*) from `tabSales Invoice` where customer = %s""",(doc.customer)) if new_customer[0][0] == 1: refrel_value = value / 2 ref_customer = frappe.get_value("Customer",{"name":doc.customer},"referred_customer") if ref_customer: frappe.get_doc({ "doctype" : "Loyalty Point Entry", "loyalty_program" : val_point.loyalty_program, "loyalty_program_tier" : val_point.loyalty_program_tier, "customer" : ref_customer, "loyalty_points" : refrel_value, "expiry_date" : val_point.expiry_date, "posting_date": val_point.posting_date, "company" : val_point.company }).save(ignore_permissions = True) data_points = get_dashboard_info('Customer', doc.customer) outstanding = 0 for data_point in data_points: if data_point['total_unpaid']: outstanding += data_point['total_unpaid'] if outstanding and doc.doctype == 'POS Invoice': customer_name = frappe.db.get_value('Customer', doc.customer, 'customer_name') frappe.msgprint(get_link_to_form('Customer', doc.customer) + " - " + customer_name + " has an outstanding of " + str(outstanding)) @frappe.whitelist() def update_loyalty_account(doc, action): if(doc.redeem_loyalty_points == 1): redeem_amount = 0 for item in doc.items: if(frappe.get_value("Item",item.item_code,'eligible_for_redeem')): redeem_amount += item.amount if(redeem_amount < doc.loyalty_amount ): frappe.throw("Loyalty points can only be used to redeem the eligible items.") acc = frappe.db.get_value('Company', doc.company, 'loyalty_redemption_expense_account') cost_center = frappe.db.get_value('Company', doc.company, 'cost_center') if not doc.loyalty_redemption_account: doc.loyalty_redemption_account = acc if not doc.loyalty_redemption_cost_center: doc.loyalty_redemption_cost_center = cost_center @frappe.whitelist() def get_all_balances(pos_profile): payments = frappe.db.get_list('POS Payment Method', {'parent': pos_profile}, 'mode_of_payment') company = frappe.db.get_value('POS Profile', pos_profile, 'company') res = {} for payment in payments: if payment.mode_of_payment: balance, idx = get_current_balance(company, payment.mode_of_payment, 0) res[payment.mode_of_payment] = balance return res @frappe.whitelist() def get_current_balance(company,mode_of_pay,idx): doc = frappe.db.sql("""select mpa.default_account from `tabMode of Payment` as mp inner join `tabMode of Payment Account` as mpa on mpa.parent = mp.name where mpa.company = %s and mp.name = %s""",(company,mode_of_pay)) if(len(doc)): current_balance = get_balance_on(account = doc[0][0],company = company, ignore_account_permission=True) return(current_balance,int(idx)) @frappe.whitelist() def get_customer_data(customer,company): if customer: doc = frappe.get_doc("Customer",customer) data_points = get_dashboard_info(doc.doctype, doc.name, doc.loyalty_program) res = { 'total_unpaid': 0, 'billing_this_year': 0, 'info': '', 'loyalty_points': 0 } for data_point in data_points: if data_point['total_unpaid']: res['total_unpaid'] += data_point['total_unpaid'] if data_point['billing_this_year']: res['billing_this_year'] += data_point['billing_this_year'] if 'loyalty_points' not in data_point: data_point['loyalty_points'] = 0 if 'loyalty_points' in data_point: if company == data_point["company"]: res['loyalty_points'] = data_point['loyalty_points'] res['info'] += f"Company: {data_point['company']}, \n Outstanding: {data_point['total_unpaid']}, \n Turn Over: {data_point['billing_this_year']}, \n Loyalty Points: {data_point['loyalty_points']} \n\n" return res @frappe.whitelist() def get_account(company): doc = frappe.get_doc("Company",company) return(doc.loyalty_redemption_expense_account) def save_customer(doc,action): for links in doc.links: if(links.link_doctype == "Customer"): customer = frappe.get_doc("Customer",links.link_name) customer.save() def add_mobile_search(doc, action): phone_numbers = frappe.db.sql("""select group_concat(phone.phone) as all_numbers from tabCustomer as customer inner join `tabContact Phone` as phone inner join `tabContact` as contact on contact.name = phone.parent inner join `tabDynamic Link` as dl on dl.link_doctype = 'Customer' and dl.parenttype = 'Contact' and dl.link_name = customer.name and dl.parent = contact.name where customer.name = %s group by phone.phone""", doc.name, as_dict = 1) number_ = "" if len(phone_numbers): for number in range(len(phone_numbers)): if 'all_numbers' in phone_numbers[number]: number_ += phone_numbers[number]['all_numbers'] if(number != len(phone_numbers) - 1): number_ += "," doc.mobile_search = number_ def add_vehicle_log(doc, action): if doc.delivering_driver and doc.vehicle and (doc.current_odometer_value or doc.return_odometer_value): vehicle_log = frappe.new_doc('Vehicle Log') vehicle_log.license_plate = doc.vehicle vehicle_log.employee = frappe.db.get_value('Driver', doc.delivering_driver, 'employee') if doc.return_odometer_value: vehicle_log.odometer = doc.return_odometer_value elif doc.current_odometer_value: vehicle_log.odometer = doc.current_odometer_value vehicle_log.date = doc.posting_date vehicle_log.purpose = 'Sales Delivery' vehicle_log.remarks = doc.name vehicle_log.save() vehicle_log.submit() def get_fiscal_year_short_form(): fy = frappe.db.get_single_value('Global Defaults', 'current_fiscal_year') return fy.split('-')[0][2:] def name_sales_invoice(doc, action): abbr = frappe.get_cached_value('Company', doc.company, 'abbr') fy = get_fiscal_year_short_form() if doc.is_pos: doc.name = parse_naming_series(f'{abbr}POSI{fy}-.######') else: doc.name = parse_naming_series(f'{abbr}SI{fy}-.######') def name_sales_order(doc, action): fy = get_fiscal_year_short_form() abbr = frappe.get_cached_value('Company', doc.company, 'abbr') doc.name = parse_naming_series(f"{abbr}SO{fy}-.######") def name_purchase_order(doc, action): fy = get_fiscal_year_short_form() abbr = frappe.get_cached_value('Company', doc.company, 'abbr') doc.name = parse_naming_series(f"{abbr}PO{fy}-.######") def name_purchase_invoice(doc, action): fy = get_fiscal_year_short_form() abbr = frappe.get_cached_value('Company', doc.company, 'abbr') doc.name = parse_naming_series(f"{abbr}PI{fy}-.######") def name_purchase_receipt(doc, action): fy = get_fiscal_year_short_form() abbr = frappe.get_cached_value('Company', doc.company, 'abbr') doc.name = parse_naming_series(f"{abbr}PR{fy}-.######") def name_payment_entry(doc, action): fy = get_fiscal_year_short_form() abbr = frappe.get_cached_value('Company', doc.company, 'abbr') doc.name = parse_naming_series(f"{abbr}PAY{fy}-.######") def name_pos_invoice(doc, action): fy = get_fiscal_year_short_form() abbr = frappe.get_cached_value('Company', doc.company, 'abbr') doc.name = parse_naming_series(f"{abbr}POI{fy}-.######") def get_gstno(doc,action): gstin = frappe.get_value("Address",{"name" : doc.customer_address},['gstin']) if gstin: doc.gst_no = " " elif doc.tax_id: doc.gst_no = doc.tax_id else: doc.gst_no = " " if(doc.total_unpaid): doc.outstanding_pf = doc.total_unpaid else: data = get_customer_data(doc.customer,doc.company) doc.outstanding_pf = data["total_unpaid"] phone = frappe.db.sql("""select cp.phone from `tabContact Phone` as cp inner join (select con.name as conname from `tabContact` as con inner join `tabDynamic Link` as dl on dl.parent = con.name where dl.link_name = %s) as con on con.conname = cp.parent""",(doc.customer),as_list = 1) number = "" for no in range(len(phone)): number += phone[no][0] if(no != len(phone) - 1): number += "," doc.mobile = number def scgst(doc,action): for items in doc.items: if items.item_tax_template: sgst = 0 cgst = 0 tax = frappe.db.sql("""select ttd.tax_type,ttd.tax_rate from `tabItem Tax Template` as tt inner join `tabItem Tax Template Detail` as ttd on tt.name = ttd.parent where tt.name = %s""",(items.item_tax_template),as_dict = 1) for _tax in tax: data = _tax["tax_type"] data = data.split(" - ") if("SGST" in data): sgst = _tax["tax_rate"] elif("CGST" in data): cgst = _tax["tax_rate"] if sgst and cgst : break rate = cgst + sgst items.sgst = round((items.amount - (items.amount/(1 + (float(rate)/100))))/2,2) items.cgst = round((items.amount - (items.amount/(1 + (float(rate)/100))))/2,2) else: items.sgst = 0 items.cgst = 0 @frappe.whitelist() def get_address(store_branch): return(frappe.get_value("Address",{"store_branch" : store_branch},'name')) @frappe.whitelist() def get_mobile_number(customer): return(frappe.get_value("Customer",{"name" : customer},'mobile_no')) @frappe.whitelist() def create_events_from_vehicle_remainder(doc, action): if doc.remainders: for prop in doc.remainders: if frappe.db.exists('Event', {'vehicle': doc.name, 'remainder_property': prop.property}): exisiting_event = frappe.get_doc('Event', {'vehicle': doc.name, 'remainder_property': prop.property}) if prop.remind_before_in_days: start = datetime.combine(datetime.strptime(prop.date, '%Y-%m-%d') - timedelta(days=prop.remind_before_in_days), datetime.min.time()) else: start = datetime.combine(datetime.strptime(prop.date, '%Y-%m-%d'), datetime.min.time()) if prop.assign_to: is_present = 0 for participant in exisiting_event.event_participants: if participant.reference_docname == prop.assign_to: is_present = 1 break if not is_present: exisiting_event.append("event_participants", { "reference_doctype": 'Employee', "reference_docname": prop.assign_to, }) exisiting_event.starts_on = start exisiting_event.status = 'Open' exisiting_event.all_day = 1 if prop.is_recurring: exisiting_event.repeat_this_event = 1 exisiting_event.repeat_on = prop.repeat_on exisiting_event.repeat_till = prop.repeat_till else: exisiting_event.repeat_this_event = 0 exisiting_event.description = prop.remarks exisiting_event.save(ignore_permissions=True) else: event = frappe.new_doc('Event') event.subject = doc.name + ' - ' + prop.property event.event_category = 'Event' event.event_type = 'Private' event.vehicle = doc.name event.remainder_property = prop.property if prop.remind_before_in_days: start = datetime.combine(datetime.strptime(prop.date, '%Y-%m-%d') - timedelta(days=prop.remind_before_in_days), datetime.min.time()) else: start = datetime.combine(datetime.strptime(prop.date, '%Y-%m-%d'), datetime.min.time()) if prop.assign_to: event.append("event_participants", { "reference_doctype": 'Employee', "reference_docname": prop.assign_to, }) event.starts_on = start event.status = 'Open' event.all_day = 1 if prop.is_recurring: event.repeat_this_event = 1 event.repeat_on = prop.repeat_on event.repeat_till = prop.repeat_till else: event.repeat_this_event = 0 event.description = prop.remarks event.save(ignore_permissions=True) @frappe.whitelist() def pos_qty(value,doc): qty = 0 for item in doc.items: qty += float(item.qty) return(qty) @frappe.whitelist() def get_sales_summary(company,pos_profile): date_ = datetime.now() date_ = date_.date() str_date = str(date_) _date = datetime.strptime(str_date,"%Y-%m-%d") existing_customer = frappe.db.sql("""select count(si.name) as count,sum(grand_total) as sales from `tabSales Invoice` as si inner join `tabCustomer` as cos on cos.name = si.customer where si.posting_date = %s and si.company = %s and cos.creation < %s and si.pos_profile = %s""",(date_,company,_date,pos_profile),as_dict = 1) new_customer = frappe.db.sql("""select count(si.name) as count,sum(grand_total) as sales from `tabSales Invoice` as si inner join `tabCustomer` as cos on cos.name = si.customer where si.posting_date = %s and si.company = %s and cos.creation >= %s and si.pos_profile = %s""",(date_,company,_date,pos_profile),as_dict = 1) # outstanding = frappe.db.sql("""select count(si.name) as count,sum(outstanding_amount) as sales from `tabSales Invoice` as si inner join `tabCustomer` as cos on cos.name = si.customer where si.posting_date = %s and si.company = %s and cos.creation >= %s and si.outstanding_amount > %s""",(date_,company,_date,"0"),as_dict = 1) total_count = 0 total_sales = 0 final_result = [] if len(existing_customer): existing_customer = existing_customer[0].update({"particular": "Existing Customer"}) if existing_customer["count"]: total_count += int(existing_customer["count"]) if existing_customer["sales"]: total_sales += float(existing_customer["sales"]) else: existing_customer["sales"] = 0 final_result.append(existing_customer) if len(new_customer): new_customer = new_customer[0].update({"particular": "New Customer"}) if new_customer["count"]: total_count += int(new_customer["count"]) if new_customer["sales"]: total_sales += float(new_customer["sales"]) else: new_customer["sales"] = 0 final_result.append(new_customer) # if len(outstanding): # outstanding = outstanding[0].update({"particular": "Outstanding"}) # if not outstanding["sales"]: # outstanding["sales"] = 0 # final_result.append(outstanding) final_result.append({"particular": "Total","count":total_count,"sales":total_sales}) return(final_result) @frappe.whitelist() def get_target_summary(company,pos_profile,posting_date): print(pos_profile) starting_date = posting_date.split("-") starting_date[2] = "01" starting_date = starting_date[0] + "-" + starting_date[1] + "-" + starting_date[2] starting_date = datetime.strptime(starting_date,"%Y-%m-%d").date() posting_date = datetime.strptime(posting_date,"%Y-%m-%d").date() annual = frappe.db.sql("""select sum(grand_total) from `tabSales Invoice` where company = %s and pos_profile = %s""",(company,pos_profile)) monthly = frappe.db.sql("""select sum(grand_total) from `tabSales Invoice` where company = %s and pos_profile = %s and posting_date between %s and %s""",(company,pos_profile,starting_date,posting_date)) branch = frappe.get_value("POS Profile",{"name": pos_profile},"branch") print(branch) target = frappe.get_list("Branch",{"name" : branch},['monthly_target','annual_target_']) print(target) print(annual) target_summary = [] target_summary.append({"target":"Monthly","target_amount" : target[0]["monthly_target"],"sales_amount" : monthly[0][0]}) target_summary.append({"target":"Annual","target_amount" : target[0]["annual_target_"],"sales_amount" : annual[0][0]}) print(target_summary) return(target_summary) @frappe.whitelist() def get_recent_items_from_pos(filters,fields,limit): value = frappe.db.sql("""select chld.branch as branch, chld.name as name, chld.grand_total as grand_total, chld.posting_date as posting_date, chld.creation, chld.posting_time as posting_time, chld.currency as currency, chld.status as status, chld.day_count as day_count, cpy.abbr as abbrivation from `tabCompany` as cpy inner join ( select ifnull( concat(" (", sit.branch, ")"), concat(" (", sit.warehouse, ")") ) as branch, sit.item_name as name, sit.amount as grand_total, si.posting_date, si.creation, si.posting_time, si.price_list_currency as currency, concat(FORMAT(sit.qty, 2), ' QTY') as status, CONCAT( DATEDIFF(CURDATE(), si.posting_date), ' Days
guild to edit. This may be the object or the ID of an existing guild. Other Parameters ---------------- nick : hikari.undefined.UndefinedNoneOr[builtins.str] If provided, the new nick for the member. If `builtins.None`, will remove the members nick. Requires the `MANAGE_NICKNAMES` permission. roles : hikari.undefined.UndefinedOr[typing.Collection[hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialRole]]] If provided, the new roles for the member. Requires the `MANAGE_ROLES` permission. mute : hikari.undefined.UndefinedOr[builtins.bool] If provided, the new server mute state for the member. Requires the `MUTE_MEMBERS` permission. deaf : hikari.undefined.UndefinedOr[builtins.bool] If provided, the new server deaf state for the member. Requires the `DEAFEN_MEMBERS` permission. voice_channel : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildVoiceChannel]]] If provided, `builtins.None` or the object or the ID of an existing voice channel to move the member to. If `builtins.None`, will disconnect the member from voice. Requires the `MOVE_MEMBERS` permission and the `CONNECT` permission in the original voice channel and the target voice channel. !!! note If the member is not in a voice channel, this will take no effect. reason : hikari.undefined.UndefinedOr[builtins.str] If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters. Raises ------ hikari.errors.BadRequestError If any of the fields that are passed have an invalid value. hikari.errors.ForbiddenError If you are missing a permission to do an action. hikari.errors.UnauthorizedError If you are unauthorized to make the request (invalid/missing token). hikari.errors.NotFoundError If the guild or the user are not found. hikari.errors.RateLimitTooLongError Raised in the event that a rate limit occurs that is longer than `max_rate_limit` when making a request. hikari.errors.RateLimitedError Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur. hikari.errors.InternalServerError If an internal error occurs on Discord while handling the request. """ @abc.abstractmethod async def edit_my_nick( self, guild: snowflakes.SnowflakeishOr[guilds.Guild], nick: typing.Optional[str], *, reason: undefined.UndefinedOr[str] = undefined.UNDEFINED, ) -> None: """Edit the associated token's member nick. Parameters ---------- guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild] The guild to edit. This may be the object or the ID of an existing guild. nick : typing.Optional[builtins.str] The new nick. If `builtins.None`, will remove the nick. Other Parameters ---------------- reason : hikari.undefined.UndefinedOr[builtins.str] If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters. Raises ------ hikari.errors.ForbiddenError If you are missing the `CHANGE_NICKNAME` permission. hikari.errors.UnauthorizedError If you are unauthorized to make the request (invalid/missing token). hikari.errors.NotFoundError If the guild is not found. hikari.errors.RateLimitTooLongError Raised in the event that a rate limit occurs that is longer than `max_rate_limit` when making a request. hikari.errors.RateLimitedError Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur. hikari.errors.InternalServerError If an internal error occurs on Discord while handling the request. """ @abc.abstractmethod async def add_role_to_member( self, guild: snowflakes.SnowflakeishOr[guilds.PartialGuild], user: snowflakes.SnowflakeishOr[users.PartialUser], role: snowflakes.SnowflakeishOr[guilds.PartialRole], *, reason: undefined.UndefinedOr[str] = undefined.UNDEFINED, ) -> None: """Add a role to a member. Parameters ---------- guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild] The guild where the member is in. This may be the object or the ID of an existing guild. user : hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser] The user to add the role to. This may be the object or the ID of an existing user. role : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialRole] The role to add. This may be the object or the ID of an existing role. Other Parameters ---------------- reason : hikari.undefined.UndefinedOr[builtins.str] If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters. Raises ------ hikari.errors.ForbiddenError If you are missing the `MANAGE_ROLES` permission. hikari.errors.UnauthorizedError If you are unauthorized to make the request (invalid/missing token). hikari.errors.NotFoundError If the guild, user or role are not found. hikari.errors.RateLimitTooLongError Raised in the event that a rate limit occurs that is longer than `max_rate_limit` when making a request. hikari.errors.RateLimitedError Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur. hikari.errors.InternalServerError If an internal error occurs on Discord while handling the request. """ @abc.abstractmethod async def remove_role_from_member( self, guild: snowflakes.SnowflakeishOr[guilds.PartialGuild], user: snowflakes.SnowflakeishOr[users.PartialUser], role: snowflakes.SnowflakeishOr[guilds.PartialRole], *, reason: undefined.UndefinedOr[str] = undefined.UNDEFINED, ) -> None: """Remove a role from a member. Parameters ---------- guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild] The guild where the member is in. This may be the object or the ID of an existing guild. user : hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser] The user to remove the role from. This may be the object or the ID of an existing user. role : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialRole] The role to remove. This may be the object or the ID of an existing role. Other Parameters ---------------- reason : hikari.undefined.UndefinedOr[builtins.str] If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters. Raises ------ hikari.errors.ForbiddenError If you are missing the `MANAGE_ROLES` permission. hikari.errors.UnauthorizedError If you are unauthorized to make the request (invalid/missing token). hikari.errors.NotFoundError If the guild, user or role are not found. hikari.errors.RateLimitTooLongError Raised in the event that a rate limit occurs that is longer than `max_rate_limit` when making a request. hikari.errors.RateLimitedError Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur. hikari.errors.InternalServerError If an internal error occurs on Discord while handling the request. """ @abc.abstractmethod async def kick_user( self, guild: snowflakes.SnowflakeishOr[guilds.PartialGuild], user: snowflakes.SnowflakeishOr[users.PartialUser], *, reason: undefined.UndefinedOr[str] = undefined.UNDEFINED, ) -> None: """Kick a member from a guild. Parameters ---------- guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild] The guild to kick the member from. This may be the object or the ID of an existing guild. user : hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser] The user to kick. This may be the object or the ID of an existing user. Other Parameters ---------------- reason : hikari.undefined.UndefinedOr[builtins.str] If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters. Raises ------ hikari.errors.ForbiddenError If you are missing the `KICK_MEMBERS` permission. hikari.errors.UnauthorizedError If you are unauthorized to make the request (invalid/missing token). hikari.errors.NotFoundError If the guild or user are not found. hikari.errors.RateLimitTooLongError Raised in the event that a rate limit occurs that is longer than `max_rate_limit` when making a request. hikari.errors.RateLimitedError Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur. hikari.errors.InternalServerError If an internal error occurs on Discord while handling the request. """ kick_member = kick_user """This is simply an alias for readability.""" @abc.abstractmethod async def ban_user( self, guild: snowflakes.SnowflakeishOr[guilds.PartialGuild], user: snowflakes.SnowflakeishOr[users.PartialUser], *, delete_message_days: undefined.UndefinedOr[int] = undefined.UNDEFINED, reason: undefined.UndefinedOr[str] = undefined.UNDEFINED, ) -> None: """Ban a member from a guild. Parameters ---------- guild : hikari.snowflakes.SnowflakeishOr[hikari.guilds.PartialGuild] The guild to ban the member from. This may be the object or the ID of an existing guild. user : hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser] The user to kick. This may be the object or the ID of an existing user. Other Parameters ---------------- delete_message_days : hikari.undefined.UndefinedNoneOr[int] If provided, the number of days to delete messages for.
""" refobj.deleted = True if refobj.reference: assert refobj not in refobj.reference.content for r in refobj.reference.content: self.get_refobjinter().delete(r) def import_reference(self, refobj, reference): """Import the given reference :param refobj: the refobj :type refobj: :class:`Refobj` :param reference: the reference object. E.g. in Maya a reference node :returns: None :rtype: None :raises: NotImplementedError """ for r in reference.content: r.referencedby = None reference.content = [] refobj.reference = None def import_taskfile(self, refobj, taskfileinfo): """Import the given taskfileinfo and update the refobj :param refobj: the refobject :type refobj: refobject :param taskfileinfo: the taskfileinfo to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: NotImplementedError """ refobj.taskfile = djadapter.taskfiles.get(task=taskfileinfo.task, version=taskfileinfo.version, releasetype=taskfileinfo.releasetype, descriptor=taskfileinfo.descriptor, typ=taskfileinfo.typ) Refobj("Asset", None, None, refobj.taskfile, None) def is_replaceable(self, refobj): """Return whether the given reference of the refobject is replaceable or if it should just get deleted and loaded again. :param refobj: the refobject to query :type refobj: refobj :returns: True, if replaceable :rtype: bool :raises: NotImplementedError """ return True def fetch_option_taskfileinfos(self, element): """Fetch the options for possible files to load, replace etc for the given element. :param element: The element for which the options should be fetched. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: The options :rtype: list of :class:`TaskFileInfo` :raises: NotImplementedError """ tfs = djadapter.taskfiles.filter(task__content_type=ContentType.objects.get_for_model(element), task__object_id=element.pk, typ=djadapter.FILETYPES['mayamainscene'], releasetype=djadapter.RELEASETYPES['release']) l = [] for tf in tfs: tfi = TaskFileInfo(task=tf.task, version=tf.version, releasetype=tf.releasetype, descriptor=tf.descriptor, typ=tf.typ) l.append(tfi) return l def create_options_model(self, taskfileinfos): """Create a new treemodel that has the taskfileinfos as internal_data of the leaves. :returns: the option model with :class:`TaskFileInfo` as internal_data of the leaves. :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: NotImplementedError """ rootdata = ListItemData(["Asset/Shot", "Task", "Descriptor", "Version", "Releasetype"]) rootitem = TreeItem(rootdata) for tfi in taskfileinfos: tfidata = TaskFileInfoItemData(tfi) TreeItem(tfidata, parent=rootitem) return TreeModel(rootitem) def get_suggestions(self, reftrack): """Return a list with possible children for this reftrack :param reftrack: the reftrack which needs suggestions :type reftrack: :class:`Reftrack` :returns: list of suggestions, tuples of type and element. :rtype: list :raises: NotImplementedError """ element = reftrack.get_element() elements = list(element.assets.all()) elements.append(element) typ = reftrack.get_typ() return [(typ, e) for e in elements] def get_scene_suggestions(self, current): """Return a list with elements for reftracks for the current scene with this type. :param reftrack: the reftrack which needs suggestions :type reftrack: :class:`Reftrack` :returns: list of suggestions, tuples of type and element. :rtype: list :raises: None """ return [current] RefobjInterface.register_type('Asset', AssetReftypeInterface) @pytest.fixture(scope='function', autouse=True) def refobjclass(request): def fin(): Refobj.instances = [] request.addfinalizer(fin) @pytest.fixture(scope='function') def reftrackroot(): return ReftrackRoot() @pytest.fixture(scope='function') def refobjinter(djprj): current = djprj.shots[0] return DummyRefobjInterface(current) def test_wrap(djprj, reftrackroot, refobjinter): l = [] for tf in djprj.assettaskfiles[:6]: refobj = Refobj('Asset', None, None, tf, False) l.append(refobj) l[0].parent = l[1] l[2].parent = l[1] l[3].parent = l[2] l[1].parent = l[4] tracks = Reftrack.wrap(reftrackroot, refobjinter, l) assert tracks[0].get_parent() is tracks[1] assert tracks[1].get_parent() is tracks[4] assert tracks[2].get_parent() is tracks[1] assert tracks[3].get_parent() is tracks[2] assert tracks[4].get_parent() is None for t in tracks: assert t.get_typ() == 'Asset' assert t is reftrackroot.get_reftrack(t.get_refobj()) assert t.status() == Reftrack.IMPORTED # assert if suggestions have been created suggestions = t.get_suggestions() for c in t._children: for i, (typ, element) in enumerate(suggestions): if c.get_typ() == typ and c.get_element() == element: del suggestions[i] break assert suggestions == [],\ "Not all suggestions were created after wrapping. Suggestions missing %s" % suggestions def test_wrap_scene(djprj, reftrackroot, refobjinter): tf = djprj.assettaskfiles[0] Refobj('Asset', None, None, tf, False) Refobj('Asset', None, None, tf, False) Refobj('Asset', None, None, tf, False) tracks = Reftrack.wrap_scene(reftrackroot, refobjinter) assert len(tracks) == 4 for t in tracks: if t.get_refobj() is None: assert t.get_element() == djprj.shots[0] else: assert t.get_element() == tf.task.element def test_reftrackinit_raise_error(djprj, reftrackroot, refobjinter): with pytest.raises(TypeError): Reftrack(reftrackroot, refobjinter, typ='Asset') with pytest.raises(TypeError): Reftrack(reftrackroot, refobjinter, element=djprj.assets[0]) with pytest.raises(TypeError): refobj = Refobj('Asset', None, None, djprj.assettaskfiles[0], None) Reftrack(reftrackroot, refobjinter, refobj=refobj, typ='Asset', element=djprj.assets[0]) with pytest.raises(ValueError): Reftrack(reftrackroot, refobjinter, typ='Shader', element=djprj.assets[0]) def test_create_empty(djprj, reftrackroot, refobjinter): r1 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[0]) r2 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[1], parent=r1) assert r1 in reftrackroot._reftracks assert r2 in reftrackroot._reftracks assert r2.get_treeitem().parent() is r1.get_treeitem() assert r2.get_parent() is r1 assert r1.status() is None assert r2.status() is None assert not r1.alien() assert r2.alien() assert r1.get_typ() == 'Asset' assert r2.get_typ() == 'Asset' def test_alien(djprj, reftrackroot): current = djprj.assets[0] refobjinter = DummyRefobjInterface(current) r1 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[0]) r2 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[1]) r3 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[1], parent=r2) assert not r1.alien() assert r2.alien() assert not r3.alien() refobjinter = DummyRefobjInterface(None) r4 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[0]) r5 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[1]) r6 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[1], parent=r5) assert r4.alien() assert r5.alien() assert not r6.alien() @mock.patch.object(AssetReftypeInterface, "get_suggestions") def test_delete(mock_suggestions, djprj, reftrackroot): mock_suggestions.return_value = [] current = djprj.assets[0] refobjinter = DummyRefobjInterface(current) ref0 = Reference() ref1 = Reference() ref2 = Reference() ref4 = Reference() robj0 = Refobj('Asset', None, ref0, djprj.assettaskfiles[-1], None) robj1 = Refobj('Asset', robj0, ref1, djprj.assettaskfiles[0], ref0) robj2 = Refobj('Asset', robj1, ref2, djprj.assettaskfiles[0], ref1) robj3 = Refobj('Asset', robj2, None, djprj.assettaskfiles[0], None) robj4 = Refobj('Asset', robj0, ref4, djprj.assettaskfiles[0], None) robj5 = Refobj('Asset', robj4, None, djprj.assettaskfiles[0], ref0) robj6 = Refobj('Asset', robj4, None, djprj.assettaskfiles[0], None) tracks = Reftrack.wrap(reftrackroot, refobjinter, [robj0, robj1, robj2, robj3, robj4, robj5, robj6]) assert tracks[0].get_all_children() == [tracks[1], tracks[4], tracks[2], tracks[5], tracks[6], tracks[3]] assert tracks[6].get_all_children() == [] assert tracks[4].get_all_children() == [tracks[5], tracks[6]] assert tracks[2].get_children_to_delete() == [tracks[3]] assert tracks[0].get_children_to_delete() == [tracks[4], tracks[6], tracks[3]] assert tracks[4].get_children_to_delete() == [tracks[5], tracks[6]] tracks[2].delete() assert tracks[2]._children == [] assert tracks[2].get_refobj() is None assert tracks[2] in reftrackroot._reftracks assert tracks[3].get_refobj() is None assert tracks[3] not in reftrackroot._reftracks assert tracks[3].get_parent() is None assert robj3.deleted assert tracks[0].alien() tracks[0].delete() assert robj4.deleted assert robj0.deleted for i, t in enumerate(tracks): assert t not in reftrackroot._reftracks def test_duplicate(djprj, reftrackroot, refobjinter): ref = Reference() robj0 = Refobj('Asset', None, ref, djprj.assettaskfiles[0], None) robj1 = Refobj('Asset', robj0, None, djprj.assettaskfiles[0], None) tracks = Reftrack.wrap(reftrackroot, refobjinter, [robj0, robj1]) tracks.append(Reftrack(root=reftrackroot, refobjinter=refobjinter, typ='Asset', element=djprj.assettaskfiles[1], parent=tracks[1])) for t in tracks: d = t.duplicate() assert d.get_root() is t.get_root() assert d.get_refobjinter() is t.get_refobjinter() assert d.get_typ() is t.get_typ() assert d.get_element() is t.get_element() assert d.get_parent() is t.get_parent() assert d.status() is None assert d.get_treeitem().parent() is t.get_treeitem().parent() def test_throw_children_away(djprj, reftrackroot, refobjinter): robj0 = Refobj('Asset', None, None, djprj.assettaskfiles[0], None) robj1 = Refobj('Asset', robj0, None, djprj.assettaskfiles[0], None) robj2 = Refobj('Asset', robj1, None, djprj.assettaskfiles[0], None) robj3 = Refobj('Asset', None, None, djprj.assettaskfiles[0], None) tracks = Reftrack.wrap(reftrackroot, refobjinter, [robj0, robj1, robj2, robj3]) tracks[0].throw_children_away() assert tracks[0]._children == [] assert tracks[1].get_parent() is None assert tracks[1].get_treeitem().parent() is None assert tracks[1].get_treeitem()._model is None assert tracks[0].get_treeitem().child_count() == 0 assert tracks[1] not in reftrackroot._reftracks assert tracks[2] not in reftrackroot._reftracks assert tracks[3] in reftrackroot._reftracks assert refobjinter.exists(tracks[1].get_refobj()) assert refobjinter.exists(tracks[2].get_refobj()) def test_fetch_new_children(djprj, reftrackroot, refobjinter): robj0 = Refobj('Asset', None, None, djprj.assettaskfiles[0], None) t0 = Reftrack.wrap(reftrackroot, refobjinter, [robj0])[0] robj1 = Refobj('Asset', None, None, djprj.assettaskfiles[0], None) t1 = Reftrack.wrap(reftrackroot, refobjinter, [robj1])[0] t0.throw_children_away() assert t0 in reftrackroot._reftracks assert t1 in reftrackroot._reftracks assert t0.get_refobj() in reftrackroot._parentsearchdict assert t1.get_refobj() in reftrackroot._parentsearchdict robj2 = Refobj('Asset', robj0, None, djprj.assettaskfiles[0], None) robj3 = Refobj('Asset', robj2, None, djprj.assettaskfiles[0], None) t2, t3 = Reftrack.wrap(reftrackroot, refobjinter, [robj2, robj3]) t0.throw_children_away() for t in (t2, t3): assert t not in reftrackroot._reftracks assert t.get_refobj() not in reftrackroot._parentsearchdict assert refobjinter.exists(t.get_refobj()) assert t2.get_parent() is None assert t2.get_treeitem().parent() is None # try wrapping them again Reftrack.wrap(reftrackroot, refobjinter, [robj2, robj3]) def test_create_refobject(djprj, reftrackroot, refobjinter): robj0 = Refobj('Asset', None, None, djprj.assettaskfiles[0], None) t0 = Reftrack.wrap(reftrackroot, refobjinter, [robj0])[0] t1 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[0], parent=t0) robj1 = t1.create_refobject() assert robj1.parent is robj0 assert robj1.typ == 'Asset' @mock.patch.object(AssetReftypeInterface, "get_suggestions") def test_reference(mock_suggestions, djprj, reftrackroot, refobjinter): mock_suggestions.return_value = [] t0 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[0], parent=None) assert reftrackroot._reftracks == set([t0]) t0.reference(TaskFileInfo.create_from_taskfile(djprj.assettaskfiles[0])) assert t0 in reftrackroot._reftracks assert len(t0._children) == 1 t1 = t0._children[0] assert t1.get_parent() is t0 robj0 = t0.get_refobj() robj1 = t1.get_refobj() assert robj0.taskfile == djprj.assettaskfiles[0] assert robj1.parent is robj0 assert robj0.parent is None assert robj0.typ == 'Asset' assert robj0.get_status() == Reftrack.LOADED assert t0.status() == Reftrack.LOADED tfi = t0.get_taskfileinfo() reftfi = TaskFileInfo.create_from_taskfile(djprj.assettaskfiles[0]) assert tfi.version == reftfi.version assert tfi.task == reftfi.task assert tfi.releasetype == reftfi.releasetype assert tfi.descriptor == reftfi.descriptor t2 = Reftrack(reftrackroot, refobjinter, typ='Asset', element=djprj.assets[0], parent=t0) t2.reference(TaskFileInfo.create_from_taskfile(djprj.assettaskfiles[0])) t3 = t2._children[0] assert len(t2._children) == 1 assert t2.get_parent() is t0 robj2 = t2.get_refobj() robj3 = t3.get_refobj() assert robj2.taskfile == djprj.assettaskfiles[0] assert robj2.parent is robj0 assert robj3.parent is robj2 assert robj2.typ == 'Asset' assert robj2.get_status() == Reftrack.LOADED assert t2.status() == Reftrack.LOADED tfi = t2.get_taskfileinfo() reftfi =
<filename>src/digirock/_fluids/_oil.py """Classes for Oil like Fluids""" from typing import Dict, Tuple, Union import numpy as np import xarray as xr from .._exceptions import WorkflowError from ..utils.ecl import EclStandardConditions from ..utils._decorators import check_props, mutually_exclusive, broadcastable from ..utils import check_broadcastable from ..typing import NDArrayOrFloat, PropsDict from ..fluids import bw92 from ..fluids import ecl as fluid_ecl from ._fluid import Fluid class BaseOil(Fluid): """Base Oil Class for common methods. Attributes: name (str): name of the fluid api (float): API gravity of oil. std_density (float): Standard bulk density in g/cc at 15.6degC. """ @mutually_exclusive("api", "std_density") def __init__(self, name: str = None, api: float = None, std_density: float = None): """ `api` and `std_density` are mutually exclusive inputs. Args: name: Name of fluid api: Oil API std_density: Standard bulk density in g/cc at 15.6degC """ super().__init__(name=name, keys=["bo"]) if api is not None: self.set_api(api) elif std_density is not None: self.set_standard_density(std_density) else: self.api = None self.std_density = None def set_api(self, api: float): """Set the density of the oil using API gravity. Args: api: Api of oil. """ self.api = api self.std_density = 141.5 / (self.api + 131.5) def set_standard_density(self, std_density: float): """Set the density of the oil at standard pressure and temperature (15.6 degC). Args: std_density: The density of oil at standard conditions (g/cc) """ self.std_density = std_density self.api = 141.5 / self.std_density - 131.5 def get_summary(self) -> dict: summary = super().get_summary() summary.update( { "api": self.api, "std_density": self.std_density, } ) return summary class DeadOil(BaseOil): """Dead Oil fluid class for oils with no dissolved gasses. Attributes: name (str): name of the fluid api (float): API gravity of oil. std_density (float): Standard bulk density in g/cc at 15.6degC. bo (float, xarray.DataArray): The formation volume factor or table. """ @mutually_exclusive("api", "std_density") def __init__(self, name: str = None, api: float = None, std_density: float = None): """ `api` and `std_density` are mutually exclusive inputs. Args: name: Name of fluid api: Oil API std_density: Standard bulk density in g/cc at 15.6degC """ super().__init__(name=name, std_density=std_density, api=api) self.pvt = None def set_api(self, api: float): """Set the density of the oil using API gravity. Args: api: Api of oil. """ self.api = api self.std_density = 141.5 / (self.api + 131.5) def set_standard_density(self, std_density: float): """Set the density of the oil at standard pressure and temperature (15.6 degC). Args: std_density: The density of oil at standard conditions (g/cc) """ self.std_density = std_density self.api = 141.5 / self.std_density - 131.5 def set_pvt(self, bo: NDArrayOrFloat, pres: NDArrayOrFloat = None): """Set the PVT table for DeadOil. If pressure is not specified bo should be a constant. Args: bo: Bo constant or table matching pressure input. pres: Pressures that bo is defined at. Defaults to None. Raises: ValueError: When inputs are incorrect. """ if pres is None and isinstance(bo, (float, int)): self.pvt = {"type": "constant", "bo": bo} elif pres is None: raise ValueError(f"bo input is wrong type, got {type(bo)}") else: pres = np.array(pres).squeeze() bo = np.array(bo).squeeze() if bo.shape != pres.shape and bo.ndim > 1: raise ValueError("Expected 1d arrays of same length.") self.pvt = { "type": "table", "bo": "table", "pres": "table", "bo_table": xr.DataArray(bo, coords=[pres], dims=["pres"]), } def bo(self, pres: NDArrayOrFloat = None) -> NDArrayOrFloat: """Get the formation volume factor (bo) at pressure if specified. Args: pres: Pressure to sample bo (MPa), required when Bo is a table. Returns: Formation volume factor fvf (frac) """ if self.pvt["type"] == "table" and pres is None: raise ValueError( "Bo is a table and the pressure argument must be specified." ) if self.pvt["type"] == "constant": return self.pvt["bo"] else: return fluid_ecl.oil_fvf_table( self.pvt["bo_table"].pres.values, self.pvt["bo_table"].values, pres ) @check_props("temp", "pres") def density(self, props: PropsDict, **kwargs) -> NDArrayOrFloat: """Temperature and pressure dependent density for dead oil adjusted for FVF. Uses BW92 [`oil_density`][digirock.fluids.bw92.oil_density]. Args: props: A dictionary of properties; requires `temp` (degC) and `pressure` (MPa) kwargs: ignored Returns: Oil density (g/cc) """ return bw92.oil_density(self.std_density, props["pres"], props["temp"]) @check_props("temp", "pres", broadcastable=("temp", "pres", "bo")) def velocity( self, props: PropsDict, **kwargs, ) -> NDArrayOrFloat: """Temperature and pressure dependent acoustic velocity for dead oil adjusted for FVF. Uses BW92 [`oil_velocity`][digirock.fluids.bw92.oil_velocity], gas Rs is assumed to be 0. Args: props: A dictionary of properties; requires `temp` (degC) and `pressure` (MPa); optional bo (vfrac) else use class constant or table. kwargs: ignored Returns: Oil acoustic velocity (m/s) """ bo = props.get("bo") if bo is None: bo = self.bo(props["pres"]) return bw92.oil_velocity( self.std_density, props["pres"], props["temp"], 0, 0, bo ) def bulk_modulus( self, props: PropsDict, **kwargs, ) -> NDArrayOrFloat: """Temperature and pressure dependent bulk modulus for dead oil adjusted for FVF. Uses BW92 [`oil_bulkmod`][digirock.fluids.bw92.oil_bulkmod]. Args: props: A dictionary of properties; requires `temp` (degC) and `pressure` (MPa); optional bo (vfrac) else use class constant or table. kwargs: ignored Returns: Oil modulus (GPa) """ return bw92.oil_bulkmod(self.density(props), self.velocity(props)) def get_summary(self) -> dict: summary = super().get_summary() summary.update( { "pvt": self.pvt, } ) return summary class OilBW92(BaseOil): """Oil fluid class for oils with dissolved gas, i.e. Live Oil. Attributes: name (str): name of the fluid api (float): API gravity of oil. std_density (float): Standard bulk density in g/cc at 15.6degC. gas_sg (float): The dissolved gas standard gravity. pvt (dict, xarray.DataArray): PVT table for Oil """ @mutually_exclusive("api", "std_density") def __init__( self, name: str = None, api: float = None, std_density: float = None, gas_sg: float = None, ): """ `api` and `std_density` are mutually exclusive inputs. Args: name: Name of fluid api: Oil API std_density: Standard bulk density in g/cc at 15.6degC """ self.gas_sg = gas_sg self.pvt = None super().__init__(name=name, api=api, std_density=std_density) self.register_key("rs") self.rst = None def set_rst( self, rs: NDArrayOrFloat, pres: NDArrayOrFloat = None, ): """Set the RS table for Oil. The solution gas ratio `rs` i[] set for tables of `bo` and `pres`. Args: rs: The solution gas ratio for bo or bo table. Has shape (M, ) pres: Pressure values (MPa) to match rs if defined. Has shape (M, ). """ rs = np.atleast_1d(rs) pres = np.atleast_1d(pres) if pres is not None else None # constants for rs and bo if rs.size == 1: self.rst = {"type": "constant", "rs": rs[0], "pres": pres} elif len(rs.shape) > 1 and pres is None: raise ValueError("presure requires for list of `rs`") elif rs.shape != pres.shape: raise ValueError( f"`pres` {pres.shape} and `rs` {rs.shape} must have same shape" ) elif rs.shape == pres.shape: table = xr.DataArray(data=rs, coords={"pres": pres}) self.rst = { "type": "table", "rs": "table", "pres": "table", "rs_table": table, } else: raise NotImplementedError("Unknown combination of rs and bo") @broadcastable("temp", "pres") def _get_rsbo( self, temp: NDArrayOrFloat, pres: NDArrayOrFloat ) -> Tuple[NDArrayOrFloat, NDArrayOrFloat]: if self.rst is None: raise WorkflowError( "_get_rsbo", "RS/PRESSURE relationship needs to be set using `set_rst()`", ) if self.rst["type"] == "constant": rs = self.rst["rs"] elif self.rst["type"] == "table": rs = self.rst["rs_table"].interp(pres=pres).values else: raise NotImplementedError(f"PVT of type {self.rst['type']} is unknown") if self.std_density is not None: fvf = bw92.oil_fvf(self.std_density, self.gas_sg, rs, temp) else: raise WorkflowError( "std_density", "Set an oil standard density or api first." ) return rs, fvf @check_props("temp", "pres") def bo(self, props: PropsDict) -> NDArrayOrFloat: """Calculate the oil formation volume factor (bo) using BW92. Set the attribute `bo` using BW92 [oil_fvf][digirock.fluids.bw92.oil_fvf]. Args: props: A dictionary of properties; requires `temp` (degC) and `pressure` (MPa) Returns: Formation volume factor FVF (L/L) """ _, fvf = self._get_rsbo(props["temp"], props["pres"]) return fvf @check_props("pres") def rs(self, props: PropsDict) -> NDArrayOrFloat: """Calculate the solution gas (rs) from pressure/rs table. Args: props: A dictionary of properties; requires `pressure` (MPa) Returns: solution gas (L/L) """ # temperatue is dummy rs, _ = self._get_rsbo(100.0, props["pres"]) return rs def _process_bo_rs(self, props: PropsDict) -> Tuple[NDArrayOrFloat, NDArrayOrFloat]: # If RS or BO are not supplied, calculate from the table rs = props.get("rs") fvf = props.get("bo") if rs is None or fvf is None: rs_l, fvf_l = self._get_rsbo(props["temp"], props["pres"]) return fvf_l if fvf is None else fvf, rs_l if rs is None else rs else: return fvf, rs @check_props("temp", "pres", broadcastable=("temp", "pres", "rs", "bo")) def density(self, props: PropsDict, **kwargs) -> NDArrayOrFloat: """Temperature and pressure dependent density for Oil with adjustments for `rs` (solution gas) and `bo` (FVF). Density is calculated using BW92
# -------------------------------------------------------------------- # Copyright (c) stabilaclick. All rights reserved. # Licensed under the MIT License. # See License.txt in the project root for license information. # -------------------------------------------------------------------- from datetime import datetime from typing import ( Any, Tuple, List ) from eth_abi import encode_abi from stb_utils import ( is_string, is_integer, is_boolean, is_hex, encode_hex ) from stabilaapi.exceptions import ( InvalidStabilaError, StabilaError, InvalidAddress ) from stabilaapi.common.validation import is_valid_url DEFAULT_TIME = datetime.now() START_DATE = int(DEFAULT_TIME.timestamp() * 1000) class TransactionBuilder(object): def __init__(self, stabila): self.stabila = stabila def send_transaction(self, to, amount, account=None): """Creates a transaction of transfer. If the recipient address does not exist, a corresponding account will be created. Args: to (str): to address amount (float): amount account (str): from address Returns: Transaction contract data """ # If the address of the sender is not specified, we prescribe the default if account is None: account = self.stabila.default_address.hex if not self.stabila.isAddress(to): raise InvalidStabilaError('Invalid recipient address provided') if not isinstance(amount, float) or amount <= 0: raise InvalidStabilaError('Invalid amount provided') _to = self.stabila.address.to_hex(to) _from = self.stabila.address.to_hex(account) if _to == _from: raise StabilaError('Cannot transfer STB to the same account') response = self.stabila.manager.request('/wallet/createtransaction', { 'to_address': _to, 'owner_address': _from, 'amount': self.stabila.toUnit(amount) }) return response def send_token(self, to, amount, token_id, account=None): """Transfer Token Args: to (str): is the recipient address amount (int): is the amount of token to transfer. must be integer instead of float token_id (any): Token Name and id account: (str): is the address of the withdrawal account Returns: Token transfer Transaction raw data """ # If the address of the sender is not specified, we prescribe the default if account is None: account = self.stabila.default_address.hex if not self.stabila.isAddress(to): raise InvalidStabilaError('Invalid recipient address provided') if not isinstance(amount, int) or amount <= 0: raise InvalidStabilaError('Invalid amount provided') if not token_id: raise InvalidStabilaError('Invalid token ID provided') if not self.stabila.isAddress(account): raise InvalidStabilaError('Invalid origin address provided') _to = self.stabila.address.to_hex(to) _from = self.stabila.address.to_hex(account) _token_id = self.stabila.toHex(text=str(token_id)) if _to == _from: raise StabilaError('Cannot transfer STB to the same account') # In case if "STB" is specified, we redirect to another method. if is_string(token_id) and token_id.upper() == 'STB': return self.send_transaction(_to, amount, _from) return self.stabila.manager.request('/wallet/transferasset', { 'to_address': _to, 'owner_address': _from, 'asset_name': _token_id, 'amount': amount }) def cd_balance(self, amount, duration, resource, account=None): """ Cds an amount of STB. Will give bandwidth OR Ucr and stabila Power(voting rights) to the owner of the cded tokens. Args: amount (int): number of cded stb duration (int): duration in days to be cded resource (str): type of resource, must be either "UCR" or "BANDWIDTH" account (str): address that is freezing stb account """ # If the address of the sender is not specified, we prescribe the default if account is None: account = self.stabila.default_address.hex if resource not in ('BANDWIDTH', 'UCR',): raise InvalidStabilaError('Invalid resource provided: Expected "BANDWIDTH" or "UCR"') if not is_integer(amount) or amount <= 0: raise InvalidStabilaError('Invalid amount provided') if not is_integer(duration) or duration < 3: raise InvalidStabilaError('Invalid duration provided, minimum of 3 days') if not self.stabila.isAddress(account): raise InvalidStabilaError('Invalid address provided') response = self.stabila.manager.request('/wallet/cdbalance', { 'owner_address': self.stabila.address.to_hex(account), 'cded_balance': self.stabila.toUnit(amount), 'cded_duration': int(duration), 'resource': resource }) if 'Error' in response: raise StabilaError(response['Error']) return response def uncd_balance(self, resource='BANDWIDTH', account=None): """ Uncd STB that has passed the minimum cd duration. Unfreezing will remove bandwidth and stabila Power. Args: resource (str): type of resource, must be either "UCR" or "BANDWIDTH" account (str): address that is freezing stb account """ # If the address of the sender is not specified, we prescribe the default if account is None: account = self.stabila.default_address.hex if resource not in ('BANDWIDTH', 'UCR',): raise InvalidStabilaError('Invalid resource provided: Expected "BANDWIDTH" or "UCR"') if not self.stabila.isAddress(account): raise InvalidStabilaError('Invalid address provided') response = self.stabila.manager.request('/wallet/uncdbalance', { 'owner_address': self.stabila.address.to_hex(account), 'resource': resource }) if 'Error' in response: raise ValueError(response['Error']) return response def purchase_token(self, to: str, token_id: str, amount: int, buyer=None): """Purchase a Token Creates an unsigned ICO token purchase transaction. Args: to (str): is the address of the Token issuer token_id (str): is the name of the token amount (int): is the number of tokens created buyer (str): is the address of the Token owner """ if buyer is None: buyer = self.stabila.default_address.hex if not self.stabila.isAddress(to): raise InvalidAddress('Invalid to address provided') if not len(token_id): raise ValueError('Invalid token ID provided') if amount <= 0: raise ValueError('Invalid amount provided') _to = self.stabila.address.to_hex(to) _from = self.stabila.address.to_hex(buyer) return self.stabila.manager.request('/wallet/participateassetissue', { 'to_address': _to, 'owner_address': _from, 'asset_name': self.stabila.toHex(text=token_id), 'amount': int(amount) }) def withdraw_block_rewards(self, address: str = None): """Withdraw block rewards Creates an unsigned Super Representative award balance withdraw transaction. Args: address (str): Optional address to withdraw from. """ if not address: address = self.stabila.default_address.hex if not self.stabila.isAddress(address): raise InvalidAddress('Invalid address provided') return self.stabila.manager.request('/wallet/withdrawbalance', { 'owner_address': self.stabila.address.to_hex(address) }) def apply_for_sr(self, url, address=None): """Apply to become a super representative Args: url (str): official website address address (str): address """ # If the address of the sender is not specified, we prescribe the default if address is None: address = self.stabila.default_address.hex if not self.stabila.isAddress(address): raise StabilaError('Invalid address provided') if not is_valid_url(url): raise StabilaError('Invalid url provided') return self.stabila.manager.request('/wallet/createwitness', { 'owner_address': self.stabila.address.to_hex(address), 'url': self.stabila.toHex(text=url) }) def vote(self, votes: List[Tuple[str, int]], voter_address: str = None): """Vote Vote on the super representative Args: votes (dict): dictionary of SR address : vote count key-value pair voter_address: voter address Examples: >>> from stabilaapi import Stabila >>> data = [ >>> ('TRJpw2uqohP7FUmAEJgt57wakRn6aGQU6Z', 1) >>> ] >>> stabila = Stabila() >>> stabila.transaction.vote(data) """ if voter_address is None: voter_address = self.stabila.default_address.hex _view_vote = [] # We create a cycle to check all the received data for voting. for sr_address, vote_count in votes: if not self.stabila.isAddress(sr_address): raise InvalidAddress( 'Invalid SR address provided: ' + sr_address ) if not is_integer(vote_count) or vote_count <= 0: raise ValueError( 'Invalid vote count provided for SR: ' + sr_address ) _view_vote.append({ 'vote_address': self.stabila.address.to_hex(sr_address), 'vote_count': int(vote_count) }) return self.stabila.manager.request('/wallet/votewitnessaccount', { 'owner_address': self.stabila.address.to_hex(voter_address), 'votes': _view_vote }) def create_proposal(self, parameters: Any, issuer_address=None): """Creates a proposal to modify the network. Can only be created by a current Super Representative. Args: parameters (Any): proposal parameters issuer_address: owner address Examples: >>> from stabilaapi import Stabila >>> data = [ >>> {'key': 1, 'value': 2}, >>> {'key': 1, 'value': 2} >>> ] >>> stabila = Stabila() >>> stabila.transaction.create_proposal(data) """ if issuer_address is None: issuer_address = self.stabila.default_address.hex if not self.stabila.isAddress(issuer_address): raise InvalidAddress('Invalid issuerAddress provided') return self.stabila.manager.request('/wallet/proposalcreate', { 'owner_address': self.stabila.address.to_hex(issuer_address), 'parameters': parameters }) def vote_proposal(self, proposal_id, has_approval, voter_address=None): """Proposal approval Args: proposal_id (int): proposal id has_approval (bool): Approved voter_address (str): Approve address """ # If the address of the sender is not specified, we prescribe the default if voter_address is None: voter_address = self.stabila.default_address.hex if not self.stabila.isAddress(voter_address): raise StabilaError('Invalid voter_address address provided') if not is_integer(proposal_id) or proposal_id < 0: raise StabilaError('Invalid proposal_id provided') if not is_boolean(has_approval): raise StabilaError('Invalid has_approval provided') return self.stabila.manager.request('/wallet/proposalapprove', { 'owner_address': self.stabila.address.to_hex(voter_address), 'proposal_id': int(proposal_id), 'is_add_approval': bool(has_approval) }) def delete_proposal(self, proposal_id: int, issuer_address: str = None): """Delete proposal Args: proposal_id (int): proposal id issuer_address (str): delete the person's address Results: Delete the proposal's transaction """ # If the address of the sender is not specified, we prescribe the default if issuer_address is None: issuer_address = self.stabila.default_address.hex if not self.stabila.isAddress(issuer_address): raise InvalidStabilaError('Invalid issuer_address provided') if not isinstance(proposal_id, int) or proposal_id < 0: raise InvalidStabilaError('Invalid proposal_id provided') return self.stabila.manager.request('/wallet/proposaldelete', { 'owner_address': self.stabila.address.to_hex(issuer_address), 'proposal_id': int(proposal_id) }) def update_account(self, account_name, account: str = None): """Modify account name Note: Username is allowed to edit only once. Args: account_name (str): name of the account account (str): address Returns: modified Transaction Object """ # If the address of the sender is not specified, we prescribe the default if account is None: account = self.stabila.default_address.hex if not is_string(account_name): raise ValueError('Name must be a string') if not self.stabila.isAddress(account): raise StabilaError('Invalid origin address provided') response = self.stabila.manager.request('/wallet/updateaccount', { 'account_name': self.stabila.toHex(text=account_name), 'owner_address': self.stabila.address.to_hex(account) }) return response def create_smart_contract(self, **kwargs): """Deploy Contract Deploys a contract. Returns TransactionExtention, which contains an unsigned transaction. Example: .. code-block:: python >>> from stabilaapi import Stabila >>> >>> stabila = Stabila() >>> stabila.transaction_builder.create_smart_contract( >>> fee_limit=10**6,
# 校验命名的result_table_id惟一性 meta_res_tables = MetaAPi.get_result_tables({"result_table_ids": result_table_id_list}, raw=True) if meta_res_tables["result"]: meta_data_list = meta_res_tables["data"] if meta_data_list: err_result_table_id = "" for meta_dict in meta_data_list: err_result_table_id += meta_dict["result_table_id"] + "," raise Exception("参数校验失败:表[" + err_result_table_id + "]已存在!") else: raise Exception("查询meta api查询result_table_id惟一性接口调用出错!") random_name = str(uuid.uuid1())[:8] task_name = dd_data_set_id + "_" + str(standard_version_id) + "_" + random_name # 以下调用dataflow接口生成dataflow任务 nodes_configs_dict = { "bk_username": created_by, "project_id": project_id, "flow_name": task_name, "nodes": nodes, } complete_flow_body = json.dumps(nodes_configs_dict) flow_res_dict = DataFlowAPI.create_dataflow(params=nodes_configs_dict, raw=True) print("create_dataflow_result:", flow_res_dict) result = flow_res_dict["result"] message = flow_res_dict["message"] data = flow_res_dict["data"] if result: flow_id = data["flow_id"] else: raise Exception("调用dataflow创建接口报错:" + message) description = "" data_set_type = dd_data_set_type data_set_id = dd_data_set_id task_status = "ready" edit_status = "editting" standardization_type = 0 result_table_id = dd_result_table_id result_table_name = dd_result_table_name source_type = "standard" task_content_name = "task_content_name" task_type = "detaildata" sql = dd_sql node_config = dd_node_config # 给标准表打标签 tag_targets_list = [] standard_type = "user_standard" # 用户标准化 if project_id == STANDARD_PROJECT_ID: standard_type = "mark_standard" # 集市标准化 for rt_id in result_table_id_list: dstantaction.get_tag_target_obj(tag_targets_list, rt_id, standard_type, bk_biz_id, project_id) for tagged_code in tag_list: dstantaction.get_tag_target_obj(tag_targets_list, rt_id, tagged_code, bk_biz_id, project_id) # 明细数据 dstantaction.get_tag_target_obj(tag_targets_list, result_table_id_list[0], "details", bk_biz_id, project_id) for rt_id in result_table_id_list[1:]: # 汇总数据 dstantaction.get_tag_target_obj(tag_targets_list, rt_id, "summarized", bk_biz_id, project_id) tag_target_params = {"bk_username": created_by, "tag_targets": tag_targets_list} tagged_res_dict = DstanAPi.tagged(tag_target_params, raw=True) if tagged_res_dict: if not tagged_res_dict["result"]: raise Exception("打标签失败!") else: with auto_meta_sync(using="bkdata_basic"): dm_task_config = DmTaskConfig( task_name=task_name, project_id=project_id, standard_version_id=standard_version_id, description=description, data_set_type=data_set_type, data_set_id=data_set_id, standardization_type=standardization_type, task_status=task_status, edit_status=edit_status, created_by=created_by, flow_id=flow_id, ) dm_task_config.save() task_id = dm_task_config.id # task_content_config = DmTaskContentConfig(task_id=task_id, parent_id='[-1]', # standard_version_id=standard_version_id, # source_type=source_type, # result_table_id=result_table_id, # result_table_name=result_table_name, # task_content_name=task_content_name, # task_type=task_type, # task_content_sql=sql, node_config=node_config, # request_body=complete_request_body, # flow_body=complete_flow_body, # created_by=created_by) # task_content_config.save() # task_content_id = task_content_config.id task_content_config_list = [ DmTaskContentConfig( task_id=task_id, parent_id="[-1]", standard_version_id=standard_version_id, standard_content_id=task_config[0].get("standard_content_id", 0), source_type=source_type, result_table_id=result_table_id, result_table_name=result_table_name, task_content_name=task_content_name, task_type=task_type, task_content_sql=sql, node_config=node_config, request_body=complete_request_body, flow_body=complete_flow_body, created_by=created_by, ) ] i = 1 for indicator_table_id in result_table_id_list[1:]: task_content_config_list.append( DmTaskContentConfig( task_id=task_id, parent_id="[-1]", standard_version_id=standard_version_id, standard_content_id=task_config[i].get("standard_content_id", 0), source_type=source_type, result_table_id=task_config[i].get("result_table_id", ""), result_table_name=task_config[i].get("result_table_name", ""), task_content_name=task_content_name, task_type="indicator", task_content_sql=task_config[i].get("sql", ""), node_config=task_config[i].get("node_config", ""), request_body=complete_request_body, flow_body=complete_flow_body, created_by=created_by, ) ) i += 1 task_content_id_list = [] if task_content_config_list: for each in task_content_config_list: each.save() task_content_id_list.append(each.id) # 批量插入dm_task_detail表数据 # dm_task_detail_list = [DmTaskDetail(task_id=task_id, task_content_id=task_content_id, # standard_version_id=standard_version_id, # bk_biz_id=bk_biz_id, project_id=project_id, # data_set_type=data_set_type, # data_set_id=result_table_id_list[0], # task_type='detaildata', active=1, # created_by=created_by)] # 第一个是detaildata # for indicator_table_id in result_table_id_list[1:]: # 后面是indicator的 # dm_task_detail_list.append(DmTaskDetail(task_id=task_id, task_content_id=task_content_id, # standard_version_id=standard_version_id, # bk_biz_id=bk_biz_id, project_id=project_id, # data_set_type=data_set_type, # data_set_id=indicator_table_id, # task_type='indicator', active=1, # created_by=created_by)) dm_task_detail_list = [ DmTaskDetail( task_id=task_id, task_content_id=task_content_id_list[0], standard_version_id=standard_version_id, standard_content_id=task_config[0].get("standard_content_id", 0), bk_biz_id=bk_biz_id, project_id=project_id, data_set_type=data_set_type, data_set_id=result_table_id_list[0], task_type="detaildata", active=1, created_by=created_by, ) ] # 第一个是detaildata i = 1 for indicator_table_id in result_table_id_list[1:]: # 后面是indicator的 dm_task_detail_list.append( DmTaskDetail( task_id=task_id, task_content_id=task_content_id_list[i], standard_version_id=standard_version_id, standard_content_id=task_config[i].get("standard_content_id", 0), bk_biz_id=bk_biz_id, project_id=project_id, data_set_type=data_set_type, data_set_id=indicator_table_id, task_type="indicator", active=1, created_by=created_by, ) ) i += 1 if dm_task_detail_list: for tmp_obj in dm_task_detail_list: tmp_obj.save() return Response({"task_id": task_id, "flow_id": flow_id}) @list_route(methods=["post"], url_path="update") @params_valid(serializer=TaskUpdateSerializer) def task_update(self, request, params): """ @api {post} /datamanage/dstantools/tasks/create/ 更新任务 @apiVersion 0.1.0 @apiGroup DMTaskConfig @apiName update_task @apiParam {String} task_id 任务id @apiParam {String} task_name 任务名称 @apiParam {Integer} project_id 项目id @apiParam {Integer} standard_version_id 标准id @apiParam {String} data_set_type 输入数据集类型:[raw_data/result_table] @apiParam {String} data_set_id 输入数据集id:result_table_id/data_id的值 @apiParam {String} sql 标准化sql @apiParam {String} result_table_id 标准化结果表id @apiParam {String} result_table_name 标准化结果表中文名 @apiParam {String} task_type 任务类型[detaildata/indicator] @apiParam {String} created_by 创建人 @apiParam {String} node_config 节点配置信息,参考创建dataflow的配置信息 @apiParamExample {json} 参数样例: { "task_id":任务id, "task_name":"test_update", "project_id":1, "standard_version_id":1, "data_set_type":"result_table", "data_set_id":"1_rest_ful", "sql":"select * from test", "result_table_id":"test_result_id", "result_table_name":"测试表update2222", "task_type":"detaildata", "created_by":"admin", "node_config":"{}" } @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "result": true, "errors": null, "message": "ok", "code": "1500200", "data": 35 } """ task_id = params.get("task_id") task_name = params.get("task_name") project_id = params.get("project_id") standard_version_id = params.get("standard_version_id") description = params.get("description", "") data_set_type = params.get("data_set_type") data_set_id = params.get("data_set_id") standardization_type = params.get("standardization_type", 0) task_status = params.get("task_status", "ready") edit_status = params.get("edit_status", "editting") sql = params.get("sql") node_config = params.get("node_config") result_table_id = params.get("result_table_id") result_table_name = params.get("result_table_name") source_type = params.get("source_type", "standard") task_content_name = params.get("task_content_name", "task_content_name") task_type = params.get("task_type", "detaildata") created_by = params.get("created_by") # 校验sql合规性 sql_parse_result = DataFlowAPI.parse_sql(params={"sql": "SELECT a+b*c as task_id,name from test"}, raw=True) print(sql_parse_result) with transaction.atomic(): DmTaskConfig.objects.filter(id=task_id).update( task_name=task_name, project_id=project_id, standard_version_id=standard_version_id, description=description, data_set_type=data_set_type, data_set_id=data_set_id, standardization_type=standardization_type, task_status=task_status, edit_status=edit_status, created_by=created_by, ) DmTaskContentConfig.objects.filter(task_id=task_id).update( parent_id="[-1]", standard_version_id=standard_version_id, source_type=source_type, result_table_id=result_table_id, result_table_name=result_table_name, task_content_name=task_content_name, task_type=task_type, task_content_sql=sql, node_config=node_config, created_by=created_by, ) return Response("ok") @list_route(methods=["post"], url_path="start_dataflow") @params_valid(serializer=DataFlowOperationSerializer) def start_dataflow(self, request, params): """ @api {post} /datamanage/dstantools/tasks/start_dataflow/ 启动任务 @apiVersion 0.1.0 @apiGroup DMTaskConfig @apiName start_dataflow @apiParam {Integer} flow_id flow_id的值 @apiParam {String} bk_username 用户英文名 @apiParamExample {json} 参数样例: { "flow_id":10, "bk_username":"xiaoming" } @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "result": true, "errors": null, "message": "ok", "code": "1500200", "data": 35 } """ flow_id = params.get("flow_id") bk_username = params.get("bk_username") res_dict = DataFlowAPI.start_dataflow({"bk_username": bk_username, "flow_id": flow_id}, raw=True) result, message, data = dstantaction.parse_interface_result(res_dict) if result: return Response(data) else: raise Exception(message) @list_route(methods=["post"], url_path="stop_dataflow") @params_valid(serializer=DataFlowOperationSerializer) def stop_dataflow(self, request, params): """ @api {get} /datamanage/dstantools/tasks/stop_dataflow/ 停止任务 @apiVersion 0.1.0 @apiGroup DMTaskConfig @apiName stop_dataflow @apiParam {Integer} flow_id flow_id的值 @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "result": true, "errors": null, "message": "ok", "code": "1500200", "data": 35 } """ flow_id = params.get("flow_id") bk_username = params.get("bk_username") res_dict = DataFlowAPI.stop_dataflow({"bk_username": bk_username, "flow_id": flow_id}, raw=True) result, message, data = dstantaction.parse_interface_result(res_dict) if result: return Response(data) else: raise Exception(message) @list_route(methods=["get"], url_path="get_dataflow_status") def get_dataflow_status(self, request): """ @api {get} /datamanage/dstantools/tasks/get_dataflow_status/ 获取任务状态 @apiVersion 0.1.0 @apiGroup DMTaskConfig @apiName get_dataflow_status @apiParam {Integer} flow_id flow_id的值 @apiParam {String} bk_username 用户英文名 @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "result": true, "errors": null, "message": "ok", "code": "1500200", "data": 35 } """ flow_id = request.query_params.get("flow_id") bk_username = request.query_params.get("bk_username") res_dict = DataFlowAPI.get_dataflow_status({"flow_id": flow_id, "bk_username": bk_username}, raw=True) return Response(res_dict) @list_route(methods=["get"], url_path="refresh_task_status") def refresh_task_status(self, request): """ @api {get} /datamanage/dstantools/tasks/refresh_task_status/ 刷新任务状态 @apiVersion 0.1.0 @apiGroup DMTaskConfig @apiName refresh_task_status @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "result": true, "errors": null, "message": "ok", "code": "1500200", "data": 'ok' } """ task_list = ( DmTaskConfig.objects.filter(~Q(task_status="running"), ~Q(flow_id=None)) .values("flow_id", "created_by") .order_by("id") ) with auto_meta_sync(using="bkdata_basic"): if task_list: for task in task_list: flow_id = task.get("flow_id") created_by = task.get("created_by") print(flow_id, created_by) res_dict = DataFlowAPI.get_dataflow_status( {"flow_id": flow_id, "bk_username": created_by}, raw=True ) if res_dict: result = res_dict.get("result") if result: task_status = res_dict.get("data").get("status") if task_status: dtc_obj_list = DmTaskConfig.objects.filter(flow_id=flow_id) for dtc_obj in dtc_obj_list: dtc_obj.task_status = task_status dtc_obj.save() return Response("ok") @list_route(methods=["get"], url_path="get_not_running_task_status") def get_not_running_task_status(self, request): task_list = ( DmTaskConfig.objects.filter(~Q(task_status="running"), ~Q(flow_id=None)) .values("id", "flow_id", "created_by", "task_status", "edit_status") .order_by("id") ) return Response(task_list) @list_route(methods=["get"], url_path="get_task_status") def get_task_status(self, request): task_list = ( DmTaskConfig.objects.filter(~Q(flow_id=None)) .values("id", "flow_id", "created_by", "task_status", "edit_status") .order_by("id") ) return Response(task_list) @list_route(methods=["get"], url_path="get_running_task_standard_id_info") def get_running_task_standard_info(self, request): # 得到运行任务的指标标准信息 task_list = DmTaskConfig.objects.filter(Q(task_status="running"), ~Q(flow_id=None)).values_list( "standard_version_id", flat=True ) standard_list = ( DmStandardVersionConfig.objects.filter(id__in=task_list) .extra(select={"standard_version_id": "id"}) .values("standard_version_id", "standard_id") ) return Response(standard_list) @list_route(methods=["post"], url_path="update_tasks_status") @params_valid(serializer=TasksStatusSerializer) def update_tasks_status(self, request, params): tasks_status_list = params.get("tasks_status_list") print(tasks_status_list) with auto_meta_sync(using="bkdata_basic"): if tasks_status_list: for task_dict in tasks_status_list: task_id = task_dict["task_id"] task_status = task_dict["task_status"] dtc_obj_list = DmTaskConfig.objects.filter(id=task_id) for dtc_obj in dtc_obj_list: dtc_obj.task_status = task_status dtc_obj.save() return Response("ok") @list_route(methods=["get"], url_path="get_standard_detail") def get_standard_detail(self, request): # 根据标准版本id获取标准详情 standard_version_id = request.query_params.get("standard_version_id") standard_detail_dict = MetaAPi.get_standard_detail( {"dm_standard_version_config_id": standard_version_id}, raw=True ) field_info_dict = {} if standard_detail_dict["result"]: data = standard_detail_dict["data"] if data: standard_content = data["standard_content"] if standard_content: for content in standard_content: standard_info = content["standard_info"] standard_fields = content["standard_fields"] standard_content_type = standard_info["standard_content_type"] if standard_content_type == "detaildata": for field_dict in standard_fields: field_info_dict[field_dict["field_name"].lower()] = field_dict return Response(field_info_dict) @list_route(methods=["post"], url_path="get_data_query_result") @params_valid(serializer=SqlQuerySerializer) def get_data_query_result(self, request, params): # 封装统一查询接口 """ @api {post} /datamanage/dstantools/tasks/get_data_query_result/ 返回数据查询结果 @apiVersion 0.1.0 @apiGroup DMTaskConfig @apiName get_data_query_result @apiParam {String} sql 查询的sql[默认返回10条查询结果] @apiParamExample {json} 参数样例: { "standard_version_id":206, "sql": "SELECT ip FROM 591_durant1115 WHERE thedate>='20190311' ORDER BY dtEventTime DESC LIMIT 10" } @apiSuccessExample Success-Response: HTTP/1.1 200 OK { "result": true, "errors": null, "message": "ok", "code": "1500200", "data": { "list": [ { "dtEventTimeStamp": 1552277281000, "report_time": "2019-03-11 12:08:01", "log": "Mon Mar 11 12:08:01 CST 2019|60", "dtEventTime": "2019-03-11 12:08:01", "ip": "x.x.x.x", "gseindex": 1143863, "thedate": 20190311, "path": "/tmp/mayi/2.log", "localTime": "2019-03-11 12:08:00", "_valid_result_": { "gseindex": "不符合值约束[值范围]:[1 ~ 100]" } }, { "dtEventTimeStamp": 1552277281000, "report_time": "2019-03-11 12:08:01", "log": "Mon Mar 11 12:08:01 CST 2019|59", "dtEventTime": "2019-03-11 12:08:01", "ip": "x.x.x.x", "gseindex": 1143863, "thedate": 20190311, "path": "/tmp/mayi/2.log", "localTime": "2019-03-11 12:08:00", "_valid_result_": { "gseindex": "不符合值约束[值范围]:[1 ~ 100]" } }, { "dtEventTimeStamp": 1552277281000, "report_time": "2019-03-11 12:08:01", "log": "Mon Mar 11 12:08:01 CST 2019|58", "dtEventTime": "2019-03-11 12:08:01", "ip": "x.x.x.x", "gseindex": 1143863, "thedate": 20190311, "path": "/tmp/mayi/2.log", "localTime": "2019-03-11 12:08:00", "_valid_result_": { "gseindex": "不符合值约束[值范围]:[1 ~ 100]" } }, { "dtEventTimeStamp": 1552277281000, "report_time": "2019-03-11 12:08:01", "log": "Mon Mar 11 12:08:01 CST 2019|57", "dtEventTime": "2019-03-11 12:08:01", "ip": "x.x.x.x", "gseindex": 1143863, "thedate": 20190311, "path": "/tmp/mayi/2.log", "localTime": "2019-03-11 12:08:00", "_valid_result_": { "gseindex":
accepts_sparse = True supports_gpu = True goal = ["reg"] @property def est_class(self): """Return the estimator's class.""" return self.T._get_gpu(LinearRegression) class Ridge(BaseModel): """Linear least squares with l2 regularization.""" acronym = "Ridge" fullname = "Ridge Estimator" needs_scaling = True accepts_sparse = True supports_gpu = True goal = ["class", "reg"] @property def est_class(self): """Return the estimator's class.""" if self.T.goal == "class": return RidgeClassifier else: return self.T._get_gpu(RidgeRegressor) def get_dimensions(self): """Return a list of the bounds for the hyperparameters.""" if self._gpu: solvers = ["eig", "svd", "cd"] else: solvers = ["auto", "svd", "cholesky", "lsqr", "sparse_cg", "sag", "saga"] return [ Real(1e-3, 10, "log-uniform", name="alpha"), Categorical(solvers, name="solver"), ] class Lasso(BaseModel): """Linear Regression with lasso regularization.""" acronym = "Lasso" fullname = "Lasso Regression" needs_scaling = True accepts_sparse = True supports_gpu = True goal = ["reg"] @property def est_class(self): """Return the estimator's class.""" return self.T._get_gpu(LassoRegressor) @staticmethod def get_dimensions(): """Return a list of the bounds for the hyperparameters.""" return [ Real(1e-3, 10, "log-uniform", name="alpha"), Categorical(["cyclic", "random"], name="selection"), ] class ElasticNet(BaseModel): """Linear Regression with elasticnet regularization.""" acronym = "EN" fullname = "ElasticNet Regression" needs_scaling = True accepts_sparse = True supports_gpu = True goal = ["reg"] @property def est_class(self): """Return the estimator's class.""" return self.T._get_gpu(ElasticNetRegressor) @staticmethod def get_dimensions(): """Return a list of the bounds for the hyperparameters.""" return [ Real(1e-3, 10, "log-uniform", name="alpha"), Categorical(half_to_one_exc, name="l1_ratio"), Categorical(["cyclic", "random"], name="selection"), ] class LeastAngleRegression(BaseModel): """Least Angle Regression.""" acronym = "Lars" fullname = "Least Angle Regression" needs_scaling = True accepts_sparse = False supports_gpu = True goal = ["reg"] @property def est_class(self): """Return the estimator's class.""" return self.T._get_gpu(Lars, "cuml.experimental.linear_model") class BayesianRidge(BaseModel): """Bayesian ridge regression.""" acronym = "BR" fullname = "Bayesian Ridge" needs_scaling = True accepts_sparse = False supports_gpu = False goal = ["reg"] @property def est_class(self): """Return the estimator's class.""" return BayesianRidgeRegressor @staticmethod def get_dimensions(): """Return a list of the bounds for the hyperparameters.""" return [ Integer(100, 1000, name="n_iter"), Categorical([1e-6, 1e-4, 1e-2, 1e-1, 1], name="alpha_1"), Categorical([1e-6, 1e-4, 1e-2, 1e-1, 1], name="alpha_2"), Categorical([1e-6, 1e-4, 1e-2, 1e-1, 1], name="lambda_1"), Categorical([1e-6, 1e-4, 1e-2, 1e-1, 1], name="lambda_2"), ] class AutomaticRelevanceDetermination(BaseModel): """Automatic Relevance Determination.""" acronym = "ARD" fullname = "Automatic Relevant Determination" needs_scaling = True accepts_sparse = False supports_gpu = False goal = ["reg"] @property def est_class(self): """Return the estimator's class.""" return ARDRegression @staticmethod def get_dimensions(): """Return a list of the bounds for the hyperparameters.""" return [ Integer(100, 1000, name="n_iter"), Categorical([1e-6, 1e-4, 1e-2, 1e-1, 1], name="alpha_1"), Categorical([1e-6, 1e-4, 1e-2, 1e-1, 1], name="alpha_2"), Categorical([1e-6, 1e-4, 1e-2, 1e-1, 1], name="lambda_1"), Categorical([1e-6, 1e-4, 1e-2, 1e-1, 1], name="lambda_2"), ] class HuberRegression(BaseModel): """Huber regression.""" acronym = "Huber" fullname = "<NAME>" needs_scaling = True accepts_sparse = False supports_gpu = False goal = ["reg"] @property def est_class(self): """Return the estimator's class.""" return HuberRegressor @staticmethod def get_dimensions(): """Return a list of the bounds for the hyperparameters.""" return [ Real(1, 10, "log-uniform", name="epsilon"), Integer(50, 500, name="max_iter"), Categorical([1e-4, 1e-3, 1e-2, 1e-1, 1], name="alpha"), ] class Perceptron(BaseModel): """Linear Perceptron classification.""" acronym = "Perc" fullname = "Perceptron" needs_scaling = True accepts_sparse = False supports_gpu = False goal = ["class"] @property def est_class(self): """Return the estimator's class.""" return Perc def get_parameters(self, x): """Return a dictionary of the model's hyperparameters.""" params = super().get_parameters(x) if self._get_param(params, "penalty") != "elasticnet": params.pop("l1_ratio", None) return params @staticmethod def get_dimensions(): """Return a list of the bounds for the hyperparameters.""" return [ Categorical([None, "l2", "l1", "elasticnet"], name="penalty"), Categorical([1e-4, 1e-3, 1e-2, 0.1, 1, 10], name="alpha"), Categorical([0.05, 0.15, 0.30, 0.45, 0.60, 0.75, 0.90], name="l1_ratio"), Integer(500, 1500, name="max_iter"), Real(1e-2, 10, "log-uniform", name="eta0"), ] class LogisticRegression(BaseModel): """Logistic Regression.""" acronym = "LR" fullname = "Logistic Regression" needs_scaling = True accepts_sparse = True supports_gpu = True goal = ["class"] @property def est_class(self): """Return the estimator's class.""" return self.T._get_gpu(LR) def get_parameters(self, x): """Return a dictionary of the model's hyperparameters.""" params = super().get_parameters(x) # Limitations on penalty + solver combinations penalty = self._get_param(params, "penalty") solver = self._get_param(params, "solver") cond_1 = penalty == "none" and solver == "liblinear" cond_2 = penalty == "l1" and solver not in ("liblinear", "saga") cond_3 = penalty == "elasticnet" and solver != "saga" if cond_1 or cond_2 or cond_3: params.replace_value("penalty", "l2") # Change to default value if self._get_param(params, "penalty") != "elasticnet": params.pop("l1_ratio", None) elif self._get_param(params, "l1_ratio") is None: # l1_ratio can't be None with elasticnet (select value randomly) params.replace_value("l1_ratio", random.choice(zero_to_one_exc)) if self._get_param(params, "penalty") == "none": params.pop("C", None) return params def get_dimensions(self): """Return a list of the bounds for the hyperparameters.""" solvers = ["lbfgs", "newton-cg", "liblinear", "sag", "saga"] dimensions = [ Categorical(["l1", "l2", "elasticnet", "none"], name="penalty"), Real(1e-3, 100, "log-uniform", name="C"), Categorical(solvers, name="solver"), Integer(100, 1000, name="max_iter"), Categorical([None, *zero_to_one_exc], name="l1_ratio"), ] if self._gpu: del dimensions[2] return dimensions class LinearDiscriminantAnalysis(BaseModel): """Linear Discriminant Analysis.""" acronym = "LDA" fullname = "Linear Discriminant Analysis" needs_scaling = False accepts_sparse = False supports_gpu = False goal = ["class"] @property def est_class(self): """Return the estimator's class.""" return LDA def get_parameters(self, x): """Return a dictionary of the model's hyperparameters.""" params = super().get_parameters(x) if self._get_param(params, "solver") == "svd": params.pop("shrinkage", None) return params @staticmethod def get_dimensions(): """Return a list of the bounds for the hyperparameters.""" return [ Categorical(["svd", "lsqr", "eigen"], name="solver"), Categorical([None, "auto", *half_to_one_inc], name="shrinkage"), ] class QuadraticDiscriminantAnalysis(BaseModel): """Quadratic Discriminant Analysis.""" acronym = "QDA" fullname = "Quadratic Discriminant Analysis" needs_scaling = False accepts_sparse = False supports_gpu = False goal = ["class"] @property def est_class(self): """Return the estimator's class.""" return QDA @staticmethod def get_dimensions(): """Return a list of the bounds for the hyperparameters.""" return [Categorical(zero_to_one_inc, name="reg_param")] class KNearestNeighbors(BaseModel): """K-Nearest Neighbors.""" acronym = "KNN" fullname = "K-Nearest Neighbors" needs_scaling = True accepts_sparse = True supports_gpu = True goal = ["class", "reg"] @property def est_class(self): """Return the estimator's class.""" if self.T.goal == "class": return self.T._get_gpu(KNeighborsClassifier, "cuml.neighbors") else: return self.T._get_gpu(KNeighborsRegressor, "cuml.neighbors") def get_dimensions(self): """Return a list of the bounds for the hyperparameters.""" dimensions = [Integer(1, 100, name="n_neighbors")] if not self._gpu: dimensions.extend( [ Categorical(["uniform", "distance"], name="weights"), Categorical( categories=["auto", "ball_tree", "kd_tree", "brute"], name="algorithm", ), Integer(20, 40, name="leaf_size"), Integer(1, 2, name="p"), ] ) return dimensions class RadiusNearestNeighbors(BaseModel): """Radius Nearest Neighbors.""" acronym = "RNN" fullname = "<NAME>" needs_scaling = True accepts_sparse = True supports_gpu = False goal = ["class", "reg"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._distances = None @property def distances(self): """Return distances between a random subsample of rows.""" if self._distances is None: # If called only for estimator, there's no data to calculate # distances so return the estimator's default radius value: 1 if hasattr(self.T, "_branches"): numerical_cols = self.X_train.select_dtypes("number") self._distances = cdist( numerical_cols.sample( n=min(50, len(self.X_train)), random_state=self.T.random_state, ), numerical_cols.sample( n=min(50, len(self.X_train)), random_state=self.T.random_state, ), ).flatten() else: self._distances = 1 return self._distances @property def est_class(self): """Return the estimator's class.""" if self.T.goal == "class": return RadiusNeighborsClassifier else: return RadiusNeighborsRegressor def _get_default_params(self): """Custom method to return a valid radius.""" x0 = super()._get_default_params() # Replace sklearn's default value for the mean of the distances x0.replace_value("radius", np.mean(self.distances)) return x0 def get_estimator(self, **params): """Return the model's estimator with unpacked parameters.""" if self.T.goal == "class": return self.est_class( outlier_label=params.pop("outlier_label", "most_frequent"), radius=params.pop("radius", np.mean(self.distances)), n_jobs=params.pop("n_jobs", self.T.n_jobs), **params, ) else: return self.est_class( radius=params.pop("radius", np.mean(self.distances)), n_jobs=params.pop("n_jobs", self.T.n_jobs), **params, ) def get_dimensions(self): """Return a list of the bounds for the hyperparameters.""" return [ Real(min(self.distances), max(self.distances), name="radius"), Categorical(["uniform", "distance"], name="weights"), Categorical(["auto", "ball_tree", "kd_tree", "brute"], name="algorithm"), Integer(20, 40, name="leaf_size"), Integer(1, 2, name="p"), ] class DecisionTree(BaseModel): """Single Decision Tree.""" acronym = "Tree" fullname = "Decision Tree" needs_scaling = False accepts_sparse = True supports_gpu = False goal = ["class", "reg"] @property def est_class(self): """Return the estimator's class.""" if self.T.goal == "class": return DecisionTreeClassifier else: return DecisionTreeRegressor def get_dimensions(self): """Return a list of the bounds for the hyperparameters.""" if self.T.goal == "class": criterion = ["gini", "entropy"] else: criterion = ["squared_error", "absolute_error", "friedman_mse", "poisson"] return [ Categorical(criterion, name="criterion"), Categorical(["best", "random"], name="splitter"), Categorical([None, *range(1, 17)], name="max_depth"), Integer(2, 20, name="min_samples_split"), Integer(1, 20, name="min_samples_leaf"), Categorical( categories=["auto", "sqrt", "log2", *half_to_one_exc, None], name="max_features", ), Real(0, 0.035, name="ccp_alpha"), ] class Bagging(BaseModel): """Bagging model (with decision tree as base estimator).""" acronym = "Bag" fullname = "Bagging" needs_scaling = False accepts_sparse = True supports_gpu = False goal = ["class", "reg"] @property def est_class(self): """Return the estimator's class.""" if self.T.goal == "class": return BaggingClassifier else: return BaggingRegressor @staticmethod def get_dimensions(): """Return a
# System libs import os import time # import math import random import argparse from distutils.version import LooseVersion # Numerical libs import torch import torch.nn as nn # Our libs from mit_semseg.config import cfg from eval import evaluate from mit_semseg.dataset import ValDataset from mit_semseg.dataset import TrainDataset from mit_semseg.models import ModelBuilder, SegmentationModule from mit_semseg.utils import AverageMeter, parse_devices, setup_logger, accuracy from mit_semseg.lib.utils import as_numpy from mit_semseg.lib.nn import async_copy_to from mit_semseg.lib.nn import UserScatteredDataParallel, user_scattered_collate, patch_replication_callback import matplotlib.pyplot as plt from datetime import datetime from torchvision import transforms import numpy as np def denormalize(x): mean = torch.Tensor([0.485, 0.456, 0.406]).view(3, 1, 1).type_as(x) std = torch.Tensor([0.229, 0.224, 0.225]).view(3, 1, 1).type_as(x) return x * std + mean # train one epoch def train(segmentation_module, iterator, optimizers, history, epoch, cfg, gpus, nets): batch_time = AverageMeter() data_time = AverageMeter() ave_total_loss = AverageMeter() ave_acc = AverageMeter() ave_acc_binary = AverageMeter() segmentation_module.train(not cfg.TRAIN.fix_bn) # main loop tic = time.time() for i in range(cfg.TRAIN.epoch_iters): # load a batch of data batch_data = next(iterator[0]) data_time.update(time.time() - tic) segmentation_module.zero_grad() # adjust learning rate cur_iter = i + (epoch - 1) * cfg.TRAIN.epoch_iters adjust_learning_rate(optimizers, cur_iter, cfg) # img_ori = batch_data[0]['img_ori'] # print('img_ori.shape :', img_ori.shape) # segSize = (batch_data[0]['img_ori'].shape[1], # batch_data[0]['img_ori'].shape[2]) # print('segSize :', segSize) # del batch_data[0]['img_ori'] # # forward pass # # print('batch_data type :', type(batch_data[0])) # # print('batch_data[0]img_data shape :', batch_data[0]['img_data'][0].shape) # # print('batch_data[0]img_ori shape:', batch_data[0]['img_ori'][0].shape) # batch_tensor = denormalize(batch_data[0]['img_data'][0]) # # print('batch_tensor shape :', batch_tensor.shape) # image = transforms.ToPILImage()(batch_tensor) #.convert("RGB") # # image = batch_tensor.cpu().detach().numpy().transpose(1, 2, 0) # np_image = np.asarray(image) # batch_seg_tensor = (batch_data[0]['seg_label'][0]) # # label = transforms.ToPILImage()(batch_seg_tensor) # # np_label = np.asarray(label) # np_label = batch_seg_tensor.cpu().detach().numpy() # # image = batch_data[0]['img_data'][0].cpu().detach().numpy().transpose(1, 2, 0) # print('image min max :', np_image.min(), np_image.max()) # print('np_image.shape :', np_image.shape) # print('np_label.shape :', np_label.shape) # # print('image shape :', image.size) # print() # plt.subplot(131) # # plt.imshow(img_ori[0]) # # plt.axis('off') # plt.subplot(132) # plt.imshow(np_image) # # plt.axis('off') # # plt.savefig('./batch_tensor/%s.png' % int(datetime.now().timestamp())) # plt.subplot(133) # plt.imshow(np_label) # # plt.axis('off') # plt.savefig('./batch_tensor/%s.png' % int(datetime.now().timestamp())) loss, acc, acc_binary = segmentation_module(batch_data, object_index=cfg.MODEL.object_index) # pred = segmentation_module(batch_data, segSize=segSize) # print('pred.shape :', pred.shape) loss = loss.mean() acc = acc.mean() acc_binary = acc_binary.mean() # Backward # optimizer.zero_grad() loss.backward() for optimizer in optimizers: optimizer.step() # validation part # if i % cfg.TRAIN.disp_iter == 0: val_data = next(iterator[1]) val_data = val_data[0] seg_label = as_numpy(val_data['seg_label'][0]) img_resized_list = val_data['img_data'] torch.cuda.synchronize() with torch.no_grad(): segSize = (seg_label.shape[0], seg_label.shape[1]) # print('segSize :', segSize) # Use for binary loss # scores = torch.zeros(1, 2, segSize[0], segSize[1]) # scores = torch.zeros(1, cfg.DATASET.num_class, segSize[0], segSize[1]) scores = async_copy_to(scores, gpus[0]) for img in img_resized_list: feed_dict = val_data.copy() feed_dict['img_data'] = img del feed_dict['img_ori'] del feed_dict['info'] # print('type(feed_dict) :', type(feed_dict)) feed_dict = async_copy_to(feed_dict, gpus[0]) # forward pass scores_tmp = segmentation_module([feed_dict], object_index=cfg.MODEL.object_index, segSize=segSize) # print('scores_tmp.shape :', scores_tmp.shape) scores = scores + scores_tmp / len(cfg.DATASET.imgSizes) # _, pred = torch.max(scores, dim=1) # pred = as_numpy(pred.squeeze(0).cpu()) # Uae for binary loss # pred = scores[:, [0], :, :].squeeze(1) pred = as_numpy(pred.squeeze(0).cpu()) binary_seg_label = np.where(seg_label == cfg.MODEL.object_index, 0, 1) # binary_seg_label_tensor = torch.from_numpy(binary_seg_label[np.newaxis,: ,:]).cuda().type(torch.int64) # print('scores.shape, binary_seg_label_tensor.shape :', scores.shape, binary_seg_label_tensor.shape) # val_loss = segmentation_module.crit(scores, torch.from_numpy(binary_seg_label[np.newaxis,: ,:]).cuda().type(torch.int64)) # print('shape comparing :', scores.shape, val_data['seg_label'].shape) # print('scores.shape, seg_label.shape :', scores.shape, seg_label.shape) val_loss = segmentation_module.crit(scores, val_data['seg_label'].cuda()) # acc, pix = accuracy(pred, seg_label) # print('pred.shape, binary_seg_label.shape :', pred.shape, binary_seg_label.shape) # print('pred.shape, as_numpy(seg_label_gpu)[0].shape :', pred.shape, as_numpy(seg_label_gpu)[0].shape) # val_acc, val_pix = accuracy(pred, binary_seg_label) val_acc, val_pix = accuracy(pred, seg_label) # print('-------------------- Epoch {} Val_Accuracy: {:4.2f}, Val_Loss: {:.6f} --------------------'.format(epoch, val_acc * 100, val_loss)) # measure elapsed time batch_time.update(time.time() - tic) tic = time.time() # update average loss and acc ave_total_loss.update(loss.data.item()) ave_acc.update(acc.data.item()*100) ave_acc_binary.update(acc_binary.data.item()*100) # calculate accuracy, and display if i % cfg.TRAIN.disp_iter == 0: print('Epoch: [{}][{}/{}], Time: {:.2f}, Data: {:.2f}, ' 'lr_encoder: {:.6f}, lr_decoder: {:.6f}, ' 'Accuracy: {:4.2f}, Accuracy_Binary: {:4.2f}, Loss: {:.6f}, ' 'Val_Accuracy: {:4.2f}, Val_Loss: {:.6f}' .format(epoch, i, cfg.TRAIN.epoch_iters, batch_time.average(), data_time.average(), cfg.TRAIN.running_lr_encoder, cfg.TRAIN.running_lr_decoder, ave_acc.average(), ave_acc_binary.average(), ave_total_loss.average(), val_acc * 100, val_loss.data.item())) fractional_epoch = epoch - 1 + 1. * i / cfg.TRAIN.epoch_iters history['train']['epoch'].append(fractional_epoch) history['train']['loss'].append(loss.data.item()) history['train']['acc'].append(acc.data.item()) # Checkpoint Best Model Ever # # Monitor Loss # # if abs(val_loss.data.item()) < cfg.VAL.min_loss: # cfg.VAL.min_loss = abs(val_loss.data.item()) # print('minimum val_loss :', abs(val_loss.data.item()), end=' ') # # print('minimum val_loss :', val_loss.data.item(), end=' ') # checkpoint(nets, history, cfg, epoch+1) # Monitor Acc # if val_acc > cfg.VAL.max_acc: cfg.VAL.max_acc = float(val_acc) print('maximum val_acc :', val_acc, end=' ') checkpoint(nets, history, cfg, epoch+1) # # validation part # # val_data = next(iterator[1]) # val_data = val_data[0] # seg_label = as_numpy(val_data['seg_label'][0]) # img_resized_list = val_data['img_data'] # torch.cuda.synchronize() # with torch.no_grad(): # segSize = (seg_label.shape[0], seg_label.shape[1]) # # print('segSize :', segSize) # # scores = torch.zeros(1, cfg.DATASET.num_class, segSize[0], segSize[1]) # scores = torch.zeros(1, 2, segSize[0], segSize[1]) # scores = async_copy_to(scores, gpus[0]) # for img in img_resized_list: # feed_dict = val_data.copy() # feed_dict['img_data'] = img # del feed_dict['img_ori'] # del feed_dict['info'] # # print('type(feed_dict) :', type(feed_dict)) # feed_dict = async_copy_to(feed_dict, gpus[0]) # # forward pass # scores_tmp = segmentation_module([feed_dict], object_index=cfg.MODEL.object_index, segSize=segSize) # scores = scores + scores_tmp / len(cfg.DATASET.imgSizes) # _, pred = torch.max(scores, dim=1) # pred = as_numpy(pred.squeeze(0).cpu()) # # pred = scores[:, [0], :, :].squeeze(1) # # pred = as_numpy(pred.squeeze(0).cpu()) # binary_seg_label = np.where(seg_label == cfg.MODEL.object_index, 0, 1) # binary_seg_label_tensor = torch.from_numpy(binary_seg_label[np.newaxis,: ,:]).cuda().type(torch.int64) # # print('scores.shape, binary_seg_label_tensor.shape :', scores.shape, binary_seg_label_tensor.shape) # val_loss = segmentation_module.crit(scores, binary_seg_label_tensor) # # acc, pix = accuracy(pred, seg_label) # val_acc, val_pix = accuracy(pred, binary_seg_label) # print('-------------------- Epoch {} Val_Accuracy: {:4.2f}, Val_Loss: {:.6f} --------------------'.format(epoch, val_acc * 100, val_loss)) def checkpoint(nets, history, cfg, epoch): print('Saving checkpoints...') (net_encoder, net_decoder, unet, crit) = nets dict_encoder = net_encoder.state_dict() dict_decoder = net_decoder.state_dict() dict_unet = unet.state_dict() torch.save( history, '{}/history_epoch_{}.pth'.format(cfg.DIR, cfg.MODEL.object_index)) torch.save( dict_encoder, '{}/encoder_epoch_{}.pth'.format(cfg.DIR, cfg.MODEL.object_index)) torch.save( dict_decoder, '{}/decoder_epoch_{}.pth'.format(cfg.DIR, cfg.MODEL.object_index)) torch.save( dict_unet, '{}/unet_epoch_{}.pth'.format(cfg.DIR, cfg.MODEL.object_index)) # torch.save( # history, # '{}/history_epoch_{}.pth'.format(cfg.DIR, epoch)) # torch.save( # dict_encoder, # '{}/encoder_epoch_{}.pth'.format(cfg.DIR, epoch)) # torch.save( # dict_decoder, # '{}/decoder_epoch_{}.pth'.format(cfg.DIR, epoch)) def group_weight(module): group_decay = [] group_no_decay = [] for m in module.modules(): if isinstance(m, nn.Linear): group_decay.append(m.weight) if m.bias is not None: group_no_decay.append(m.bias) elif isinstance(m, nn.modules.conv._ConvNd): group_decay.append(m.weight) if m.bias is not None: group_no_decay.append(m.bias) elif isinstance(m, nn.modules.batchnorm._BatchNorm): if m.weight is not None: group_no_decay.append(m.weight) if m.bias is not None: group_no_decay.append(m.bias) assert len(list(module.parameters())) == len(group_decay) + len(group_no_decay) groups = [dict(params=group_decay), dict(params=group_no_decay, weight_decay=.0)] return groups def create_optimizers(nets, cfg): # (net_encoder, net_decoder, crit) = nets (net_encoder, net_decoder, unet, crit) = nets optimizer_encoder = torch.optim.SGD( group_weight(net_encoder), lr=cfg.TRAIN.lr_encoder, momentum=cfg.TRAIN.beta1, weight_decay=cfg.TRAIN.weight_decay) optimizer_decoder = torch.optim.SGD( group_weight(net_decoder), lr=cfg.TRAIN.lr_decoder, momentum=cfg.TRAIN.beta1, weight_decay=cfg.TRAIN.weight_decay) optimizer_unet = torch.optim.SGD( group_weight(unet), lr=cfg.TRAIN.lr_unet, momentum=cfg.TRAIN.beta1, weight_decay=cfg.TRAIN.weight_decay) return (optimizer_encoder, optimizer_decoder, optimizer_unet) def adjust_learning_rate(optimizers, cur_iter, cfg): scale_running_lr = ((1. - float(cur_iter) / cfg.TRAIN.max_iters) ** cfg.TRAIN.lr_pow) cfg.TRAIN.running_lr_encoder = cfg.TRAIN.lr_encoder * scale_running_lr cfg.TRAIN.running_lr_decoder = cfg.TRAIN.lr_decoder * scale_running_lr cfg.TRAIN.running_lr_unet = cfg.TRAIN.lr_unet * scale_running_lr (optimizer_encoder, optimizer_decoder, optimizer_unet) = optimizers for param_group in optimizer_encoder.param_groups: param_group['lr'] = cfg.TRAIN.running_lr_encoder for param_group in optimizer_decoder.param_groups: param_group['lr'] = cfg.TRAIN.running_lr_decoder for param_group in optimizer_unet.param_groups: param_group['lr'] = cfg.TRAIN.running_lr_unet def main(cfg, gpus): # Network Builders net_encoder = ModelBuilder.build_encoder( arch=cfg.MODEL.arch_encoder.lower(), fc_dim=cfg.MODEL.fc_dim, weights=cfg.MODEL.weights_encoder) net_decoder = ModelBuilder.build_decoder( arch=cfg.MODEL.arch_decoder.lower(), fc_dim=cfg.MODEL.fc_dim, num_class=cfg.DATASET.num_class, weights=cfg.MODEL.weights_decoder) unet = ModelBuilder.build_unet(n_channels=5, n_classes=2, bilinear=True, weights=cfg.MODEL.weights_unet) crit = nn.NLLLoss(ignore_index=-1) if cfg.MODEL.arch_decoder.endswith('deepsup'): segmentation_module = SegmentationModule( net_encoder, net_decoder, unet, crit, cfg.TRAIN.deep_sup_scale) else: segmentation_module = SegmentationModule( net_encoder, net_decoder, unet, crit) # Dataset and Loader dataset_train = TrainDataset( cfg.DATASET.root_dataset, cfg.DATASET.list_train, cfg.DATASET, batch_per_gpu=cfg.TRAIN.batch_size_per_gpu) loader_train = torch.utils.data.DataLoader( dataset_train, batch_size=len(gpus), # we have modified data_parallel shuffle=False, # we do not use this param collate_fn=user_scattered_collate, num_workers=cfg.TRAIN.workers, drop_last=True, pin_memory=True) dataset_val = ValDataset( cfg.DATASET.root_dataset, cfg.DATASET.list_val, cfg.DATASET) loader_val = torch.utils.data.DataLoader( dataset_val, batch_size=cfg.VAL.batch_size, shuffle=False, collate_fn=user_scattered_collate, num_workers=5, drop_last=True) print('1 Epoch = {} iters'.format(cfg.TRAIN.epoch_iters)) # create loader iterator iterator_train = iter(loader_train) iterator_val = iter(loader_val) # load nets into gpu if len(gpus) > 1: segmentation_module = UserScatteredDataParallel( segmentation_module, device_ids=gpus) # For sync bn patch_replication_callback(segmentation_module) segmentation_module.cuda() # Set up optimizers # nets = (net_encoder, net_decoder, crit) nets = (net_encoder, net_decoder, unet, crit) optimizers = create_optimizers(nets, cfg) # Main loop history = {'train': {'epoch': [], 'loss': [], 'acc': []}} # min_loss = np.Inf for epoch in range(cfg.TRAIN.start_epoch, cfg.TRAIN.num_epoch): print('cfg.VAL.min_loss :', cfg.VAL.min_loss) train(segmentation_module, (iterator_train, iterator_val), optimizers, history, epoch+1, cfg, gpus, nets) # checkpointing # checkpoint(nets, history, cfg, epoch+1) print('Training Done!') if __name__ == '__main__': assert LooseVersion(torch.__version__) >= LooseVersion('0.4.0'), \ 'PyTorch>=0.4.0 is required' parser = argparse.ArgumentParser( description="PyTorch Semantic Segmentation Training"
} """ def combine_two_layers_of_processors(sh_in, sh_out, registry): """ Elaborate a new set of processors based on the combination of two existing sets of processors A table specifying which processor sets are combined is passed as input (sh_in) A set of processors is created :param sh_in: :param sh_out: Just to show errors and warnings. No content is modified :param registry: :return: """ m = binary_mask_from_worksheet(sh_in, True) # True for cells containing numbers # Locate the matrix with numbers. Assume this defines the labels to consider, they will be around the matrix t = obtain_rectangular_submatrices(m) t = t[0] # Take just the first element # print(t[0]) v = worksheet_to_numpy_array(sh_in) for t in [(t[0], t[1], t[2], t[3]), (t[0] + 1, t[1], t[2], t[3]), (t[0], t[1], t[2] + 1, t[3])]: f = v[t[0]:t[1], t[2]:t[3]].astype(np.float64) row_sum = np.sum(f, axis=1) # A column vector. If "all ones", the container will be along rows col_sum = np.sum(f, axis=0) # A row vector. If "all ones", the container will be along columns container_situation = None if np.allclose(row_sum, 1, 1e-2): container_situation = "in_rows" if np.allclose(col_sum, 1, 1e-2): if container_situation: show_message(sh_out, t[0] - 1, t[1] - 1, "ERROR: both rows and columns should not sum to ones") container_situation = "in_columns" if container_situation: break if not container_situation: show_message(sh_out, t[0] - 1, t[1] - 1, "Warning: neither the sum of rows nor of columns is summing to ones", type="warning") # Read cell containing the specification of the processors. # The FIRST is the CONTAINED (child), the SECOND the CONTAINER (parent). # They are specified separated by "/" or "-". # Iterate to find both in the registry, obtain "registry_entries" RegistryEntry = collections.namedtuple('RegistryEntry', 'name registry_name registry_entry') registry_entries = [] for s in re.split("\/|\-|_", sh_in.title[8:]): # v[t[0]-1, t[2]-1] if "Upscaled_"+s.strip() in registry: registry_entries.append(RegistryEntry(s.strip(), "Upscaled_"+s.strip(), registry["Upscaled_"+s.strip()])) elif s.strip() in registry: registry_entries.append(RegistryEntry(s.strip(), s.strip(), registry[s.strip()])) if len(registry_entries) != 2: show_message(sh_out, 0, 0, "ERROR, there should be two registry entries recognized. Either the registry " "does not contain these processors or they are written incorrectly") # Identify taxonomic ranks. These ranks identify the processors # Concatenate all the taxonomic_ranks t_ranks = [(k, v) for k, v in registry_entries[0].registry_entry["taxonomic_ranks"].items()] + \ [(k, v) for k, v in registry_entries[1].registry_entry["taxonomic_ranks"].items()] n_ranks_first_processor = len(registry_entries[0].registry_entry["taxonomic_rank_levels"]) # Find the rows and cols containing taxon specifications lst = [] for rup in range(t[0] - 1, -1, -1): # Take a slice of labels. Using "set" avoid repetitions. Elaborate a tuple lst.append((set(v[rup, t[2]:t[3]]), "row", rup)) for cleft in range(t[2] - 1, -1, -1): # Take a slice of labels. Using "set" avoid repetitions. Elaborate a tuple lst.append((set(v[t[0]:t[1], cleft]), "col", cleft)) col_idx = [] row_idx = [] for l in lst: found = False for e in l[0]: for t_rank in t_ranks: if e and cell_content_to_str(e) in t_rank[1]: found = True break if found: break if found: if l[1] == "col": col_idx.append(l[2]) else: row_idx.append(l[2]) # Sweep the matrix of numbers warned_not_founds = set() new_procs = create_dictionary() # Newly obtained container processors for r in range(t[0], t[1]): for c in range(t[2], t[3]): if v[r, c] < 1e-3: continue # Clear taxon identification for each processor taxa0 = {} taxa1 = {} # Find the taxa, for each processor type involved for rup in row_idx: e = cell_content_to_str(v[rup, c]) found = False for i, t_rank in enumerate(t_ranks): if e and cell_content_to_str(e) in t_rank[1]: if i < n_ranks_first_processor: idx = i taxa = taxa0 entry = 0 else: idx = i - n_ranks_first_processor taxa = taxa1 entry = 1 found = True # Add taxon to the processor type taxa[registry_entries[entry].registry_entry["taxonomic_rank_levels"][idx]] = e if not found: cell_pos = (rup + 1, c + 1) print(sh_in.title + " ("+str(cell_pos[0])+", "+str(cell_pos[1])+") not found") if e: if cell_pos not in warned_not_founds: warned_not_founds.add(cell_pos) show_message(sh_out, cell_pos[0], cell_pos[1], "WARNING: subtype '"+e+"' not found. Processors to be combined cannot be identified properly.", "warning") for cleft in col_idx: e = cell_content_to_str(v[r, cleft]) found = False for i, t_rank in enumerate(t_ranks): if e and e in t_rank[1]: if i < n_ranks_first_processor: idx = i taxa = taxa0 entry = 0 else: idx = i - n_ranks_first_processor taxa = taxa1 entry = 1 found = True # Add taxon to the processor type taxa[registry_entries[entry].registry_entry["taxonomic_rank_levels"][idx]] = e if not found: cell_pos = (r + 1, cleft + 1) print(sh_in.title + " ("+str(cell_pos[0])+", "+str(cell_pos[1])+") not found") if e: if cell_pos not in warned_not_founds: warned_not_founds.add(cell_pos) show_message(sh_out, cell_pos[0], cell_pos[1], "WARNING: subtype '"+e+"' not found. Processors to be combined cannot be identified properly.", "warning") # Identify processors taxa = [taxa0, taxa1] processors = [] for entry in [0, 1]: try: p = registry_entries[entry].registry_entry["processors"][tuple([registry_entries[entry].name]+[taxa[entry][rn] for rn in registry_entries[entry].registry_entry["taxonomic_rank_levels"]])] processors.append(p) except: # Not found. The combination may be referring to a processor which has not been detailed previously pass if len(processors) != 2: show_message(sh_out, r + 1, c + 1, "WARNING: did not find two processors to combine", "warning") continue S = processors[0] T = processors[1] if T["full_name"] in new_procs: T2 = new_procs[T["full_name"]] else: T2 = clone_processor(T) # Clone processor and its children new_procs[T["full_name"]] = T2 S2 = clone_processor(S) # Clone processor and its children add_child_to(contained=S2, container=T2, factor=v[r, c]) container = registry_entries[1] registry["Upscaled_"+container.name] = \ {"processors_taxonomy": container.registry_entry["processors_taxonomy"], # All the taxonomic types of processors, except the first level "processors": new_procs, # The processors, also indexed by the full taxonomic types "taxonomic_rank_levels": container.registry_entry["taxonomic_rank_levels"], # Names of the taxonomic ranks "taxonomic_ranks": container.registry_entry["taxonomic_ranks"] # Names contained in each of the taxonomic ranks } def pivot_table(sh_writable, df, rows, cols, aggs, values, show_totals): """ Given Pivot Table parameters, elaborate it and put it in the output worksheet :param sh_writable: :param df: :param rows: :param cols: :param aggs: :param values: :param show_totals: :return: Nothing. Results are written into the worksheet "sh_writable" """ df2 = None if len(rows) > 0 and len(cols) > 0 and values: if df.shape[0] == 0: show_message(sh_writable, 1, 1, "Warning: no data from the specified query", type="warning") else: df2 = pd.pivot_table(df, values=values, index=rows, columns=cols, aggfunc=aggs, fill_value=np.NaN, margins=show_totals, dropna=True, margins_name="Total") if df2.shape[0] * df2.shape[1] > 40000: df2 = None show_message(sh_writable, 1, 1, "ERROR: the resulting pivot table cannot be shown because there are " "too many cells (" + str(df2.shape[0]*df2.shape[1]) + "). Please, reconsider the parameters.") else: # df2 = df2.swaplevel(0, len(df2.columns.names)-1, axis=1) i = 0 # Number of levels of the columns Index nidx_rows = len(df2.columns.names) # Count the number of levels of the rows Index if isinstance(df2.index, pd.MultiIndex): nidx_cols = len(df2.index.names) else: nidx_cols = 1 # Reference point start = (nidx_rows, nidx_cols) # Reset worksheet sh_out = reset_worksheet(sh_writable) # Put the values at (nr+1, nc+1) for r in range(df2.shape[0]): for c in range(df2.shape[1]): sh_out.cell(row=r + start[0] + 1, column=c + start[1] + 1, value=df2.iloc[r, c]) # Put the columns Index from (:, nc+1) on for c in range(df2.shape[1]): for r, l in enumerate(df2.columns.values[c]): sh_out.cell(row=r + 1, column=c + start[1] + 1, value=str(l)) # Put the rows Index from (nr+1, :) on for r in range(df2.shape[0]): if isinstance(df2.index, pd.MultiIndex): for c, l in enumerate(df2.index.values[r]): sh_out.cell(row=r + start[0] + 1, column=c + 1, value=str(l)) else: sh_out.cell(row=r + start[0] + 1, column=0 + 1, value=str(df2.index[r])) # TODO Check consecutive values, to merge, in horizontal or in vertical # Mark the Pivot Table sh_out.cell(row=1, column=1, value="Pivot table") return df2 def read_and_calculate_pivot_table(sh, sh_writable, registry, dfs, df=None): # Read parameters row_c = None col_c = None agg_c = None sh_c = None rows = [] cols = [] sh_name = None some_error = False for c in range(sh.max_column): cname = sh.cell(row=0 + 1, column=c + 1).value if not cname: continue if strcmp(cname, "Sheet") and df is None: sh_c = c # Sheet from where to read the input dataframe sh_name = sh.cell(row=1 + 1, column=c + 1).value if sh_name in dfs: df = dfs[sh_name] else: df = list_processors(sh_name[5:], sh_writable.cell(row=1 + 1, column=sh_c + 1), registry, dfs) if df is None: some_error = True show_message(sh_writable, 1 + 1, sh_c + 1, "ERROR:
<filename>DynaMETE_Rfunctions_FlexibleFunctions.py ''' This file defines all of the necessary functions for DynaMETE, including the transition functions and the structure function R. This function does NOT include sums over n, since it is designed to be a more flexible version incorporating different transition functions. This will be very slow for large N or E. It also defines the METE constraint for beta, which is needed, and a function to obtain mete_lambdas. To change the functional form of the transition functions, you need only change f, h, and/or q, and the corresponding function dfdt, dhdt, and/or dqdt. This version specifically replaces d0/E_c n/e^(-1/3) with d0/E_c n^2/e^(-1/3) to test adding a new degree of freedom in n dependence. ''' # Import import numpy as np import pandas as pd from scipy.optimize import fsolve from scipy import integrate # METE functions def beta_constraint(b,s): '''This is the beta constraint in METE with give state variables. Use this as a function call to get beta. Inputs s as state variables, call S, N, or E Also inputs beta outputs beta constraint to minimize''' return b*np.log(1/(1-np.exp(-b)))-s['S']/s['N'] def get_beta(s,b0=0.0001): '''This returns beta from METE. Inputs s as state variables.''' return fsolve(beta_constraint,b0,args=s)[0] def mete_lambdas(s,b0=0.0001): '''This returns the METE lambdas for a given set of state variables. Inputs s as state variables, call S, N, or E Optional input of an initial beta, if we know it's going to be somewhere other than small positive. outputs array of lambdas''' beta = get_beta(s,b0) l2 = s['S']/(s['E']-s['N']) ls = np.array([beta-l2,l2,0,0,0]) return ls # Transition functions # The idea here is to make everything easy to change by changing only these functions. # For f def fb0(s,p): return p['b0'] def fd0(s,p): return -p['d0']*s['E']/p['Ec'] def fm0(s,p): return p['m0']/s['N'] def f(n,e,s,p): '''Transition function for dN/dt. n and e are microscopic variables. s are state variables, call S, N, or E p are parameters, call b0, d0, m0, w0, w10, Ec, or mu ''' return (fb0(s,p)+fd0(s,p)*n)*n/e**(1/3)+fm0(s,p)*n # For h def hw0(s,p): return p['w0'] def hd0(s,p): return -p['d0']*s['E']/p['Ec'] def hw10(s,p): b0i=0.0001 beta = get_beta(s,b0i) return -p['w10']/np.log(1/beta)**(2/3) def hm0(s,p): return p['m0']/s['N'] def h(n,e,s,p): '''Transition function for dE/dt. n and e are microscopic variables. s are state variables, call S, N, or E p are parameters, call b0, d0, m0, w0, w1, Ec, or mu ''' return (hw0(s,p)+hd0(s,p)*n)*n*e**(2/3)+hw10(s,p)*n*e+hm0(s,p)*n # For q def qc(s,p): return p['m0']*np.exp(-p['mu']*s['S']-np.euler_gamma) def qd0(s,p): return -s['S']*p['d0']*s['E']/p['Ec'] def q(n,e,s,p): '''Transition function for dS/dt. n and e are microscopic variables. s are state variables, call S, N, or E p are parameters, call b0, d0, m0, w0, w10, Ec, or mu For now this doesn't implement speciation models, ie. s1=s2=0''' # Set up kronecker delta in an easy way. Round n to nearest int, if it's 1 then include term # I actually need this to be vectorized, so let's do it slightly differently. # First check if n is scalar if np.isscalar(n): kn1 = int(np.rint(n))==1 else: kn1 = np.zeros(len(n)) kn_arg = np.where(np.rint(n)==1) # I included the rounded int here because really this kronecker delta can be defined in continuous space # In that case there should also be a correction factor though, but let's ignore that. # The good news here is that below we only pass in arange, which by default passes in integers # So we should be ok as long as we are only using arange for passing in ranges of n # That is because arange rounds the variable it takes in so it can take steps of length 1 kn1[kn_arg] = 1 return qc(s,p) + qd0(s,p)*kn1/e**(1/3) # Also need derivatives for lambda dynamics. Note that these have to be manually editted for alternate f,h,q def dfdt(n,e,s,p,ds): return fd0(s,p)/s['E']*ds['dE']*n**2/e**(1/3) - fm0(s,p)*ds['dN']/s['N']*n def dhdt(n,e,s,p,ds): return hd0(s,p)/s['E']*ds['dE']*n**2*e**(2/3) - hm0(s,p)*ds['dN']/s['N']*n def dqdt(n,e,s,p,ds): # See q for how the kronecker delta works. if np.isscalar(n): kn1 = int(np.rint(n))==1 else: kn1 = np.zeros(len(n)) kn_arg = np.where(np.rint(n)==1) kn1[kn_arg] = 1 return -qc(s,p)*ds['dS']*p['mu'] + qd0(s,p)*(ds['dS']/s['S']+ds['dE']/s['E'])*kn1/e**(1/3) # R itself def R(n,e,l,s,p): '''Unnormalized struture function for DynaMETE. n,e are microscopic variables. l are lambdas s are state variables, call S, N, or E p are parameters, call b0, d0, m0, w0, w10, Ec, or mu ''' return np.exp(-l[0]*n-l[1]*n*e-l[2]*f(n,e,s,p)-l[3]*h(n,e,s,p)-l[4]*q(n,e,s,p)) # For calculating a single mean with specific powers of n and e def mean_pow(npow,epow,l,s,p,z=1): ''' This function returns the mean of n^npow*e^epow over the R function. It is NOT normalized, but it does take in z as an optional argument to normalize. This function uses quad integral over log e for each n then sums over n. Note that npow=epow=0 corresponds to Z, so by default these are not normalized. l are lambdas s are state variables, call S, N, or E p are parameters, call b0, d0, m0, w0, w10, Ec, or mu ''' nrange = np.arange(s['N'])+1 eint = integrate.quad_vec(lambda loge: np.exp(loge*(1+epow))*R(nrange,np.exp(loge),l,s,p),0,np.log(s['E']))[0] return np.sum(nrange**npow*eint)/z # For calculating a covariance with specific powers of n and e for each function def cov_pow(npow,epow,l,s,p,z): ''' This function returns the covariance of two functions with the form n^npow*e^epow over the R function. You have to pass in the normalization so that things are faster than calculating normalization each time. npow and epow should both be 2d arrays with the functions. For example, if you want COV(n^2,ne), pass npow=[2,1], epow=[0,1] This function uses quad integral over log e for each n then sums over n. z is the normalization l are lambdas s are state variables, call S, N, or E p are parameters, call b0, d0, m0, w0, w10, Ec, or mu ''' nrange = np.arange(s['N'])+1 # Get integral over both functions ffeint = integrate.quad_vec(lambda loge: np.exp(loge*(1+np.sum(epow)))*R(nrange,np.exp(loge),l,s,p),0,np.log(s['E']))[0] ff = np.sum(nrange**np.sum(npow)*ffeint)/z # Get integral over each function f1f2 = 1 for nn,ee in zip(npow,epow): feint = integrate.quad_vec(lambda loge: np.exp(loge*(1+ee))*R(nrange,np.exp(loge),l,s,p),0,np.log(s['E']))[0] f1f2 *= np.sum(nrange**nn*feint)/z return ff-f1f2 # For calculating a single mean over an arbitrary function # Use mean_pow for non-functions def mean(func,l,s,p,*args,z=1): ''' This function returns the mean of an arbitrary function over the R function. It is NOT normalized, but it does take in z as an optional argument to normalize. Because I put *args first, you have to use z=z0 if you want to put in a normalization. The arbitrary function must take arguments of the form (n,e,s,p) for this to work. This is the form of the f,h, and q functions above. You can pass additional arguments as required for the function (ie. pass ds for df/dt) To pass in n or n*e, use lambda n,e,s,p: n or lambda n,e,s,p: n*e, or similar. Alternatively, use mean_pow This function uses quad integral over log e for each n then sums over n. l are lambdas s are state variables, call S, N, or E p are parameters, call b0, d0, m0, w0, w10, Ec, or mu z is the normalization ''' nrange = np.arange(s['N'])+1 # Below is to make this easier for lambda functions, but it isn't worth it. Just require s and p passed, # and let other things be passed as args if needed. # Check if we need args by looking at function passed in # funcargs = func.__code__.co_argcount # if funcargs >= 4: # args = s,p,args eint = integrate.quad_vec(lambda loge: np.exp(loge)*R(nrange,np.exp(loge),l,s,p)*func(nrange,np.exp(loge),s,p,*args),0,np.log(s['E']))[0] return np.sum(eint)/z # For calculating a covariance # Note if you want to do this with non-functions, use cov_pow def cov(func1,func2,l,s,p,z,*args): ''' This function returns the covariance of two arbitrary functions over the R function. You have to pass in the normalization so that things are faster than calculating normalization each time. The arbitrary functions must take arguments of the form (n,e,s,p) for this to work. This is the form of the f,h, and q functions above. You can pass additional arguments as required for the function (ie. pass ds for df/dt) To pass in n or n*e, use lambda n,e,s,p: n or lambda n,e,s,p: n*e, or similar. This function uses quad integral over log e for each n then sums over n. l are lambdas s are state variables, call S, N, or E p are parameters, call b0, d0, m0, w0, w10, Ec, or mu z is the normalization
from py_snap_helpers import * import otbApplication from ogr import osr import ogr import gdal import geopandas as gp import os import pandas as pd import numpy as np from shapely.geometry import box from shapely.wkt import loads import sys gdal.UseExceptions() #sys.path.append('/opt/OTB/lib/python') #sys.path.append('/opt/OTB/lib/libfftw3.so.3') #sys.path.append('/opt/anaconda/bin') #os.environ['OTB_APPLICATION_PATH'] = '/opt/OTB/lib/otb/applications' #os.environ['LD_LIBRARY_PATH'] = '/opt/OTB/lib' #os.environ['ITK_AUTOLOAD_PATH'] = '/opt/OTB/lib/otb/applications' os.environ['PREFIX'] = '/opt/anaconda/envs/env_ewf_satcen_03_03_01/' sys.path.append(os.path.join(os.environ['PREFIX'], 'bin')) os.environ['_JAVA_OPTIONS'] = '-Xms24g -Xmx24g' from gdal_calc import Calc as gdalCalc import cioppy ciop = cioppy.Cioppy() def check_existence(product): if os.path.isfile('{}'.format(product)): print('output file: {} generated successfully.'.format(product)) else: raise RuntimeError('Missing output file: {}.dim'.format(product)) def get_metadata(input_references, data_path): if isinstance(input_references, str): search_params = dict() search_params['do'] = 'terradue' products = gp.GeoDataFrame(ciop.search(end_point=input_references, params=search_params, output_fields='identifier,self,wkt,startdate,enddate,enclosure,orbitDirection,track,orbitNumber', timeout=360000, model='EOP')) else: temp_results = [] for index, self in enumerate(input_references): search_params = dict() search_params['do'] = 'terradue' temp_results.append(ciop.search(end_point=self, params=search_params, output_fields='identifier,self,wkt,startdate,enddate,enclosure,orbitDirection,track,orbitNumber', model='EOP')[0]) products = gp.GeoDataFrame(temp_results) products = products.merge(products.apply(lambda row: analyse(row, data_path), axis=1), left_index=True, right_index=True) return products def analyse(row, data_path): series = dict() series['local_path'] = os.path.join(data_path, row['identifier'], row['identifier'] + '.SAFE', 'manifest.safe') return pd.Series(series) def bbox_to_wkt(bbox): return box(*[float(c) for c in bbox.split(',')]).wkt def get_inteserction_aoi_prod(aoi,prod_wkt): return loads(prod_wkt).intersection(loads(aoi)).wkt def zone(coordinates): if 56 <= coordinates[1] < 64 and 3 <= coordinates[0] < 12: return 32 if 72 <= coordinates[1] < 84 and 0 <= coordinates[0] < 42: if coordinates[0] < 9: return 31 elif coordinates[0] < 21: return 33 elif coordinates[0] < 33: return 35 return 37 return int((coordinates[0] + 180) / 6) + 1 ,'CDEFGHJKLMNPQRSTUVWXX'[int((coordinates[1] + 80) / 8)] def get_epsg(row,epsg): #search = ciop.search(end_point=reference, params=[], output_fields='self,enclosure,wkt') #x=loads(search[0]['wkt']).centroid.coords epsg_codes = dict() if epsg =='None': x=loads(row['wkt']).centroid.coords coord=x[0] z, l = zone(coord) # The EPSG code is 32600+zone for positive latitudes and 32700+zone for negatives. if coord[0]>=0 : EPSG='EPSG:326'+str(z) else: EPSG='EPSG:327'+str(z) epsg_codes['epsg'] = EPSG else: epsg_codes['epsg'] = epsg return pd.Series(epsg_codes) def pre_process(gpt_path, products, aoi, resolution='10.0', polarization=None, orbit_type=None, dem_type='SRTM 1Sec HGT',show_graph=False): #mygraph = GraphProcessor() for index, product in products.iterrows(): #aoi_subset = get_inteserction_aoi_prod(aoi,products['wkt'][index]) mygraph = GraphProcessor(gpt_path) operator = 'Read' parameters = get_operator_default_parameters(operator) node_id = 'Read-{0}'.format(index) source_node_id = '' parameters['file'] = product.local_path mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'Apply-Orbit-File' parameters = get_operator_default_parameters(operator) if orbit_type == 'Restituted': parameters['orbitType'] = 'Sentinel Restituted (Auto Download)' node_id = 'Apply-Orbit-File-{0}'.format(index) mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'ThermalNoiseRemoval' node_id = 'ThermalNoiseRemoval-{0}'.format(index) parameters = get_operator_default_parameters(operator) if polarization is not None: parameters['selectedPolarisations'] = polarization mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'Calibration' node_id = 'Calibration-{0}'.format(index) parameters = get_operator_default_parameters(operator) parameters['auxFile'] = 'Product Auxiliary File' parameters['outputImageInComplex'] = 'false' parameters['outputImageScaleInDb'] = 'false' parameters['createGammaBand'] = 'false' parameters['createBetaBand'] = 'false' parameters['selectedPolarisations'] = '' parameters['outputSigmaBand'] = 'true' parameters['outputGammaBand'] = 'false' parameters['outputBetaBand'] = 'false' if polarization is not None: parameters['selectedPolarisations'] = polarization mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id ####Burst Merging operator = 'TOPSAR-Deburst' parameters = get_operator_default_parameters(operator) node_id = 'TOPSAR-Deburst' mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'Terrain-Correction' node_id = 'Terrain-Correction-{0}'.format(index) parameters = get_operator_default_parameters(operator) parameters['mapProjection'] = product.epsg #'AUTO:42001' parameters['pixelSpacingInMeter'] = resolution parameters['nodataValueAtSea'] = 'true' #parameters['demName'] = 'SRTM 1Sec HGT' #parameters['demName'] = 'SRTM 3Sec' parameters['demName'] = dem_type mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'Subset' node_id = 'Subset-{0}'.format(index) parameters = get_operator_default_parameters(operator) parameters['geoRegion'] = aoi parameters['copyMetadata'] = 'true' mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'Write' parameters = get_operator_default_parameters(operator) parameters['file'] = product.identifier parameters['formatName'] = 'BEAM-DIMAP' node_id = 'Write-{0}'.format(index) mygraph.add_node(node_id, operator, parameters, source_node_id) if show_graph: mygraph.view_graph() mygraph.run() def speckle_filter(gpt_path, products, working_dir='.', show_graph=True): mygraph = GraphProcessor(gpt_path) operator = 'Read' parameters = get_operator_default_parameters(operator) node_id_0 = 'Read-0' source_node_id = '' parameters['file'] = os.path.join(working_dir,'{}.dim'.format(products.identifier.values[0])) mygraph.add_node(node_id_0, operator, parameters, source_node_id) operator = 'Read' parameters = get_operator_default_parameters(operator) node_id_1 = 'Read-1' source_node_id = '' parameters['file'] = os.path.join(working_dir,'{}.dim'.format(products.identifier.values[1])) mygraph.add_node(node_id_1, operator, parameters, source_node_id) sources = dict() sources['master'] = node_id_0 sources['slave'] = node_id_1 operator = 'Collocate' parameters = get_operator_default_parameters(operator) node_id = 'Collocate' parameters['targetProductName'] = '_collocated' parameters['targetProductType'] = 'COLLOCATED' parameters['renameMasterComponents'] = 'true' parameters['renameSlaveComponents'] = 'true' parameters['masterComponentPattern']='before' parameters['slaveComponentPattern'] = 'after' parameters['resamplingType'] = 'NEAREST_NEIGHBOUR' mygraph.add_node(node_id, operator, parameters, sources) source_node_id = node_id operator = 'Multi-Temporal-Speckle-Filter' parameters = get_operator_default_parameters(operator) node_id = 'Multi-Temporal-Speckle-Filter' parameters['sourceBands'] = 'before,after' parameters['filter'] = 'Lee Sigma' parameters['filterSizeX'] = '3' parameters['filterSizeY'] = '3' parameters['dampingFactor'] = '2' parameters['estimateENL'] = 'true' parameters['enl'] = '1.0' parameters['numLooksStr'] = '1' parameters['windowSize'] = '7x7' parameters['targetWindowSizeStr'] = '3x3' parameters['sigmaStr'] = '0.9' parameters['anSize'] = '50' mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'Write' parameters = get_operator_default_parameters(operator) parameters['file'] = 'mtsf' parameters['formatName'] = 'BEAM-DIMAP' node_id = 'Write' mygraph.add_node(node_id, operator, parameters, source_node_id) if show_graph: mygraph.view_graph() mygraph.run() def create_stack(gpt_path, products, working_dir='.', show_graph=True): mygraph = GraphProcessor(gpt_path) operator = 'ProductSet-Reader' parameters = get_operator_default_parameters(operator) parameters['fileList'] = ','.join([ '{}.dim'.format(n) for n in products.identifier.values]) node_id = 'ProductSet-Reader' source_node_id = '' #parameters['file'] = product.local_path mygraph.add_node(node_id, operator, parameters, '') source_node_id = node_id operator = 'CreateStack' parameters = get_operator_default_parameters(operator) node_id = 'CreateStack' parameters['extent'] = 'Minimum' parameters['resamplingType'] = 'BICUBIC_INTERPOLATION' mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'Write' parameters = get_operator_default_parameters(operator) parameters['file'] = 'stack' parameters['formatName'] = 'BEAM-DIMAP' node_id = 'Write' mygraph.add_node(node_id, operator, parameters, source_node_id) if show_graph: mygraph.view_graph() mygraph.run() def list_bands(product, working_dir='.'): reader = ProductIO.getProductReader('BEAM-DIMAP') product = reader.readProductNodes(os.path.join(working_dir,product), None) return list(product.getBandNames()) def change_detection(gpt_path, input_product, output_product, expression, show_graph=False): mygraph = GraphProcessor(gpt_path) operator = 'Read' parameters = get_operator_default_parameters(operator) node_id = 'Read' source_node_id = '' parameters['file'] = input_product mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'BandMaths' parameters = get_operator_default_parameters(operator) bands = '''<targetBands> <targetBand> <name>change_detection</name> <type>float32</type> <expression>{}</expression> <description/> <unit/> <noDataValue>NaN</noDataValue> </targetBand> </targetBands>'''.format(expression) parameters['targetBandDescriptors'] = bands node_id = 'BandMaths' mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'Write' parameters = get_operator_default_parameters(operator) parameters['file'] = output_product parameters['formatName'] = 'GeoTIFF-BigTIFF' node_id = 'Write' mygraph.add_node(node_id, operator, parameters, source_node_id) if show_graph: mygraph.view_graph() mygraph.run() def convert_dim(gpt_path, input_product, show_graph=False): mygraph = GraphProcessor(gpt_path) operator = 'Read' parameters = get_operator_default_parameters(operator) node_id = 'Read' source_node_id = '' parameters['file'] = input_product mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'LinearToFromdB' node_id = 'LinearToFromdB' parameters = get_operator_default_parameters(operator) mygraph.add_node(node_id, operator, parameters, source_node_id) source_node_id = node_id operator = 'Write' parameters = get_operator_default_parameters(operator) parameters['file'] = input_product.replace('.dim', '_db.tif') parameters['formatName'] = 'GeoTIFF-BigTIFF' node_id = 'Write' mygraph.add_node(node_id, operator, parameters, source_node_id) if show_graph: mygraph.view_graph() mygraph.run() return input_product.replace('.dim', '_db.tif') def cog(input_tif, output_tif): translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co TILED=YES ' \ '-co COPY_SRC_OVERVIEWS=YES ' \ '-co BIGTIFF=YES ' \ '-co COMPRESS=LZW')) ds = gdal.Open(input_tif, gdal.OF_READONLY) gdal.SetConfigOption('COMPRESS_OVERVIEW', 'DEFLATE') ds.BuildOverviews('NEAREST', [2,4,8,16,32]) ds = None ds = gdal.Open(input_tif) gdal.Translate(output_tif, ds, options=translate_options) ds = None os.remove('{}.ovr'.format(input_tif)) os.remove(input_tif) def get_image_wkt(product): src = gdal.Open(product) ulx, xres, xskew, uly, yskew, yres = src.GetGeoTransform() max_x = ulx + (src.RasterXSize * xres) min_y = uly + (src.RasterYSize * yres) min_x = ulx max_y = uly source = osr.SpatialReference() source.ImportFromWkt(src.GetProjection()) target = osr.SpatialReference() target.ImportFromEPSG(4326) transform = osr.CoordinateTransformation(source, target) result_wkt = box(transform.TransformPoint(min_x, min_y)[0], transform.TransformPoint(min_x, min_y)[1], transform.TransformPoint(max_x, max_y)[0], transform.TransformPoint(max_x, max_y)[1]).wkt return result_wkt def create_composite(input_products, output_product, band_expressions): BandMathX = otbApplication.Registry.CreateApplication("BandMathX") BandMathX.SetParameterStringList('il', input_products) BandMathX.SetParameterString('out', 'temp_red_green_blue.tif') BandMathX.SetParameterString('exp', ';'.join(band_expressions)) BandMathX.ExecuteAndWriteOutput() Convert = otbApplication.Registry.CreateApplication('DynamicConvert') Convert.SetParameterString('in', 'temp_red_green_blue.tif') Convert.SetParameterString('out', output_product) Convert.SetParameterString('type', 'linear') Convert.SetParameterString('channels', 'rgb') Convert.ExecuteAndWriteOutput() os.remove('temp_red_green_blue.tif') return output_product def create_mask(in_composite, out_mask): #gdal_calc.py --calc="logical_and(logical_and(A==255, B==0), C==0)" -A $1 --A_band=1 -B $1 --B_band=2 -C $1 --C_band=3 --outfile=${1::-8}.mask.tif #command = '/opt/anaconda/envs/env_ewf_satcen_03_03_01/bin/gdal_calc.py --calc="logical_and(logical_and(A==255, B==0), C==0)" -A {0} --A_band=1 -B {0} --B_band=2 -C {0} --C_band=3 --outfile={1}'.format(in_composite, out_mask) # Run the command. os.system() returns value zero if the command was executed succesfully #out = os.system(command) #if out !=0: # print('ERROR gdla_calc out: {}'.format(out)) calc_exp="logical_and(logical_and(A==255, B==0), C==0)" gdalCalc(calc=calc_exp, A=in_composite, A_band=1, B=in_composite, B_band=2, C=in_composite, C_band=3, outfile=out_mask) def create_rbb(in_rgb, out_rbb): #gdal_translate -ot UInt16 -a_nodata 256 ${1::-14}RED-BLUE.rgb.tif ${1::-8}.acd.tif -co COMPRESS=LZW -b 1 -b 3 -b 3 translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co COMPRESS=LZW '\ '-ot UInt16 ' \ '-a_nodata 256 ' \ '-b 1 -b 3 -b 3 ')) ds = gdal.Open(in_rgb, gdal.OF_READONLY) gdal.Translate(out_rbb, ds, options=translate_options) def write_tif(layer, output_tif, width,
<filename>anuran/utils.py """ The utils module contains functions used by other modules for multiprocessing. """ __author__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'Development' __license__ = 'Apache 2.0' import networkx as nx import pandas as pd from random import sample import numpy as np import logging.handlers from copy import deepcopy logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def _generate_null_parallel(values): """ This function takes a list of networks. For each network, a list with length n is generated, with each item in the list being a permutation of the original network. This is returned as a list of lists with this structure: ---List corresponding to each original network (length networks) ---List of permutations per original network (length n) For the positive controls, list structure is inverted. The purpose of this is to keep networks together in a list that share a synthetic core; unlike the negative control models, these cannot be resampled from the list to generate new groups. ---List corresponding to each permutation per network group ---List corresponding to each original network (length networks) :param values: Dictionary containing values for generating null models :return: Tuples with settings and randomized networks """ network = networks = name = fraction = prev = n = mode = None try: network = values['network'] networks = values['networks'] name = values['name'] fraction = values['fraction'] prev = values['prev'] n = values['n'] mode = values['mode'] except KeyError: logger.error('Could not unpack dictionary!', exc_info=True) timeout = [] preserve_deg = [] if network: nulls = _generate_negative_control(network=network, n=n, mode=mode) else: nulls, timeout, preserve_deg = _generate_positive_control(networks=networks, fraction=fraction, prev=prev, n=n, mode=mode) if len(timeout) > 0: for key in timeout: logger.warning('Could not create good degree-preserving core models for network ' + key) if len(preserve_deg) > 0: for key in preserve_deg: logger.info('Deleting random edge instead of preserving ' 'degree distribution for positive control ' + key + '.') if fraction: params = (mode, name, 'core', fraction, prev) else: params = (mode, name, mode) return params, nulls def _generate_positive_control(networks, fraction, prev, n, mode): """ Generates n positive control models across the group of supplied networks. The core here is specified as a percentage of the union network size and prevalence as the number of networks where edges should occur. :param networks: List of tuples, each tuple (network name, networkx object) :param fraction: Fraction of conserved edges in network union :param prev: Prevalence of conserved edges across networks :param n: Number of groups to generate :param mode: Degree or random networks :return: Tuples with randomized networks """ nulls = list() # all null models need to preserve the same edges all_edges = _get_union(networks) timeout = [] preserve_deg = [] for i in range(n): nulls.append([]) keep = sample(all_edges, round(len(all_edges) * float(fraction))) # create lists to distribute edges over according to core prevalence keep_subsets = [[] for x in range(len(networks))] occurrence = round(float(prev) * len(networks)) for edge in keep: indices = sample(range(len(networks)), occurrence) for k in indices: keep_subsets[k].append(edge) for j in range(len(networks)): network = networks[j] if mode == 'random': nulls[i].append((network[0], _randomize_network(network[1], keep_subsets[j]))) elif mode == 'degree': if network[0] in timeout: # if the network has timed out before, # reduce the number of tries. deg = _randomize_dyads(network[1], keep_subsets[j], timeout=True) else: deg = _randomize_dyads(network[1], keep_subsets[j], timeout=False) nulls[i].append((network[0], deg[0])) if deg[1]: timeout.append(network[0]) if deg[2]: preserve_deg.append(network[0]) return nulls, timeout, preserve_deg def _generate_negative_control(network, n, mode): nulls = list() timeout = False for j in range(n): if mode == 'random': nulls.append((network[0], _randomize_network(network[1], keep=[]))) elif mode == 'degree': deg = _randomize_dyads(network[1], keep=[], timeout=timeout) nulls.append((network[0], deg[0])) timeout = deg[1] if timeout: logger.warning('Could not create good degree-preserving models for network ' + network[0]) return nulls def _generate_centralities_parallel(model_list): """ This function takes a list of null models or networks, where each item in the list is a tuple. The tuple contains the network name and the NetworkX object. This function adds centrality rankings to the tuple. :param model_list: List of list of networks, with networks given as a tuple (name and networkX object) :return: """ centrality_list = [] for network in model_list: centrality_list.append((network[0], network[1], {'Degree': _centrality_percentile(nx.degree_centrality(network[1])), 'Closeness': _centrality_percentile(nx.closeness_centrality(network[1])), 'Betweenness': _centrality_percentile(nx.betweenness_centrality(network[1]))})) return centrality_list def _centrality_percentile(centrality): """ Given a dictionary of centralities, this function returns the percentile score of nodes in a graph. :param centrality: Dictionary with nodes as keys and centralities as values. :return: """ if len(centrality) > 0: ranking = pd.DataFrame.from_dict(centrality, orient='index') ranking['rank'] = ranking[0].rank(pct=True) ranking = ranking['rank'].to_dict() else: ranking = None return ranking def _randomize_network(network, keep): """ This function returns a network with the same nodes and edge number as the input network. However, each edge is placed randomly. :param network: NetworkX object :param keep: List of conserved edges :return: Randomized network """ null = nx.Graph().to_undirected() null.add_nodes_from(network.nodes) if keep: if len(keep[0]) == 3: null.add_weighted_edges_from(keep) else: null.add_edges_from(keep) num = len(network.edges) - len(null.edges) randomized_weights = nx.get_edge_attributes(network, 'weight') if len(randomized_weights) > 0: for edge in null.edges: randomized_weights.pop(edge, None) randomized_weights = sample(list(randomized_weights.values()), len(randomized_weights)) for edge in range(num): created = False while not created: new_edge = sample(null.nodes, 2) if new_edge not in null.edges: null.add_edge(new_edge[0], new_edge[1], weight=randomized_weights[edge]) created = True return null def _randomize_dyads(network, keep, timeout): """ This function returns a network with the same nodes and edge number as the input network. Each edge is swapped rather than moved, so the degree distribution is preserved. :param network: NetworkX object in tuple, with first item in tuple being network name :param keep: List of conserved edges :param timeout: If true, previous iterations of this function timed out. :return: Randomized network with preserved degree distribution """ null = nx.Graph().to_undirected() null.add_nodes_from(network.nodes) null.add_edges_from(network.edges) nx.set_edge_attributes(null, nx.get_edge_attributes(network, 'weight'), 'weight') # we should carry out twice the number of swaps than the number of nodes with swappable edges # this should usually fully randomize the network swaps = 2 * len(network.edges) # creates a list of lists with each of the sublists containing nodes with same degree # if the previous iteration produced a timeout, # maxcount is reduced to 100 to speed up computation # for very small networks, the number of tries is also reduced if timeout or len(null) < 100: maxcount = 100 else: maxcount = 10000000 # large number, but should allow deg model timeout = False for swap in range(swaps): success = False count = 0 while not success and not timeout: # samples a set of nodes with swappable edges if count > maxcount: timeout = True dyad = sample(null.edges, 2) # samples two nodes that could have edges swapped if (dyad[0][0], dyad[1][0]) in null.edges: count += 1 continue elif (dyad[1][1], dyad[0][1]) in null.edges: count += 1 continue elif dyad[0][0] == dyad[1][0] or dyad[0][1] == dyad[1][1]: # if there is a triplet, we can't swap since once node would gain an edge count += 1 continue else: null.add_edge(dyad[0][0], dyad[1][0], weight=null.edges[dyad[0]]['weight']) null.add_edge(dyad[0][1], dyad[1][1], weight=null.edges[dyad[1]]['weight']) null.remove_edge(dyad[0][0], dyad[0][1]) null.remove_edge(dyad[1][0], dyad[1][1]) success = True preserve_deg = True if keep: # need weightless_keep to check if neighbour # is in core network if len(keep[0]) == 3: weightless_keep = [(edge[0], edge[1]) for edge in keep] else: weightless_keep = keep # add targeted swaps so edges are preserved across networks for edge in keep: if (edge[0], edge[1]) in null.edges: if len(edge) == 3: # if the edge already exists, only update weight null.edges[(edge[0], edge[1])]['weight'] = edge[2] else: # generate list of neighbours where # edge is not in core removed_core = deepcopy(null) removed_core.remove_edges_from(weightless_keep) try: neighbour1 = sample(list(nx.neighbors(removed_core, edge[0])), 1) neighbour2 = sample(list(nx.neighbors(removed_core, edge[1])), 1) except (ValueError, nx.NetworkXError): # 2 possibilities: # node is not connected in this specific graph # or node has no neighbours beyond core edges neighbour1 = [] neighbour2 = [] if len(neighbour1) == 0 or len(neighbour2) == 0: # it is not possible to preserve degree perfectly # if the new core node has no other edges to delete. # next-best thing: # when adding one edge, # also remove one edge preserve_deg = False # make sure not to delete edges in core del_edges = null.edges for other_edge in keep: del_edges = [x for x in del_edges if x != (other_edge[0],
found.') raise finally: if flib: flib.close() return entries def saveOld(self, dictstr, treestr, libstr): """ Save the current database to a set of text files using the old-style syntax. """ self.saveOldDictionary(dictstr) if treestr != '': self.saveOldTree(treestr) # RMG-Java does not require a frequencies_groups/Library.txt file to # operate, but errors are raised upon importing to Py if this file is # not found. This check prevents the placeholder from being discarded. if 'StatesGroups' not in self.__class__.__name__: self.saveOldLibrary(libstr) def saveOldDictionary(self, path): """ Save the current database dictionary to a text file using the old-style syntax. """ entries = [] entriesNotInTree = [] # If we have tree information, save the dictionary in the same order as # the tree (so that it saves in the same order each time) def getLogicNodeComponents(entry_or_item): """ If we want to save an entry, but that is a logic node, we also want to save its components, recursively. This is a horribly complicated way to *not* save in the dictionary any things which are not accessed from (or needed to define things that are accessed from) the tree. """ if isinstance(entry_or_item, Entry): entry = entry_or_item item = entry.item nodes = [entry] else: entry = None item = entry_or_item nodes = [] if isinstance(item, LogicNode): for child in item.components: if isinstance(child, LogicNode): nodes.extend(getLogicNodeComponents(child)) else: nodes.extend(getLogicNodeComponents(self.entries[child])) return nodes else: return [entry] if len(self.top) > 0: for entry in self.top: entries.extend(getLogicNodeComponents(entry)) for descendant in self.descendants(entry): for entry2 in getLogicNodeComponents(descendant): if entry2 not in entries: entries.append(entry2) # Don't forget entries that aren't in the tree for entry in self.entries.values(): if entry not in entries: entriesNotInTree.append(entry) entriesNotInTree.sort(key=lambda x: (x.index, x.label)) # Otherwise save the dictionary in any order else: # Save the library in order by index entries = self.entries.values() entries.sort(key=lambda x: (x.index, x.label)) def comment(s): "Return the string, with each line prefixed with '// '" return '\n'.join('// ' + line if line else '' for line in s.split('\n')) try: f = open(path, 'w') f.write('////////////////////////////////////////////////////////////////////////////////\n') f.write('//\n') f.write('// {0} dictionary\n'.format(self.name)) f.write('//\n') f.write('////////////////////////////////////////////////////////////////////////////////\n') f.write('\n') for entry in entries: f.write(entry.label + '\n') if isinstance(entry.item, Molecule): try: f.write(entry.item.toAdjacencyList(removeH=True, oldStyle=True) + '\n') except InvalidAdjacencyListError: f.write("// Couldn't save in old syntax adjacency list. Here it is in new syntax:\n") f.write(comment(entry.item.toAdjacencyList(removeH=False, oldStyle=False) + '\n')) elif isinstance(entry.item, Group): f.write(entry.item.toAdjacencyList(oldStyle=True).replace('{2S,2T}', '2') + '\n') elif isinstance(entry.item, LogicOr): f.write('{0}\n\n'.format(entry.item).replace('OR{', 'Union {')) elif entry.label[0:7] == 'Others-': assert isinstance(entry.item, LogicNode) f.write('{0}\n\n'.format(entry.item)) else: raise DatabaseError('Unexpected item with label {0} encountered in dictionary while attempting to save.'.format(entry.label)) if entriesNotInTree: f.write(comment("These entries do not appear in the tree:\n\n")) for entry in entriesNotInTree: f.write(comment(entry.label + '\n')) if isinstance(entry.item, Molecule): f.write(comment(entry.item.toAdjacencyList(removeH=False) + '\n')) elif isinstance(entry.item, Group): f.write(comment(entry.item.toAdjacencyList().replace('{2S,2T}','2') + '\n')) elif isinstance(entry.item, LogicOr): f.write(comment('{0}\n\n'.format(entry.item).replace('OR{', 'Union {'))) elif entry.label[0:7] == 'Others-': assert isinstance(entry.item, LogicNode) f.write(comment('{0}\n\n'.format(entry.item))) else: raise DatabaseError('Unexpected item with label {0} encountered in dictionary while attempting to save.'.format(entry.label)) f.close() except IOError, e: logging.exception('Unable to save old-style dictionary to "{0}".'.format(os.path.abspath(path))) raise def generateOldTree(self, entries, level): """ Generate a multi-line string representation of the current tree using the old-style syntax. """ string = '' for entry in entries: # Write current node string += '{0}L{1:d}: {2}\n'.format(' ' * (level-1), level, entry.label) # Recursively descend children (depth-first) string += self.generateOldTree(entry.children, level+1) return string def saveOldTree(self, path): """ Save the current database tree to a text file using the old-style syntax. """ try: f = open(path, 'w') f.write('////////////////////////////////////////////////////////////////////////////////\n') f.write('//\n') f.write('// {0} tree\n'.format(self.name)) f.write('//\n') f.write('////////////////////////////////////////////////////////////////////////////////\n') f.write('\n') f.write(self.generateOldTree(self.top, 1)) f.close() except IOError, e: logging.exception('Unable to save old-style tree to "{0}".'.format(os.path.abspath(path))) raise def saveOldLibrary(self, path): """ Save the current database library to a text file using the old-style syntax. """ try: # Save the library in order by index entries = self.entries.values() entries.sort(key=lambda x: x.index) f = codecs.open(path, 'w', 'utf-8') records = [] for entry in entries: if entry.data is not None: data = entry.data if not isinstance(data, str): data = self.generateOldLibraryEntry(data) records.append((entry.index, [entry.label], data, entry.shortDesc)) records.sort() f.write('////////////////////////////////////////////////////////////////////////////////\n') f.write('//\n') f.write('// {0} library\n'.format(self.name)) f.write('//\n') f.write('////////////////////////////////////////////////////////////////////////////////\n') f.write('\n') for index, labels, data, comment in records: f.write('{:<6d} '.format(index)) for label in labels: f.write('{:<32s} '.format(label)) if isinstance(data, basestring): f.write('{:s} '.format(data)) else: f.write('{:s} '.format(' '.join(['{:<10g}'.format(d) for d in data]))) f.write(u' {:s}\n'.format(comment)) f.close() except IOError, e: logging.exception('Unable to save old-style library to "{0}".'.format(os.path.abspath(path))) raise def __hashLabels(self, labels): """ Convert a list of string `labels` to a list of single strings that represent permutations of the individual strings in the `labels` list:: >>> hashLabels(['a','b']) ['a;b', 'b;a'] """ return ';'.join(labels) def ancestors(self, node): """ Returns all the ancestors of a node, climbing up the tree to the top. """ if isinstance(node, str): node = self.entries[node] ancestors = [] parent = node.parent if parent is not None: ancestors = [parent] ancestors.extend(self.ancestors(parent)) return ancestors def descendants(self, node): """ Returns all the descendants of a node, climbing down the tree to the bottom. """ if isinstance(node, str): node = self.entries[node] descendants = [] for child in node.children: descendants.append(child) descendants.extend(self.descendants(child)) return descendants def matchNodeToNode(self, node, nodeOther): """ Return `True` if `node` and `nodeOther` are identical. Otherwise, return `False`. Both `node` and `nodeOther` must be Entry types with items containing Group or LogicNode types. """ if isinstance(node.item, Group) and isinstance(nodeOther.item, Group): return self.matchNodeToStructure(node,nodeOther.item, atoms=nodeOther.item.getLabeledAtoms()) and self.matchNodeToStructure(nodeOther,node.item,atoms=node.item.getLabeledAtoms()) elif isinstance(node.item,LogicOr) and isinstance(nodeOther.item,LogicOr): return node.item.matchLogicOr(nodeOther.item) else: # Assume nonmatching return False def matchNodeToChild(self, parentNode, childNode): """ Return `True` if `parentNode` is a parent of `childNode`. Otherwise, return `False`. Both `parentNode` and `childNode` must be Entry types with items containing Group or LogicNode types. If `parentNode` and `childNode` are identical, the function will also return `False`. """ if isinstance(parentNode.item, Group) and isinstance(childNode.item, Group): if self.matchNodeToStructure(parentNode,childNode.item, atoms=childNode.item.getLabeledAtoms(), strict=True) is True: if self.matchNodeToStructure(childNode,parentNode.item, atoms=parentNode.item.getLabeledAtoms(), strict=True) is False: return True return False #If the parentNode is a Group and the childNode is a LogicOr there is nothing to check, #except that the parent is listed in the attributes. However, we do need to check that everything down this #family line is consistent, which is done in the databaseTest unitTest elif isinstance(parentNode.item, Group) and isinstance(childNode.item, LogicOr): ancestorNode = childNode.parent while ancestorNode: if ancestorNode is parentNode: return True else: ancestorNode = ancestorNode.parent else: return False elif isinstance(parentNode.item,LogicOr): return childNode.label in parentNode.item.components def matchNodeToStructure(self, node, structure, atoms, strict=False): """ Return :data:`True` if the `structure` centered at `atom` matches the structure at `node` in the dictionary. The structure at `node` should have atoms with the appropriate labels because they are set on loading and never change. However, the atoms in `structure` may not have the correct labels, hence the `atoms` parameter. The `atoms` parameter may include extra labels, and so we only require that every labeled atom in the functional group represented by `node` has an equivalent labeled atom in `structure`. Matching to structure is more strict than to node. All labels in structure must be found in node. However the reverse is not true, unless `strict` is set to True. =================== ======================================================== Attribute Description =================== ======================================================== `node` Either an Entry or a key in the self.entries dictionary which has a Group or LogicNode as its Entry.item `structure` A Group or a Molecule `atoms` Dictionary of {label: atom} in the structure. A possible dictionary is the one produced by structure.getLabeledAtoms() `strict` If set to ``True``, ensures that all the node's atomLabels are matched by in the structure =================== ======================================================== """ if isinstance(node, str): node = self.entries[node] group = node.item if isinstance(group, LogicNode): return group.matchToStructure(self, structure, atoms, strict) else: # try to pair up labeled atoms centers = group.getLabeledAtoms() initialMap = {} for label in centers.keys(): # Make sure the labels are in both group and structure. if label not in atoms: logging.log(0, "Label {0} is in group {1} but not in structure".format(label, node)) if strict: # structure must match all labeled atoms in node if strict is set to True return False continue # with the next
"""Provide functions used to estimate coexistence points""" import numpy as np from scipy import optimize def delta_f(f1new: float,f2new: float,f: np.ndarray) -> np.ndarray: """ Calculate the difference between next and current integration points Parameters ---------- f1new : float The next integration point f1 in the coexistence line f2new : float The next integration point f2 in the coexistence line f: np.ndarray [2,iphase] Current integration points f1 and f2 Returns ------- df : [2,iphase] Difference between next and current integration points """ df = np.zeros((2,2)) df[0,:] = f1new - f[0,:] df[1,:] = f2new - f[1,:] return df def poly_coefficients(df: np.ndarray,z: np.ndarray,cov: np.ndarray) -> np.ndarray: """ Calculate the coefficients in the free energy polynomial Parameters ---------- df : [2,iphase] Difference between next and current integration points z: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of currrent point (f1,f2) for both I and II phases cov: np.ndarray [3,iphase] Covariances [cov(z1,Z1),cov(z2,Z2),cov(z1,Z2)] of current point for both I and II phases Returns ------- df : [6,2] Coefficients in the free energy polynomial """ coef = np.zeros((6,2)) coef[0,:] = z[0,:]*df[0,:] coef[1,:] = z[1,:]*df[1,:] coef[2,:] = cov[0,:]*df[0,:]**2 coef[3,:] = cov[1,:]*df[1,:]**2 coef[4,:] = cov[2,:]*df[0,:]*df[1,:] coef[5,:] = cov[2,:]*df[0,:] return coef def first_guess_newton(free_energy: np.ndarray,z: np.ndarray,f1new: float,f: np.ndarray)->float: """ Calculate the first guess for the new point f2 in the coexistence line Parameters ---------- free_energy: np.ndarray [iphase] Free energy of phases I and II in the current point z: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of currrent point (f1,f2) for both I and II phases f1new : float The next integration point f1 in the coexistence line f: np.ndarray [2,iphase] Current integration points f1 and f2 Returns ------- f2new0 : float First guess for the new point f2 in the coexistence line """ f20_a = free_energy[0] - free_energy[1] +z[0,0]*(f1new-f[0,0]) - z[0,1]*(f1new-f[0,1]) f20_b = -z[1,0]*f[1,0]+z[1,1]*f[1,1] f2new0 = (f20_a+f20_b)/(z[1,1] - z[1,0]) return f2new0 def f_first_point(f2new: float,free_energy:np.ndarray,z:np.ndarray,cov:np.ndarray,f1new:float,f:np.ndarray)->float: """ Free energy difference function of the next point to be optimized if the Number of points is equal to 1 or one is refining the estimation Parameters ---------- f1new : float The next integration point f1 in the coexistence line f2new : float The next integration point f2 in the coexistence line free_energy: np.ndarray [iphase] Free energy of phases I and II in the current point z: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of currrent point (f1,f2) for both I and II phases cov: np.ndarray [3,iphase] Covariances [cov(z1,Z1),cov(z2,Z2),cov(z1,Z2)] of current point for both I and II phases f: np.ndarray [2,iphase] Current integration points f1 and f2 Returns ------- fun[1] - fun[2] : float Free energy difference in the next point """ fun = np.zeros(2) df = delta_f(f1new,f2new,f) coef=poly_coefficients(df,z,cov) fun = (free_energy+coef[0,:] + coef[1,:]-0.5*(coef[2,:] + coef[3,:]) - coef[4,:]) return fun[0] - fun[1] def df_first_point(f2new: float,free_energy:np.ndarray,z: np.ndarray,cov: np.ndarray,f1new: float,f: np.ndarray) -> float: """ Calculate the partial derivative of Free energy difference function (f_first_point) with respect to the new coexistence point (f2) Parameters ---------- f1new : float The next integration point f1 in the coexistence line f2new : float The next integration point f2 in the coexistence line z: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of currrent point (f1,f2) for both I and II phases cov: np.ndarray [3,iphase] Covariances [cov(z1,Z1),cov(z2,Z2),cov(z1,Z2)] of current point for both I and II phases f: np.ndarray [2,iphase] Current integration points f1 and f2 Returns ------- dfun[1] - dfun[2] : float Partial derivative of Free energy difference function """ dfun = np.zeros(2) df = delta_f(f1new,f2new,f) dfun = z[1,:] -cov[1,:]*df[1,:] - cov[2,:]*df[0,:] return dfun[0] - dfun[1] def refine_coex(free_energy:np.ndarray,z: np.ndarray,cov: np.ndarray,f: np.ndarray,ene:np.ndarray) -> 'tuple[np.ndarray,np.ndarray,np.ndarray,np.ndarray]': """ Refines the near coexistence data Parameters ---------- f1new : float The next integration point f1 in the coexistence line f2new : float The next integration point f2 in the coexistence line z: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of currrent point (f1,f2) for both I and II phases cov: np.ndarray [3,iphase] Covariances [cov(z1,Z1),cov(z2,Z2),cov(z1,Z2)] of current point for both I and II phases f: np.ndarray [2,iphase] Current integration points f1 and f2 ene: np.ndarray [iphase] Average potential energy for both I and II phases Returns ------- zsat : np.ndarray Refined conjugate varibales (z1,z2) of currrent point (f1,f2) for both I and II phases f2sat : np.ndarray Refined point (f2) for both I and II phases enesat : np.ndarray Estimation of saturated average potential energy for both I and II phases """ Npoints = np.shape(f)[1] enesat = np.zeros((Npoints,2)) zsat = np.zeros((2,Npoints,2)) f2sat = np.zeros(Npoints) free_energy_zsat = np.zeros((Npoints,2)) for i in range(Npoints): f2new0 = f[1,i,0] f1sat = f[0,i,0] f2sat[i] = optimize.newton(f_first_point, f2new0,fprime=df_first_point, args=(free_energy[i,:],z[:,i,:],cov[:,i,:],f1sat,f[:,i,:]), maxiter=500) df = delta_f(f1sat,f2sat[i],f[:,i,:]) zsat[0,i,:] = z[0,i,:] -cov[0,i,:]*df[0,:] - cov[2,i,:]*df[1,:] zsat[1,i,:] = z[1,i,:] -cov[1,i,:]*df[1,:] - cov[2,i,:]*df[0,:] coef=poly_coefficients(df,zsat[:,i,:],cov[:,i,:]) #redundancy free_energy_zsat[i,:] = (free_energy[i,:]+coef[0,:] + coef[1,:]-0.5*(coef[2,:] + coef[3,:]) - coef[4,:]) enesat[i,:] = ene[i,:] - cov[2,i,:]*df[1,:] sat_prop = dict() sat_prop["z_sat"] =zsat sat_prop["free_energy_sat"] = free_energy_zsat sat_prop["ene_sat"] = enesat sat_prop["f2_sat"] = f2sat return sat_prop#zsat,free_energy_zsat,enesat,f2sat def cal_free_energy(f_a: np.ndarray,f_b: np.ndarray,z_a: np.ndarray,z_b: np.ndarray,cov_a: np.ndarray,cov_b: np.ndarray,free_energy_a: np.ndarray) -> np.ndarray: """ Calculate the free-energy differences between the previous and current stats simulated for each phase, and hence estimate the free energy of current state Parameters ---------- f_b : np.ndarray Current integration points f1 and f2 f_b : np.ndarray Previous integration points f1 and f2 z_b: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of currrent point (f1,f2) for both I and II phases z_a: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of previous point (f1,f2) for both I and II phases cov_b: np.ndarray [3,iphase] Covariances [cov(z1,Z1),cov(z2,Z2),cov(z1,Z2)] of current point for both I and II phases cov_a: np.ndarray [3,iphase] Covariances [cov(z1,Z1),cov(z2,Z2),cov(z1,Z2)] of previous point for both I and II phases free_energy_a: np.ndarray [iphase] Free energy of phases I and II in the previous point Returns ------- free_energy_b : np.ndarray Free energy of phases I and II in the current point """ df = delta_f(f_b[0,:],f_b[1,:],f_a) coef_a=poly_coefficients(df,z_a,cov_a) coef_b=poly_coefficients(df,z_b,cov_b) free_energy_b = (free_energy_a+0.5*(coef_a[0,:]+coef_b[0,:]+ coef_a[1,:]+coef_b[1,:])+(coef_b[2,:]-coef_a[2,:]+coef_b[3,:]-coef_a[3,:])/12 +(coef_b[4,:]-coef_a[4,:])/6) return free_energy_b def calculate_first_point(f1new: float,f: np.ndarray,free_energy: np.ndarray, z: np.ndarray, cov: np.ndarray) -> float: """ Calculate the first next point in the integration in the Nf1f2 ensemble or Refines the next point in the integration in the Nf1f2 ensemble Parameters ---------- f1new : float The next integration point f1 in the coexistence line f: np.ndarray [2,iphase] Current integration points f1 and f2 free_energy: np.ndarray [iphase] Free energy of the phases z: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of previous point (f1,f2) for both I and II phases cov: np.ndarray [3,iphase] Covariances [cov(z1,Z1),cov(z2,Z2),cov(z1,Z2)] of previous point for both I and II phases Returns ------- f2new : float The next property 2 point in the integration or Refined current point(f2) """ f2new0 = first_guess_newton(free_energy[0,:],z[:,0,:],f1new,f[:,0,:]) f2new = optimize.newton(f_first_point, f2new0,fprime=df_first_point, args=(free_energy[0,:],z[:,0,:],cov[:,0,:],f1new,f[:,0,:]), maxiter=500) return f2new def f_next_point(f2new: float,free_energyb: np.ndarray,za: np.ndarray,zb: np.ndarray,covb: np.ndarray,f1new: float,fa: np.ndarray,fb: np.ndarray) -> float: """ Free energy difference function of the next point to be optimized if the Number of points is greater than 1 REF : J. Chem. Phys. 146, 134508 (2017) Parameters ---------- f1new : float The next integration point f1 in the coexistence line f2new : float The next integration point f2 in the coexistence line free_energyb: np.ndarray [iphase] Free energy of phases I and II in the current point zb: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of currrent point (f1,f2) for both I and II phases za: np.ndarray [2,iphase] Conjugate varibales (z1,z2) of previous point (f1,f2) for both I and II phases covb: np.ndarray [3,iphase] Covariances [cov(z1,Z1),cov(z2,Z2),cov(z1,Z2)] of current point for both I and II phases f_b : np.ndarray [2,iphase] Current integration points f1 and f2 f_b : np.ndarray [2,iphase] Previous integration points f1 and f2 Returns ------- fun[1] - fun[2] : float Free energy difference in the next point """ fun = np.zeros(2) dfab = delta_f(fb[0,:],fb[1,:],fa) omega1 =
<gh_stars>0 import torch import torch.nn as nn from torch.autograd import Variable import torch.autograd as autograd import os import numpy as np import random import math from util import cal_macc import tcvae.tcvae as tcvae from tcvae.tcvae import logsumexp def get_pretrain_classifier(data, opt): train_classes = data.seenclasses.numpy().tolist() test_s_data = data.test_seen_feature test_s_label = data.test_seen_label x_dim = 2048 num_classes = len(train_classes) clf = nn.Linear(x_dim, num_classes).cuda() model_file = "out/%s_pretrain_clf.pkl" % opt.dataset if os.path.exists(model_file): states = torch.load(model_file) clf.load_state_dict(states) else: epoch = 500 batch = 128 num_batch = data.ntrain // batch # train_manager = DataManager(train_data, epoch, batch) # val_manager = DataManager(test_s_data, epoch, batch) # clf = nn.Sequential(nn.Linear(x_dim, 1000), nn.ReLU(), nn.Linear(1000, num_classes)).cuda() loss_function = nn.CrossEntropyLoss() loss_function = loss_function.cuda() # set_optimizer = torch.optim.SGD(clf.parameters(), lr=0.01, momentum=0.9, dampening=0.9, weight_decay=0.001) set_optimizer = torch.optim.Adam(clf.parameters(), lr=0.001, betas=(0.5, 0.999)) max_macc = 0.0 for ep in range(epoch): clf.train() for i in range(num_batch): x, s, y = data.next_seen_batch(batch, return_label=True) y = [train_classes.index(item) for item in y] y = torch.from_numpy(np.array(y)).cuda() # s = Variable(torch.from_numpy(att_feats[y])).float().cuda() set_optimizer.zero_grad() x = nn.Dropout(p=0.2)(x) scores = clf(x) loss = loss_function(scores, y) loss.backward() set_optimizer.step() corrects = [] preds = [] clf.eval() for i in range(0, test_s_data.shape[0], batch): end_idx = min(test_s_data.shape[0], i + batch) x = test_s_data[i:end_idx] y = test_s_label[i:end_idx] y = [train_classes.index(item) for item in y] y = np.array(y) scores = clf(x) pred = scores.data.cpu().numpy().argmax(axis=1) corrects += y.tolist() preds += pred.tolist() # correct = np.array(correct) macc = cal_macc(truth=corrects, pred=preds) print("Epoch %d: Loss: %.3f Acc %.3f" % (ep, loss, macc)) if macc > max_macc: torch.save(clf.state_dict(), model_file) states = torch.load(model_file) clf.load_state_dict(states) clf.eval() for param in clf.parameters(): param.requires_grad = False return clf def sample_with_gradient(mean, log_var): batch_size = mean.shape[0] latent_size = mean.shape[1] std = torch.exp(log_var) eps = torch.randn([batch_size, latent_size]).cpu() eps = Variable(eps.cuda()) z = eps * std + mean # torch.Size([64, 312]) return z def conditional_sample(netE, netF, netG, netDec, x, y, opt, deterministic=False, z0=False): # x is feature vector # y is attribute vector if not opt.survae: means, log_var = netE(x, y) if deterministic: z = means else: # z = torch.normal(means, torch.exp(0.5 * log_var)) z = sample_with_gradient(means, 0.5 * log_var) else: z, _ = netE(x, y) if z0: z = torch.zeros(z.shape).cuda() x_gen = netG(z, c=y) if netF is not None: _ = netDec(x_gen) dec_hidden_feat = netDec.getLayersOutDet() # no detach layers feedback_out = netF(dec_hidden_feat) x_gen = netG(z, a1=opt.a2, c=y, feedback_layers=feedback_out) return x_gen def sample_using_zprior(netF, netG, netDec, y, opt, deterministic=False): syn_noise = torch.zeros(y.shape[0], opt.latent_size).cuda() syn_noise.normal_(0, 1) x_gen = netG(syn_noise, c=y) if netF is not None: _ = netDec(x_gen) dec_hidden_feat = netDec.getLayersOutDet() # no detach layers feedback_out = netF(dec_hidden_feat) x_gen = netG(syn_noise, a1=opt.a2, c=y, feedback_layers=feedback_out) return x_gen def generate_syn_feature_cf(netE, netF, netG, netDec, batch_x, classes, data, opt, n_samples=1, deterministic=False): ''' This assumes that we are using no y for encoder ''' assert not opt.encoder_use_y attributes = data.attribute batch_size = batch_x.shape[0] total_samples_per_x = len(classes) * n_samples x_input = batch_x.repeat_interleave(total_samples_per_x, dim=0) s_per_x = attributes[classes].repeat_interleave(n_samples, dim=0) s_input = s_per_x.repeat(batch_size, 1) classes_pt = torch.from_numpy(np.array(classes)).cuda() y = classes_pt.repeat_interleave(n_samples).repeat(batch_size) samples = conditional_sample(netE, netF, netG, netDec, x_input, s_input, opt, deterministic=deterministic) return samples.view(batch_size, total_samples_per_x, -1), y.view(batch_size, -1).cpu().numpy() # batch * (classes*n_samples) * x_dim def contrastive_loss(netE, netF, netG, netDec, seen_clf, batch_x, batch_l, data, opt, deterministic=False, temperature=1.0, K=30): ''' # V1: positive samples are batch_x. negative samples are generated using test classes batch_size = batch_x.shape[0] x_dim = batch_x.shape[1] train_classes = data.seenclasses.numpy().tolist() n_samples = 1 cf_x, _ = generate_syn_feature_cf(netE, netF, netG, netDec, batch_x, data.unseenclasses, data, opt, n_samples=n_samples, deterministic=deterministic) batch_l_in_seen = np.array([train_classes.index(item) for item in batch_l]) batch_l_in_seen = torch.from_numpy(batch_l_in_seen).cuda() cf_x = cf_x.view(-1, x_dim) cf_logits = seen_clf(cf_x).view(batch_size, -1, data.ntrain_class) batch_logits = seen_clf(batch_x) gt_logits = torch.gather(batch_logits, 1, batch_l_in_seen.unsqueeze(1)) t = batch_l_in_seen.unsqueeze(1).expand(-1, 50).unsqueeze(2) cf_logits_at_gt = torch.gather(cf_logits, 2, t).squeeze(2) contra_logits = torch.cat((gt_logits, cf_logits_at_gt), dim=1) label = torch.zeros(batch_size).cuda().long() contrastive_loss = nn.CrossEntropyLoss()(contra_logits / temperature, label) return contrastive_loss ''' # V2: positive samples are reconstructed batch_x. negative samples are generated using other seenclasses batch_size = batch_x.shape[0] x_dim = batch_x.shape[1] s_dim = data.attribute.shape[1] batch_s = data.attribute[batch_l] train_classes = data.seenclasses.numpy().tolist() # gen_classes = data.seenclasses.numpy().tolist() + data.unseenclasses.numpy().tolist() gen_classes = train_classes attributes = Variable(torch.zeros((batch_size, K + 1, s_dim))).cuda() x = Variable(torch.zeros((batch_size, K + 1, x_dim))).cuda() for i in range(batch_size): # First element is ground-truth attributes[i][0] = batch_s[i] # Negative samples negative_classes = [item for item in gen_classes if item != batch_l[i]] negative_classes_selected = random.sample(negative_classes, K) negative_attributes = data.attribute[negative_classes_selected, :] attributes[i, 1:] = negative_attributes x[i] = batch_x[i].unsqueeze(0).expand(K + 1, -1) xv = x.view(batch_size * (K + 1), -1) yv = attributes.view(batch_size * (K + 1), -1) dictionary = conditional_sample(netE, netF, netG, netDec, xv, yv, opt, deterministic=deterministic) # V3: using euclidean distance if opt.contra_v == 4 or opt.contra_v == 3: dictionary = dictionary.view(batch_size, K + 1, x_dim) batch_x_expanded = batch_x.unsqueeze(1).expand(batch_size, K + 1, -1) neg_dist = -((batch_x_expanded - dictionary) ** 2).mean(dim=2) * temperature # N*(K+1) label = torch.zeros(batch_size).cuda().long() contrastive_loss_euclidean = nn.CrossEntropyLoss()(neg_dist, label) # V2: using pretrain classifier if opt.contra_v == 4 or opt.contra_v == 2: batch_l_in_seen = np.array([train_classes.index(item) for item in batch_l]) batch_l_in_seen = torch.from_numpy(batch_l_in_seen).cuda() t = batch_l_in_seen.unsqueeze(1).expand(-1, K + 1).unsqueeze(2) logits = seen_clf(dictionary).view(batch_size, K + 1, -1) logits_at_gt = torch.gather(logits, 2, t).squeeze(2) * temperature # batch_size * (K+1) label = torch.zeros(batch_size).cuda().long() contrastive_loss_clf = nn.CrossEntropyLoss()(logits_at_gt, label) if opt.contra_v == 2: return contrastive_loss_clf if opt.contra_v == 3: return contrastive_loss_euclidean if opt.contra_v == 4: # V4: using pretrain classifier as well as euclidean distance return contrastive_loss_clf + contrastive_loss_euclidean def mse_loss(X, x_recon): # x_recon = model.conditional_sample(X, S, deterministic=deterministic) mse_loss_val = nn.MSELoss()(x_recon, X) return mse_loss_val # TCVAE def get_tcvae_kl_loss(mean, log_var, z, beta, opt): batch_size = mean.shape[0] z_dim = mean.shape[1] log_var *= 0.5 # this code base scales the output of parameter network prior_parameters = torch.zeros(batch_size, z_dim, 2).cuda() z_params = torch.cat((mean.unsqueeze(2), log_var.unsqueeze(2)), dim=2) prior_dist = tcvae.Normal() q_dist = tcvae.Normal() zs = z logpz = prior_dist.log_density(zs, params=prior_parameters).view(batch_size, -1).sum(1) logqz_condx = q_dist.log_density(zs, params=z_params).view(batch_size, -1).sum(1) _logqz = q_dist.log_density( zs.view(batch_size, 1, z_dim), z_params.view(1, batch_size, z_dim, q_dist.nparams) ) logqz_prodmarginals = (logsumexp(_logqz, dim=1, keepdim=False) - math.log(batch_size * opt.ntrain)).sum(1) logqz = (logsumexp(_logqz.sum(2), dim=1, keepdim=False) - math.log(batch_size * opt.ntrain)) kld = (logqz_condx - logqz) + beta * (logqz - logqz_prodmarginals) + (logqz_prodmarginals - logpz) return kld.mean() def loss_fn(recon_x, x, mean, log_var, opt, z, beta=1.0): if opt.recon == "bce": BCE = torch.nn.functional.binary_cross_entropy(recon_x + 1e-12, x.detach(), size_average=False) BCE = BCE.sum() / x.size(0) elif opt.recon == "l2": BCE = torch.sum(torch.pow(recon_x - x.detach(), 2), 1).mean() elif opt.recon == "l1": BCE = torch.sum(torch.abs(recon_x - x.detach()), 1).mean() if not opt.z_disentangle: KLD = -0.5 * torch.sum(1 + log_var - mean.pow(2) - log_var.exp()) / x.size(0) elif not opt.zd_tcvae: KLD = -0.5 * beta * torch.sum(1 + log_var - mean.pow(2) - log_var.exp()) / x.size(0) else: KLD = get_tcvae_kl_loss(mean, log_var, z, beta, opt) return (BCE + KLD) def sample(data, opt, return_label): return data.next_seen_batch(opt.batch_size, return_label) # input_res.copy_(batch_feature) # input_att.copy_(batch_att) def WeightedL1(pred, gt): wt = (pred - gt).pow(2) wt /= wt.sum(1).sqrt().unsqueeze(1).expand(wt.size(0), wt.size(1)) loss = wt * (pred - gt).abs() return loss.sum() / loss.size(0) def generate_syn_feature(generator, classes, attribute, num, netF=None, netDec=None, opt=None): nclass = classes.size(0) syn_feature = torch.FloatTensor(nclass * num, opt.resSize).cuda() syn_label = torch.LongTensor(nclass * num) syn_att = torch.FloatTensor(num, opt.attSize) if opt.survae: syn_noise = torch.FloatTensor(num, 100) else: syn_noise = torch.FloatTensor(num, opt.nz) if opt.cuda: syn_att = syn_att.cuda() syn_noise = syn_noise.cuda() for i in range(nclass): iclass = classes[i] iclass_att = attribute[iclass] syn_att.copy_(iclass_att.repeat(num, 1)) syn_noise.normal_(0, 1) syn_noisev = Variable(syn_noise) syn_attv = Variable(syn_att) fake = generator(syn_noisev, c=syn_attv) if netF is not None: dec_out = netDec(fake) # only to call the forward function of decoder dec_hidden_feat = netDec.getLayersOutDet() # no detach layers feedback_out = netF(dec_hidden_feat) fake = generator(syn_noisev, a1=opt.a2, c=syn_attv, feedback_layers=feedback_out) output = fake syn_feature.narrow(0, i * num, num).copy_(output.data) syn_label.narrow(0, i * num, num).fill_(iclass) return syn_feature, syn_label def calc_gradient_penalty(netD, real_data, fake_data, input_att, opt): alpha = torch.rand(opt.batch_size, 1) alpha = alpha.expand(real_data.size()) if opt.cuda: alpha = alpha.cuda() interpolates = alpha * real_data + ((1 - alpha) * fake_data) if opt.cuda: interpolates = interpolates.cuda() interpolates = Variable(interpolates, requires_grad=True) disc_interpolates = netD(interpolates, Variable(input_att)) ones = torch.ones(disc_interpolates.size()) if opt.cuda: ones = ones.cuda() gradients = autograd.grad(outputs=disc_interpolates, inputs=interpolates, grad_outputs=ones, create_graph=True, retain_graph=True, only_inputs=True)[0] gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() * opt.lambda1 return gradient_penalty def compute_dec_out(netDec, test_X, new_size): start = 0 ntest = test_X.size()[0] new_test_X = torch.zeros(ntest, new_size).cuda() batch_size = 128 for i in range(0, ntest, batch_size): end = min(ntest, start
raise NotImplementedError('Method not implemented!') def DicomImageWidth(self, request, context): """DicomImage messages """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomImageHeight(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomImageSOPInstanceUID(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomImageCompletePath(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomImageDate(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomImageNumberOfFrames(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomImageModality(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomImageSeries(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomImageSliceLocation(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomImageInstanceNumber(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesPaths(self, request, context): """DicomSeries messages """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesPreviousSeries(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesNextSeries(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesSortedImages(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesStudy(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesImages(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesSeriesInstanceUID(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesSeriesSOPClassUID(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesSeriesDescription(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesModality(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesName(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomSeriesDate(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyPaths(self, request, context): """DicomStudy messages """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyImages(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyModalities(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyNoFiles(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyRawNoFiles(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyNoFilesExcludingMultiFrames(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyNumberOfImages(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudySeries(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyName(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyDate(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyDateAdded(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyDateOfBirth(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyInstitutionName(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyModality(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyPatientID(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyPatientUID(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyPatientSex(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyPerformingPhysician(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyReferringPhysician(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyStudyInstanceUID(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DicomStudyStudyName(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_OsiriXServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'OsirixCurrentBrowser': grpc.unary_unary_rpc_method_handler( servicer.OsirixCurrentBrowser, request_deserializer=utilities__pb2.Empty.FromString, response_serializer=osirix__pb2.OsirixCurrentBrowserResponse.SerializeToString, ), 'OsirixFrontmostViewer': grpc.unary_unary_rpc_method_handler( servicer.OsirixFrontmostViewer, request_deserializer=utilities__pb2.Empty.FromString, response_serializer=osirix__pb2.OsirixFrontmostViewerResponse.SerializeToString, ), 'OsirixDisplayed2DViewers': grpc.unary_unary_rpc_method_handler( servicer.OsirixDisplayed2DViewers, request_deserializer=utilities__pb2.Empty.FromString, response_serializer=osirix__pb2.OsirixDisplayed2DViewersResponse.SerializeToString, ), 'OsirixFrontmostVRController': grpc.unary_unary_rpc_method_handler( servicer.OsirixFrontmostVRController, request_deserializer=utilities__pb2.Empty.FromString, response_serializer=osirix__pb2.OsirixFrontmostVRControllerResponse.SerializeToString, ), 'OsirixDisplayedVRControllers': grpc.unary_unary_rpc_method_handler( servicer.OsirixDisplayedVRControllers, request_deserializer=utilities__pb2.Empty.FromString, response_serializer=osirix__pb2.OsirixDisplayedVRControllersResponse.SerializeToString, ), 'ROIFlipHorizontally': grpc.unary_unary_rpc_method_handler( servicer.ROIFlipHorizontally, request_deserializer=types__pb2.ROI.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIFlipVertically': grpc.unary_unary_rpc_method_handler( servicer.ROIFlipVertically, request_deserializer=types__pb2.ROI.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIArea': grpc.unary_unary_rpc_method_handler( servicer.ROIArea, request_deserializer=types__pb2.ROI.FromString, response_serializer=roi__pb2.ROIAreaResponse.SerializeToString, ), 'ROICentroid': grpc.unary_unary_rpc_method_handler( servicer.ROICentroid, request_deserializer=types__pb2.ROI.FromString, response_serializer=roi__pb2.ROICentroidResponse.SerializeToString, ), 'ROIRotate': grpc.unary_unary_rpc_method_handler( servicer.ROIRotate, request_deserializer=roi__pb2.ROIRotateRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIMove': grpc.unary_unary_rpc_method_handler( servicer.ROIMove, request_deserializer=roi__pb2.ROIMoveRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIPix': grpc.unary_unary_rpc_method_handler( servicer.ROIPix, request_deserializer=types__pb2.ROI.FromString, response_serializer=roi__pb2.ROIPixResponse.SerializeToString, ), 'ROIName': grpc.unary_unary_rpc_method_handler( servicer.ROIName, request_deserializer=types__pb2.ROI.FromString, response_serializer=roi__pb2.ROINameResponse.SerializeToString, ), 'ROISetName': grpc.unary_unary_rpc_method_handler( servicer.ROISetName, request_deserializer=roi__pb2.ROISetNameRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIColor': grpc.unary_unary_rpc_method_handler( servicer.ROIColor, request_deserializer=types__pb2.ROI.FromString, response_serializer=roi__pb2.ROIColorResponse.SerializeToString, ), 'ROISetColor': grpc.unary_unary_rpc_method_handler( servicer.ROISetColor, request_deserializer=roi__pb2.ROISetColorRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIOpacity': grpc.unary_unary_rpc_method_handler( servicer.ROIOpacity, request_deserializer=types__pb2.ROI.FromString, response_serializer=roi__pb2.ROIOpacityResponse.SerializeToString, ), 'ROISetOpacity': grpc.unary_unary_rpc_method_handler( servicer.ROISetOpacity, request_deserializer=roi__pb2.ROISetOpacityRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIThickness': grpc.unary_unary_rpc_method_handler( servicer.ROIThickness, request_deserializer=types__pb2.ROI.FromString, response_serializer=roi__pb2.ROIThicknessResponse.SerializeToString, ), 'ROISetThickness': grpc.unary_unary_rpc_method_handler( servicer.ROISetThickness, request_deserializer=roi__pb2.ROISetThicknessRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIPoints': grpc.unary_unary_rpc_method_handler( servicer.ROIPoints, request_deserializer=types__pb2.ROI.FromString, response_serializer=roi__pb2.ROIPointsResponse.SerializeToString, ), 'ROISetPoints': grpc.unary_unary_rpc_method_handler( servicer.ROISetPoints, request_deserializer=roi__pb2.ROISetPointsRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIVolumeTexture': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeTexture, request_deserializer=types__pb2.ROIVolume.FromString, response_serializer=roivolume__pb2.ROIVolumeTextureResponse.SerializeToString, ), 'ROIVolumeSetTexture': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeSetTexture, request_deserializer=roivolume__pb2.ROIVolumeSetTextureRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIVolumeVolume': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeVolume, request_deserializer=types__pb2.ROIVolume.FromString, response_serializer=roivolume__pb2.ROIVolumeVolumeResponse.SerializeToString, ), 'ROIVolumeColor': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeColor, request_deserializer=types__pb2.ROIVolume.FromString, response_serializer=roivolume__pb2.ROIVolumeColorResponse.SerializeToString, ), 'ROIVolumeSetColor': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeSetColor, request_deserializer=roivolume__pb2.ROIVolumeSetColorRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIVolumeOpacity': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeOpacity, request_deserializer=types__pb2.ROIVolume.FromString, response_serializer=roivolume__pb2.ROIVolumeOpacityResponse.SerializeToString, ), 'ROIVolumeSetOpacity': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeSetOpacity, request_deserializer=roivolume__pb2.ROIVolumeSetOpacityRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIVolumeFactor': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeFactor, request_deserializer=types__pb2.ROIVolume.FromString, response_serializer=roivolume__pb2.ROIVolumeFactorResponse.SerializeToString, ), 'ROIVolumeSetFactor': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeSetFactor, request_deserializer=roivolume__pb2.ROIVolumeSetFactorRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIVolumeVisible': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeVisible, request_deserializer=types__pb2.ROIVolume.FromString, response_serializer=roivolume__pb2.ROIVolumeVisibleResponse.SerializeToString, ), 'ROIVolumeSetVisible': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeSetVisible, request_deserializer=roivolume__pb2.ROIVolumeSetVisibleRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ROIVolumeName': grpc.unary_unary_rpc_method_handler( servicer.ROIVolumeName, request_deserializer=types__pb2.ROIVolume.FromString, response_serializer=roivolume__pb2.ROIVolumeNameResponse.SerializeToString, ), 'DCMPixConvertToRGB': grpc.unary_unary_rpc_method_handler( servicer.DCMPixConvertToRGB, request_deserializer=dcmpix__pb2.DCMPixConvertToRGBRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'DCMPixConvertToBW': grpc.unary_unary_rpc_method_handler( servicer.DCMPixConvertToBW, request_deserializer=dcmpix__pb2.DCMPixConvertToBWRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'DCMPixIsRGB': grpc.unary_unary_rpc_method_handler( servicer.DCMPixIsRGB, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixIsRGBResponse.SerializeToString, ), 'DCMPixComputeROI': grpc.unary_unary_rpc_method_handler( servicer.DCMPixComputeROI, request_deserializer=dcmpix__pb2.DCMPixComputeROIRequest.FromString, response_serializer=dcmpix__pb2.DCMPixComputeROIResponse.SerializeToString, ), 'DCMPixROIValues': grpc.unary_unary_rpc_method_handler( servicer.DCMPixROIValues, request_deserializer=dcmpix__pb2.DCMPixROIValuesRequest.FromString, response_serializer=dcmpix__pb2.DCMPixROIValuesResponse.SerializeToString, ), 'DCMPixShape': grpc.unary_unary_rpc_method_handler( servicer.DCMPixShape, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixShapeResponse.SerializeToString, ), 'DCMPixSpacing': grpc.unary_unary_rpc_method_handler( servicer.DCMPixSpacing, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixSpacingResponse.SerializeToString, ), 'DCMPixOrigin': grpc.unary_unary_rpc_method_handler( servicer.DCMPixOrigin, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixOriginResponse.SerializeToString, ), 'DCMPixOrientation': grpc.unary_unary_rpc_method_handler( servicer.DCMPixOrientation, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixOrientationResponse.SerializeToString, ), 'DCMPixSliceLocation': grpc.unary_unary_rpc_method_handler( servicer.DCMPixSliceLocation, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixSliceLocationResponse.SerializeToString, ), 'DCMPixSourceFile': grpc.unary_unary_rpc_method_handler( servicer.DCMPixSourceFile, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixSourceFileResponse.SerializeToString, ), 'DCMPixImage': grpc.unary_unary_rpc_method_handler( servicer.DCMPixImage, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixImageResponse.SerializeToString, ), 'DCMPixSetImage': grpc.unary_unary_rpc_method_handler( servicer.DCMPixSetImage, request_deserializer=dcmpix__pb2.DCMPixSetImageRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'DCMPixGetMapFromROI': grpc.unary_unary_rpc_method_handler( servicer.DCMPixGetMapFromROI, request_deserializer=dcmpix__pb2.DCMPixGetMapFromROIRequest.FromString, response_serializer=dcmpix__pb2.DCMPixGetMapFromROIResponse.SerializeToString, ), 'DCMPixDicomImage': grpc.unary_unary_rpc_method_handler( servicer.DCMPixDicomImage, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixDicomImageResponse.SerializeToString, ), 'DCMPixDicomSeries': grpc.unary_unary_rpc_method_handler( servicer.DCMPixDicomSeries, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixDicomSeriesResponse.SerializeToString, ), 'DCMPixDicomStudy': grpc.unary_unary_rpc_method_handler( servicer.DCMPixDicomStudy, request_deserializer=types__pb2.DCMPix.FromString, response_serializer=dcmpix__pb2.DCMPixDicomStudyResponse.SerializeToString, ), 'VRControllerViewer2D': grpc.unary_unary_rpc_method_handler( servicer.VRControllerViewer2D, request_deserializer=types__pb2.VRController.FromString, response_serializer=vrcontroller__pb2.VRControllerViewer2DResponse.SerializeToString, ), 'VRControllerBlendingController': grpc.unary_unary_rpc_method_handler( servicer.VRControllerBlendingController, request_deserializer=types__pb2.VRController.FromString, response_serializer=vrcontroller__pb2.VRControllerBlendingControllerResponse.SerializeToString, ), 'VRControllerStyle': grpc.unary_unary_rpc_method_handler( servicer.VRControllerStyle, request_deserializer=types__pb2.VRController.FromString, response_serializer=vrcontroller__pb2.VRControllerStyleResponse.SerializeToString, ), 'VRControllerTitle': grpc.unary_unary_rpc_method_handler( servicer.VRControllerTitle, request_deserializer=types__pb2.VRController.FromString, response_serializer=vrcontroller__pb2.VRControllerTitleResponse.SerializeToString, ), 'VRControllerROIVolumes': grpc.unary_unary_rpc_method_handler( servicer.VRControllerROIVolumes, request_deserializer=types__pb2.VRController.FromString, response_serializer=vrcontroller__pb2.VRControllerROIVolumesResponse.SerializeToString, ), 'VRControllerRenderingMode': grpc.unary_unary_rpc_method_handler( servicer.VRControllerRenderingMode, request_deserializer=types__pb2.VRController.FromString, response_serializer=vrcontroller__pb2.VRControllerRenderingModeResponse.SerializeToString, ), 'VRControllerSetRenderingMode': grpc.unary_unary_rpc_method_handler( servicer.VRControllerSetRenderingMode, request_deserializer=vrcontroller__pb2.VRControllerSetRenderingModeRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'VRControllerWLWW': grpc.unary_unary_rpc_method_handler( servicer.VRControllerWLWW, request_deserializer=types__pb2.VRController.FromString, response_serializer=vrcontroller__pb2.VRControllerWLWWResponse.SerializeToString, ), 'VRControllerSetWLWW': grpc.unary_unary_rpc_method_handler( servicer.VRControllerSetWLWW, request_deserializer=vrcontroller__pb2.VRControllerSetWLWWRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ViewerControllerCloseViewer': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerCloseViewer, request_deserializer=types__pb2.ViewerController.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ViewerControllerPixList': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerPixList, request_deserializer=viewercontroller__pb2.ViewerControllerPixListRequest.FromString, response_serializer=viewercontroller__pb2.ViewerControllerPixListResponse.SerializeToString, ), 'ViewerControllerNeedsDisplayUpdate': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerNeedsDisplayUpdate, request_deserializer=types__pb2.ViewerController.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ViewerControllerROIList': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerROIList, request_deserializer=viewercontroller__pb2.ViewerControllerROIListRequest.FromString, response_serializer=viewercontroller__pb2.ViewerControllerROIListResponse.SerializeToString, ), 'ViewerControllerNewROI': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerNewROI, request_deserializer=viewercontroller__pb2.ViewerControllerNewROIRequest.FromString, response_serializer=viewercontroller__pb2.ViewerControllerNewROIResponse.SerializeToString, ), 'ViewerControllerCurDCM': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerCurDCM, request_deserializer=types__pb2.ViewerController.FromString, response_serializer=viewercontroller__pb2.ViewerControllerCurDCMResponse.SerializeToString, ), 'ViewerControllerROIsWithName': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerROIsWithName, request_deserializer=viewercontroller__pb2.ViewerControllerROIsWithNameRequest.FromString, response_serializer=viewercontroller__pb2.ViewerControllerROIsWithNameResponse.SerializeToString, ), 'ViewerControllerSelectedROIs': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerSelectedROIs, request_deserializer=types__pb2.ViewerController.FromString, response_serializer=viewercontroller__pb2.ViewerControllerSelectedROIsResponse.SerializeToString, ), 'ViewerControllerIsDataVolumic': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerIsDataVolumic, request_deserializer=viewercontroller__pb2.ViewerControllerIsDataVolumicRequest.FromString, response_serializer=viewercontroller__pb2.ViewerControllerIsDataVolumicResponse.SerializeToString, ), 'ViewerControllerCopyViewerWindow': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerCopyViewerWindow, request_deserializer=viewercontroller__pb2.ViewerControllerCopyViewerWindowRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ViewerControllerResampleViewerController': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerResampleViewerController, request_deserializer=viewercontroller__pb2.ViewerControllerResampleViewerControllerRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ViewerControllerBlendingController': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerBlendingController, request_deserializer=types__pb2.ViewerController.FromString, response_serializer=viewercontroller__pb2.ViewerControllerBlendingControllerResponse.SerializeToString, ), 'ViewerControllerVRControllers': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerVRControllers, request_deserializer=types__pb2.ViewerController.FromString, response_serializer=viewercontroller__pb2.ViewerControllerVRControllersResponse.SerializeToString, ), 'ViewerControllerTitle': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerTitle, request_deserializer=types__pb2.ViewerController.FromString, response_serializer=viewercontroller__pb2.ViewerControllerTitleResponse.SerializeToString, ), 'ViewerControllerModality': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerModality, request_deserializer=types__pb2.ViewerController.FromString, response_serializer=viewercontroller__pb2.ViewerControllerModalityResponse.SerializeToString, ), 'ViewerControllerMovieIdx': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerMovieIdx, request_deserializer=types__pb2.ViewerController.FromString, response_serializer=viewercontroller__pb2.ViewerControllerMovieIdxResponse.SerializeToString, ), 'ViewerControllerSetMovieIdx': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerSetMovieIdx, request_deserializer=viewercontroller__pb2.ViewerControllerSetMovieIdxRequest.FromString, response_serializer=utilities__pb2.Response.SerializeToString, ), 'ViewerControllerMaxMovieIdx': grpc.unary_unary_rpc_method_handler( servicer.ViewerControllerMaxMovieIdx, request_deserializer=types__pb2.ViewerController.FromString,
<filename>pyupdater/vendor/PyInstaller/hooks/hookutils.py #----------------------------------------------------------------------------- # Copyright (c) 2013, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import glob import os import os.path import sys import PyInstaller import PyInstaller.compat as compat from PyInstaller.compat import is_darwin, is_win from PyInstaller.utils import misc import PyInstaller.log as logging logger = logging.getLogger(__name__) # All these extension represent Python modules or extension modules PY_EXECUTABLE_SUFFIXES = set(['.py', '.pyc', '.pyd', '.pyo', '.so']) # these suffixes represent python extension modules try: from importlib.machinery import EXTENSION_SUFFIXES as PY_EXTENSION_SUFFIXES except ImportError: import imp PY_EXTENSION_SUFFIXES = set([f[0] for f in imp.get_suffixes() if f[2] == imp.C_EXTENSION]) # These extensions represent Python executables and should therefore be # ignored when collecting data files. PY_IGNORE_EXTENSIONS = set(['.py', '.pyc', '.pyd', '.pyo', '.so', 'dylib']) # Some hooks need to save some values. This is the dict that can be used for # that. # # When running tests this variable should be reset before every test. # # For example the 'wx' module needs variable 'wxpubsub'. This tells PyInstaller # which protocol of the wx module should be bundled. hook_variables = {} def __exec_python_cmd(cmd): """ Executes an externally spawned Python interpreter and returns anything that was emitted in the standard output as a single string. """ # Prepend PYTHONPATH with pathex pp = os.pathsep.join(PyInstaller.__pathex__) old_pp = compat.getenv('PYTHONPATH') if old_pp: pp = os.pathsep.join([old_pp, pp]) compat.setenv("PYTHONPATH", pp) try: try: txt = compat.exec_python(*cmd) except OSError, e: raise SystemExit("Execution failed: %s" % e) finally: if old_pp is not None: compat.setenv("PYTHONPATH", old_pp) else: compat.unsetenv("PYTHONPATH") return txt.strip() def exec_statement(statement): """Executes a Python statement in an externally spawned interpreter, and returns anything that was emitted in the standard output as a single string. """ cmd = ['-c', statement] return __exec_python_cmd(cmd) def exec_script(script_filename, *args): """ Executes a Python script in an externally spawned interpreter, and returns anything that was emitted in the standard output as a single string. To prevent missuse, the script passed to hookutils.exec-script must be located in the `hooks/utils` directory. """ script_filename = os.path.join('utils', os.path.basename(script_filename)) script_filename = os.path.join(os.path.dirname(__file__), script_filename) if not os.path.exists(script_filename): raise SystemError("To prevent missuse, the script passed to " "hookutils.exec-script must be located in " "the `hooks/utils` directory.") # Scripts might be importing some modules. Add PyInstaller code to pathex. pyinstaller_root_dir = os.path.dirname(os.path.abspath(PyInstaller.__path__[0])) PyInstaller.__pathex__.append(pyinstaller_root_dir) cmd = [script_filename] cmd.extend(args) return __exec_python_cmd(cmd) def eval_statement(statement): txt = exec_statement(statement).strip() if not txt: # return an empty string which is "not true" but iterable return '' return eval(txt) def eval_script(scriptfilename, *args): txt = exec_script(scriptfilename, *args).strip() if not txt: # return an empty string which is "not true" but iterable return '' return eval(txt) def get_pyextension_imports(modname): """ Return list of modules required by binary (C/C++) Python extension. Python extension files ends with .so (Unix) or .pyd (Windows). It's almost impossible to analyze binary extension and its dependencies. Module cannot be imported directly. Let's at least try import it in a subprocess and get the difference in module list from sys.modules. This function could be used for 'hiddenimports' in PyInstaller hooks files. """ statement = """ import sys # Importing distutils filters common modules, especiall in virtualenv. import distutils original_modlist = sys.modules.keys() # When importing this module - sys.modules gets updated. import %(modname)s all_modlist = sys.modules.keys() diff = set(all_modlist) - set(original_modlist) # Module list contain original modname. We do not need it there. diff.discard('%(modname)s') # Print module list to stdout. print(list(diff)) """ % {'modname': modname} module_imports = eval_statement(statement) if not module_imports: logger.error('Cannot find imports for module %s' % modname) return [] # Means no imports found or looking for imports failed. #module_imports = filter(lambda x: not x.startswith('distutils'), module_imports) return module_imports def qt4_plugins_dir(): qt4_plugin_dirs = eval_statement( "from PyQt4.QtCore import QCoreApplication;" "app=QCoreApplication([]);" "print(map(unicode,app.libraryPaths()))") if not qt4_plugin_dirs: logger.error("Cannot find PyQt4 plugin directories") return "" for d in qt4_plugin_dirs: if os.path.isdir(d): return str(d) # must be 8-bit chars for one-file builds logger.error("Cannot find existing PyQt4 plugin directory") return "" def qt4_phonon_plugins_dir(): qt4_plugin_dirs = eval_statement( "from PyQt4.QtGui import QApplication;" "app=QApplication([]); app.setApplicationName('pyinstaller');" "from PyQt4.phonon import Phonon;" "v=Phonon.VideoPlayer(Phonon.VideoCategory);" "print(map(unicode,app.libraryPaths()))") if not qt4_plugin_dirs: logger.error("Cannot find PyQt4 phonon plugin directories") return "" for d in qt4_plugin_dirs: if os.path.isdir(d): return str(d) # must be 8-bit chars for one-file builds logger.error("Cannot find existing PyQt4 phonon plugin directory") return "" def qt4_plugins_binaries(plugin_type): """Return list of dynamic libraries formatted for mod.pyinstaller_binaries.""" binaries = [] pdir = qt4_plugins_dir() files = misc.dlls_in_dir(os.path.join(pdir, plugin_type)) # Windows: # # dlls_in_dir() grabs all files ending with *.dll, *.so and *.dylib in a certain # directory. On Windows this would grab debug copies of Qt 4 plugins, which then # causes PyInstaller to add a dependency on the Debug CRT __in addition__ to the # release CRT. # # Since debug copies of Qt4 plugins end with "d4.dll" we filter them out of the # list. # if is_win: files = [f for f in files if not f.endswith("d4.dll")] for f in files: binaries.append(( # TODO fix this hook to use hook-name.py attribute 'binaries'. os.path.join('qt4_plugins', plugin_type, os.path.basename(f)), f, 'BINARY')) return binaries def qt4_menu_nib_dir(): """Return path to Qt resource dir qt_menu.nib. OSX only""" menu_dir = '' # Detect MacPorts prefix (usually /opt/local). # Suppose that PyInstaller is using python from macports. macports_prefix = sys.executable.split('/Library')[0] # list of directories where to look for qt_menu.nib dirs = [] # Look into user-specified directory, just in case Qt4 is not installed # in a standard location if 'QTDIR' in os.environ: dirs += [ os.path.join(os.environ['QTDIR'], "QtGui.framework/Versions/4/Resources"), os.path.join(os.environ['QTDIR'], "lib", "QtGui.framework/Versions/4/Resources"), ] # If PyQt4 is built against Qt5 look for the qt_menu.nib in a user # specified location, if it exists. if 'QT5DIR' in os.environ: dirs.append(os.path.join(os.environ['QT5DIR'], "src", "plugins", "platforms", "cocoa")) dirs += [ # Qt4 from MacPorts not compiled as framework. os.path.join(macports_prefix, 'lib', 'Resources'), # Qt4 from MacPorts compiled as framework. os.path.join(macports_prefix, 'libexec', 'qt4-mac', 'lib', 'QtGui.framework', 'Versions', '4', 'Resources'), # Qt4 installed into default location. '/Library/Frameworks/QtGui.framework/Resources', '/Library/Frameworks/QtGui.framework/Versions/4/Resources', '/Library/Frameworks/QtGui.Framework/Versions/Current/Resources', ] # Qt from Homebrew homebrewqtpath = get_homebrew_path('qt') if homebrewqtpath: dirs.append( os.path.join(homebrewqtpath,'lib','QtGui.framework','Versions','4','Resources') ) # Check directory existence for d in dirs: d = os.path.join(d, 'qt_menu.nib') if os.path.exists(d): menu_dir = d break if not menu_dir: logger.error('Cannot find qt_menu.nib directory') return menu_dir def qt5_plugins_dir(): if 'QT_PLUGIN_PATH' in os.environ and os.path.isdir(os.environ['QT_PLUGIN_PATH']): return str(os.environ['QT_PLUGIN_PATH']) qt5_plugin_dirs = eval_statement( "from PyQt5.QtCore import QCoreApplication;" "app=QCoreApplication([]);" "print(map(unicode,app.libraryPaths()))") if not qt5_plugin_dirs: logger.error("Cannot find PyQt5 plugin directories") return "" for d in qt5_plugin_dirs: if os.path.isdir(d): return str(d) # must be 8-bit chars for one-file builds logger.error("Cannot find existing PyQt5 plugin directory") return "" def qt5_phonon_plugins_dir(): qt5_plugin_dirs = eval_statement( "from PyQt5.QtGui import QApplication;" "app=QApplication([]); app.setApplicationName('pyinstaller');" "from PyQt5.phonon import Phonon;" "v=Phonon.VideoPlayer(Phonon.VideoCategory);" "print(map(unicode,app.libraryPaths()))") if not qt5_plugin_dirs: logger.error("Cannot find PyQt5 phonon plugin directories") return "" for d in qt5_plugin_dirs: if os.path.isdir(d): return str(d) # must be 8-bit chars for one-file builds logger.error("Cannot find existing PyQt5 phonon plugin directory") return "" def qt5_plugins_binaries(plugin_type): """Return list of dynamic libraries formatted for mod.pyinstaller_binaries.""" binaries = [] pdir = qt5_plugins_dir() files = misc.dlls_in_dir(os.path.join(pdir, plugin_type)) for f in files: binaries.append(( os.path.join('qt5_plugins', plugin_type, os.path.basename(f)), f, 'BINARY')) return binaries def qt5_menu_nib_dir(): """Return path to Qt resource dir qt_menu.nib. OSX only""" menu_dir = '' # If the QT5DIR env var is set then look there first. It should be set to the # qtbase dir in the Qt5 distribution. dirs = [] if 'QT5DIR' in os.environ: dirs.append(os.path.join(os.environ['QT5DIR'], "src", "plugins", "platforms", "cocoa")) dirs.append(os.path.join(os.environ['QT5DIR'], "src", "qtbase", "src", "plugins", "platforms", "cocoa")) # As of the time of writing macports doesn't yet support Qt5. So this is # just modified from the Qt4 version. # FIXME: update this when MacPorts supports Qt5 # Detect MacPorts prefix (usually /opt/local). # Suppose that PyInstaller is using python from macports. macports_prefix = sys.executable.split('/Library')[0] # list of directories where to look for qt_menu.nib dirs.extend( [ # Qt5 from MacPorts not compiled as framework. os.path.join(macports_prefix, 'lib', 'Resources'), # Qt5 from MacPorts compiled as framework. os.path.join(macports_prefix, 'libexec', 'qt5-mac', 'lib', 'QtGui.framework', 'Versions', '5', 'Resources'), # Qt5 installed into default location. '/Library/Frameworks/QtGui.framework/Resources', '/Library/Frameworks/QtGui.framework/Versions/5/Resources', '/Library/Frameworks/QtGui.Framework/Versions/Current/Resources', ]) # Qt5 from Homebrew homebrewqtpath = get_homebrew_path('qt5') if homebrewqtpath: dirs.append( os.path.join(homebrewqtpath,'src','qtbase','src','plugins','platforms','cocoa') ) # Check directory existence for d in dirs: d = os.path.join(d, 'qt_menu.nib') if os.path.exists(d): menu_dir = d break if not menu_dir: logger.error('Cannot find qt_menu.nib directory') return menu_dir def
<filename>xrd_simulator/polycrystal.py """The polycrystal module is used to represent a polycrystalline sample. The :class:`xrd_simulator.polycrystal.Polycrystal` object holds the function :func:`xrd_simulator.polycrystal.Polycrystal.diffract` which may be used to compute diffraction. To move the sample spatially, the function :func:`xrd_simulator.polycrystal.Polycrystal.transform` can be used. Here is a minimal example of how to instantiate a polycrystal object and save it to disc: Examples: .. literalinclude:: examples/example_init_polycrystal.py Below follows a detailed description of the polycrystal class attributes and functions. """ import numpy as np import dill import copy from xfab import tools from xrd_simulator.scattering_unit import ScatteringUnit from xrd_simulator import utils, laue class Polycrystal(): """Represents a multi-phase polycrystal as a tetrahedral mesh where each element can be a single crystal The polycrystal is created in laboratory coordinates. At instantiation it is assumed that the sample and lab coordinate systems are aligned. Args: mesh (:obj:`xrd_simulator.mesh.TetraMesh`): Object representing a tetrahedral mesh which defines the geometry of the sample. (At instantiation it is assumed that the sample and lab coordinate systems are aligned.) orientation (:obj:`numpy array`): Per element orientation matrices (sometimes known by the capital letter U), (``shape=(N,3,3)``) or (``shape=(3,3)``) if the orientation is the same for all elements. The orientation matrix maps from crystal coordinates to sample coordinates. strain (:obj:`numpy array`): Per element strain tensor, in lab coordinates, (``shape=(N,3,3)``) or (``shape=(3,3)``) if the strain is the same for all elements elements. phases (:obj:`xrd_simulator.phase.Phase` or :obj:`list` of :obj:`xrd_simulator.phase.Phase`): Phase of the polycrystal, or for multiphase samples, a list of all phases present in the polycrystal. element_phase_map (:obj:`numpy array`): Index of phase that elements belong to such that phases[element_phase_map[i]] gives the xrd_simulator.phase.Phase object of element number i. None if the sample is composed of a single phase. (Defaults to None) Attributes: mesh_lab (:obj:`xrd_simulator.mesh.TetraMesh`): Object representing a tetrahedral mesh which defines the geometry of the sample in a fixed lab frame coordinate system. This quantity is updated when the sample transforms. mesh_sample (:obj:`xrd_simulator.mesh.TetraMesh`): Object representing a tetrahedral mesh which defines the geometry of the sample in a sample coordinate system. This quantity is not updated when the sample transforms. orientation_lab (:obj:`numpy array`): Per element orientation matrices mapping from the crystal to the lab coordinate system, this quantity is updated when the sample transforms. (``shape=(N,3,3)``). orientation_sample (:obj:`numpy array`): Per element orientation matrices mapping from the crystal to the sample coordinate system., this quantity is not updated when the sample transforms. (``shape=(N,3,3)``). strain_lab (:obj:`numpy array`): Per element strain tensor in a fixed lab frame coordinate system, this quantity is updated when the sample transforms. (``shape=(N,3,3)``). strain_sample (:obj:`numpy array`): Per element strain tensor in a sample coordinate system., this quantity is not updated when the sample transforms. (``shape=(N,3,3)``). phases (:obj:`list` of :obj:`xrd_simulator.phase.Phase`): List of all unique phases present in the polycrystal. element_phase_map (:obj:`numpy array`): Index of phase that elements belong to such that phases[element_phase_map[i]] gives the xrd_simulator.phase.Phase object of element number i. """ def __init__( self, mesh, orientation, strain, phases, element_phase_map=None): self.orientation_lab = self._instantiate_orientation(orientation, mesh) self.strain_lab = self._instantiate_strain(strain, mesh) self.element_phase_map, self.phases = self._instantiate_phase(phases, element_phase_map, mesh) self._eB = self._instantiate_eB(self.orientation_lab, self.strain_lab, self.phases, self.element_phase_map, mesh) # Assuming sample and lab frames to be aligned at instantiation. self.mesh_lab = copy.deepcopy(mesh) self.mesh_sample = copy.deepcopy(mesh) self.strain_sample = np.copy(self.strain_lab) self.orientation_sample = np.copy(self.orientation_lab) def diffract( self, beam, detector, rigid_body_motion, min_bragg_angle=0, max_bragg_angle=None, verbose=True): """Compute diffraction from the rotating and translating polycrystal while illuminated by an xray beam. The xray beam interacts with the polycrystal producing scattering units which are stored in a detector frame. The scattering units may be rendered as pixelated patterns on the detector by using a detector rendering option. Args: beam (:obj:`xrd_simulator.beam.Beam`): Object representing a monochromatic beam of xrays. detector (:obj:`xrd_simulator.detector.Detector`): Object representing a flat rectangular detector. rigid_body_motion (:obj:`xrd_simulator.motion.RigidBodyMotion`): Rigid body motion object describing the polycrystal transformation as a function of time on the domain (time=[0,1]) over which diffraction is to be computed. min_bragg_angle (:obj:`float`): Minimum Bragg angle (radians) below which to not compute diffraction. Defaults to 0. max_bragg_angle (:obj:`float`): Maximum Bragg angle (radians) after which to not compute diffraction. By default the max_bragg_angle is approximated by wrapping the detector corners in a cone with apex at the sample centroid. verbose (:obj:`bool`): Prints progress. Defaults to True. """ min_bragg_angle, max_bragg_angle = self._get_bragg_angle_bounds( detector, beam, min_bragg_angle, max_bragg_angle) for phase in self.phases: with utils._verbose_manager(verbose): phase.setup_diffracting_planes( beam.wavelength, min_bragg_angle, max_bragg_angle) rho_0_factor = -beam.wave_vector.dot(rigid_body_motion.rotator.K2) rho_1_factor = beam.wave_vector.dot(rigid_body_motion.rotator.K) rho_2_factor = beam.wave_vector.dot( np.eye(3, 3) + rigid_body_motion.rotator.K2) scattering_units = [] proximity_intervals = beam._get_proximity_intervals( self.mesh_lab.espherecentroids, self.mesh_lab.eradius, rigid_body_motion) for ei in range(self.mesh_lab.number_of_elements): if verbose: progress_bar_message = "Computing scattering from a total of " + \ str(self.mesh_lab.number_of_elements) + " elements" progress_fraction = float( ei + 1) / self.mesh_lab.number_of_elements utils._print_progress( progress_fraction, message=progress_bar_message) # skip elements not illuminated if proximity_intervals[ei][0] is None: continue element_vertices_0 = self.mesh_lab.coord[self.mesh_lab.enod[ei], :] G_0 = laue.get_G(self.orientation_lab[ei], self._eB[ei], self.phases[self.element_phase_map[ei]].miller_indices.T) rho_0s = rho_0_factor.dot(G_0) rho_1s = rho_1_factor.dot(G_0) rho_2s = rho_2_factor.dot(G_0) + np.sum((G_0 * G_0), axis=0) / 2. for hkl_indx in range(G_0.shape[1]): for time in laue.find_solutions_to_tangens_half_angle_equation( rho_0s[hkl_indx], rho_1s[hkl_indx], rho_2s[hkl_indx], rigid_body_motion.rotation_angle): if time is not None: if utils._contained_by_intervals( time, proximity_intervals[ei]): element_vertices = rigid_body_motion( element_vertices_0.T, time).T # TODO: Consider plane equations representation of # elements avoiding ConvexHull calls in # beam.intersect() scattering_region = beam.intersect( element_vertices) if scattering_region is not None: G = rigid_body_motion.rotate( G_0[:, hkl_indx], time) scattered_wave_vector = G + beam.wave_vector scattering_unit = ScatteringUnit(scattering_region, scattered_wave_vector, beam.wave_vector, beam.wavelength, beam.polarization_vector, rigid_body_motion.rotation_axis, time, self.phases[self.element_phase_map[ei]], hkl_indx) scattering_units.append(scattering_unit) detector.frames.append(scattering_units) def transform(self, rigid_body_motion, time): """Transform the polycrystal by performing a rigid body motion (translation + rotation) This function will update the polycrystal mesh (update in lab frame) with any dependent quantities, such as face normals etc. Likewise, it will update the per element crystal orientation matrices (U) as well as the lab frame description of strain tensors. Args: rigid_body_motion (:obj:`xrd_simulator.motion.RigidBodyMotion`): Rigid body motion object describing the polycrystal transformation as a function of time on the domain time=[0,1]. time (:obj:`float`): Time between [0,1] at which to call the rigid body motion. """ angle_to_rotate = rigid_body_motion.rotation_angle * time Rot_mat = rigid_body_motion.rotator.get_rotation_matrix( angle_to_rotate) new_nodal_coordinates = rigid_body_motion( self.mesh_lab.coord.T, time=time).T self.mesh_lab.update(new_nodal_coordinates) for ei in range(self.mesh_lab.number_of_elements): self.orientation_lab[ei] = np.dot( Rot_mat, self.orientation_lab[ei]) self.strain_lab[ei] = np.dot( Rot_mat, np.dot( self.strain_lab[ei], Rot_mat.T)) def save(self, path, save_mesh_as_xdmf=True): """Save polycrystal to disc (via pickling). Args: path (:obj:`str`): File path at which to save, ending with the desired filename. save_mesh_as_xdmf (:obj:`bool`): If true, saves the polycrystal mesh with associated strains and crystal orientations as a .xdmf for visualization (sample coordinates). The results can be vizualised with for instance paraview (https://www.paraview.org/). The resulting data fields of the mesh data are the 6 unique components of the small strain tensor (in sample coordinates) and the 3 Bunge Euler angles (Bunge, <NAME>. (1982). Texture Analysis in Materials Science. London: Butterworths.). Additionally a single field specifying the material phases of the sample will be saved. """ if not path.endswith(".pc"): pickle_path = path + ".pc" with open(pickle_path, "wb") as f: dill.dump(self, f, dill.HIGHEST_PROTOCOL) if save_mesh_as_xdmf: element_data = {} element_data['Small Strain Tensor Component xx'] = self.strain_sample[:, 0, 0] element_data['Small Strain Tensor Component yy'] = self.strain_sample[:, 1, 1] element_data['Small Strain Tensor Component zz'] = self.strain_sample[:, 2, 2] element_data['Small Strain Tensor Component xy'] = self.strain_sample[:, 0, 1] element_data['Small Strain Tensor Component xz'] = self.strain_sample[:, 0, 2] element_data['Small Strain Tensor Component yz'] = self.strain_sample[:, 1, 2] element_data['Bunge Euler Angle phi_1'] = [] element_data['Bunge Euler Angle Phi'] = [] element_data['Bunge Euler Angle phi_2'] = [] for U in self.orientation_sample: phi_1, PHI, phi_2 = tools.u_to_euler(U) element_data['Bunge Euler Angle phi_1'].append(phi_1) element_data['Bunge Euler Angle Phi'].append(PHI) element_data['Bunge Euler Angle phi_2'].append(phi_2) element_data['Material Phase Index'] = self.element_phase_map self.mesh_sample.save(path + ".xdmf", element_data=element_data) @classmethod def load(cls, path): """Load polycrystal from disc (via pickling). Args: path (:obj:`str`): File path at which to load, ending with the desired filename. .. warning:: This function will unpickle data from the provied path. The pickle module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source. """ if not path.endswith(".pc"): raise ValueError("The loaded polycrystal file must end with .pc") with open(path, 'rb') as f: return dill.load(f) def _instantiate_orientation(self, orientation, mesh): """Instantiate the
<filename>sklearn/cluster/_agglomerative.py """Hierarchical Agglomerative Clustering These routines perform some hierarchical agglomerative clustering of some input data. Authors : <NAME>, <NAME>, <NAME>, <NAME> License: BSD 3 clause """ import warnings from heapq import heapify, heappop, heappush, heappushpop import numpy as np from scipy import sparse from scipy.sparse.csgraph import connected_components from ..base import BaseEstimator, ClusterMixin from ..metrics.pairwise import paired_distances from ..metrics import DistanceMetric from ..metrics._dist_metrics import METRIC_MAPPING from ..utils import check_array from ..utils._fast_dict import IntFloatDict from ..utils.fixes import _astype_copy_false from ..utils.graph import _fix_connected_components from ..utils.validation import check_memory # mypy error: Module 'sklearn.cluster' has no attribute '_hierarchical_fast' from . import _hierarchical_fast as _hierarchical # type: ignore from ._feature_agglomeration import AgglomerationTransform ############################################################################### # For non fully-connected graphs def _fix_connectivity(X, connectivity, affinity): """ Fixes the connectivity matrix. The different steps are: - copies it - makes it symmetric - converts it to LIL if necessary - completes it if necessary. Parameters ---------- X : array-like of shape (n_samples, n_features) Feature matrix representing `n_samples` samples to be clustered. connectivity : sparse matrix, default=None Connectivity matrix. Defines for each sample the neighboring samples following a given structure of the data. The matrix is assumed to be symmetric and only the upper triangular half is used. Default is `None`, i.e, the Ward algorithm is unstructured. affinity : {"euclidean", "precomputed"}, default="euclidean" Which affinity to use. At the moment `precomputed` and ``euclidean`` are supported. `euclidean` uses the negative squared Euclidean distance between points. Returns ------- connectivity : sparse matrix The fixed connectivity matrix. n_connected_components : int The number of connected components in the graph. """ n_samples = X.shape[0] if connectivity.shape[0] != n_samples or connectivity.shape[1] != n_samples: raise ValueError( "Wrong shape for connectivity matrix: %s when X is %s" % (connectivity.shape, X.shape) ) # Make the connectivity matrix symmetric: connectivity = connectivity + connectivity.T # Convert connectivity matrix to LIL if not sparse.isspmatrix_lil(connectivity): if not sparse.isspmatrix(connectivity): connectivity = sparse.lil_matrix(connectivity) else: connectivity = connectivity.tolil() # Compute the number of nodes n_connected_components, labels = connected_components(connectivity) if n_connected_components > 1: warnings.warn( "the number of connected components of the " "connectivity matrix is %d > 1. Completing it to avoid " "stopping the tree early." % n_connected_components, stacklevel=2, ) # XXX: Can we do without completing the matrix? connectivity = _fix_connected_components( X=X, graph=connectivity, n_connected_components=n_connected_components, component_labels=labels, metric=affinity, mode="connectivity", ) return connectivity, n_connected_components def _single_linkage_tree( connectivity, n_samples, n_nodes, n_clusters, n_connected_components, return_distance, ): """ Perform single linkage clustering on sparse data via the minimum spanning tree from scipy.sparse.csgraph, then using union-find to label. The parent array is then generated by walking through the tree. """ from scipy.sparse.csgraph import minimum_spanning_tree # explicitly cast connectivity to ensure safety connectivity = connectivity.astype("float64", **_astype_copy_false(connectivity)) # Ensure zero distances aren't ignored by setting them to "epsilon" epsilon_value = np.finfo(dtype=connectivity.data.dtype).eps connectivity.data[connectivity.data == 0] = epsilon_value # Use scipy.sparse.csgraph to generate a minimum spanning tree mst = minimum_spanning_tree(connectivity.tocsr()) # Convert the graph to scipy.cluster.hierarchy array format mst = mst.tocoo() # Undo the epsilon values mst.data[mst.data == epsilon_value] = 0 mst_array = np.vstack([mst.row, mst.col, mst.data]).T # Sort edges of the min_spanning_tree by weight mst_array = mst_array[np.argsort(mst_array.T[2], kind="mergesort"), :] # Convert edge list into standard hierarchical clustering format single_linkage_tree = _hierarchical._single_linkage_label(mst_array) children_ = single_linkage_tree[:, :2].astype(int) # Compute parents parent = np.arange(n_nodes, dtype=np.intp) for i, (left, right) in enumerate(children_, n_samples): if n_clusters is not None and i >= n_nodes: break if left < n_nodes: parent[left] = i if right < n_nodes: parent[right] = i if return_distance: distances = single_linkage_tree[:, 2] return children_, n_connected_components, n_samples, parent, distances return children_, n_connected_components, n_samples, parent ############################################################################### # Hierarchical tree building functions def ward_tree(X, *, connectivity=None, n_clusters=None, return_distance=False): """Ward clustering based on a Feature matrix. Recursively merges the pair of clusters that minimally increases within-cluster variance. The inertia matrix uses a Heapq-based representation. This is the structured version, that takes into account some topological structure between samples. Read more in the :ref:`User Guide <hierarchical_clustering>`. Parameters ---------- X : array-like of shape (n_samples, n_features) Feature matrix representing `n_samples` samples to be clustered. connectivity : sparse matrix, default=None Connectivity matrix. Defines for each sample the neighboring samples following a given structure of the data. The matrix is assumed to be symmetric and only the upper triangular half is used. Default is None, i.e, the Ward algorithm is unstructured. n_clusters : int, default=None `n_clusters` should be less than `n_samples`. Stop early the construction of the tree at `n_clusters.` This is useful to decrease computation time if the number of clusters is not small compared to the number of samples. In this case, the complete tree is not computed, thus the 'children' output is of limited use, and the 'parents' output should rather be used. This option is valid only when specifying a connectivity matrix. return_distance : bool, default=False If `True`, return the distance between the clusters. Returns ------- children : ndarray of shape (n_nodes-1, 2) The children of each non-leaf node. Values less than `n_samples` correspond to leaves of the tree which are the original samples. A node `i` greater than or equal to `n_samples` is a non-leaf node and has children `children_[i - n_samples]`. Alternatively at the i-th iteration, children[i][0] and children[i][1] are merged to form node `n_samples + i`. n_connected_components : int The number of connected components in the graph. n_leaves : int The number of leaves in the tree. parents : ndarray of shape (n_nodes,) or None The parent of each node. Only returned when a connectivity matrix is specified, elsewhere 'None' is returned. distances : ndarray of shape (n_nodes-1,) Only returned if `return_distance` is set to `True` (for compatibility). The distances between the centers of the nodes. `distances[i]` corresponds to a weighted Euclidean distance between the nodes `children[i, 1]` and `children[i, 2]`. If the nodes refer to leaves of the tree, then `distances[i]` is their unweighted Euclidean distance. Distances are updated in the following way (from scipy.hierarchy.linkage): The new entry :math:`d(u,v)` is computed as follows, .. math:: d(u,v) = \\sqrt{\\frac{|v|+|s|} {T}d(v,s)^2 + \\frac{|v|+|t|} {T}d(v,t)^2 - \\frac{|v|} {T}d(s,t)^2} where :math:`u` is the newly joined cluster consisting of clusters :math:`s` and :math:`t`, :math:`v` is an unused cluster in the forest, :math:`T=|v|+|s|+|t|`, and :math:`|*|` is the cardinality of its argument. This is also known as the incremental algorithm. """ X = np.asarray(X) if X.ndim == 1: X = np.reshape(X, (-1, 1)) n_samples, n_features = X.shape if connectivity is None: from scipy.cluster import hierarchy # imports PIL if n_clusters is not None: warnings.warn( "Partial build of the tree is implemented " "only for structured clustering (i.e. with " "explicit connectivity). The algorithm " "will build the full tree and only " "retain the lower branches required " "for the specified number of clusters", stacklevel=2, ) X = np.require(X, requirements="W") out = hierarchy.ward(X) children_ = out[:, :2].astype(np.intp) if return_distance: distances = out[:, 2] return children_, 1, n_samples, None, distances else: return children_, 1, n_samples, None connectivity, n_connected_components = _fix_connectivity( X, connectivity, affinity="euclidean" ) if n_clusters is None: n_nodes = 2 * n_samples - 1 else: if n_clusters > n_samples: raise ValueError( "Cannot provide more clusters than samples. " "%i n_clusters was asked, and there are %i " "samples." % (n_clusters, n_samples) ) n_nodes = 2 * n_samples - n_clusters # create inertia matrix coord_row = [] coord_col = [] A = [] for ind, row in enumerate(connectivity.rows): A.append(row) # We keep only the upper triangular for the moments # Generator expressions are faster than arrays on the following row = [i for i in row if i < ind] coord_row.extend( len(row) * [ ind, ] ) coord_col.extend(row) coord_row = np.array(coord_row, dtype=np.intp, order="C") coord_col = np.array(coord_col, dtype=np.intp, order="C") # build moments as a list moments_1 = np.zeros(n_nodes, order="C") moments_1[:n_samples] = 1 moments_2 = np.zeros((n_nodes, n_features), order="C") moments_2[:n_samples] = X inertia = np.empty(len(coord_row), dtype=np.float64, order="C") _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, inertia) inertia = list(zip(inertia, coord_row, coord_col)) heapify(inertia) # prepare the main fields parent = np.arange(n_nodes, dtype=np.intp) used_node = np.ones(n_nodes, dtype=bool) children = [] if return_distance: distances = np.empty(n_nodes - n_samples) not_visited = np.empty(n_nodes, dtype=np.int8, order="C") # recursive merge loop for k in
<filename>position/models.py # position/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- # Diagrams here: https://docs.google.com/drawings/d/1DsPnl97GKe9f14h41RPeZDssDUztRETGkXGaolXCeyo/edit from django.db import models from election_office_measure.models import CandidateCampaign, MeasureCampaign from exception.models import handle_exception, handle_exception_silently, handle_record_found_more_than_one_exception,\ handle_record_not_found_exception, handle_record_not_saved_exception from organization.models import Organization from twitter.models import TwitterUser from django.contrib.auth.models import User # from voter.models import Voter # Replace User with this once we have figured out User -> Voter object linking SUPPORT = 'SUPPORT' STILL_DECIDING = 'STILL_DECIDING' NO_STANCE = 'NO_STANCE' INFORMATION_ONLY = 'INFO_ONLY' OPPOSE = 'OPPOSE' POSITION_CHOICES = ( # ('SUPPORT_STRONG', 'Strong Supports'), # I do not believe we will be offering 'SUPPORT_STRONG' as an option (SUPPORT, 'Supports'), (STILL_DECIDING, 'Still deciding'), (NO_STANCE, 'No stance'), (INFORMATION_ONLY, 'Information only'), (OPPOSE, 'Opposes'), # ('OPPOSE_STRONG', 'Strongly Opposes'), # I do not believe we will be offering 'OPPOSE_STRONG' as an option ) class PositionEntered(models.Model): """ Any position entered by any person gets its own PositionEntered entry. We then generate Position entries that get used to display an particular org's position. """ # We are relying on built-in Python id field # The id for the generated position that this PositionEntered entry influences position_id = models.BigIntegerField(null=True, blank=True) date_entered = models.DateTimeField(verbose_name='date entered', null=True) # The organization this position is for organization_id = models.BigIntegerField(null=True, blank=True) # The voter expressing the opinion voter_id = models.BigIntegerField(null=True, blank=True) # The election this position is for election_id = models.BigIntegerField(verbose_name='election id', null=True, blank=True) # The unique We Vote id of the tweet that is the source of the position tweet_source_id = models.BigIntegerField(null=True, blank=True) # This is the voter / authenticated user who entered the position for an organization # (NOT the voter expressing opinion) voter_entering_position = models.ForeignKey( User, verbose_name='authenticated user who entered position', null=True, blank=True) # The Twitter user account that generated this position twitter_user_entered_position = models.ForeignKey(TwitterUser, null=True, verbose_name='') # This is the candidate/politician that the position refers to. # Either candidate_campaign is filled OR measure_campaign, but not both # candidate_campaign = models.ForeignKey( # CandidateCampaign, verbose_name='candidate campaign', null=True, blank=True, # related_name='positionentered_candidate') candidate_campaign_id = models.BigIntegerField(verbose_name='id of candidate_campaign', null=True, blank=True) # Useful for queries based on Politicians -- not the main table we use for ballot display though politician_id = models.BigIntegerField(verbose_name='', null=True, blank=True) # This is the measure/initiative/proposition that the position refers to. # Either measure_campaign is filled OR candidate_campaign, but not both # measure_campaign = models.ForeignKey( # MeasureCampaign, verbose_name='measure campaign', null=True, blank=True, related_name='positionentered_measure') measure_campaign_id = models.BigIntegerField(verbose_name='id of measure_campaign', null=True, blank=True) # Strategic denormalization - this is redundant but will make generating the voter guide easier. # geo = models.ForeignKey(Geo, null=True, related_name='pos_geo') # issue = models.ForeignKey(Issue, null=True, blank=True, related_name='') stance = models.CharField(max_length=15, choices=POSITION_CHOICES, default=NO_STANCE) # supporting/opposing statement_text = models.TextField(null=True, blank=True,) statement_html = models.TextField(null=True, blank=True,) # A link to any location with more information about this position more_info_url = models.URLField(blank=True, null=True, verbose_name='url with more info about this position') # Did this position come from a web scraper? from_scraper = models.BooleanField(default=False) # Was this position certified by an official with the organization? organization_certified = models.BooleanField(default=False) # Was this position certified by an official We Vote volunteer? volunteer_certified = models.BooleanField(default=False) # link = models.URLField(null=True, blank=True,) # link_title = models.TextField(null=True, blank=True, max_length=128) # link_site = models.TextField(null=True, blank=True, max_length=64) # link_txt = models.TextField(null=True, blank=True) # link_img = models.URLField(null=True, blank=True) # Set this to True after getting all the link details (title, txt, img etc) # details_loaded = models.BooleanField(default=False) # video_embed = models.URLField(null=True, blank=True) # spam_flag = models.BooleanField(default=False) # abuse_flag = models.BooleanField(default=False) # orig_json = models.TextField(blank=True) def __unicode__(self): return self.stance class Meta: ordering = ('date_entered',) def is_support(self): if self.stance == SUPPORT: return True return False def is_oppose(self): if self.stance == OPPOSE: return True return False def is_no_stance(self): if self.stance == NO_STANCE: return True return False def is_information_only(self): if self.stance == INFORMATION_ONLY: return True return False def is_still_deciding(self): if self.stance == STILL_DECIDING: return True return False def candidate_campaign(self): try: candidate_campaign = CandidateCampaign.objects.get(id=self.candidate_campaign_id) except CandidateCampaign.MultipleObjectsReturned as e: handle_record_found_more_than_one_exception(e) print "position.candidate_campaign Found multiple" return None except CandidateCampaign.DoesNotExist as e: handle_exception_silently(e) print "position.candidate_campaign did not find" return None return candidate_campaign def organization(self): try: organization = Organization.objects.get(id=self.organization_id) except Organization.MultipleObjectsReturned as e: handle_record_found_more_than_one_exception(e) print "position.candidate_campaign Found multiple" return None except Organization.DoesNotExist as e: handle_exception_silently(e) print "position.candidate_campaign did not find" return None return organization class Position(models.Model): """ This is a table of data generated from PositionEntered. Not all fields copied over from PositionEntered """ # We are relying on built-in Python id field # The PositionEntered entry that was copied into this entry based on verification rules position_entered_id = models.BigIntegerField(null=True, blank=True) date_entered = models.DateTimeField(verbose_name='date entered', null=True) # The organization this position is for organization_id = models.BigIntegerField(null=True, blank=True) # The election this position is for election_id = models.BigIntegerField(verbose_name='election id', null=True, blank=True) candidate_campaign = models.ForeignKey( CandidateCampaign, verbose_name='candidate campaign', null=True, blank=True, related_name='position_candidate') # Useful for queries based on Politicians -- not the main table we use for ballot display though politician_id = models.BigIntegerField(verbose_name='', null=True, blank=True) # This is the measure/initiative/proposition that the position refers to. # Either measure_campaign is filled OR candidate_campaign, but not both measure_campaign = models.ForeignKey( MeasureCampaign, verbose_name='measure campaign', null=True, blank=True, related_name='position_measure') stance = models.CharField(max_length=15, choices=POSITION_CHOICES) # supporting/opposing statement_text = models.TextField(null=True, blank=True,) statement_html = models.TextField(null=True, blank=True,) # A link to any location with more information about this position more_info_url = models.URLField(blank=True, null=True, verbose_name='url with more info about this position') def __unicode__(self): return self.name class Meta: ordering = ('date_entered',) # def display_ballot_item_name(self): # """ # Organization supports 'ballot_item_name' (which could be a campaign name, or measure name # :return: # """ # # Try to retrieve the candidate_campaign # if candidate_campaign.id: class PositionListForCandidateCampaign(models.Model): """ A way to retrieve all of the positions stated about this CandidateCampaign """ # candidate_campaign = models.ForeignKey( # CandidateCampaign, null=False, blank=False, verbose_name='candidate campaign') # position = models.ForeignKey( # PositionEntered, null=False, blank=False, verbose_name='position about candidate') def retrieve_all_positions_for_candidate_campaign(self, candidate_campaign_id, stance_we_are_looking_for): # TODO Error check stance_we_are_looking_for # Retrieve the support positions for this candidate_campaign_id organization_position_list_found = False try: organization_position_list = PositionEntered.objects.order_by('date_entered') organization_position_list = organization_position_list.filter(candidate_campaign_id=candidate_campaign_id) # SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE organization_position_list = organization_position_list.filter(stance=stance_we_are_looking_for) # organization_position_list = organization_position_list.filter(election_id=election_id) if len(organization_position_list): organization_position_list_found = True except Exception as e: handle_record_not_found_exception(e) if organization_position_list_found: return organization_position_list else: organization_position_list = {} return organization_position_list def calculate_positions_followed_by_voter( self, all_positions_list_for_candidate_campaign, organizations_followed_by_voter): """ We need a list of positions that were made by an organization that this voter follows :param all_positions_list_for_candidate_campaign: :param organizations_followed_by_voter: :return: """ this_voter_id = 1 positions_followed_by_voter = [] # Only return the positions if they are from organizations the voter follows for position in all_positions_list_for_candidate_campaign: if position.voter_id == this_voter_id: # TODO DALE Is this the right way to do this? positions_followed_by_voter.append(position) elif position.organization_id in organizations_followed_by_voter: print "position {position_id} followed by voter (org {org_id})".format( position_id=position.id, org_id=position.organization_id) positions_followed_by_voter.append(position) return positions_followed_by_voter def calculate_positions_not_followed_by_voter( self, all_positions_list_for_candidate_campaign, organizations_followed_by_voter): """ We need a list of positions that were made by an organization that this voter follows :param all_positions_list_for_candidate_campaign: :param organizations_followed_by_voter: :return: """ positions_not_followed_by_voter = [] # Only return the positions if they are from organizations the voter follows for position in all_positions_list_for_candidate_campaign: # Some positions are for individual voters, so we want to filter those out if position.organization_id \ and position.organization_id not in organizations_followed_by_voter: print "position {position_id} NOT followed by voter (org {org_id})".format( position_id=position.id, org_id=position.organization_id) positions_not_followed_by_voter.append(position) return positions_not_followed_by_voter class PositionEnteredManager(models.Model): def __unicode__(self): return "PositionEnteredManager" def retrieve_organization_candidate_campaign_position(self, organization_id, candidate_campaign_id): """ Find a position based on the organization_id & candidate_campaign_id :param organization_id: :param candidate_campaign_id: :return: """ position_id = 0 voter_id = 0 measure_campaign_id = 0 position_entered_manager = PositionEnteredManager() return position_entered_manager.retrieve_position( position_id, organization_id, voter_id, candidate_campaign_id, measure_campaign_id) def retrieve_voter_candidate_campaign_position(self, voter_id, candidate_campaign_id): organization_id = 0 position_id = 0 measure_campaign_id = 0 position_entered_manager = PositionEnteredManager() return position_entered_manager.retrieve_position( position_id, organization_id, voter_id, candidate_campaign_id, measure_campaign_id) def retrieve_position_from_id(self, position_id): organization_id = 0 voter_id = 0 candidate_campaign_id = 0 measure_campaign_id = 0 position_entered_manager = PositionEnteredManager() return position_entered_manager.retrieve_position( position_id, organization_id, voter_id, candidate_campaign_id, measure_campaign_id) def retrieve_position(self, position_id, organization_id, voter_id, candidate_campaign_id, measure_campaign_id): error_result = False exception_does_not_exist = False exception_multiple_object_returned = False position_on_stage = PositionEntered() try: if position_id > 0: position_on_stage = PositionEntered.objects.get(id=position_id) position_id = position_on_stage.id elif organization_id > 0 and candidate_campaign_id > 0: position_on_stage = PositionEntered.objects.get( organization_id=organization_id, candidate_campaign_id=candidate_campaign_id) #
# import the necessary packages import cv2 from imutils.perspective import four_point_transform import pytesseract import argparse import imutils import re import numpy as np import io from PIL import Image, ImageEnhance, ImageFilter import datetime from collections import namedtuple import os def ocr_code(): # empty output folder dir = '/home/pi/output' for f in os.listdir(dir): os.remove(os.path.join(dir, f)) restart_code = 0 print(datetime.datetime.now()) # in terminal: python ocr.py -i input/mail1.jpg # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image" , required=False, help="path to input image to be OCR'd") ap.add_argument("-d", "--debug", type=int, default=1, help="whether or not we are visualizing each step of the pipeline") ap.add_argument("-c", "--min-conf", type=int, default=0, help="minimum confidence value to filter weak text detection") # check to see if *digit only* OCR should be performed, and if so, update our Tesseract OCR options # ap.add_argument("-d", "--digits", type=int, default=1, help="whether or not *digits only* OCR will be performed") # if args["digits"] > 0: # options = "outputbase digits" # text = pytesseract.image_to_string(rgb, config=options) # load the input image from disk args = vars(ap.parse_args()) if args["image"]: orig = cv2.imread(args["image"]) else: orig = cv2.imread("/home/pi/2.jpg") # for our project, the 1.jpg image is the latest image captured cv2.imwrite("/home/pi/output/0-original.jpg", orig) # resize input image and compute the ratio of the *new* width to the *old* width image = orig.copy() image = imutils.resize(image, width=600) ratio = orig.shape[1] / float(image.shape[1]) # convert the image to grayscale, blur it, and apply edge detection to reveal the outline of the input image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(blurred, 30, 150) # or try cv2.Canny(blurred, 75, 200) # save outputs for troubleshooting # (NOT USED) if args["debug"] == 1: cv2.imwrite("/home/pi/output/1-gray.jpg", gray) cv2.imwrite("/home/pi/output/2-blurred.jpg", blurred) cv2.imwrite("/home/pi/output/3-edged.jpg", edged) # ================================================ IMAGE OUTLINE ============================================= # detect contours in the edge map, sort them by size (in descending order), and grab the largest contours # Use a copy of the image e.g. edged.copy() because findContours alters the image cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5] # initialize a contour that corresponds to the input image outline contours = None # loop over the contours for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) # if this is the first contour we've encountered that has four vertices, then we can assume we've found the input image if len(approx) == 4: contours = approx break height, width, channels = image.shape # if the input image contour is empty then our script could not find the outline of the item if contours is None: # raise Exception(("Could not find receipt outline. Try debugging your edge detection and contour steps.")) print("\nCould not find outline.") # "Try debugging your edge detection and contour steps." # If no contours are found, assume the boundary is the contour so that we have some output contours = np.array([[[0, 0]],[[0, height]],[[width, height]],[[width, 0]]], dtype=np.int32) # Add a padding to improve OCR on text close to edges padding = 5 contours[0][0][0] = contours[0][0][0] - padding # max(0, contours[0][0][0] - padding) contours[0][0][1] = contours[0][0][1] - padding # max(0, contours[0][0][1] - padding) contours[1][0][0] = contours[1][0][0] - padding # max(0, contours[1][0][0] - padding) contours[1][0][1] = contours[1][0][1] + padding # min(height, contours[1][0][1] + padding) contours[2][0][0] = contours[2][0][0] + padding # min(width, contours[2][0][0] + padding) contours[2][0][1] = contours[2][0][1] + padding # min(height, contours[2][0][1] + padding) contours[3][0][0] = contours[3][0][0] + padding # min(width, contours[3][0][0] + padding) contours[3][0][1] = contours[3][0][1] - padding # max(0, contours[3][0][1] - padding) print("\nSo we continue assuming the full image needs to be OCR'ed.") print("\nContours: \n", contours) # print("Contour Shape: ", contours.shape) # print(type(contours),contours.dtype) # draw the contour of the input image on the image outline = image.copy() cv2.drawContours(outline, [contours], -1, (0, 255, 0), 2) # -1 signifies drawing all contours cv2.imwrite("/home/pi/output/4-outline.jpg", outline) # apply a four-point perspective transform to the *original* image to obtain a top-down bird's-eye view of the input image card = four_point_transform(orig, contours.reshape(4, 2) * ratio) cv2.imwrite("/home/pi/output/5-transformed.jpg", card) # convert the input image from BGR to RGB channel ordering rgb = cv2.cvtColor(card, cv2.COLOR_BGR2RGB) cv2.imwrite("/home/pi/output/6-rgb.jpg", rgb) # Enhance image to get clearer results from image_to_text enhancedimage = Image.open("/home/pi/output/6-rgb.jpg") # enhancedimage = enhancedimage.convert('L') enhancedimage = enhancedimage.convert("RGBA") newimdata = [] datas = enhancedimage.getdata() for item in datas: if item[0] < 220 or item[1] < 220 or item[2] < 220: newimdata.append(item) else: newimdata.append((255, 255, 255)) enhancedimage.putdata(newimdata) enhancedimage = enhancedimage.filter(ImageFilter.MedianFilter()) # a little blur enhancer = ImageEnhance.Contrast(enhancedimage) enhancedimage = enhancer.enhance(2) enhancer = ImageEnhance.Sharpness(enhancedimage) enhancedimage = enhancer.enhance(2) # Convert image to black and white enhancedimage = enhancedimage.convert('1') enhancedimage.save("/home/pi/output/7-enhanced.jpg") # ================================================ BACKUP ==================================================== # use Tesseract to OCR the image # text_full_for_backup = pytesseract.image_to_string(enhancedimage) # print("\nRAW OUTPUT") # print("=============") # print(text_full_for_backup) # backup_text = open('/home/pi/output/backup.txt', 'w+') # backup_text.writelines([str(datetime.datetime.now()),"\n"]) # backup_text.writelines(text_full_for_backup) # backup_text.close() # # (NOT USED) Clean up text: strip out non-ASCII text from text because OpenCV replaces each unknown character with a ? # # text = "".join([c if ord(c) < 128 else "" for c in text]).strip() # # ================================= SPLITTING SENDER vs RECEIVER LOCATIONS ===================================== print("\nTrying to OCR original image.") # # create a named tuple which we can use to create locations of the input document which we wish to OCR OCRLocation = namedtuple("OCRLocation", ["id", "bbox", "filter_keywords"]) # # "bbox": Bounding box coordinates use the order [x, y, w, h] where x and y are the top-left coordinates, and w and h are the width and height # # "filter_keywords": A list of words that we do not wish to consider for OCR while restart_code < 8 : # We are looping our code so that we can try # restart_code = 0: Use RGB image # restart_code = 1: Use enhanced image # restart_code = 2: Rotate RGB image 90 CW # restart_code = 3: Rotate RGB image 90 CCW # restart_code = 4: Rotate RGB image 180 # restart_code = 5: Rotate enhanced image 90 CW # restart_code = 6: Rotate enhanced image 90 CCW # restart_code = 7: Rotate enhanced image 180 if restart_code == 0: enhancedimage = cv2.imread("/home/pi/output/6-rgb.jpg") elif restart_code == 1: print("OCR failed. Trying again with enhanced image (code ", restart_code, ")\n") enhancedimage = cv2.imread("/home/pi/output/7-enhanced.jpg") elif restart_code == 2: print("OCR failed. Trying again with 90 CW rotation (code ", restart_code, ")\n") enhancedimage = cv2.imread("/home/pi/output/6-rgb.jpg") enhancedimage = cv2.rotate(enhancedimage, cv2.ROTATE_90_CLOCKWISE) elif restart_code == 3: print("OCR failed. Trying again with 90 CCW rotation (code ", restart_code, ")\n") enhancedimage = cv2.imread("/home/pi/output/6-rgb.jpg") enhancedimage = cv2.rotate(enhancedimage, cv2.ROTATE_90_COUNTERCLOCKWISE) elif restart_code == 4: print("OCR failed. Trying again with 180 rotation (code ", restart_code, ")\n") enhancedimage = cv2.imread("/home/pi/output/6-rgb.jpg") enhancedimage = cv2.rotate(enhancedimage, cv2.ROTATE_180) elif restart_code == 5: print("OCR failed. Trying again with 90 CW rotation (code ", restart_code, ")\n") enhancedimage = cv2.imread("/home/pi/output/7-enhanced.jpg") enhancedimage = cv2.rotate(enhancedimage, cv2.ROTATE_90_CLOCKWISE) elif restart_code == 6: print("OCR failed. Trying again with 90 CCW rotation (code ", restart_code, ")\n") enhancedimage = cv2.imread("/home/pi/output/7-enhanced.jpg") enhancedimage = cv2.rotate(enhancedimage, cv2.ROTATE_90_COUNTERCLOCKWISE) elif restart_code == 7: print("OCR failed. Trying again with 180 rotation (code ", restart_code, ")\n") enhancedimage = cv2.imread("/home/pi/output/7-enhanced.jpg") enhancedimage = cv2.rotate(enhancedimage, cv2.ROTATE_180) cv2.imwrite("/home/pi/output/8-locations.jpg", enhancedimage) height, width, channels = enhancedimage.shape # define the locations of each area of the document we wish to OCR # sender_start_point = (0, 0) # sender_end_point = (int(width/2), int(height/4)) # receiver_start_point = (0, int(height/4)) # receiver_end_point = (int(width), int(height)) # end point - not distance from start (like bbox) OCR_LOCATIONS = [ OCRLocation("sender", (0, 0, int(width/2), int(height/3)), ["sender", "name", "address"]), OCRLocation("receiver", (0, int(height/3), int(width), int(height*2/3)), ["receiver", "name", "address"]), ] # initialize a results list to store the document OCR parsing results parsingResults = [] if restart_code == 1: # before you start OCR_locations for rotated image, save a backup of original image in case unable to OCR so we can see what original OCR locations to determine why it failed cv2.imwrite("/home/pi/output/8a-RGBlocations.jpg", boundinglocations) if restart_code == 2: # before you start OCR_locations for rotated image, save a backup of original image in case unable to OCR so we can see what original OCR locations to determine why it failed cv2.imwrite("/home/pi/output/8b-enhancedlocations.jpg", boundinglocations) if restart_code == 3: # before you start OCR_locations for rotated image, save a backup of original image in case unable to OCR so we can see what original OCR locations to determine why it failed cv2.imwrite("/home/pi/output/8c-rotatedCWlocations.jpg", boundinglocations) if restart_code == 4: # before you start OCR_locations for rotated image, save a backup of original image in case unable to OCR so we can see what original OCR locations to determine why it failed cv2.imwrite("/home/pi/output/8d-rotatedCCWlocations.jpg", boundinglocations) # loop over the locations of the document we are going to OCR for loc in OCR_LOCATIONS: # extract the OCR ROI from the aligned image locationsimage = cv2.imread("/home/pi/output/8-locations.jpg") (x, y, w, h) = loc.bbox # draw outline on main image for reference boundinglocations = cv2.rectangle(locationsimage, (x, y), (x + w, y + h), (0, 0, 255), 5) # cv2.rectangle(image, start_point, end_point, color, thickness) # save image that shows OCR locations cv2.imwrite("/home/pi/output/8-locations.jpg", boundinglocations) roi = locationsimage[y:y + h, x:x + w] # OCR the ROI using Tesseract text = pytesseract.image_to_string(roi) # break the text into lines
self._power_dict[var] >= 3: # self._power_dict[var] -= 2 <--- replace with below self._power_dict[var] = 1 + ((-1 + self._power_dict[var]) % 2) def rename_variables(self, name_dict: Dict[str, str]): # this ends up a little more complicated than I was originally thinking, b/c # I would like to allow two variables to be updated to the same new name renamed_dict = dict() for variable, exponent in self._power_dict.items(): name = variable if variable in name_dict: name = name_dict[variable] if name in renamed_dict: renamed_dict[name] += self._power_dict[variable] renamed_dict[name] = 1 + ((-1 + renamed_dict[name]) % 2) else: renamed_dict[name] = self._power_dict[variable] return Monomial(power_dict=renamed_dict) def as_polynomial(self): return self def is_constant(self): return len(self._power_dict) == 0 def num_variables(self): return len(self._power_dict) def variable_list(self): return self._power_dict.keys() def eval(self, variable_dict: Dict): """evaluates the monomial. variable_dict is expected to be a dict containing str:Expression or Monomial:Expression pairs. The latter are constrained to be of single-variable type. """ if type(variable_dict) != dict: raise Exception("eval is not defined on this input") # sanitize inputs sanitized_variable_dict = dict() for variable, quantity in variable_dict.items(): if type(variable) == str: sanitized_variable_dict.update({variable: variable_dict[variable]}) elif type(variable) == Monomial: if variable.num_variables() != 1: raise Exception( "We do not know how to evaluate monomials of zero or several variables to a single number") else: variable_as_str = list(variable.variable_list())[0] sanitized_variable_dict.update({variable_as_str: variable_dict[variable]}) variable_dict = sanitized_variable_dict accumulator = Mod3Poly.one() for variable, quantity in self._power_dict.items(): if variable in variable_dict.keys(): accumulator *= variable_dict[variable] ** self._power_dict[variable] else: accumulator *= Monomial.as_var(variable) ** self._power_dict[variable] return accumulator def get_variable_set(self): """ returns a set containing all variable which occur in this monomial """ return {var for var in self._power_dict if self._power_dict[var] != 0} @staticmethod def unit(): """produces the unit, 1, as a monomial""" return Monomial(dict()) @staticmethod def as_var(var_name: str): return Monomial({var_name: 1}) def __mul__(self, other) -> Expression: if isinstance(other, Monomial): result_power_dict = self._power_dict.copy() for key in other._power_dict.keys(): if key in result_power_dict.keys(): result_power_dict[key] += other._power_dict[key] while result_power_dict[key] >= 3: result_power_dict[key] -= 2 else: result_power_dict[key] = other._power_dict[key] return Monomial(result_power_dict) elif isinstance(other, Mod3Poly) or is_integer(other): return self.as_poly() * other else: return BinaryOperation('TIMES', self, other) # raise TypeError("unsupported operand type(s) for *: '{}' and '{}'".format(self.__class__, type(other))) __rmul__ = __mul__ def __neg__(self): return (-1) * self def __pow__(self, power, **kwargs): if type(power) == Mod3Poly and power.is_constant(): power = power[Monomial.unit()] assert is_integer(power) if power == 0: return Monomial.unit() elif power == 1: return self elif power == 2: return self * self # Now handle higher powers; probably not going to happen too much for this application # (int) half power root int_root = self ** (power // 2) if power % 2 == 0: return int_root * int_root else: return int_root * int_root * self def as_poly(self): """converts this monomial to a polynomial with only one term""" return Mod3Poly({self: 1}) def __add__(self, other): if isinstance(other, Mod3Poly): return other + self.as_poly() elif isinstance(other, Monomial): return self.as_poly() + other.as_poly() elif is_integer(other): return self.as_poly() + other elif isinstance(other, Expression): return BinaryOperation("PLUS", self, other) else: raise TypeError("unsupported operand type(s) for +: '{}' and '{}'".format(self.__class__, type(other))) def __radd__(self, other): return self + other def __sub__(self, other): return self + ((-1) * other) def __rsub__(self, other): return ((-1) * self) + other def __eq__(self, other): if type(other) == str: other = Monomial.as_var(other) if type(other) == Monomial: return self._power_dict == other._power_dict elif type(other) == Mod3Poly: if len(other.coeff_dict) == 1: monomial, coeff = list(other.coeff_dict)[0] return coeff == 1 and monomial == self else: return False elif is_integer(other) and self == Monomial.unit(): return other == 1 else: return False def __ne__(self, other): if type(other) == str: other = Monomial.as_var(other) return not (self == other) def __lt__(self, other): self_vars = set(self._power_dict.keys()) if type(other) == str: other = Monomial.as_var(other) other_vars = set(other._power_dict.keys()) # if we have a var that they don't we cannot be "smaller" if len(self_vars - other_vars) > 0: return False # check that we do not exceed and are smaller at least once at_least_once_less = False for var in self_vars: if self._power_dict[var] > other._power_dict[var]: return False elif self._power_dict[var] < other._power_dict[var]: at_least_once_less = True return at_least_once_less or len(other_vars - self_vars) > 0 def __le__(self, other): self_vars = set(self._power_dict.keys()) if type(other) == str: other = Monomial.as_var(other) other_vars = set(other._power_dict.keys()) # if we have a var that they don't we cannot be "smaller" if len(self_vars - other_vars) > 0: return False # check that we do not exceed for var in self_vars: if self._power_dict[var] > other._power_dict[var]: return False return True def __gt__(self, other): self_vars = set(self._power_dict.keys()) if type(other) == str: other = Monomial.as_var(other) other_vars = set(other._power_dict.keys()) # if they have a var that they don't we cannot be "greater" if len(other_vars - self_vars) > 0: return False # check that we are not smaller and are greater at least once at_least_once_greater = False for var in other_vars: if self._power_dict[var] < other._power_dict[var]: return False elif self._power_dict[var] > other._power_dict[var]: at_least_once_greater = True return at_least_once_greater or len(self_vars - other_vars) > 0 def __ge__(self, other): self_vars = set(self._power_dict.keys()) if type(other) == str: other = Monomial.as_var(other) other_vars = set(other._power_dict.keys()) # if they have a var that they don't we cannot be "greater" if len(other_vars - self_vars) > 0: return False # check that we are not smaller for var in other_vars: if self._power_dict[var] < other._power_dict[var]: return False return True def __hash__(self): return sum(hash(k) for k in self._power_dict.keys()) + \ sum(hash(v) for v in self._power_dict.values()) def __str__(self): if self._power_dict == {}: return "1" else: variables = sorted(self._power_dict.keys()) return "*".join([str(var) + "^" + str(self._power_dict[var]) if self._power_dict[var] > 1 else str(var) for var in variables]) __repr__ = __str__ def as_c_expression(self): if self._power_dict == {}: return "1" else: variables = sorted(self._power_dict.keys()) return "*".join(["mod3pow(" + str(var) + "," + str(self._power_dict[var]) + ")" if self._power_dict[var] > 1 else str(var) for var in variables if self._power_dict[var] != 0]) # def as_sympy(self): # # sympy empty product is 1, consistent with power_dict # return sympy.prod([sympy.Symbol(var, integer=True) ** pow # for var, pow in self._power_dict.items()]) # # Fun fact: sympy doesn't recognize Symbol(var) and Symbol(var, integer=True) to be the same def as_numpy_str(self, variables) -> str: if len(self._power_dict) == 0: return "1" return '(' + \ '*'.join(["1".format(variables.index(var), self._power_dict[var]) if self._power_dict[var] == 0 else "state[{0}]".format(variables.index(var)) if self._power_dict[var] == 1 else "(state[{0}]**{1})".format(variables.index(var), self._power_dict[var]) for var in self._power_dict]) + \ ')' #################################################################################################### class Mod3Poly(Expression): """a sparse polynomial class""" def __init__(self, coeffs: Union[Dict, int]): if type(coeffs) == dict: self.coeff_dict = {monomial: coeffs[monomial] for monomial in coeffs if coeffs[monomial] != 0} elif is_integer(coeffs): self.coeff_dict = {Monomial.unit(): (coeffs % 3)} else: raise TypeError("unsupported initialization type for '{}': '{}'".format(self.__class__, type(coeffs))) def rename_variables(self, name_dict: Dict[str, str]): return Mod3Poly(coeffs={monomial.rename_variables(name_dict): coeff for monomial, coeff in self.coeff_dict.items()}) @staticmethod def zero(): return Mod3Poly({Monomial.unit(): 0}) @staticmethod def one(): return Mod3Poly({Monomial.unit(): 1}) def as_polynomial(self): return self def __int__(self): self.__clear_zero_monomials() if len(self.coeff_dict) > 1 or (len(self.coeff_dict) == 1 and Monomial.unit() not in self.coeff_dict): raise Exception("cannot cast non-constant polynomial to int") if Monomial.unit() in self.coeff_dict: return self.coeff_dict[Monomial.unit()] else: return 0 def eval(self, variable_dict): """evaluates the polynomial. variable_dict is expected to be a dict containing str:Expression or Monomial:Expression pairs. The latter are constrained to be of single-variable type. """ if type(variable_dict) != dict: raise Exception("Mod3Poly.eval is not defined on this input") accumulator = Mod3Poly.zero() for monomial, coeff in self.coeff_dict.items(): accumulator += coeff * monomial.eval(variable_dict) return accumulator def get_variable_set(self): """return a set containing all variables which occur in this polynomial""" var_set = set() for monomial in self.coeff_dict: var_set = var_set.union(monomial.get_variable_set()) return var_set def __clear_zero_monomials(self): """purge unneeded data""" self.coeff_dict = {monomial: self.coeff_dict[monomial] for monomial in self.coeff_dict if self.coeff_dict[monomial] != 0} # assure at least one entry if len(self.coeff_dict) == 0: self.coeff_dict = {Monomial.unit(): 0} def is_constant(self): # possibly unnecessary self.__clear_zero_monomials() num_nonzero_monomial = len(self.coeff_dict) if num_nonzero_monomial > 1: return False elif num_nonzero_monomial == 0: return True else: # only one entry return Monomial.unit() in self.coeff_dict def __getitem__(self, index): if index in self.coeff_dict: return self.coeff_dict[index] else: return 0 def __setitem__(self, index, value): self.coeff_dict[index] = value def __add__(self, other): if is_integer(other): self_copy = Mod3Poly(self.coeff_dict) self_copy[Monomial.unit()] = (self_copy[Monomial.unit()] + other) % 3
# -*- coding: utf-8 -*- import re import os import logging from xml.etree import cElementTree as ET from multiprocessing import Process, cpu_count, JoinableQueue, Queue from sys import version_info from sys import getsizeof from collections import OrderedDict # Initiate global variables python_major_version = version_info.major log = logging.getLogger(__name__) _ttp_ = {"macro": {}, "python_major_version": python_major_version, "global_vars": {}} """ ============================================================================== TTP LAZY IMPORT SYSTEM ============================================================================== """ class CachedModule(): """Class that contains name of the function and path to module/file that contains that function, on first call to this class, function will be imported into _ttp_ dictionary, subsequent calls we call function directly """ def __init__(self, import_path, parent_dir, function_name, functions): self.import_path = import_path self.parent_dir = parent_dir self.function_name = function_name self.parent_module_functions = functions def load(self): # import cached function and insert it into _ttp_ dictionary abs_import = "ttp." if __name__ == "__main__" or __name__ == "__mp_main__": abs_import = "" path = "{abs}{imp}".format(abs=abs_import, imp=self.import_path) module = __import__(path, fromlist=[None]) setattr(module, "_ttp_", _ttp_) try: _name_map_ = getattr(module, "_name_map_") except AttributeError: _name_map_ = {} for func_name in self.parent_module_functions: name = _name_map_.get(func_name, func_name) _ttp_[self.parent_dir][name] = getattr(module, func_name) def __call__(self, *args, **kwargs): # this method invoked on CachedModule class call, triggering function import log.info("calling CachedModule: module '{}', function '{}'".format(self.import_path, self.function_name)) self.load() # call original function return _ttp_[self.parent_dir][self.function_name](*args, **kwargs) def lazy_import_functions(): """function to collect a list of all files/directories within ttp module, parse .py files using ast and extract information about all functions to cache them within _ttp_ dictionary """ log.info("ttp.lazy_import_functions: starting functions lazy import") import ast # get exclusion suffix if python_major_version == 2: exclude = "_py3.py" elif python_major_version == 3: exclude = "_py2.py" module_files = [] exclude_modules = ["ttp.py"] # create a list of all ttp module files for item in os.walk(os.path.dirname(__file__)): root, dirs, files = item module_files += [open("{}/{}".format(root, f), "r") for f in files if ( f.endswith(".py") and not f.startswith("_") and not f.endswith(exclude) and not f in exclude_modules)] log.info("ttp.lazy_import_functions: files loaded, starting ast parsing") # get all functions from modules and cache them in _ttp_ for module_file in module_files: node = ast.parse(module_file.read()) assignments = [n for n in node.body if isinstance(n, ast.Assign)] functions = [n.name for n in node.body if isinstance(n, ast.FunctionDef)] functions = [f for f in functions if (not f.startswith("_"))] # get _name_map_ _name_map_ = {} for assignment in assignments: # stop if _name_map_ already found if _name_map_: break for target in assignment.targets: if target.id == "_name_map_": _name_map_.update({ key.s: assignment.value.values[index].s for index, key in enumerate(assignment.value.keys) }) # fill in _ttp_ dictionary with CachedModule class parent_path, filename = os.path.split(module_file.name) _, parent_dir = os.path.split(parent_path) for func_name in functions: name = _name_map_.get(func_name, func_name) path = "{}.{}".format(parent_dir, filename.replace(".py", "")) _ttp_.setdefault(parent_dir, {})[name] = CachedModule(path, parent_dir, name, functions) log.info("ttp.lazy_import_functions: finished functions lazy import") """ ============================================================================== MAIN TTP CLASS ============================================================================== """ class ttp(): """ Template Text Parser main class to load data, templates, lookups, variables and dispatch data to parser object to parse in single or multiple processes, construct final results and run outputs. **Parameters** * ``data`` file object or OS path to text file or directory with text files with data to parse * ``template`` file object or OS path to text file with template * ``base_path`` (str) base OS path prefix to load data from for template's inputs * ``log_level`` (str) level of logging "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL" * ``log_file`` (str) path where to save log file * ``vars`` dictionary of variables to make available to ttp parser Example:: from ttp import ttp parser = ttp(data="/os/path/to/data/dir/", template="/os/path/to/template.txt") parser.parse() result = parser.result(format="json") print(result[0]) """ def __init__(self, data='', template='', log_level="WARNING", log_file=None, base_path='', vars={}): self.__data_size = 0 self.__datums_count = 0 self.__data = [] self.__templates = [] self.base_path = base_path self.multiproc_threshold = 5242880 # in bytes, equal to 5MBytes self.vars = vars # dictionary of variables to add to each template vars self.lookups = {} # setup logging if used as a module if __name__ != '__main__': logging_config(log_level, log_file) # lazy import all functions lazy_import_functions() # check if data given, if so - load it: if data is not '': self.add_input(data=data) # check if template given, if so - load it if template is not '': self.add_template(template=template) def add_input(self, data, input_name='Default_Input', groups=['all']): """Method to load additional data to be parsed. This data will be used to fill in template input with input_name and parse that data against a list of provided groups. **Parameters** * ``data`` file object or OS path to text file or directory with text files with data to parse * ``input_name`` (str) name of the input to put data in, default is *Default_Input* * ``groups`` (list) list of group names to use to parse this input data """ # form a list of ((type, url|text,), input_name, groups,) tuples data_items = _ttp_["utils"]["load_files"](path=data, read=False) if data_items: self.__data.append((data_items, input_name, groups,)) def set_input(self, data, input_name='Default_Input', groups=['all']): """Method to replace existing templates data with new set of data. This method run clear_input first and add_input method after that. **Parameters** * ``data`` file object or OS path to text file or directory with text files with data to parse * ``input_name`` (str) name of the input to put data in, default is *Default_Input* * ``groups`` (list) list of group names to use to parse this input data """ self.clear_input() self.add_input(data=data, input_name=input_name, groups=groups) def clear_input(self): """Method to delete all input data for all templates, can be used prior to adding new set of data to parse with same templates, instead of re-initializing ttp object. """ self.__data = [] self.__data_size = 0 self.__datums_count = 0 for template in self.__templates: template.inputs = {} def _update_templates_with_data(self): """Method to add data to templates from self.__data and calculate overall data size and count """ self.__data_size = 0 self.__datums_count = 0 for template in self.__templates: # update template inputs with data [template.update_input(data=i[0], input_name=i[1], groups=i[2]) for i in self.__data] # get overall data size and count for input_name, input_obj in template.inputs.items(): self.__datums_count += len(input_obj.data) # get data size for i in input_obj.data: if i[0] == "file_name": self.__data_size += os.path.getsize(i[1]) elif i[0] == "text_data": self.__data_size += getsizeof(i[1]) def add_template(self, template, template_name=None): """Method to load TTP templates into the parser. **Parameters** * ``template`` file object or OS path to text file with template * ``template_name`` (str) name of the template """ log.debug("ttp.add_template - loading template") # get a list of [(type, text,)] tuples or empty list [] items = _ttp_["utils"]["load_files"](path=template, read=True) for i in items: template_obj = _template_class( template_text=i[1], base_path=self.base_path, ttp_vars=self.vars, name=template_name) # if templates are empty - no 'template' tags in template: if template_obj.templates == []: self.__templates.append(template_obj) else: self.__templates += template_obj.templates def add_lookup(self, name, text_data="", include=None, load="python", key=None): """Method to add lookup table data to all templates loaded so far. Lookup is a text representation of structure that can be loaded into python dictionary using one of the available loaders - python, csv, ini, yaml, json. **Parameters** * ``name`` (str) name to assign to this lookup table to reference in templates * ``text_data`` (str) text to load lookup table/dictionary from * ``include`` (str) absolute or relative /os/path/to/lookup/table/file.txt * ``load`` (str) name of TTP loader to use to load table data * ``key`` (str) specify key column for csv loader to construct dictionary ``include`` can accept relative OS path - relative to the directory where TTP will be invoked either using CLI tool or as a module """ lookup_data = _ttp_["utils"]["load_struct"](text_data=text_data, include=include, load=load, key=key) self.lookups.update({name: lookup_data}) [template.add_lookup({name: lookup_data}) for template in self.__templates] def add_vars(self, vars): """Method to add variables to ttp and its templates to reference during parsing **Parameters** * ``vars`` dictionary of variables to make available to ttp parser """ if isinstance(vars, dict): self.vars.update(vars) [template.add_vars(vars) for template in self.__templates] def parse(self, one=False, multi=False): """Method to parse data with templates. **Parameters** * ``one`` (boolean) if set to
from __future__ import division ''' *********************************************************** File: softmaxModels.py Allows for the creation, and use of Softmax functions Version 1.3.0: Added Discretization function Version 1.3.1: Added Likelihood weighted Importance sampling *********************************************************** ''' __author__ = "<NAME>" __copyright__ = "Copyright 2017, Cohrint" __credits__ = ["<NAME>", "<NAME>"] __license__ = "GPL" __version__ = "1.3.1" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" import numpy as np; import random; from random import random; import matplotlib.pyplot as plt from scipy.stats import multivariate_normal as mvn import warnings import math import copy import time from numpy.linalg import inv,det,svd,solve from gaussianMixtures import Gaussian from gaussianMixtures import GM from mpl_toolkits.mplot3d import Axes3D from scipy import compress import scipy.linalg as linalg from copy import deepcopy from scipy import sparse from sklearn.linear_model import LogisticRegression class Softmax: def __init__(self,weights= None,bias = None): ''' Initialize with either: 1. Nothing, for empty softmax model 2. Vector of weights (n x d) and bias (nx1) ''' self.weights = weights; self.bias = bias; if(self.weights is not None): self.size = len(self.weights); self.alpha = 3; self.zeta_c = [0]*len(self.weights); for i in range(0,len(self.weights)): self.zeta_c[i] = random()*10; def nullspace(self,A,atol=1e-13,rtol=0): ''' Finds the nullspace of a matrix ''' A = np.atleast_2d(A) u, s, vh = svd(A) tol = max(atol, rtol * s[0]) nnz = (s >= tol).sum() ns = vh[nnz:].conj().T return ns; def distance(self,x1,y1,x2,y2): ''' The distance formula for 2d systems ''' dist = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2); dist = math.sqrt(dist); return dist; def buildRectangleModel(self,recBounds,steepness = 1): ''' Builds a softmax model in 2 dimensions with a rectangular interior class Inputs recBounds: A 2x2 list, with the coordinates of the lower left and upper right corners of the rectangle steepness: A scalar determining how steep the bounds between softmax classes are ''' B = np.matrix([-1,0,recBounds[0][0],1,0,-recBounds[1][0],0,1,-recBounds[1][1],0,-1,recBounds[0][1]]).T; M = np.zeros(shape=(12,15)); #Boundry: Left|Near rowSB = 0; classNum1 = 1; classNum2 = 0; for i in range(0,3): M[3*rowSB+i,3*classNum2+i] = -1; M[3*rowSB+i,3*classNum1+i] = 1; #Boundry: Right|Near rowSB = 1; classNum1 = 2; classNum2 = 0; for i in range(0,3): M[3*rowSB+i,3*classNum2+i] = -1; M[3*rowSB+i,3*classNum1+i] = 1; #Boundry: Up|Near rowSB = 2; classNum1 = 3; classNum2 = 0; for i in range(0,3): M[3*rowSB+i,3*classNum2+i] = -1; M[3*rowSB+i,3*classNum1+i] = 1; #Boundry: Down|Near rowSB = 3; classNum1 = 4; classNum2 = 0; for i in range(0,3): M[3*rowSB+i,3*classNum2+i] = -1; M[3*rowSB+i,3*classNum1+i] = 1; A = np.hstack((M,B)); # print(np.linalg.matrix_rank(A)) # print(np.linalg.matrix_rank(M)) Theta = linalg.lstsq(M,B)[0].tolist(); weight = []; bias = []; for i in range(0,len(Theta)//3): weight.append([Theta[3*i][0],Theta[3*i+1][0]]); bias.append(Theta[3*i+2][0]); steep = steepness; self.weights = (np.array(weight)*steep).tolist(); self.bias = (np.array(bias)*steep).tolist(); self.size = len(self.weights); self.alpha = 3; self.zeta_c = [0]*len(self.weights); for i in range(0,len(self.weights)): self.zeta_c[i] = random()*10; def buildOrientedRecModel(self,centroid,orient,length,width,steepness = 1): ''' Builds a rectangular model at the specified centroid with the parameters given ''' theta1 = orient*math.pi/180; h = math.sqrt((width/2)*(width/2) + (length/2)*(length/2)); theta2 = math.asin((width/2)/h); s1 = h*math.sin(theta1+theta2); s2 = h*math.cos(theta1+theta2); s3 = h*math.sin(theta1-theta2); s4 = h*math.cos(theta1-theta2); points = []; points = [[centroid[0]+s2,centroid[1]+s1],[centroid[0]+s4,centroid[1]+s3],[centroid[0]-s2,centroid[1]-s1],[centroid[0]-s4,centroid[1]-s3]]; self.buildPointsModel(points,steepness=steepness); def buildGeneralModel(self,dims,numClasses,boundries,B,steepness=1): ''' Builds a softmax model according to the full specification of boudries and a normal vector Inputs dims: the dimensionality of the model numClasses: the number of classes in the model boundries: a list of [2x1] lists which spec out the boundries required in the model B: a list of normals and constants for each boundry steepness: A scalar determining how steep the bounds between softmax classes are ''' M = np.zeros(shape=(len(boundries)*(dims+1),numClasses*(dims+1))); for j in range(0,len(boundries)): for i in range(0,dims+1): M[(dims+1)*j+i,(dims+1)*boundries[j][1]+i] = -1; M[(dims+1)*j+i,(dims+1)*boundries[j][0]+i] = 1; A = np.hstack((M,B)); Theta = linalg.lstsq(M,B)[0].tolist(); weight = []; bias = []; for i in range(0,len(Theta)//(dims+1)): wtmp=[]; for j in range(0,dims): wtmp.append(Theta[(dims+1)*i+j][0]) weight.append(wtmp); bias.append(Theta[(dims+1)*i+dims][0]); steep = steepness; self.weights = (np.array(weight)*steep).tolist(); self.bias = (np.array(bias)*steep).tolist(); self.size = len(self.weights); self.alpha = 3; self.zeta_c = [0]*len(self.weights); for i in range(0,len(self.weights)): self.zeta_c[i] = random()*10; def buildPointsModel(self,points,steepness=1): ''' Builds a 2D softmax model by constructing an interior class from the given points Inputs points: list of 2D points that construct a convex polygon steepness: A scalar determining how steep the bounds between softmax classes are ''' dims = 2; pointsx = [p[0] for p in points]; pointsy = [p[1] for p in points]; centroid = [sum(pointsx)/len(points),sum(pointsy)/len(points)]; #for each point to the next, find the normal between them. B = []; for i in range(0,len(points)): p1 = points[i]; if(i == len(points)-1): p2 = points[0]; else: p2 = points[i+1]; mid = []; for i in range(0,len(p1)): mid.append((p1[i]+p2[i])/2) H = np.matrix([[p1[0],p1[1],1],[p2[0],p2[1],1],[mid[0],mid[1],1]]); Hnull = (self.nullspace(H)).tolist(); distMed1 = self.distance(mid[0]+Hnull[0][0],mid[1]+Hnull[1][0],centroid[0],centroid[1]); distMed2 = self.distance(mid[0]-Hnull[0][0],mid[1]-Hnull[1][0],centroid[0],centroid[1]); if(distMed1 < distMed2): Hnull[0][0] = -Hnull[0][0]; Hnull[1][0] = -Hnull[1][0]; Hnull[2][0] = -Hnull[2][0]; for j in Hnull: B.append(j[0]); B = np.matrix(B).T; numClasses = len(points)+1; boundries = []; for i in range(1,numClasses): boundries.append([i,0]); M = np.zeros(shape=(len(boundries)*(dims+1),numClasses*(dims+1))); for j in range(0,len(boundries)): for i in range(0,dims+1): M[(dims+1)*j+i,(dims+1)*boundries[j][1]+i] = -1; M[(dims+1)*j+i,(dims+1)*boundries[j][0]+i] = 1; A = np.hstack((M,B)); #print(np.linalg.matrix_rank(A)) #print(np.linalg.matrix_rank(M)) Theta = linalg.lstsq(M,B)[0].tolist(); weight = []; bias = []; for i in range(0,len(Theta)//(dims+1)): weight.append([Theta[(dims+1)*i][0],Theta[(dims+1)*i+1][0]]); bias.append(Theta[(dims+1)*i+dims][0]); steep = steepness; self.weights = (np.array(weight)*steep).tolist(); self.bias = (np.array(bias)*steep).tolist(); self.size = len(self.weights); self.alpha = 3; self.zeta_c = [0]*len(self.weights); for i in range(0,len(self.weights)): self.zeta_c[i] = random()*10; def buildTriView(self,pose,length = 3,steepness = 2): l = length; #Without Cutting triPoints = [[pose[0],pose[1]],[pose[0]+l*math.cos(2*-0.261799+math.radians(pose[2])),pose[1]+l*math.sin(2*-0.261799+math.radians(pose[2]))],[pose[0]+l*math.cos(2*0.261799+math.radians(pose[2])),pose[1]+l*math.sin(2*0.261799+math.radians(pose[2]))]]; #With Cutting lshort = 0.5 triPoints = [[pose[0]+lshort*math.cos(2*0.261799+math.radians(pose[2])),pose[1]+lshort*math.sin(2*0.261799+math.radians(pose[2]))],[pose[0]+lshort*math.cos(2*-0.261799+math.radians(pose[2])),pose[1]+lshort*math.sin(2*-0.261799+math.radians(pose[2]))],[pose[0]+l*math.cos(2*-0.261799+math.radians(pose[2])),pose[1]+l*math.sin(2*-0.261799+math.radians(pose[2]))],[pose[0]+l*math.cos(2*0.261799+math.radians(pose[2])),pose[1]+l*math.sin(2*0.261799+math.radians(pose[2]))]]; self.buildPointsModel(triPoints,steepness=steepness); def Estep(self,weight,bias,prior_mean,prior_var,alpha = 0.5,zeta_c = 1,softClassNum=0): ''' Runs the Expectation step of the Variational Bayes algorithm ''' #start the VB EM step lamb = [0]*len(weight); for i in range(0,len(weight)): lamb[i] = self._lambda(zeta_c[i]); hj = 0; suma = 0; for c in range(0,len(weight)): if(softClassNum != c): suma += weight[c]; tmp2 = 0; for c in range(0,len(weight)): tmp2+=lamb[c]*(alpha-bias[c])*weight[c]; hj = 0.5*(weight[softClassNum]-suma)+2*tmp2; Kj = 0; for c in range(0,len(weight)): Kj += lamb[c]*weight[c]*weight[c]; Kj = Kj*2; Kp = prior_var**-1; hp = Kp*prior_mean; Kl = Kp+Kj; hl = hp+hj; mean = (Kl**-1)*hl; var = Kl**-1; yc = [0]*len(weight); yc2= [0]*len(weight); for c in range(0,len(weight)): yc[c] = weight[c]*mean + bias[c]; yc2[c] = weight[c]*(var + mean*mean)*weight[c] + 2*weight[c]*mean*bias[c] + bias[c]**2; return [mean,var,yc,yc2]; def Mstep(self,m,yc,yc2,zeta_c,alpha,steps): ''' Runs the Maximization Step of the Variational Bayes algorithm ''' z = zeta_c; a = alpha; for i in range(0,steps): for c in range(0,len(yc)): z[c] = math.sqrt(yc2[c] + a**2 - 2*a*yc[c]); num_sum = 0; den_sum = 0; for c in range(0,len(yc)): num_sum += self._lambda(z[c])*yc[c]; den_sum += self._lambda(z[c]); a = ((m-2)/4 + num_sum)/den_sum; return [z,a] def _lambda(self, zeta_c): return 1 / (2 * zeta_c) * ( (1 / (1 + np.exp(-zeta_c))) - 0.5) def calcCHat(self,prior_mean,prior_var,mean,var,alpha,zeta_c,yc,yc2,mod): prior_var = np.matrix(prior_var); prior_mean = np.matrix(prior_mean); var_hat = np.matrix(var); mu_hat = np.matrix(mean); #KLD = 0.5*(np.log(prior_var/var) + prior_var**-1*var + (prior_mean-mean)*(prior_var**-1)*(prior_mean-mean)); KLD = 0.5 * (np.log(det(prior_var) / det(var_hat)) + np.trace(inv(prior_var) .dot (var_hat)) + (prior_mean - mu_hat).T .dot (inv(prior_var)) .dot (prior_mean - mu_hat)); suma = 0; for c in range(0,len(zeta_c)): suma += 0.5 * (alpha + zeta_c[c] - yc[c]) \ - self._lambda(zeta_c[c]) * (yc2[c] - 2 * alpha * yc[c] + alpha ** 2 - zeta_c[c] ** 2) \ - np.log(1 + np.exp(zeta_c[c])) return yc[mod] - alpha + suma - KLD + 1; def numericalProduct(self,prior,meas,low=0,high=5,res =100,vis = True): ''' Multiplies a 1D softmax model by a 1D gaussian mixture over a range For comparison to VB ''' [x,softmax] = self.plot1D(low,high,res,vis = False); prod = [0 for i in range(0,len(x))]; for i in range(0,len(x)): prod[i] = prior.pointEval(x[i])*softmax[meas][i]; if(vis == False): return [x,prod]; else: plt.plot(x,prod); plt.show(); def vb_update(self, measurement, prior_mean,prior_var): ''' Runs the variational Bayes update ''' w = np.array(self.weights) b = np.array(self.bias) m = len(w); j = measurement; xis = self.zeta_c; alpha = self.alpha; prior_var = np.array(prior_var); prior_mean = np.array(prior_mean); converged = False EM_step = 0 while not converged and EM_step < 10000: ################################################################ # STEP 1 - EXPECTATION ################################################################ # PART A ####################################################### # find g_j sum1 = 0 for c in range(m): if c != j: sum1 += b[c] sum2 = 0 for c in range(m): sum2 = xis[c] / 2 \ + self._lambda(xis[c]) * (xis[c] ** 2 - (b[c] - alpha) ** 2) \ - np.log(1 + np.exp(xis[c])) g_j = 0.5 * (b[j] - sum1) + alpha * (m / 2 - 1) + sum2 # find h_j sum1 = 0 for c in range(m): if c != j: sum1 += w[c] sum2 = 0 for c in range(m): sum2 += self._lambda(xis[c]) * (alpha - b[c]) * w[c] h_j = 0.5 * (w[j] - sum1) + 2 * sum2 # find K_j sum1 = 0 for c in range(m): sum1 += self._lambda(xis[c]) * np.outer(w[c], (w[c])) K_j = 2 * sum1 K_p = inv(prior_var) g_p = -0.5 * (np.log(np.linalg.det(2 * np.pi * prior_var))) \ + prior_mean.T .dot (K_p) .dot (prior_var) h_p = K_p .dot (prior_mean) g_l = g_p + g_j h_l = h_p + h_j K_l = K_p + K_j mu_hat = inv(K_l) .dot (h_l) var_hat = inv(K_l) # PART B ####################################################### y_cs = np.zeros(m) y_cs_squared = np.zeros(m) for c in range(m): y_cs[c] = w[c].T .dot (mu_hat) + b[c] y_cs_squared[c] = w[c].T .dot \ (var_hat + np.outer(mu_hat, mu_hat.T)) .dot (w[c]) \ + 2 * w[c].T .dot (mu_hat) * b[c] + b[c] ** 2 ################################################################ # STEP 2 - MAXIMIZATION ################################################################ for i in range(100): # n_{lc} # PART A ###################################################### # Find xis for c in range(m): xis[c] = np.sqrt(y_cs_squared[c] + alpha ** 2 - 2 * alpha * y_cs[c]) # PART B ###################################################### # Find alpha num_sum = 0 den_sum = 0 for c in range(m): num_sum += self._lambda(xis[c]) * y_cs[c] den_sum += self._lambda(xis[c]) alpha =
help menu and tab completion self.hidden_commands = ['eof', '_relative_run_script'] # Initialize history self._persistent_history_length = persistent_history_length self._initialize_history(persistent_history_file) # Commands to exclude from the history command self.exclude_from_history = ['eof', 'history'] # Dictionary of macro names and their values self.macros = dict() # type: Dict[str, Macro] # Keeps track of typed command history in the Python shell self._py_history = [] # The name by which Python environments refer to the PyBridge to call app commands self.py_bridge_name = 'app' # Defines app-specific variables/functions available in Python shells and pyscripts self.py_locals = dict() # True if running inside a Python script or interactive console, False otherwise self._in_py = False self.statement_parser = StatementParser(terminators=terminators, multiline_commands=multiline_commands, shortcuts=shortcuts) # Stores results from the last command run to enable usage of results in a Python script or interactive console # Built-in commands don't make use of this. It is purely there for user-defined commands and convenience. self.last_result = None # Used by run_script command to store current script dir as a LIFO queue to support _relative_run_script command self._script_dir = [] # type: List[str] # Context manager used to protect critical sections in the main thread from stopping due to a KeyboardInterrupt self.sigint_protection = utils.ContextFlag() # If the current command created a process to pipe to, then this will be a ProcReader object. # Otherwise it will be None. It's used to know when a pipe process can be killed and/or waited upon. self._cur_pipe_proc_reader = None # type: Optional[utils.ProcReader] # Used to keep track of whether we are redirecting or piping output self._redirecting = False # Used to keep track of whether a continuation prompt is being displayed self._at_continuation_prompt = False # The multiline command currently being typed which is used to tab complete multiline commands. self._multiline_in_progress = '' # Set the header used for the help function's listing of documented functions self.doc_header = "Documented commands (use 'help -v' for verbose/'help <topic>' for details):" # The error that prints when no help information can be found self.help_error = "No help on {}" # The error that prints when a non-existent command is run self.default_error = "{} is not a recognized command, alias, or macro" # If non-empty, this string will be displayed if a broken pipe error occurs self.broken_pipe_warning = '' # Commands that will run at the beginning of the command loop self._startup_commands = [] # type: List[str] # If a startup script is provided and exists, then execute it in the startup commands if startup_script: startup_script = os.path.abspath(os.path.expanduser(startup_script)) if os.path.exists(startup_script): script_cmd = "run_script {}".format(utils.quote_string(startup_script)) if silent_startup_script: script_cmd += "> {}".format(os.devnull) self._startup_commands.append(script_cmd) # Transcript files to run instead of interactive command loop self._transcript_files = None # type: Optional[List[str]] # Check for command line args if allow_cli_args: parser = argparse.ArgumentParser() parser.add_argument('-t', '--test', action="store_true", help='Test against transcript(s) in FILE (wildcards OK)') callopts, callargs = parser.parse_known_args() # If transcript testing was called for, use other arguments as transcript files if callopts.test: self._transcript_files = callargs # If commands were supplied at invocation, then add them to the command queue elif callargs: self._startup_commands.extend(callargs) elif transcript_files: self._transcript_files = transcript_files # Set the pager(s) for use with the ppaged() method for displaying output using a pager if sys.platform.startswith('win'): self.pager = self.pager_chop = 'more' else: # Here is the meaning of the various flags we are using with the less command: # -S causes lines longer than the screen width to be chopped (truncated) rather than wrapped # -R causes ANSI "style" escape sequences to be output in raw form (i.e. colors are displayed) # -X disables sending the termcap initialization and deinitialization strings to the terminal # -F causes less to automatically exit if the entire file can be displayed on the first screen self.pager = 'less -RXF' self.pager_chop = 'less -SRXF' # This boolean flag determines whether or not the cmd2 application can interact with the clipboard self._can_clip = can_clip # This determines the value returned by cmdloop() when exiting the application self.exit_code = 0 # This lock should be acquired before doing any asynchronous changes to the terminal to # ensure the updates to the terminal don't interfere with the input being typed or output # being printed by a command. self.terminal_lock = threading.RLock() # Commands that have been disabled from use. This is to support commands that are only available # during specific states of the application. This dictionary's keys are the command names and its # values are DisabledCommand objects. self.disabled_commands = dict() # type: Dict[str, DisabledCommand] # If any command has been categorized, then all other commands that haven't been categorized # will display under this section in the help output. self.default_category = 'Uncategorized' # The default key for sorting string results. Its default value performs a case-insensitive alphabetical sort. # If natural sorting is preferred, then set this to NATURAL_SORT_KEY. # cmd2 uses this key for sorting: # command and category names # alias, macro, settable, and shortcut names # tab completion results when self.matches_sorted is False self.default_sort_key = Cmd.ALPHABETICAL_SORT_KEY ############################################################################################################ # The following variables are used by tab completion functions. They are reset each time complete() is run # in _reset_completion_defaults() and it is up to completer functions to set them before returning results. ############################################################################################################ # If True and a single match is returned to complete(), then a space will be appended # if the match appears at the end of the line self.allow_appended_space = True # If True and a single match is returned to complete(), then a closing quote # will be added if there is an unmatched opening quote self.allow_closing_quote = True # An optional hint which prints above tab completion suggestions self.completion_hint = '' # Header which prints above CompletionItem tables self.completion_header = '' # Used by complete() for readline tab completion self.completion_matches = [] # Use this list if you need to display tab completion suggestions that are different than the actual text # of the matches. For instance, if you are completing strings that contain a common delimiter and you only # want to display the final portion of the matches as the tab completion suggestions. The full matches # still must be returned from your completer function. For an example, look at path_complete() which # uses this to show only the basename of paths as the suggestions. delimiter_complete() also populates # this list. self.display_matches = [] # Used by functions like path_complete() and delimiter_complete() to properly # quote matches that are completed in a delimited fashion self.matches_delimited = False # Set to True before returning matches to complete() in cases where matches have already been sorted. # If False, then complete() will sort the matches using self.default_sort_key before they are displayed. self.matches_sorted = False ############################################################################################################ # The following code block loads CommandSets, verifies command names, and registers subcommands. # This block should appear after all attributes have been created since the registration code # depends on them and it's possible a module's on_register() method may need to access some. ############################################################################################################ # Load modular commands self._installed_command_sets = [] # type: List[CommandSet] self._cmd_to_command_sets = {} # type: Dict[str, CommandSet] if command_sets: for command_set in command_sets: self.register_command_set(command_set) if auto_load_commands: self._autoload_commands() # Verify commands don't have invalid names (like starting with a shortcut) for cur_cmd in self.get_all_commands(): valid, errmsg = self.statement_parser.is_valid_command(cur_cmd) if not valid: raise ValueError("Invalid command name {!r}: {}".format(cur_cmd, errmsg)) # Add functions decorated to be subcommands self._register_subcommands(self) def find_commandsets(self, commandset_type: Type[CommandSet], *, subclass_match: bool = False) -> List[CommandSet]: """ Find all CommandSets that match the provided CommandSet type. By default, locates a CommandSet that is an exact type match but may optionally return all CommandSets that are sub-classes of the provided type :param commandset_type: CommandSet sub-class type to search for :param subclass_match: If True, return all sub-classes of provided type, otherwise only search for exact
'''Crawl Weibo data of one Sina Weibo user. The Weibo data include: Short text, JPG/GIF images, live photos, and videos. The crawler simulates the login of Sina Weibo by using a session (not cookie)! Author: <NAME> @ University of Exeter Date: 16th April 2019 (Update: 20th April 2019) Contact: <EMAIL> <EMAIL> Copyright (c) 2019 <NAME> ''' # Python 3.7 import json import os import re import shutil import time import requests from lxml import html from pyCrawler_function import crawl_image from pyCrawler_function import crawl_photo from pyCrawler_function import crawl_video # 0. Specify reconnection settings (important). IF_RECONNECT = False # True - Run the crawler in the reconnection mode. # False - Run the crawler in the normal mode. # Set the serial number of the starting card/post (reconnection mode). TAG_STARTCARD = 29 if IF_RECONNECT: tag_card = TAG_STARTCARD else: tag_card = 0 # 1. Specify user settings. # 1.1 Simulate the login of Sina Weibo by using the session (important). S_URL = r'https://passport.weibo.cn/signin/login' # Fixed. S_DATA = {'username': 'XXXXX', # Replace XXXXX with the username of a valid Sina Weibo account. 'password': '<PASSWORD>', # Replace YYYYY with the password of the Sina Weibo account. 'savestate': '1', 'r': r'', 'ec': '0', 'pagerefer': '', 'entry': 'mweibo', 'wentry': '', 'loginfrom': '', 'client_id': '', 'code': '', 'qq': '', 'mainpageflag': '1', 'hff': '', 'hfp': '' } S_HEADER = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'en-GB,en;q=0.5', 'Connection': 'keep-alive', 'Referer': 'https://passport.weibo.cn/signin/login', 'Host': 'passport.weibo.cn' } session = requests.session() session.post(url=S_URL, data=S_DATA, headers=S_HEADER) # The information of 'S_DATA' and 'S_HEADER' can be obtained as below: # -> Open 'https://passport.weibo.cn/signin/login' in browser # -> Login with a valid Sina Weibo account # -> DevTools (F12) -> 'XHR' (tag) -> Refresh the web page (F5) # -> Open 'login' (file) in 'Name' (tag) -> 'Headers' (tag) # -> To obtain 'S_DATA', see 'Form Data' (label). # -> To obtain 'S_HEADER', see 'Request Headers' (label). # 1.2 Set the request URL of the target Sina Weibo user (important). USER_URL = r'https://m.weibo.cn/api/container/getIndex?type=uid&value=3347059490&containerid=1076033347059490' # The information of 'USER_URL' can be obtained as below: # -> Open 'https://m.weibo.cn/u/3347059490' in browser # -> Login with a valid Sina Weibo account # -> DevTools (F12) -> 'XHR' (tag) -> Refresh the web page (F5) # -> Open '*getindex...' (file) in 'Name' (tag) -> 'Headers' (tag) # -> To obtain 'USER_URL', see 'General' (label) -> 'Request URL'. # Note: # '3347059490' is the unique ID of the target Sina Weibo user. # The ID can be found in the address bar by opening the user's homepage in browser. # 1.3 Set the amount of web pages for crawling (important). PAGE_AMOUNT = 3 # Note: # The number of Weibo posts on the first web page is 13. # The number of Weibo posts on the other web page is 10. # The 'PAGE_AMOUNT' should be greater than 10% of the amount of Weibo posts. # 1.4 Set the nickname of the target Sina Weibo user. USER_NAME = 'Demo' # 1.5 Create the folder for saving Weibo data. PATH_FOLDER = USER_NAME + '_WeiboData/' if not IF_RECONNECT: # Do not re-create the folder in the reconnection mode. if os.path.exists(PATH_FOLDER): shutil.rmtree(PATH_FOLDER) os.mkdir(PATH_FOLDER) # 1.6 Set the TXT file for saving Weibo information. PATH_FILE_TXT = PATH_FOLDER + USER_NAME + '_WeiboPost_Records.txt' # 1.7 Select the type of Weibo data for crawling (0 - No or 1 - Yes). IF_IMAGE = 1 IF_PHOTO = 1 IF_VIDEO = 1 IF_LIVE2GIF = True # True - Convert live photos to GIF images. # False - Not convert live photos to GIF images. # 1.8 Set the delay of the crawler. TIME_DELAY = 3 # 2. Request 'cards' information from web pages. print('\n' + 40 * '=' + '\n' + 'Crawling Weibo Data of User - ' + USER_NAME + '\n' + 40 * '=') count_page = 0 # The serial number of web pages (starts from '1'). count_card = 0 # The serial number of cards/posts on one web page (starts from '1'). while count_page < PAGE_AMOUNT: count_page += 1 print('\n' + 40 * '-' + '\n' + 'Step 1 - Crawl \'cards\' Information' + '\n' + 40 * '-' + '\n') print('Start crawling \'cards\' on the page %d/%d.' % (count_page, PAGE_AMOUNT)) cards_list = [] # The 'cards' of all web pages. url = USER_URL + '&page=' + str(count_page) res = session.get(url) content = json.loads(res.text) # <dict> cards_list.append(content['data']['cards']) # content['data']['cards'] <list> time.sleep(TIME_DELAY) # Suspend TIME_DELAY seconds after requesting 'cards' from one web page. print('Complete!') # 3. Crawl Weibo data on one web page. # Note: Crawling Weibo data after crawling 'cards' on one web page might avoid the failure of downloading videos. print('\n' + 40 * '-' + '\n' + 'Step 2 - Crawl Weibo Data of ' + USER_NAME + '\n' + 40 * '-' + '\n') for cards in cards_list: for card in cards: count_card += 1 if IF_RECONNECT and count_card < tag_card: continue # Go back to 'count_card += 1'. if IF_RECONNECT and count_card == tag_card: # Delete the sub-folders for saving the starting card/post. path_image = PATH_FOLDER + str(count_card) + '/' if os.path.exists(path_image): shutil.rmtree(path_image) path_photo = PATH_FOLDER + str(count_card) + '_livephoto/' if os.path.exists(path_photo): shutil.rmtree(path_photo) path_video = PATH_FOLDER + str(count_card) + '_video/' if os.path.exists(path_video): shutil.rmtree(path_video) # Create sub-folders for saving Weibo data. path_image = PATH_FOLDER + str(count_card) + '/' os.mkdir(path_image) path_photo = PATH_FOLDER + str(count_card) + '_livephoto/' os.mkdir(path_photo) path_video = PATH_FOLDER + str(count_card) + '_video/' os.mkdir(path_video) print('Start crawling the ' + str(count_card) + '-th Weibo post on the page %d/%d.' % (count_page, PAGE_AMOUNT)) if card['card_type'] == 9: # The Weibo post which 'card_type = 9' has data. mid = card['mblog']['id'] publish_time = card['mblog']['created_at'] # 3.1 Crawl short text. print('Is LONG text?', card['mblog']['isLongText']) text = '' if card['mblog']['isLongText'] == 'True': # The string is 'True' not 'true'. text = '{LongText}' elif card['mblog']['isLongText'] == 'False': # The string is 'False' not 'false'. text = card['mblog']['text'] else: text = card['mblog']['text'] # Convert text to normal format (by removing hyperlinks). tree = html.fromstring(text) text = tree.xpath('string(.)') # Save text to the TXT file. with open(PATH_FILE_TXT, 'a', encoding='utf-8') as ff: ff.write('\n' + 'The ' + str(count_card) + '-th Weibo id: ' + str(mid) + '\n') ff.write('*** Published on ' + publish_time + ' ***' + '\n') if text: ff.write(text + '\n') else: print('*****Error: Failed to extract text.') ff.write('*****Error: Failed to extract text.' + '\n') # 3.2 Crawl JPG/GIF images. if IF_IMAGE == 1: # Step 1 Get the URL of JPG/GIF images. image_jpg_urls = [] image_gif_urls = [] url = 'https://m.weibo.cn/status/' + mid res = session.get(url).text # <str> # Find the URL of large JPG/GIF images. image_jpg_urls = re.findall('https://.*large.*.jpg', res) # <list> image_gif_urls = re.findall('https://.*large.*.gif', res) # <list> # Find the URL of small JPG/GIF images if no large image is found. if not image_jpg_urls: image_jpg_urls = re.findall('https://.*orj360.*.jpg', res) if not image_gif_urls: image_gif_urls = re.findall('https://.*orj360.*.gif', res) # Step 2 Crawl JPG/GIF images. if image_jpg_urls: crawl_image(PATH_FILE_TXT, path_image, image_jpg_urls, '.jpg') if image_gif_urls: crawl_image(PATH_FILE_TXT, path_image, image_gif_urls, '.gif') # 3.3 Crawl live photos. if IF_PHOTO == 1: # Step 1 Get the URL of live photos (videos). photo_urls = [] photo_url_start = 'https://video.weibo.com/media/play?livephoto=//us.sinaimg.cn/' # Fixed. photo_url_end = '.mov&KID=unistore,videomovSrc' # Fixed. # Find the URL of live photos (videos). card_info = '' if 'retweeted_status' not in card['mblog']: card_info = card['mblog'] elif 'retweeted_status' in card['mblog']: card_info = card['mblog']['retweeted_status'] else: card_info = '' if card_info: if 'pic_video' in card_info: photo_str = card_info['pic_video'] photo_list = re.split('[,]', photo_str) for photo in photo_list: # E.g., 'photo' = '0:000voDMsjx07t57qM583010f0100alDF0k01'. photo_code = re.split('[:]', photo)[1] photo_url = photo_url_start + photo_code + photo_url_end photo_urls.append(photo_url) # Step 2 Crawl live photos. if photo_urls: crawl_photo(PATH_FILE_TXT, path_photo, photo_urls, if_live2gif=IF_LIVE2GIF) # 3.4 Crawl videos. if IF_VIDEO == 1: # Step 1 Get the URL of videos. video_urls = [] # A Weibo post can only have one video. video_hd_url = '' # The URL of HD video source. video_sd_url = '' # The URL of SD video source. # Find the URL of videos. card_info = '' if 'retweeted_status' not in card['mblog']: try: card_info = card['mblog']['page_info']['media_info'] except: card_info = '' elif 'retweeted_status' in card['mblog']: try: card_info = card['mblog']['retweeted_status']['page_info']['media_info'] except: card_info = '' if card_info: # Find the URL of HD video source. try: video_hd_url = card_info['mp4_hd_url'] except: video_hd_url =
:param S: :type S: Handle_Adaptor3d_HSurface & :param Tol: :type Tol: float :rtype: None """ _ProjLib.ProjLib_ComputeApprox_swiginit(self,_ProjLib.new_ProjLib_ComputeApprox(*args)) def BSpline(self, *args): """ :rtype: Handle_Geom2d_BSplineCurve """ return _ProjLib.ProjLib_ComputeApprox_BSpline(self, *args) def Bezier(self, *args): """ :rtype: Handle_Geom2d_BezierCurve """ return _ProjLib.ProjLib_ComputeApprox_Bezier(self, *args) def Tolerance(self, *args): """ * returns the reached Tolerance. :rtype: float """ return _ProjLib.ProjLib_ComputeApprox_Tolerance(self, *args) def __del__(self): try: self.thisown = False GarbageCollector.garbage.collect_object(self) except: pass ProjLib_ComputeApprox.BSpline = new_instancemethod(_ProjLib.ProjLib_ComputeApprox_BSpline,None,ProjLib_ComputeApprox) ProjLib_ComputeApprox.Bezier = new_instancemethod(_ProjLib.ProjLib_ComputeApprox_Bezier,None,ProjLib_ComputeApprox) ProjLib_ComputeApprox.Tolerance = new_instancemethod(_ProjLib.ProjLib_ComputeApprox_Tolerance,None,ProjLib_ComputeApprox) ProjLib_ComputeApprox._kill_pointed = new_instancemethod(_ProjLib.ProjLib_ComputeApprox__kill_pointed,None,ProjLib_ComputeApprox) ProjLib_ComputeApprox_swigregister = _ProjLib.ProjLib_ComputeApprox_swigregister ProjLib_ComputeApprox_swigregister(ProjLib_ComputeApprox) class ProjLib_ComputeApproxOnPolarSurface(object): thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """ :rtype: None :param C: :type C: Handle_Adaptor3d_HCurve & :param S: :type S: Handle_Adaptor3d_HSurface & :param Tol: default value is 1.0e-4 :type Tol: float :rtype: None :param InitCurve2d: :type InitCurve2d: Handle_Adaptor2d_HCurve2d & :param C: :type C: Handle_Adaptor3d_HCurve & :param S: :type S: Handle_Adaptor3d_HSurface & :param Tol: :type Tol: float :rtype: None :param InitCurve2d: :type InitCurve2d: Handle_Adaptor2d_HCurve2d & :param InitCurve2dBis: :type InitCurve2dBis: Handle_Adaptor2d_HCurve2d & :param C: :type C: Handle_Adaptor3d_HCurve & :param S: :type S: Handle_Adaptor3d_HSurface & :param Tol: :type Tol: float :rtype: None """ _ProjLib.ProjLib_ComputeApproxOnPolarSurface_swiginit(self,_ProjLib.new_ProjLib_ComputeApproxOnPolarSurface(*args)) def Perform(self, *args): """ :param InitCurve2d: :type InitCurve2d: Handle_Adaptor2d_HCurve2d & :param C: :type C: Handle_Adaptor3d_HCurve & :param S: :type S: Handle_Adaptor3d_HSurface & :rtype: Handle_Geom2d_BSplineCurve """ return _ProjLib.ProjLib_ComputeApproxOnPolarSurface_Perform(self, *args) def BuildInitialCurve2d(self, *args): """ :param Curve: :type Curve: Handle_Adaptor3d_HCurve & :param S: :type S: Handle_Adaptor3d_HSurface & :rtype: Handle_Adaptor2d_HCurve2d """ return _ProjLib.ProjLib_ComputeApproxOnPolarSurface_BuildInitialCurve2d(self, *args) def ProjectUsingInitialCurve2d(self, *args): """ :param Curve: :type Curve: Handle_Adaptor3d_HCurve & :param S: :type S: Handle_Adaptor3d_HSurface & :param InitCurve2d: :type InitCurve2d: Handle_Adaptor2d_HCurve2d & :rtype: Handle_Geom2d_BSplineCurve """ return _ProjLib.ProjLib_ComputeApproxOnPolarSurface_ProjectUsingInitialCurve2d(self, *args) def BSpline(self, *args): """ :rtype: Handle_Geom2d_BSplineCurve """ return _ProjLib.ProjLib_ComputeApproxOnPolarSurface_BSpline(self, *args) def Curve2d(self, *args): """ :rtype: Handle_Geom2d_Curve """ return _ProjLib.ProjLib_ComputeApproxOnPolarSurface_Curve2d(self, *args) def IsDone(self, *args): """ :rtype: bool """ return _ProjLib.ProjLib_ComputeApproxOnPolarSurface_IsDone(self, *args) def __del__(self): try: self.thisown = False GarbageCollector.garbage.collect_object(self) except: pass ProjLib_ComputeApproxOnPolarSurface.Perform = new_instancemethod(_ProjLib.ProjLib_ComputeApproxOnPolarSurface_Perform,None,ProjLib_ComputeApproxOnPolarSurface) ProjLib_ComputeApproxOnPolarSurface.BuildInitialCurve2d = new_instancemethod(_ProjLib.ProjLib_ComputeApproxOnPolarSurface_BuildInitialCurve2d,None,ProjLib_ComputeApproxOnPolarSurface) ProjLib_ComputeApproxOnPolarSurface.ProjectUsingInitialCurve2d = new_instancemethod(_ProjLib.ProjLib_ComputeApproxOnPolarSurface_ProjectUsingInitialCurve2d,None,ProjLib_ComputeApproxOnPolarSurface) ProjLib_ComputeApproxOnPolarSurface.BSpline = new_instancemethod(_ProjLib.ProjLib_ComputeApproxOnPolarSurface_BSpline,None,ProjLib_ComputeApproxOnPolarSurface) ProjLib_ComputeApproxOnPolarSurface.Curve2d = new_instancemethod(_ProjLib.ProjLib_ComputeApproxOnPolarSurface_Curve2d,None,ProjLib_ComputeApproxOnPolarSurface) ProjLib_ComputeApproxOnPolarSurface.IsDone = new_instancemethod(_ProjLib.ProjLib_ComputeApproxOnPolarSurface_IsDone,None,ProjLib_ComputeApproxOnPolarSurface) ProjLib_ComputeApproxOnPolarSurface._kill_pointed = new_instancemethod(_ProjLib.ProjLib_ComputeApproxOnPolarSurface__kill_pointed,None,ProjLib_ComputeApproxOnPolarSurface) ProjLib_ComputeApproxOnPolarSurface_swigregister = _ProjLib.ProjLib_ComputeApproxOnPolarSurface_swigregister ProjLib_ComputeApproxOnPolarSurface_swigregister(ProjLib_ComputeApproxOnPolarSurface) class ProjLib_HCompProjectedCurve(OCC.Adaptor2d.Adaptor2d_HCurve2d): thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """ :rtype: None :param C: :type C: ProjLib_CompProjectedCurve & :rtype: None """ _ProjLib.ProjLib_HCompProjectedCurve_swiginit(self,_ProjLib.new_ProjLib_HCompProjectedCurve(*args)) def Set(self, *args): """ :param C: :type C: ProjLib_CompProjectedCurve & :rtype: None """ return _ProjLib.ProjLib_HCompProjectedCurve_Set(self, *args) def ChangeCurve2d(self, *args): """ :rtype: ProjLib_CompProjectedCurve """ return _ProjLib.ProjLib_HCompProjectedCurve_ChangeCurve2d(self, *args) def _kill_pointed(self): """_kill_pointed(ProjLib_HCompProjectedCurve self)""" return _ProjLib.ProjLib_HCompProjectedCurve__kill_pointed(self) def GetHandle(self): """GetHandle(ProjLib_HCompProjectedCurve self) -> Handle_ProjLib_HCompProjectedCurve""" return _ProjLib.ProjLib_HCompProjectedCurve_GetHandle(self) def __del__(self): try: self.thisown = False GarbageCollector.garbage.collect_object(self) except: pass ProjLib_HCompProjectedCurve.Set = new_instancemethod(_ProjLib.ProjLib_HCompProjectedCurve_Set,None,ProjLib_HCompProjectedCurve) ProjLib_HCompProjectedCurve.ChangeCurve2d = new_instancemethod(_ProjLib.ProjLib_HCompProjectedCurve_ChangeCurve2d,None,ProjLib_HCompProjectedCurve) ProjLib_HCompProjectedCurve._kill_pointed = new_instancemethod(_ProjLib.ProjLib_HCompProjectedCurve__kill_pointed,None,ProjLib_HCompProjectedCurve) ProjLib_HCompProjectedCurve.GetHandle = new_instancemethod(_ProjLib.ProjLib_HCompProjectedCurve_GetHandle,None,ProjLib_HCompProjectedCurve) ProjLib_HCompProjectedCurve_swigregister = _ProjLib.ProjLib_HCompProjectedCurve_swigregister ProjLib_HCompProjectedCurve_swigregister(ProjLib_HCompProjectedCurve) class Handle_ProjLib_HCompProjectedCurve(OCC.Adaptor2d.Handle_Adaptor2d_HCurve2d): thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): _ProjLib.Handle_ProjLib_HCompProjectedCurve_swiginit(self,_ProjLib.new_Handle_ProjLib_HCompProjectedCurve(*args)) DownCast = staticmethod(_ProjLib.Handle_ProjLib_HCompProjectedCurve_DownCast) def __del__(self): try: self.thisown = False GarbageCollector.garbage.collect_object(self) except: pass Handle_ProjLib_HCompProjectedCurve.Nullify = new_instancemethod(_ProjLib.Handle_ProjLib_HCompProjectedCurve_Nullify,None,Handle_ProjLib_HCompProjectedCurve) Handle_ProjLib_HCompProjectedCurve.IsNull = new_instancemethod(_ProjLib.Handle_ProjLib_HCompProjectedCurve_IsNull,None,Handle_ProjLib_HCompProjectedCurve) Handle_ProjLib_HCompProjectedCurve.GetObject = new_instancemethod(_ProjLib.Handle_ProjLib_HCompProjectedCurve_GetObject,None,Handle_ProjLib_HCompProjectedCurve) Handle_ProjLib_HCompProjectedCurve._kill_pointed = new_instancemethod(_ProjLib.Handle_ProjLib_HCompProjectedCurve__kill_pointed,None,Handle_ProjLib_HCompProjectedCurve) Handle_ProjLib_HCompProjectedCurve_swigregister = _ProjLib.Handle_ProjLib_HCompProjectedCurve_swigregister Handle_ProjLib_HCompProjectedCurve_swigregister(Handle_ProjLib_HCompProjectedCurve) def Handle_ProjLib_HCompProjectedCurve_DownCast(*args): return _ProjLib.Handle_ProjLib_HCompProjectedCurve_DownCast(*args) Handle_ProjLib_HCompProjectedCurve_DownCast = _ProjLib.Handle_ProjLib_HCompProjectedCurve_DownCast class ProjLib_HProjectedCurve(OCC.Adaptor2d.Adaptor2d_HCurve2d): thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """ :rtype: None :param C: :type C: ProjLib_ProjectedCurve & :rtype: None """ _ProjLib.ProjLib_HProjectedCurve_swiginit(self,_ProjLib.new_ProjLib_HProjectedCurve(*args)) def Set(self, *args): """ :param C: :type C: ProjLib_ProjectedCurve & :rtype: None """ return _ProjLib.ProjLib_HProjectedCurve_Set(self, *args) def ChangeCurve2d(self, *args): """ :rtype: ProjLib_ProjectedCurve """ return _ProjLib.ProjLib_HProjectedCurve_ChangeCurve2d(self, *args) def _kill_pointed(self): """_kill_pointed(ProjLib_HProjectedCurve self)""" return _ProjLib.ProjLib_HProjectedCurve__kill_pointed(self) def GetHandle(self): """GetHandle(ProjLib_HProjectedCurve self) -> Handle_ProjLib_HProjectedCurve""" return _ProjLib.ProjLib_HProjectedCurve_GetHandle(self) def __del__(self): try: self.thisown = False GarbageCollector.garbage.collect_object(self) except: pass ProjLib_HProjectedCurve.Set = new_instancemethod(_ProjLib.ProjLib_HProjectedCurve_Set,None,ProjLib_HProjectedCurve) ProjLib_HProjectedCurve.ChangeCurve2d = new_instancemethod(_ProjLib.ProjLib_HProjectedCurve_ChangeCurve2d,None,ProjLib_HProjectedCurve) ProjLib_HProjectedCurve._kill_pointed = new_instancemethod(_ProjLib.ProjLib_HProjectedCurve__kill_pointed,None,ProjLib_HProjectedCurve) ProjLib_HProjectedCurve.GetHandle = new_instancemethod(_ProjLib.ProjLib_HProjectedCurve_GetHandle,None,ProjLib_HProjectedCurve) ProjLib_HProjectedCurve_swigregister = _ProjLib.ProjLib_HProjectedCurve_swigregister ProjLib_HProjectedCurve_swigregister(ProjLib_HProjectedCurve) class Handle_ProjLib_HProjectedCurve(OCC.Adaptor2d.Handle_Adaptor2d_HCurve2d): thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): _ProjLib.Handle_ProjLib_HProjectedCurve_swiginit(self,_ProjLib.new_Handle_ProjLib_HProjectedCurve(*args)) DownCast = staticmethod(_ProjLib.Handle_ProjLib_HProjectedCurve_DownCast) def __del__(self): try: self.thisown = False GarbageCollector.garbage.collect_object(self) except: pass Handle_ProjLib_HProjectedCurve.Nullify = new_instancemethod(_ProjLib.Handle_ProjLib_HProjectedCurve_Nullify,None,Handle_ProjLib_HProjectedCurve) Handle_ProjLib_HProjectedCurve.IsNull = new_instancemethod(_ProjLib.Handle_ProjLib_HProjectedCurve_IsNull,None,Handle_ProjLib_HProjectedCurve) Handle_ProjLib_HProjectedCurve.GetObject = new_instancemethod(_ProjLib.Handle_ProjLib_HProjectedCurve_GetObject,None,Handle_ProjLib_HProjectedCurve) Handle_ProjLib_HProjectedCurve._kill_pointed = new_instancemethod(_ProjLib.Handle_ProjLib_HProjectedCurve__kill_pointed,None,Handle_ProjLib_HProjectedCurve) Handle_ProjLib_HProjectedCurve_swigregister = _ProjLib.Handle_ProjLib_HProjectedCurve_swigregister Handle_ProjLib_HProjectedCurve_swigregister(Handle_ProjLib_HProjectedCurve) def Handle_ProjLib_HProjectedCurve_DownCast(*args): return _ProjLib.Handle_ProjLib_HProjectedCurve_DownCast(*args) Handle_ProjLib_HProjectedCurve_DownCast = _ProjLib.Handle_ProjLib_HProjectedCurve_DownCast class ProjLib_HSequenceOfHSequenceOfPnt(OCC.MMgt.MMgt_TShared): thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """ :rtype: None """ _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_swiginit(self,_ProjLib.new_ProjLib_HSequenceOfHSequenceOfPnt(*args)) def IsEmpty(self, *args): """ :rtype: bool """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_IsEmpty(self, *args) def Length(self, *args): """ :rtype: int """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Length(self, *args) def Clear(self, *args): """ :rtype: None """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Clear(self, *args) def Append(self, *args): """ :param anItem: :type anItem: Handle_TColgp_HSequenceOfPnt :rtype: None :param aSequence: :type aSequence: Handle_ProjLib_HSequenceOfHSequenceOfPnt & :rtype: None """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Append(self, *args) def Prepend(self, *args): """ :param anItem: :type anItem: Handle_TColgp_HSequenceOfPnt :rtype: None :param aSequence: :type aSequence: Handle_ProjLib_HSequenceOfHSequenceOfPnt & :rtype: None """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Prepend(self, *args) def Reverse(self, *args): """ :rtype: None """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Reverse(self, *args) def InsertBefore(self, *args): """ :param anIndex: :type anIndex: int :param anItem: :type anItem: Handle_TColgp_HSequenceOfPnt :rtype: None :param anIndex: :type anIndex: int :param aSequence: :type aSequence: Handle_ProjLib_HSequenceOfHSequenceOfPnt & :rtype: None """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_InsertBefore(self, *args) def InsertAfter(self, *args): """ :param anIndex: :type anIndex: int :param anItem: :type anItem: Handle_TColgp_HSequenceOfPnt :rtype: None :param anIndex: :type anIndex: int :param aSequence: :type aSequence: Handle_ProjLib_HSequenceOfHSequenceOfPnt & :rtype: None """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_InsertAfter(self, *args) def Exchange(self, *args): """ :param anIndex: :type anIndex: int :param anOtherIndex: :type anOtherIndex: int :rtype: None """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Exchange(self, *args) def Split(self, *args): """ :param anIndex: :type anIndex: int :rtype: Handle_ProjLib_HSequenceOfHSequenceOfPnt """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Split(self, *args) def SetValue(self, *args): """ :param anIndex: :type anIndex: int :param anItem: :type anItem: Handle_TColgp_HSequenceOfPnt :rtype: None """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_SetValue(self, *args) def Value(self, *args): """ :param anIndex: :type anIndex: int :rtype: Handle_TColgp_HSequenceOfPnt """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Value(self, *args) def ChangeValue(self, *args): """ :param anIndex: :type anIndex: int :rtype: Handle_TColgp_HSequenceOfPnt """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_ChangeValue(self, *args) def Remove(self, *args): """ :param anIndex: :type anIndex: int :rtype: None :param fromIndex: :type fromIndex: int :param toIndex: :type toIndex: int :rtype: None """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Remove(self, *args) def Sequence(self, *args): """ :rtype: ProjLib_SequenceOfHSequenceOfPnt """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Sequence(self, *args) def ChangeSequence(self, *args): """ :rtype: ProjLib_SequenceOfHSequenceOfPnt """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_ChangeSequence(self, *args) def ShallowCopy(self, *args): """ :rtype: Handle_ProjLib_HSequenceOfHSequenceOfPnt """ return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_ShallowCopy(self, *args) def _kill_pointed(self): """_kill_pointed(ProjLib_HSequenceOfHSequenceOfPnt self)""" return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt__kill_pointed(self) def GetHandle(self): """GetHandle(ProjLib_HSequenceOfHSequenceOfPnt self) -> Handle_ProjLib_HSequenceOfHSequenceOfPnt""" return _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_GetHandle(self) def __del__(self): try: self.thisown = False GarbageCollector.garbage.collect_object(self) except: pass ProjLib_HSequenceOfHSequenceOfPnt.IsEmpty = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_IsEmpty,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Length = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Length,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Clear = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Clear,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Append = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Append,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Prepend = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Prepend,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Reverse = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Reverse,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.InsertBefore = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_InsertBefore,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.InsertAfter = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_InsertAfter,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Exchange = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Exchange,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Split = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Split,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.SetValue = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_SetValue,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Value = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Value,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.ChangeValue = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_ChangeValue,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Remove = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Remove,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.Sequence = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_Sequence,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.ChangeSequence = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_ChangeSequence,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.ShallowCopy = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_ShallowCopy,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt._kill_pointed = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt__kill_pointed,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt.GetHandle = new_instancemethod(_ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_GetHandle,None,ProjLib_HSequenceOfHSequenceOfPnt) ProjLib_HSequenceOfHSequenceOfPnt_swigregister = _ProjLib.ProjLib_HSequenceOfHSequenceOfPnt_swigregister ProjLib_HSequenceOfHSequenceOfPnt_swigregister(ProjLib_HSequenceOfHSequenceOfPnt) class Handle_ProjLib_HSequenceOfHSequenceOfPnt(OCC.MMgt.Handle_MMgt_TShared): thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): _ProjLib.Handle_ProjLib_HSequenceOfHSequenceOfPnt_swiginit(self,_ProjLib.new_Handle_ProjLib_HSequenceOfHSequenceOfPnt(*args)) DownCast = staticmethod(_ProjLib.Handle_ProjLib_HSequenceOfHSequenceOfPnt_DownCast) def __del__(self): try: self.thisown = False GarbageCollector.garbage.collect_object(self) except: pass Handle_ProjLib_HSequenceOfHSequenceOfPnt.Nullify = new_instancemethod(_ProjLib.Handle_ProjLib_HSequenceOfHSequenceOfPnt_Nullify,None,Handle_ProjLib_HSequenceOfHSequenceOfPnt) Handle_ProjLib_HSequenceOfHSequenceOfPnt.IsNull = new_instancemethod(_ProjLib.Handle_ProjLib_HSequenceOfHSequenceOfPnt_IsNull,None,Handle_ProjLib_HSequenceOfHSequenceOfPnt) Handle_ProjLib_HSequenceOfHSequenceOfPnt.GetObject = new_instancemethod(_ProjLib.Handle_ProjLib_HSequenceOfHSequenceOfPnt_GetObject,None,Handle_ProjLib_HSequenceOfHSequenceOfPnt) Handle_ProjLib_HSequenceOfHSequenceOfPnt._kill_pointed = new_instancemethod(_ProjLib.Handle_ProjLib_HSequenceOfHSequenceOfPnt__kill_pointed,None,Handle_ProjLib_HSequenceOfHSequenceOfPnt) Handle_ProjLib_HSequenceOfHSequenceOfPnt_swigregister = _ProjLib.Handle_ProjLib_HSequenceOfHSequenceOfPnt_swigregister Handle_ProjLib_HSequenceOfHSequenceOfPnt_swigregister(Handle_ProjLib_HSequenceOfHSequenceOfPnt) def Handle_ProjLib_HSequenceOfHSequenceOfPnt_DownCast(*args): return _ProjLib.Handle_ProjLib_HSequenceOfHSequenceOfPnt_DownCast(*args) Handle_ProjLib_HSequenceOfHSequenceOfPnt_DownCast = _ProjLib.Handle_ProjLib_HSequenceOfHSequenceOfPnt_DownCast class ProjLib_PrjFunc(object): thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """ :param C: :type C: Adaptor3d_CurvePtr & :param FixVal: :type FixVal: float :param S: :type S: Adaptor3d_SurfacePtr & :param Fix: :type Fix: int :rtype: None """ _ProjLib.ProjLib_PrjFunc_swiginit(self,_ProjLib.new_ProjLib_PrjFunc(*args)) def NbVariables(self, *args): """ * returns the number of variables of the function. :rtype: int """ return _ProjLib.ProjLib_PrjFunc_NbVariables(self, *args) def NbEquations(self, *args): """ * returns the number of equations of the function. :rtype: int """ return _ProjLib.ProjLib_PrjFunc_NbEquations(self, *args) def Value(self, *args): """ * computes the values <F> of the Functions for the variable <X>. Returns True if the computation was done successfully, False otherwise. :param X: :type X: math_Vector & :param F: :type F: math_Vector & :rtype: bool """ return _ProjLib.ProjLib_PrjFunc_Value(self, *args) def Derivatives(self, *args): """ * returns the values <D> of the derivatives for the variable <X>. Returns True if the computation was done successfully, False otherwise. :param X: :type X: math_Vector & :param D: :type D: math_Matrix & :rtype: bool """ return _ProjLib.ProjLib_PrjFunc_Derivatives(self, *args) def Values(self, *args): """ * returns the values <F> of the functions and the derivatives <D> for the variable <X>. Returns True if the computation was done successfully, False otherwise. :param X: :type X: math_Vector & :param F: :type F: math_Vector & :param D: :type D: math_Matrix & :rtype: bool """ return _ProjLib.ProjLib_PrjFunc_Values(self, *args) def Solution(self, *args): """ * returns point on surface :rtype: gp_Pnt2d """ return _ProjLib.ProjLib_PrjFunc_Solution(self, *args) def __del__(self): try: self.thisown = False GarbageCollector.garbage.collect_object(self) except: pass ProjLib_PrjFunc.NbVariables = new_instancemethod(_ProjLib.ProjLib_PrjFunc_NbVariables,None,ProjLib_PrjFunc) ProjLib_PrjFunc.NbEquations = new_instancemethod(_ProjLib.ProjLib_PrjFunc_NbEquations,None,ProjLib_PrjFunc) ProjLib_PrjFunc.Value = new_instancemethod(_ProjLib.ProjLib_PrjFunc_Value,None,ProjLib_PrjFunc) ProjLib_PrjFunc.Derivatives = new_instancemethod(_ProjLib.ProjLib_PrjFunc_Derivatives,None,ProjLib_PrjFunc) ProjLib_PrjFunc.Values = new_instancemethod(_ProjLib.ProjLib_PrjFunc_Values,None,ProjLib_PrjFunc) ProjLib_PrjFunc.Solution = new_instancemethod(_ProjLib.ProjLib_PrjFunc_Solution,None,ProjLib_PrjFunc) ProjLib_PrjFunc._kill_pointed =
<reponame>stuart-nolan/mpdb<gh_stars>0 """ mpdb: Material Property Data Base as python package yawsImport.py: Yaws Chemical Property Handbook Revision Date: 2021.08.16 SPDX-License-Identifier: BSD-2-Clause Copyright (c) 2021 <NAME>. All rights reserved. """ from mpdb.utils import dbSave, dbLoad from mpdb.eq.yaws_python import * import csv import os import re from time import strftime, sleep from math import log10 import requests from html.parser import HTMLParser class pHTML(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.out = [] def handle_data(self,data): self.out.append(data) def updateCAS(): """ find missing CAS numbers and add them in yaws csv files EDITS MAY BE REQUIRED BEFORE USE """ # import yaws db only... yawsPath = os.path.join('yaws') (db, dbMetaData) = dbLoad(interactive=True, dataDir=yawsPath) noCAS = {key:val['formula'] for (key,val) in db.items() if val['CAS'] == ''} URL = "https://toxgate.nlm.nih.gov/cgi-bin/sis/search2" PARAMS = {"queryxxx":"", "database":"hsdb", "Stemming":1, "and":1, "second_search":1, "gateway":1, "chemsyn":1} p = pHTML() CAS = {} for key,val in noCAS.items(): PARAMS["queryxxx"] = key print("Looking up %s cas number" % key) r = requests.post(url = URL, data = PARAMS) p.feed(r.text) if 'CAS Registry Number: ' in p.out: CAS[key] = p.out[p.out.index('CAS Registry Number: ')+1] print("Found %s cas: %s" % (key,CAS[key])) p.out = [] # don't spam the server... sleep(1) """ for key,val in CAS.items(): noCAS.pop(key,None) """ fileNames = ['activatedCarbonAdsorption.csv', 'criticalProperty.csv', 'energyFormationGAS.csv', 'energyFormationHUS.csv', 'enthalpyCombustion.csv', 'enthalpyFusion.csv', 'enthalpyVaporization.csv', 'henrysLaw.csv', 'liquidHeatCapacity.csv', 'liquidDensity.csv', 'liquidThermalConductivity.csv', 'liquidViscosity.csv', 'saltWaterSolubility.csv', 'solidHeatCapacity.csv', 'surfaceTension.csv', 'thermalConductivity.csv', 'vaporEnthalpyFormation.csv', 'vaporGibbsEnergyFormation.csv', 'vaporHeatCapacity.csv', 'vaporPressure.csv', 'vaporThermalConductivity.csv', 'vaporViscosity.csv', 'waterSolubility.csv'] #read the data in path = 'data' for fileName in fileNames: try: file = os.path.join(path,fileName) csvFileHandle = open(file, 'r') csvReader = csv.reader(csvFileHandle,dialect='excel') except: print("File: %s" %file+" not found. Check path and file name.") return csvRows = [] # custom update code for row in csvReader: if row[1] in CAS.keys(): #row[1] is the chemical name row[2] = CAS[row[1]] #replace CAS number csvRows.append(row) csvFileHandle.close() # rename the original csv file before saving the updated one os.rename(file,file+'.bak') #output a new csvFile csvFileHandle = open(file, 'w') csvWriter = csv.writer(csvFileHandle,dialect='excel') csvWriter.writerows(csvRows) csvFileHandle.close() class YCPH(): def __init__(self): """ Pure component chemical substance data from Yaws' Handbook of Thermodynamic and Physical Properties of Chemical Compounds. """ self.refndSpace = re.compile(r'\s+') self.reUnitSep = re.compile(r'(.*?)/(.*)') self.reCSV = re.compile(r'.*csv') self.csvPath = os.path.join('yaws') self.db = {} self.dbMetaData = {} self.importDateTime = strftime("%Y%m%d-%H%M") def importYaws(self): """ importYaws() Call the YCPH methods in the specifed sequence. Returns: [self.db, self.dbMetaData] """ # initilize db and dbMetaData in criticalProperty self.criticalProperty() # call the following functions after criticalProperty but otheriwse # without regard to sequence self.activatedCarbonAdsorption() self.energyFormationGAS() self.energyFormationHUS() self.enthalpyFusion() self.enthalpyVaporization() self.liquidDensity() self.liquidHeatCapacity() self.liquidThermalConductivity() self.liquidViscosity() self.saltWaterSolubility() self.solidHeatCapacity() self.surfaceTension() self.thermalConductivity() self.vaporEnthalpyFormation() self.vaporGibbsEnergyFormation() self.vaporHeatCapacity() self.vaporPressure() self.vaporThermalConductivity() self.vaporViscosity() self.waterSolubility() return[self.db, self.dbMetaData] def activatedCarbonAdsorption(self): """ see doc strings for criticalProperty """ csvFQPN = os.path.join(self.csvPath,'activatedCarbonAdsorption.csv') self.csvFile(csvFQPN) header = next(self.csvReader) header = [re.sub(self.refndSpace,'',h) for h in header] csvDict = {'aCAP': {'colIdx':[3,4,5], 'units':'g/100 g', 'description':'activated Carbon Adsorption Parameters', 'eqnDoc':activatedCarbonAdsorption.__doc__}, 'aCACmin': {'colIdx':[6], 'units':self.reUnitSep.match(header[6]).groups()[1], 'description':'activated Carbon Adsorption Concentration Min'}, 'aCACmax': {'colIdx':[7], 'units':self.reUnitSep.match(header[7]).groups()[1], 'description':'activated Carbon Adsorption Concentration Max'}} #update csvDict for entries common to all top level keys for key in csvDict.keys(): csvDict[key].update({'importDateTime':self.importDateTime, 'dataSource':csvFQPN}) metaDataKeys = ['description','dataSource','importDateTime', 'units','eqnDoc'] self.csv2db(csvDict,metaDataKeys) self.csvFileHandle.close() #close the file openend by csvFile def criticalProperty(self): """ criticalProperty.csv should be processed first to populate self.db and self.dbMetaData top level dictionary keys with material names. """ #1. open the csv data file csvFQPN = os.path.join(self.csvPath,'criticalProperty.csv') self.csvFile(csvFQPN) #2. get csv header (1st line) and remove white space from header entries header = next(self.csvReader) header = [re.sub(self.refndSpace,'',h) for h in header] #3. define a dictionary to decode the csv file in self.csv2db() csvDict = {'formula': {'colIdx':[0], 'units':None, 'description':'elemental formula' }, 'name': {'colIdx':[1], 'units':None, 'description':'chemical substance name' }, 'CAS': {'colIdx':[2], 'units':None, 'description':'registry number' }, 'fW': {'colIdx':[3], 'units':None, 'description':'formula Weight' }, 'nFP': {'colIdx':[4], 'units':self.reUnitSep.match(header[4]).groups()[1], 'description':'normal Freezing Point' }, 'nBP': {'colIdx':[5], 'units':self.reUnitSep.match(header[5]).groups()[1], 'description':'normal Boiling Point' }, 'critT': {'colIdx':[6], 'units':self.reUnitSep.match(header[6]).groups()[1], 'description':'critical Temperature' }, 'critP': {'colIdx':[7], 'units':self.reUnitSep.match(header[7]).groups()[1], 'description':'critical Pressure' }, 'critV': {'colIdx':[8], 'units':self.reUnitSep.match(header[8]).groups()[1], 'description':'critical Volume' }, 'critD': {'colIdx':[9], 'units':self.reUnitSep.match(header[9]).groups()[1], 'description':'critical Density' }, 'critC': {'colIdx':[10], 'units':None, 'description':'critical Compressibility' }, 'acentric': {'colIdx':[11], 'units':None, 'description':'acentric factor' }} #update csvDict for entries common to all top level keys for key in csvDict.keys(): csvDict[key].update({'importDateTime':self.importDateTime, 'dataSource':csvFQPN}) metaDataKeys = ['description','dataSource','importDateTime', 'units','eqnDoc'] self.csv2db(csvDict,metaDataKeys) self.csvFileHandle.close() #close the file openend by csvFile def csvFile(self,csvFQPN): """ utility function to open the requested csv file in the csv dir and create a csv reader for this file the calling entity should call self.csvFileHandle.close() when done with the requested csv file Parameters: csvFQPN, csv Fully Qualified Path Name as string """ try: self.csvFileHandle = open(csvFQPN, 'r') except: print("File: %s not found. Check path and file name." % csvFQPN) self.csvReader = csv.reader(self.csvFileHandle,dialect='excel') def csv2db(self,csvDict,metaDataKeys): """ Parse rows from a csv file containing yaws chemical property handbook data. For each csv file processed in which the first line contains column header information, next(self.csvReader) should be called once before calling this function. Parameters csvDict: dictionary of the form: {'<dbProp>':{'colIdx':[integer(s)], ...}, ...} - '<dbProp>' can be any string value used to identify a property (column) from the csv file input into db - e.g. 'formula', 'CAS', 'fW', etc. - Every '<dbProp>' must have a dictionary value with 'colIdx' as a key. The value for 'colIdx' must be a list of integers used to identify the column(s) to extract data from the csv file per '<dbProp>' - If the 'colIdx' value is a list with one integer, the data from this column csv will first be metaDataKeys: list of csvDict keys that should be put into self.dbMetaData[row[1]] """ for row in self.csvReader: if row[1] not in self.db: #row[1] is the chemical name self.db.update({row[1]:{}}) self.db[row[1]].update({'name':row[1]}) self.db[row[1]].update({'CAS':row[2]}) self.db[row[1]].update({'formula':row[0]}) self.dbMetaData.update({row[1]:{}}) for key, val in csvDict.items(): if len(val['colIdx']) == 1: #one col in row to process try: #see the col can be converted to a float self.db[row[1]].update({key:float(row[val['colIdx'][0]])}) except: #otherwise leave it alone (string) self.db[row[1]].update({key:row[val['colIdx'][0]]}) else: #multiple cols of floats in row to process self.db[row[1]].update({key:[(float(row[idx])) for idx in val['colIdx']]}) if key not in self.dbMetaData[row[1]]: self.dbMetaData[row[1]].update({key:{}}) for valKey,valVal in val.items(): if valKey in metaDataKeys: self.dbMetaData[row[1]][key].update({valKey:valVal}) def energyFormationGAS(self): """ see doc strings for criticalProperty """ csvFQPN = os.path.join(self.csvPath,'energyFormationGAS.csv') self.csvFile(csvFQPN) header = next(self.csvReader) header = [re.sub(self.refndSpace,'',h) for h in header] csvDict = {'eFGASState': {'colIdx':[4], 'units':None, 'description':'energy Formation GAS State'}, 'eFG298K': {'colIdx':[5], 'units':self.reUnitSep.match(header[5]).groups()[1], 'description':'energy Formation, Gibbs at 298 K'}, 'eFA298K': {'colIdx':[6], 'units':self.reUnitSep.match(header[6]).groups()[1], 'description':'energy Formation, Helmholtz at 298 K'}, 'eFGAS298K': {'colIdx':[7], 'units':self.reUnitSep.match(header[7]).groups()[1], 'description':'energy Formation, Entropy at 298 K'}} #update csvDict for entries common to all top level keys for key in csvDict.keys(): csvDict[key].update({'importDateTime':self.importDateTime, 'dataSource':csvFQPN}) metaDataKeys = ['description','dataSource','importDateTime','units'] self.csv2db(csvDict,metaDataKeys) self.csvFileHandle.close() #close the file openend by csvFile def energyFormationHUS(self): """ see doc strings for criticalProperty """ csvFQPN = os.path.join(self.csvPath,'energyFormationHUS.csv') self.csvFile(csvFQPN) header = next(self.csvReader) header = [re.sub(self.refndSpace,'',h) for h in header] csvDict = {'eFHUSState': {'colIdx':[4], 'units':None, 'description':'energy Formation HUS State'}, 'eFH298K': {'colIdx':[5], 'units':self.reUnitSep.match(header[5]).groups()[1], 'description':'energy Formation, Enthalpy at 298 K'}, 'eFU298K': {'colIdx':[6], 'units':self.reUnitSep.match(header[6]).groups()[1], 'description':'energy Formation, Internal at 298 K'}, 'eFGAS298K': {'colIdx':[7], 'units':self.reUnitSep.match(header[7]).groups()[1], 'description':'energy Formation, Entropy at 298 K'}} #update csvDict for entries common to all top level keys for key in csvDict.keys(): csvDict[key].update({'importDateTime':self.importDateTime, 'dataSource':csvFQPN}) metaDataKeys = ['description','dataSource','importDateTime','units'] self.csv2db(csvDict,metaDataKeys) self.csvFileHandle.close() #close the file openend by csvFile def enthalpyFusion(self): """ see doc strings for criticalProperty """ csvFQPN = os.path.join(self.csvPath,'enthalpyFusion.csv') self.csvFile(csvFQPN) header = next(self.csvReader) header = [re.sub(self.refndSpace,'',h) for h in header] csvDict = {'eFNFP': {'colIdx':[5], 'units':self.reUnitSep.match(header[5]).groups()[1], 'description':'enthalpy Fusion at Normal Freezing Point'}} #update csvDict for entries common to all top level keys for key in csvDict.keys(): csvDict[key].update({'importDateTime':self.importDateTime, 'dataSource':csvFQPN}) metaDataKeys = ['description','dataSource','importDateTime','units'] self.csv2db(csvDict,metaDataKeys) self.csvFileHandle.close() #close the file openend by csvFile def enthalpyVaporization(self): """ see doc strings for criticalProperty """ csvFQPN = os.path.join(self.csvPath,'enthalpyVaporization.csv') self.csvFile(csvFQPN) header = next(self.csvReader) header = [re.sub(self.refndSpace,'',h) for h in header] csvDict = {'eVP': {'colIdx':[3,4,5], 'units':'kJ/mol', 'description':'enthalpy Vaporization Parameters', 'eqnDoc':enthalpyVaporization.__doc__}, 'eVTmin': {'colIdx':[6], 'units':self.reUnitSep.match(header[6]).groups()[1], 'description':'enthalpy Vaporization Temperature Min'}, 'eVTmax': {'colIdx':[7], 'units':self.reUnitSep.match(header[7]).groups()[1], 'description':'enthalpy Vaporization Temperature Max'}} #update csvDict for entries common to all top level keys for key in csvDict.keys(): csvDict[key].update({'importDateTime':self.importDateTime, 'dataSource':csvFQPN}) metaDataKeys = ['description','dataSource','importDateTime', 'units','eqnDoc'] self.csv2db(csvDict,metaDataKeys) self.csvFileHandle.close() #close the file openend by csvFile def liquidDensity(self): """ see doc strings for criticalProperty """ csvFQPN = os.path.join(self.csvPath,'liquidDensity.csv')
import Iodine as IodineAPI import unittest class TestNetworkFunc(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): IodineAPI.newNetwork("network1") IodineAPI.newNetwork("network2") def tearDown(self): IodineAPI.clearNetworks() def test_newNetwork(self): with self.assertRaises(IodineAPI.IDRepeatError): IodineAPI.newNetwork("network1") self.assertEqual(IodineAPI.newNetwork("network3"), None) self.assertEqual(IodineAPI.newNetwork("network4"), None) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.getListOfNetworks(), ['network1', "network2", "network3", "network4"]) self.assertEqual(IodineAPI.undo(), None) self.assertEqual(IodineAPI.getListOfNetworks(), [ 'network1', "network2", "network3"]) self.assertEqual(IodineAPI.redo(), None) self.assertEqual(IodineAPI.getListOfNetworks(), ['network1', "network2", "network3", "network4"]) def test_getNetworkIndex(self): with self.assertRaises(IodineAPI.IDNotFoundError): IodineAPI.getNetworkIndex("network3") self.assertEqual(IodineAPI.getNetworkIndex("network2"), 1) self.assertEqual(IodineAPI.getNetworkIndex("network1"), 0) def test_deleteNetwork(self): with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.deleteNetwork(2) self.assertEqual(IodineAPI.deleteNetwork(1), None) self.assertEqual(IodineAPI.getListOfNetworks(), ['network1']) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual(IodineAPI.getListOfNetworks(), ['network1', "network2"]) self.assertEqual(IodineAPI.redo(), None) self.assertEqual(IodineAPI.getListOfNetworks(), ['network1']) def test_clearNetworks(self): self.assertEqual(IodineAPI.clearNetworks(), None) self.assertEqual(IodineAPI.getListOfNetworks(), []) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual(IodineAPI.getListOfNetworks(), ['network1', "network2"]) self.assertEqual(IodineAPI.redo(), None) self.assertEqual(IodineAPI.getListOfNetworks(), []) def test_getNumberOfNetworks(self): self.assertEqual(IodineAPI.getNumberOfNetworks(), 2) def test_getNetworkID(self): with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNetworkID(2) self.assertEqual(IodineAPI.getNetworkID(0), 'network1') def test_getListOfNetworks(self): self.assertEqual(IodineAPI.getListOfNetworks(), ['network1', 'network2']) class TestNodeFunc(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): IodineAPI.newNetwork("network1") IodineAPI.addNode(0, "node1", 1.1, 2.5, 5.4, 6.4) IodineAPI.addNode(0, "node2", 1.2, 3.2, 2.5, 4.1) IodineAPI.addNode(0, "node3", 2.2, 3.1, 1.5, 4.5) IodineAPI.newNetwork("network2") IodineAPI.addNode(1, "node1", 1.1, 3.5, 7.4, 6.0) def tearDown(self): IodineAPI.clearNetworks() def test_addNode(self): self.assertEqual(IodineAPI.addNode( 0, "node4", 1.1, 2.5, 5.4, 6.4), None) self.assertEqual(IodineAPI.getListOfNodeIDs( 0), ["node1", "node2", "node3", "node4"]) with self.assertRaises(IodineAPI.IDRepeatError): IodineAPI.addNode(0, "node2", 1.2, 3.2, 2.5, 4.1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.addNode(-1, "node5", 1.2, 3.2, 2.5, 4.1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.addNode(2, "node5", 1.2, 3.2, 2.5, 4.1) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.addNode(0, "node5", -1, 2.5, 5.4, 6.4) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.addNode(0, "node5", 1.1, -1, 5.4, 6.4) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.addNode(0, "node5", 1.1, 2.5, -1, 6.4) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.addNode(0, "node5", 1.1, 2.5, 0, 6.4) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.addNode(0, "node5", 1.1, 2.5, 5.4, -1) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.addNode(0, "node5", 1.1, 2.5, 5.4, 0) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual(IodineAPI.getListOfNodeIDs(0), ["node1", "node2", "node3"]) self.assertEqual(IodineAPI.redo(), None) self.assertEqual(IodineAPI.getListOfNodeIDs(0), [ "node1", "node2", "node3", "node4"]) def test_getNodeIndex(self): self.assertEqual(IodineAPI.getNodeIndex(0, "node1"), 0) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeIndex(-1, "node2") with self.assertRaises(IodineAPI.IDNotFoundError): IodineAPI.getNodeIndex(0, "node5") def test_deleteNode(self): self.assertEqual(IodineAPI.deleteNode(0, 1), None) self.assertEqual(IodineAPI.getListOfNodeIDs( 0), ["node1", "node3"]) self.assertEqual(IodineAPI.deleteNode(1, 0), None) self.assertEqual(IodineAPI.getListOfNodeIDs(1), []) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual(IodineAPI.getListOfNodeIDs(1), ["node1"]) self.assertEqual(IodineAPI.redo(), None) self.assertEqual(IodineAPI.getListOfNodeIDs(1), []) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.deleteNode(-1, 0) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.deleteNode(2, 0) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.deleteNode(0, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.deleteNode(0, 3) IodineAPI.createReaction(0, "rea1") IodineAPI.addSrcNode(0, 0, 0, 1) with self.assertRaises(IodineAPI.NodeNotFreeError): IodineAPI.deleteNode(0, 0) IodineAPI.addDestNode(0, 0, 1, 6) with self.assertRaises(IodineAPI.NodeNotFreeError): IodineAPI.deleteNode(0, 1) def test_clearNetwork(self): IodineAPI.CreateBiBi(0, "Rea1", "k1*A", 0, 1, 2, 1, 1, 2, 3, 4) self.assertEqual(IodineAPI.getListOfReactionIDs(0), ["Rea1"]) self.assertEqual(IodineAPI.clearNetwork(0), None) self.assertEqual(IodineAPI.getListOfNodeIDs(0), []) self.assertEqual(IodineAPI.getListOfReactionIDs(0), []) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual(IodineAPI.getListOfNodeIDs(0), ["node1", "node2", "node3"]) self.assertEqual(IodineAPI.getListOfReactionIDs(0), ["Rea1"]) self.assertEqual(IodineAPI.redo(), None) self.assertEqual(IodineAPI.getListOfNodeIDs(0), []) self.assertEqual(IodineAPI.getListOfReactionIDs(0), []) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.clearNetwork(-1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.clearNetwork(2) def test_getNumberOfNodes(self): self.assertEqual(IodineAPI.getNumberOfNodes(0), 3) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNumberOfNodes(-1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNumberOfNodes(2) def test_getNodeCenter(self): self.assertEqual(IodineAPI.getNodeCenter(0, 0), (3.80, 5.70)) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeCenter(-1, 0) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeCenter(2, 0) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeCenter(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeCenter(0, 3) def test_getNodeID(self): self.assertEqual(IodineAPI.getNodeID(0, 0), "node1") with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeID(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeID(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeID(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeID(1, 4) def test_getListOfNodeIDs(self): self.assertEqual(IodineAPI.getListOfNodeIDs( 0), ["node1", "node2", "node3"]) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getListOfNodeIDs(-1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getListOfNodeIDs(2) self.assertEqual(IodineAPI.clearNetwork(0), None) self.assertEqual(IodineAPI.getListOfNodeIDs(0), []) def test_getNodeCoordinateAndSize(self): self.assertEqual(IodineAPI.getNodeCoordinateAndSize( 0, 0), (1.1, 2.5, 5.4, 6.4)) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeCoordinateAndSize(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeCoordinateAndSize(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeCoordinateAndSize(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeCoordinateAndSize(1, 4) def test_getNodeFillColor(self): self.assertEqual(IodineAPI.getNodeFillColor(0, 0), (255, 150, 80, 1.0)) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFillColor(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFillColor(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFillColor(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFillColor(1, 4) def test_getNodeFillColorRGB(self): self.assertEqual(hex(IodineAPI.getNodeFillColorRGB(0, 0)), '0xff9650') with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFillColorRGB(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFillColorRGB(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFillColorRGB(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFillColorRGB(1, 4) def test_getNodeFillColorAlpha(self): self.assertAlmostEqual(IodineAPI.getNodeFillColorAlpha(0, 0), 1, 2) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFillColorAlpha(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFillColorAlpha(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFillColorAlpha(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFillColorAlpha(1, 4) def test_getNodeOutlineColor(self): self.assertEqual( IodineAPI.getNodeOutlineColor(0, 0), (255, 100, 80, 1.0)) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeOutlineColor(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeOutlineColor(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeOutlineColor(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeOutlineColor(1, 4) def test_getNodeOutlineColorRGB(self): self.assertEqual( hex(IodineAPI.getNodeOutlineColorRGB(0, 0)), '0xff6450') with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeOutlineColorRGB(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeOutlineColorRGB(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeOutlineColorRGB(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeOutlineColorRGB(1, 4) def test_getNodeOutlineColorAlpha(self): self.assertAlmostEqual(IodineAPI.getNodeOutlineColorAlpha(0, 0), 1, 2) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeOutlineColorAlpha(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeOutlineColorAlpha(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeOutlineColorAlpha(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeOutlineColorAlpha(1, 4) def test_getNodeOutlineThickness(self): self.assertEqual(IodineAPI.getNodeOutlineThickness(0, 1), 3.0) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeOutlineThickness(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeOutlineThickness(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeOutlineThickness(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeOutlineThickness(1, 4) def test_getNodeFontPointSize(self): self.assertEqual(IodineAPI.getNodeFontPointSize(0, 1), 20) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontPointSize(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontPointSize(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontPointSize(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontPointSize(1, 4) def test_getNodeFontFamily(self): self.assertEqual(IodineAPI.getNodeFontFamily(0, 0), "default") with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontFamily(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontFamily(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontFamily(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontFamily(1, 4) def test_getNodeFontStyle(self): self.assertEqual(IodineAPI.getNodeFontStyle(0, 0), "normal") with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontStyle(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontStyle(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontStyle(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontStyle(1, 4) def test_getNodeFontWeight(self): self.assertEqual(IodineAPI.getNodeFontWeight(0, 0), "default") with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontWeight(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontWeight(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontWeight(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontWeight(1, 4) def test_getNodeFontName(self): self.assertEqual(IodineAPI.getNodeFontName(0, 0), "") with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontName(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontName(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontName(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontName(1, 4) def test_getNodeFontColorRGB(self): self.assertEqual( hex(IodineAPI.getNodeFontColorRGB(0, 0)), '0x0') with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontColorRGB(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontColorRGB(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontColorRGB(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontColorRGB(1, 4) def test_getNodeFontColorAlpha(self): self.assertAlmostEqual(IodineAPI.getNodeFontColorAlpha(0, 0), 1, 2) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontColorAlpha(-1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.getNodeFontColorAlpha(3, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontColorAlpha(1, -1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.getNodeFontColorAlpha(1, 4) def test_setNodeID(self): self.assertEqual(IodineAPI.getNodeID(0, 1), "node2") self.assertEqual(IodineAPI.setNodeID(0, 1, "Node2"), None) self.assertEqual(IodineAPI.getNodeID(0, 1), "Node2") with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeID(-1, 1, "Node2") with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeID(3, 1, "Node2") with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeID(1, -1, "Node2") with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeID(1, 1, "Node2") with self.assertRaises(IodineAPI.IDRepeatError): IodineAPI.setNodeID(0, 1, "node1") with self.assertRaises(IodineAPI.IDRepeatError): IodineAPI.setNodeID(0, 1, "node3") with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual(IodineAPI.getNodeID(0, 1), "node2") self.assertEqual(IodineAPI.redo(), None) self.assertEqual(IodineAPI.getNodeID(0, 1), "Node2") def test_setNodeCoordinate(self): self.assertEqual(IodineAPI.getNodeCoordinateAndSize( 0, 1), (1.2, 3.2, 2.5, 4.1)) self.assertEqual(IodineAPI.setNodeCoordinate( 0, 1, 1.1, 2.5), None) self.assertEqual(IodineAPI.getNodeCoordinateAndSize( 0, 1), (1.1, 2.5, 2.5, 4.1)) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeCoordinate(-1, 1, 1.2, 3.2) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeCoordinate(3, 1, 1.2, 3.2) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeCoordinate(1, -1, 1.2, 3.2) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeCoordinate(1, 4, 1.2, 3.2) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeCoordinate(0, 1, -1, 2.5) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeCoordinate(0, 1, 1.1, -1) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual(IodineAPI.getNodeCoordinateAndSize( 0, 1), (1.2, 3.2, 2.5, 4.1)) self.assertEqual(IodineAPI.redo(), None) self.assertEqual(IodineAPI.getNodeCoordinateAndSize( 0, 1), (1.1, 2.5, 2.5, 4.1)) def test_setNodeSize(self): self.assertEqual(IodineAPI.getNodeCoordinateAndSize( 0, 1), (1.2, 3.2, 2.5, 4.1)) self.assertEqual(IodineAPI.setNodeSize( 0, 1, 5.4, 6.4), None) self.assertEqual(IodineAPI.getNodeCoordinateAndSize( 0, 1), (1.2, 3.2, 5.4, 6.4)) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeSize(-1, 1, 2.5, 4.1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeSize(3, 1, 2.5, 4.1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeSize(1, -1, 2.5, 4.1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeSize(1, 4, 2.5, 4.1) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeSize(0, 1, -1, 6.4) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeSize(0, 1, 0, 6.4) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeSize(0, 1, 5.4, -1) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeSize(0, 1, 5.4, 0) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual(IodineAPI.getNodeCoordinateAndSize( 0, 1), (1.2, 3.2, 2.5, 4.1)) self.assertEqual(IodineAPI.redo(), None) self.assertEqual(IodineAPI.getNodeCoordinateAndSize( 0, 1), (1.2, 3.2, 5.4, 6.4)) def test_setNodeFillColorRGB(self): self.assertEqual(hex(IodineAPI.getNodeFillColorRGB(0, 1)), '0xff9650') self.assertEqual(IodineAPI.setNodeFillColorRGB( 0, 1, 30, 180, 160), None) self.assertEqual(hex(IodineAPI.getNodeFillColorRGB(0, 1)), '0x1eb4a0') with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeFillColorRGB(-1, 1, 30, 180, 160) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeFillColorRGB(3, 1, 30, 180, 160) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeFillColorRGB(1, -1, 30, 180, 160) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeFillColorRGB(1, 4, 30, 180, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeFillColorRGB(0, 1, -1, 180, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeFillColorRGB(0, 1, 256, 180, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeFillColorRGB(0, 1, 30, -1, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeFillColorRGB(0, 1, 30, 256, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeFillColorRGB(0, 1, 30, 180, -1) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeFillColorRGB(0, 1, 30, 180, 256) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual(hex(IodineAPI.getNodeFillColorRGB(0, 1)), '0xff9650') self.assertEqual(IodineAPI.redo(), None) self.assertEqual(hex(IodineAPI.getNodeFillColorRGB(0, 1)), '0x1eb4a0') def test_setNodeFillColorAlpha(self): self.assertAlmostEqual(IodineAPI.getNodeFillColorAlpha(0, 1), 1, 2) self.assertEqual(IodineAPI.setNodeFillColorAlpha(0, 1, 0.5), None) self.assertAlmostEqual(IodineAPI.getNodeFillColorAlpha(0, 1), 0.5,2) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeFillColorAlpha(-1, 1, 1) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeFillColorAlpha(3, 1, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeFillColorAlpha(1, -1, 1) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeFillColorAlpha(1, 4, 1) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeFillColorAlpha(0, 1, -0.1) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeFillColorAlpha(0, 1, 1.1) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertAlmostEqual(IodineAPI.getNodeFillColorAlpha(0, 1), 1,2) self.assertEqual(IodineAPI.redo(), None) self.assertAlmostEqual(IodineAPI.getNodeFillColorAlpha(0, 1), 0.5,2) def test_setNodeOutlineColorRGB(self): self.assertEqual( hex(IodineAPI.getNodeOutlineColorRGB(0, 1)), '0xff6450') self.assertEqual(IodineAPI.setNodeOutlineColorRGB( 0, 1, 30, 180, 160), None) self.assertEqual( hex(IodineAPI.getNodeOutlineColorRGB(0, 1)), '0x1eb4a0') with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(-1, 1, 30, 180, 160) with self.assertRaises(IodineAPI.NetIndexOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(3, 1, 30, 180, 160) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(1, -1, 30, 180, 160) with self.assertRaises(IodineAPI.NodeIndexOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(1, 4, 30, 180, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(0, 1, -1, 180, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(0, 1, 256, 180, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(0, 1, 30, -1, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(0, 1, 30, 256, 160) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(0, 1, 30, 180, -1) with self.assertRaises(IodineAPI.VariableOutOfRangeError): IodineAPI.setNodeOutlineColorRGB(0, 1, 30, 180, 256) with self.assertRaises(IodineAPI.StackEmptyError): IodineAPI.redo() self.assertEqual(IodineAPI.undo(), None) self.assertEqual( hex(IodineAPI.getNodeOutlineColorRGB(0, 1)), '0xff6450') self.assertEqual(IodineAPI.redo(), None) self.assertEqual( hex(IodineAPI.getNodeOutlineColorRGB(0, 1)), '0x1eb4a0') def test_setNodeOutlineColorAlpha(self): self.assertAlmostEqual(IodineAPI.getNodeOutlineColorAlpha(0, 1), 1,2) self.assertEqual(IodineAPI.setNodeOutlineColorAlpha(0, 1, 0.5), None) self.assertAlmostEqual(IodineAPI.getNodeOutlineColorAlpha(0, 1), 0.5,2) with
rolepassword.replace('\'', '\'\''), encrypted=encrypted)) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role['superuser']): skip_superuser = True flags = ( {'flag': 'INHERIT', 'test': inherit}, {'flag': 'CREATEDB', 'test': createdb}, {'flag': 'CREATEROLE', 'test': createroles}, {'flag': 'SUPERUSER', 'test': superuser, 'skip': skip_superuser}, {'flag': 'REPLICATION', 'test': replication}, {'flag': 'LOGIN', 'test': login}, {'flag': 'CONNECTION LIMIT', 'test': bool(connlimit), 'addtxt': str(connlimit), 'skip': connlimit is None}, {'flag': 'ENCRYPTED', 'test': (encrypted is not None and bool(rolepassword)), 'skip': skip_passwd or isinstance(rolepassword, bool), 'cond': encrypted, 'prefix': 'UN'}, {'flag': 'PASSWORD', 'test': bool(rolepassword), 'skip': skip_passwd, 'addtxt': escaped_password}, ) for data in flags: sub_cmd = _add_role_flag(sub_cmd, **data) if sub_cmd.endswith('WITH'): sub_cmd = sub_cmd.replace(' WITH', '') if groups: if isinstance(groups, list): groups = ','.join(groups) for group in groups.split(','): sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name) return sub_cmd def _role_create(name, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, createdb=None, createroles=None, createuser=None, encrypted=None, superuser=None, login=None, connlimit=None, inherit=None, replication=None, rolepassword=None, typ_='role', groups=None, runas=None): ''' Creates a Postgres role. Users and Groups are both roles in postgres. However, users can login, groups cannot. ''' # check if role exists if user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('{0} \'{1}\' already exists'.format(typ_.capitalize(), name)) return False sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, typ_=typ_, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createroles=createroles, createuser=createuser, superuser=superuser, groups=groups, replication=replication, rolepassword=<PASSWORD> )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_create(username, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, createdb=None, createuser=None, createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=<PASSWORD>, groups=None, runas=None): ''' Creates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_create 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='<PASSWORD>' ''' return _role_create(username, typ_='user', user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createuser=createuser, createroles=createroles, inherit=inherit, login=login, connlimit=connlimit, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=<PASSWORD>, groups=groups, runas=runas) def _role_update(name, user=None, host=None, port=None, maintenance_db=None, password=None, createdb=None, createuser=None, typ_='role', createroles=None, inherit=None, login=None, connlimit=None, encrypted=None, superuser=None, replication=None, rolepassword=None, groups=None, runas=None): ''' Updates a postgres role. ''' role = role_get(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas, return_password=False) # check if user exists if not bool(role): log.info( '{0} \'{1}\' could not be found'.format(typ_.capitalize(), name) ) return False sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name) sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args( name, encrypted=encrypted, login=login, connlimit=connlimit, inherit=inherit, createdb=createdb, createuser=createuser, createroles=createroles, superuser=superuser, groups=groups, replication=replication, rolepassword=<PASSWORD>, db_role=role )) ret = _psql_prepare_and_run(['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) return ret['retcode'] == 0 def user_update(username, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, createdb=None, createuser=None, createroles=None, encrypted=None, superuser=None, inherit=None, login=None, connlimit=None, replication=None, rolepassword=<PASSWORD>, groups=None, runas=None): ''' Updates a Postgres user. CLI Examples: .. code-block:: bash salt '*' postgres.user_update 'username' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='<PASSWORD>' ''' return _role_update(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, typ_='user', inherit=inherit, login=login, connlimit=connlimit, createdb=createdb, createuser=createuser, createroles=createroles, encrypted=encrypted, superuser=superuser, replication=replication, rolepassword=<PASSWORD>, groups=groups, runas=runas) def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, runas=None): ''' Removes a role from the Postgres Server ''' # check if user exists if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'{0}\' does not exist'.format(name)) return False # user exists, proceed sub_cmd = 'DROP ROLE "{0}"'.format(name) _psql_prepare_and_run( ['-c', sub_cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): return True else: log.info('Failed to delete user \'{0}\'.'.format(name)) return False def available_extensions(user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, runas=None): ''' List available postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.available_extensions ''' exts = [] query = ( 'select * ' 'from pg_available_extensions();' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'default_version' in row and 'name' in row: exts[row['name']] = row return exts def installed_extensions(user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, runas=None): ''' List installed postgresql extensions CLI Example: .. code-block:: bash salt '*' postgres.installed_extensions ''' exts = [] query = ( 'select a.*, b.nspname as schema_name ' 'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;' ) ret = psql_query(query, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) exts = {} for row in ret: if 'extversion' in row and 'extname' in row: exts[row['extname']] = row return exts def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, runas=None): ''' Get info about an available postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_available_extension plpgsql ''' return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def get_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, runas=None): ''' Get info about an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.get_installed_extension plpgsql ''' return installed_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None) def is_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, runas=None): ''' Test if a specific extension is available CLI Example: .. code-block:: bash salt '*' postgres.is_available_extension ''' exts = available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if name.lower() in [ a.lower() for a in exts ]: return True return False def _pg_is_older_ext_ver(a, b): '''Return true if version a is lesser than b TODO: be more intelligent to test versions ''' return a < b def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is installed CLI Example: .. code-block:: bash salt '*' postgres.is_installed_extension ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) return bool(installed_ext) def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, runas=None): ''' Get lifecycle information about an extension CLI Example: .. code-block:: bash salt '*' postgres.create_metadata adminpack ''' installed_ext = get_installed_extension( name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = [_EXTENSION_NOT_INSTALLED] if installed_ext: ret = [_EXTENSION_INSTALLED] if ( ext_version is not None and _pg_is_older_ext_ver( installed_ext.get('extversion', ext_version), ext_version ) ): ret.append(_EXTENSION_TO_UPGRADE) if ( schema is not None and installed_ext.get('extrelocatable', 'f') == 't' and installed_ext.get('schema_name', schema) != schema ): ret.append(_EXTENSION_TO_MOVE) return ret def drop_extension(name, if_exists=None, restrict=None, cascade=None, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, runas=None): ''' Drop an installed postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.drop_extension 'adminpack' ''' if cascade is None: cascade = True if if_exists is None: if_exists = False if restrict is None: restrict = False args = ['DROP EXTENSION'] if if_exists: args.append('IF EXISTS') args.append(name) if cascade: args.append('CASCADE') if restrict: args.append('RESTRICT') args.append(';') cmd = ' '.join(args) if is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas): _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) ret = not is_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if not ret: log.info('Failed to drop ext: {0}'.format(name)) return ret def create_extension(name, if_not_exists=None, schema=None, ext_version=None, from_version=None, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, runas=None): ''' Install a postgresql extension CLI Example: .. code-block:: bash salt '*' postgres.create_extension 'adminpack' ''' if if_not_exists is None: if_not_exists = True mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) installed = _EXTENSION_NOT_INSTALLED not in mtdata installable = is_available_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) if installable: if not installed: args = ['CREATE EXTENSION'] if if_not_exists: args.append('IF NOT EXISTS') args.append('"{0}"'.format(name)) sargs = [] if schema: sargs.append('SCHEMA "{0}"'.format(schema)) if ext_version: sargs.append('VERSION {0}'.format(ext_version)) if from_version: sargs.append('FROM {0}'.format(from_version)) if sargs: args.append('WITH') args.extend(sargs) args.append(';') cmd = ' '.join(args).strip() else: args = [] if schema and _EXTENSION_TO_MOVE in mtdata: args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format( name, schema)) if ext_version and _EXTENSION_TO_UPGRADE in mtdata: args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format( name, ext_version)) cmd = ' '.join(args).strip() if cmd: _psql_prepare_and_run( ['-c', cmd], runas=runas, host=host, user=user, port=port, maintenance_db=maintenance_db, password=password) mtdata = create_metadata(name, ext_version=ext_version, schema=schema, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) ret = True for i in _EXTENSION_FLAGS: if (i in mtdata) and (i != _EXTENSION_INSTALLED): ret = False if not ret: log.info('Failed to create ext: {0}'.format(name)) return ret def user_remove(username, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a user from the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.user_remove 'username' ''' return _role_remove(username, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas) # Group related actions def group_create(groupname, user=None, host=None, port=None, maintenance_db=None, password=<PASSWORD>, createdb=None, createuser=None, createroles=None, encrypted=None, login=None, inherit=None, superuser=None, replication=None, rolepassword=<PASSWORD>, groups=None, runas=None): ''' Creates a Postgres group. A group is postgres is similar to a user, but cannot login. CLI Example: .. code-block:: bash salt '*' postgres.group_create 'groupname' user='user' \\ host='hostname' port='port' password='password' \\ rolepassword='<PASSWORD>' ''' return _role_create(groupname, user=user, typ_='group', host=host, port=port, maintenance_db=maintenance_db, password=password, createdb=createdb, createroles=createroles, createuser=createuser, encrypted=encrypted, login=login, inherit=inherit, superuser=superuser, replication=replication, rolepassword=<PASSWORD>, groups=groups, runas=runas) def
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''The 'grit rc2grd' tool.''' from __future__ import print_function import os.path import getopt import re import sys import six from six import StringIO import grit.node.empty from grit.node import include from grit.node import structure from grit.node import message from grit.gather import rc from grit.gather import tr_html from grit.tool import interface from grit.tool import postprocess_interface from grit.tool import preprocess_interface from grit import grd_reader from grit import lazy_re from grit import tclib from grit import util # Matches files referenced from an .rc file _FILE_REF = lazy_re.compile(r''' ^(?P<id>[A-Z_0-9.]+)[ \t]+ (?P<type>[A-Z_0-9]+)[ \t]+ "(?P<file>.*?([^"]|""))"[ \t]*$''', re.VERBOSE | re.MULTILINE) # Matches a dialog section _DIALOG = lazy_re.compile( r'^(?P<id>[A-Z0-9_]+)\s+DIALOG(EX)?\s.+?^BEGIN\s*$.+?^END\s*$', re.MULTILINE | re.DOTALL) # Matches a menu section _MENU = lazy_re.compile(r'^(?P<id>[A-Z0-9_]+)\s+MENU.+?^BEGIN\s*$.+?^END\s*$', re.MULTILINE | re.DOTALL) # Matches a versioninfo section _VERSIONINFO = lazy_re.compile( r'^(?P<id>[A-Z0-9_]+)\s+VERSIONINFO\s.+?^BEGIN\s*$.+?^END\s*$', re.MULTILINE | re.DOTALL) # Matches a stringtable _STRING_TABLE = lazy_re.compile( (r'^STRINGTABLE(\s+(PRELOAD|DISCARDABLE|CHARACTERISTICS.+|LANGUAGE.+|' r'VERSION.+))*\s*\nBEGIN\s*$(?P<body>.+?)^END\s*$'), re.MULTILINE | re.DOTALL) # Matches each message inside a stringtable, breaking it up into comments, # the ID of the message, and the (RC-escaped) message text. _MESSAGE = lazy_re.compile(r''' (?P<comment>(^\s+//.+?)*) # 0 or more lines of comments preceding the message ^\s* (?P<id>[A-Za-z0-9_]+) # id \s+ "(?P<text>.*?([^"]|""))"([^"]|$) # The message itself ''', re.MULTILINE | re.DOTALL | re.VERBOSE) # Matches each line of comment text in a multi-line comment. _COMMENT_TEXT = lazy_re.compile(r'^\s*//\s*(?P<text>.+?)$', re.MULTILINE) # Matches a string that is empty or all whitespace _WHITESPACE_ONLY = lazy_re.compile(r'\A\s*\Z', re.MULTILINE) # Finds printf and FormatMessage style format specifiers # Uses non-capturing groups except for the outermost group, so the output of # re.split() should include both the normal text and what we intend to # replace with placeholders. # TODO(joi) Check documentation for printf (and Windows variants) and FormatMessage _FORMAT_SPECIFIER = lazy_re.compile( r'(%[-# +]?(?:[0-9]*|\*)(?:\.(?:[0-9]+|\*))?(?:h|l|L)?' # printf up to last char r'(?:d|i|o|u|x|X|e|E|f|F|g|G|c|r|s|ls|ws)' # printf last char r'|\$[1-9][0-9]*)') # FormatMessage class Rc2Grd(interface.Tool): '''A tool for converting .rc files to .grd files. This tool is only for converting the source (nontranslated) .rc file to a .grd file. For importing existing translations, use the rc2xtb tool. Usage: grit [global options] rc2grd [OPTIONS] RCFILE The tool takes a single argument, which is the path to the .rc file to convert. It outputs a .grd file with the same name in the same directory as the .rc file. The .grd file may have one or more TODO comments for things that have to be cleaned up manually. OPTIONS may be any of the following: -e ENCODING Specify the ENCODING of the .rc file. Default is 'cp1252'. -h TYPE Specify the TYPE attribute for HTML structures. Default is 'tr_html'. -u ENCODING Specify the ENCODING of HTML files. Default is 'utf-8'. -n MATCH Specify the regular expression to match in comments that will indicate that the resource the comment belongs to is not translateable. Default is 'Not locali(s|z)able'. -r GRDFILE Specify that GRDFILE should be used as a "role model" for any placeholders that otherwise would have had TODO names. This attempts to find an identical message in the GRDFILE and uses that instead of the automatically placeholderized message. --pre CLASS Specify an optional, fully qualified classname, which has to be a subclass of grit.tool.PreProcessor, to run on the text of the RC file before conversion occurs. This can be used to support constructs in the RC files that GRIT cannot handle on its own. --post CLASS Specify an optional, fully qualified classname, which has to be a subclass of grit.tool.PostProcessor, to run on the text of the converted RC file. This can be used to alter the content of the RC file based on the conversion that occured. For menus, dialogs and version info, the .grd file will refer to the original .rc file. Once conversion is complete, you can strip the original .rc file of its string table and all comments as these will be available in the .grd file. Note that this tool WILL NOT obey C preprocessor rules, so even if something is #if 0-ed out it will still be included in the output of this tool Therefore, if your .rc file contains sections like this, you should run the C preprocessor on the .rc file or manually edit it before using this tool. ''' def ShortDescription(self): return 'A tool for converting .rc source files to .grd files.' def __init__(self): self.input_encoding = 'cp1252' self.html_type = 'tr_html' self.html_encoding = 'utf-8' self.not_localizable_re = re.compile('Not locali(s|z)able') self.role_model = None self.pre_process = None self.post_process = None def ParseOptions(self, args, help_func=None): '''Given a list of arguments, set this object's options and return all non-option arguments. ''' (own_opts, args) = getopt.getopt(args, 'e:h:u:n:r', ('help', 'pre=', 'post=')) for (key, val) in own_opts: if key == '-e': self.input_encoding = val elif key == '-h': self.html_type = val elif key == '-u': self.html_encoding = val elif key == '-n': self.not_localizable_re = re.compile(val) elif key == '-r': self.role_model = grd_reader.Parse(val) elif key == '--pre': self.pre_process = val elif key == '--post': self.post_process = val elif key == '--help': if help_func is None: self.ShowUsage() else: help_func() sys.exit(0) return args def Run(self, opts, args): args = self.ParseOptions(args) if len(args) != 1: print('This tool takes a single tool-specific argument, the path to the\n' '.rc file to process.') return 2 self.SetOptions(opts) path = args[0] out_path = os.path.join(util.dirname(path), os.path.splitext(os.path.basename(path))[0] + '.grd') rctext = util.ReadFile(path, self.input_encoding) grd_text = six.text_type(self.Process(rctext, path)) with util.WrapOutputStream(open(out_path, 'wb'), 'utf-8') as outfile: outfile.write(grd_text) print('Wrote output file %s.\nPlease check for TODO items in the file.' % (out_path,)) def Process(self, rctext, rc_path): '''Processes 'rctext' and returns a resource tree corresponding to it. Args: rctext: complete text of the rc file rc_path: 'resource\resource.rc' Return: grit.node.base.Node subclass ''' if self.pre_process: preprocess_class = util.NewClassInstance(self.pre_process, preprocess_interface.PreProcessor) if preprocess_class: rctext = preprocess_class.Process(rctext, rc_path) else: self.Out( 'PreProcessing class could not be found. Skipping preprocessing.\n') # Start with a basic skeleton for the .grd file root = grd_reader.Parse(StringIO( '''<?xml version="1.0" encoding="UTF-8"?> <grit base_dir="." latest_public_release="0" current_release="1" source_lang_id="en"> <outputs /> <translations /> <release seq="1"> <includes /> <structures /> <messages /> </release> </grit>'''), util.dirname(rc_path)) includes = root.children[2].children[0] structures = root.children[2].children[1] messages = root.children[2].children[2] assert (isinstance(includes, grit.node.empty.IncludesNode) and isinstance(structures, grit.node.empty.StructuresNode) and isinstance(messages, grit.node.empty.MessagesNode)) self.AddIncludes(rctext, includes) self.AddStructures(rctext, structures, os.path.basename(rc_path)) self.AddMessages(rctext, messages) self.VerboseOut('Validating that all IDs are unique...\n') root.ValidateUniqueIds() self.ExtraVerboseOut('Done validating that all IDs are unique.\n') if self.post_process: postprocess_class = util.NewClassInstance(self.post_process, postprocess_interface.PostProcessor) if postprocess_class: root = postprocess_class.Process(rctext, rc_path, root) else: self.Out( 'PostProcessing class could not be found. Skipping postprocessing.\n') return root def IsHtml(self, res_type, fname): '''Check whether both the type and file extension indicate HTML''' fext = fname.split('.')[-1].lower() return res_type == 'HTML' and fext in ('htm', 'html') def AddIncludes(self, rctext, node): '''Scans 'rctext' for included resources (e.g. BITMAP, ICON) and adds each included resource as an <include> child node of 'node'.''' for m in _FILE_REF.finditer(rctext): id = m.group('id') res_type = m.group('type').upper() fname = rc.Section.UnEscape(m.group('file')) assert fname.find('\n') == -1 if not self.IsHtml(res_type, fname): self.VerboseOut('Processing %s with ID %s (filename: %s)\n' % (res_type, id, fname)) node.AddChild(include.IncludeNode.Construct(node, id, res_type, fname)) def AddStructures(self, rctext, node, rc_filename): '''Scans 'rctext' for structured resources (e.g. menus, dialogs, version information resources and HTML templates) and adds each as a <structure> child of 'node'.''' # First add HTML includes for m in _FILE_REF.finditer(rctext): id = m.group('id') res_type = m.group('type').upper() fname = rc.Section.UnEscape(m.group('file')) if self.IsHtml(type, fname): node.AddChild(structure.StructureNode.Construct( node, id, self.html_type, fname, self.html_encoding)) # Then add all RC includes def AddStructure(res_type, id): self.VerboseOut('Processing %s with ID %s\n' % (res_type, id)) node.AddChild(structure.StructureNode.Construct(node, id, res_type, rc_filename, encoding=self.input_encoding)) for m in _MENU.finditer(rctext): AddStructure('menu', m.group('id')) for m in _DIALOG.finditer(rctext): AddStructure('dialog', m.group('id')) for m in _VERSIONINFO.finditer(rctext): AddStructure('version', m.group('id')) def AddMessages(self, rctext, node): '''Scans 'rctext' for all messages in string tables, preprocesses them as much as possible for placeholders (e.g. messages containing $1, $2 or %s, %d type format specifiers get those specifiers replaced with placeholders, and HTML-formatted messages get run through the HTML-placeholderizer). Adds each message as a <message> node child of 'node'.''' for tm in _STRING_TABLE.finditer(rctext): table = tm.group('body') for mm in _MESSAGE.finditer(table): comment_block = mm.group('comment') comment_text = [] for cm in _COMMENT_TEXT.finditer(comment_block): comment_text.append(cm.group('text')) comment_text = ' '.join(comment_text) id = mm.group('id') text = rc.Section.UnEscape(mm.group('text')) self.VerboseOut('Processing message %s (text: "%s")\n' % (id, text)) msg_obj = self.Placeholderize(text) # Messages that contain
field( default_factory=list, metadata={ "name": "OtherName", "type": "Element", } ) alias: List["PersonName.FormerName.Alias"] = field( default_factory=list, metadata={ "name": "Alias", "type": "Element", } ) generation_identifier: List["PersonName.FormerName.GenerationIdentifier"] = field( default_factory=list, metadata={ "name": "GenerationIdentifier", "type": "Element", } ) suffix: List["PersonName.FormerName.Suffix"] = field( default_factory=list, metadata={ "name": "Suffix", "type": "Element", } ) general_suffix: Optional["PersonName.FormerName.GeneralSuffix"] = field( default=None, metadata={ "name": "GeneralSuffix", "type": "Element", } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) name_details_key_ref: Optional[str] = field( default=None, metadata={ "name": "NameDetailsKeyRef", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) other_element: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##other", } ) valid_from: Optional[str] = field( default=None, metadata={ "name": "ValidFrom", "type": "Attribute", } ) valid_to: Optional[str] = field( default=None, metadata={ "name": "ValidTo", "type": "Attribute", } ) @dataclass class PrecedingTitle: """ :ivar content: :ivar type: Type of Preceding Title. Example: Honorary title. :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class Title: """ :ivar content: :ivar type: Type of Title. Example: Plural Titles such as MESSRS, Formal Degree, Honarary Degree, Sex (Mr, Mrs) etc :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class FirstName: """ :ivar content: :ivar type: Type of first name. Example: Official, Un- official, abbreviation, initial, etc :ivar name_type: Defines the name type of first name. Example: Given Name, Christian Name, Father's Name, etc. In some countries, First name could be a Family Name or a SurName. Use this attribute to define the type for this name. :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) name_type: Optional[str] = field( default=None, metadata={ "name": "NameType", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class MiddleName: """ :ivar content: :ivar type: Type of middle name. Example: Official, Un- official, abbreviation, initial, etc :ivar name_type: Defines the name type of Middle Name. Example: First name, middle name, maiden name, father's name, given name, etc. :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) name_type: Optional[str] = field( default=None, metadata={ "name": "NameType", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class NamePrefix: """ :ivar content: :ivar type: Type of last name prefix. Example: Official, Un- official, abbreviation, initial, etc :ivar name_type: Defines the type of name associated with the NamePrefix. For example the type of name is LastName and this prefix is the prefix for this last name. :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) name_type: Optional[str] = field( default=None, metadata={ "name": "NameType", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class LastName: """ :ivar content: :ivar type: Type of last name. Example: Official, Un- official, abbreviation, initial, etc :ivar name_type: Defines the name type of Last Name. Example: Father's name, Family name, Sur Name, Mother's Name, etc. In some countries, Last name could be the given name or first name. :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) name_type: Optional[str] = field( default=None, metadata={ "name": "NameType", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class OtherName: """ :ivar content: :ivar type: Type of Other name. Example: Official, Un- official, abbreviation, initial, etc :ivar name_type: Defines the name type of Other Name. Example: Maiden Name, Patronymic name, Matronymic name, etc :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) name_type: Optional[str] = field( default=None, metadata={ "name": "NameType", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class Alias: """ :ivar content: :ivar type: Type of Alias. Example: Official, UnOfficial, Close Circle, etc :ivar name_type: Defines the name type of Alias. Example: <NAME>, <NAME>, etc :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) name_type: Optional[str] = field( default=None, metadata={ "name": "NameType", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class GenerationIdentifier: """ :ivar content: :ivar type: Defines the type of generation identifier. Example: Family Titles :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class Suffix: """ :ivar content: :ivar type: Defines the type of Suffix. Example: Compressed Initials, Full suffixes, etc :ivar code: Indicates the name element code defined by postal standard groups like ECCMA, ADIS, UN/PROLIST for postal services. :ivar other_attributes: """ content: List[object] = field( default_factory=list, metadata={ "type": "Wildcard", "namespace": "##any", "mixed": True, } ) type: Optional[str] = field( default=None, metadata={ "name": "Type", "type": "Attribute", } ) code: Optional[str] = field( default=None, metadata={ "name": "Code", "type": "Attribute", } ) other_attributes: Dict = field( default_factory=dict, metadata={ "type": "Attributes", "namespace": "##other", } ) @dataclass class GeneralSuffix: """ :ivar content: :ivar
property of operation, include metric specifications. :param metric_specifications: Metric specifications of operation. :type metric_specifications: list[~azure.mgmt.storage.v2018_02_01.models.MetricSpecification] """ _attribute_map = { 'metric_specifications': {'key': 'metricSpecifications', 'type': '[MetricSpecification]'}, } def __init__( self, **kwargs ): super(ServiceSpecification, self).__init__(**kwargs) self.metric_specifications = kwargs.get('metric_specifications', None) class Sku(msrest.serialization.Model): """The SKU of the storage account. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param name: Required. Gets or sets the sku name. Required for account creation; optional for update. Note that in older versions, sku name was called accountType. Possible values include: "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS". :type name: str or ~azure.mgmt.storage.v2018_02_01.models.SkuName :ivar tier: Gets the sku tier. This is based on the SKU name. Possible values include: "Standard", "Premium". :vartype tier: str or ~azure.mgmt.storage.v2018_02_01.models.SkuTier :ivar resource_type: The type of the resource, usually it is 'storageAccounts'. :vartype resource_type: str :ivar kind: Indicates the type of storage account. Possible values include: "Storage", "StorageV2", "BlobStorage". :vartype kind: str or ~azure.mgmt.storage.v2018_02_01.models.Kind :ivar locations: The set of locations that the SKU is available. This will be supported and registered Azure Geo Regions (e.g. West US, East US, Southeast Asia, etc.). :vartype locations: list[str] :ivar capabilities: The capability information in the specified sku, including file encryption, network acls, change notification, etc. :vartype capabilities: list[~azure.mgmt.storage.v2018_02_01.models.SKUCapability] :param restrictions: The restrictions because of which SKU cannot be used. This is empty if there are no restrictions. :type restrictions: list[~azure.mgmt.storage.v2018_02_01.models.Restriction] """ _validation = { 'name': {'required': True}, 'tier': {'readonly': True}, 'resource_type': {'readonly': True}, 'kind': {'readonly': True}, 'locations': {'readonly': True}, 'capabilities': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, 'resource_type': {'key': 'resourceType', 'type': 'str'}, 'kind': {'key': 'kind', 'type': 'str'}, 'locations': {'key': 'locations', 'type': '[str]'}, 'capabilities': {'key': 'capabilities', 'type': '[SKUCapability]'}, 'restrictions': {'key': 'restrictions', 'type': '[Restriction]'}, } def __init__( self, **kwargs ): super(Sku, self).__init__(**kwargs) self.name = kwargs['name'] self.tier = None self.resource_type = None self.kind = None self.locations = None self.capabilities = None self.restrictions = kwargs.get('restrictions', None) class SKUCapability(msrest.serialization.Model): """The capability information in the specified sku, including file encryption, network acls, change notification, etc. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of capability, The capability information in the specified sku, including file encryption, network acls, change notification, etc. :vartype name: str :ivar value: A string value to indicate states of given capability. Possibly 'true' or 'false'. :vartype value: str """ _validation = { 'name': {'readonly': True}, 'value': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, } def __init__( self, **kwargs ): super(SKUCapability, self).__init__(**kwargs) self.name = None self.value = None class TrackedResource(Resource): """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, } def __init__( self, **kwargs ): super(TrackedResource, self).__init__(**kwargs) self.tags = kwargs.get('tags', None) self.location = kwargs['location'] class StorageAccount(TrackedResource): """The storage account. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str :ivar sku: Gets the SKU. :vartype sku: ~azure.mgmt.storage.v2018_02_01.models.Sku :ivar kind: Gets the Kind. Possible values include: "Storage", "StorageV2", "BlobStorage". :vartype kind: str or ~azure.mgmt.storage.v2018_02_01.models.Kind :param identity: The identity of the resource. :type identity: ~azure.mgmt.storage.v2018_02_01.models.Identity :ivar provisioning_state: Gets the status of the storage account at the time the operation was called. Possible values include: "Creating", "ResolvingDNS", "Succeeded". :vartype provisioning_state: str or ~azure.mgmt.storage.v2018_02_01.models.ProvisioningState :ivar primary_endpoints: Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object. Note that Standard_ZRS and Premium_LRS accounts only return the blob endpoint. :vartype primary_endpoints: ~azure.mgmt.storage.v2018_02_01.models.Endpoints :ivar primary_location: Gets the location of the primary data center for the storage account. :vartype primary_location: str :ivar status_of_primary: Gets the status indicating whether the primary location of the storage account is available or unavailable. Possible values include: "available", "unavailable". :vartype status_of_primary: str or ~azure.mgmt.storage.v2018_02_01.models.AccountStatus :ivar last_geo_failover_time: Gets the timestamp of the most recent instance of a failover to the secondary location. Only the most recent timestamp is retained. This element is not returned if there has never been a failover instance. Only available if the accountType is Standard_GRS or Standard_RAGRS. :vartype last_geo_failover_time: ~datetime.datetime :ivar secondary_location: Gets the location of the geo-replicated secondary for the storage account. Only available if the accountType is Standard_GRS or Standard_RAGRS. :vartype secondary_location: str :ivar status_of_secondary: Gets the status indicating whether the secondary location of the storage account is available or unavailable. Only available if the SKU name is Standard_GRS or Standard_RAGRS. Possible values include: "available", "unavailable". :vartype status_of_secondary: str or ~azure.mgmt.storage.v2018_02_01.models.AccountStatus :ivar creation_time: Gets the creation date and time of the storage account in UTC. :vartype creation_time: ~datetime.datetime :ivar custom_domain: Gets the custom domain the user assigned to this storage account. :vartype custom_domain: ~azure.mgmt.storage.v2018_02_01.models.CustomDomain :ivar secondary_endpoints: Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object from the secondary location of the storage account. Only available if the SKU name is Standard_RAGRS. :vartype secondary_endpoints: ~azure.mgmt.storage.v2018_02_01.models.Endpoints :ivar encryption: Gets the encryption settings on the account. If unspecified, the account is unencrypted. :vartype encryption: ~azure.mgmt.storage.v2018_02_01.models.Encryption :ivar access_tier: Required for storage accounts where kind = BlobStorage. The access tier used for billing. Possible values include: "Hot", "Cool". :vartype access_tier: str or ~azure.mgmt.storage.v2018_02_01.models.AccessTier :param enable_https_traffic_only: Allows https traffic only to storage service if sets to true. :type enable_https_traffic_only: bool :ivar network_rule_set: Network rule set. :vartype network_rule_set: ~azure.mgmt.storage.v2018_02_01.models.NetworkRuleSet :param is_hns_enabled: Account HierarchicalNamespace enabled if sets to true. :type is_hns_enabled: bool """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, 'sku': {'readonly': True}, 'kind': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'primary_endpoints': {'readonly': True}, 'primary_location': {'readonly': True}, 'status_of_primary': {'readonly': True}, 'last_geo_failover_time': {'readonly': True}, 'secondary_location': {'readonly': True}, 'status_of_secondary': {'readonly': True}, 'creation_time': {'readonly': True}, 'custom_domain': {'readonly': True}, 'secondary_endpoints': {'readonly': True}, 'encryption': {'readonly': True}, 'access_tier': {'readonly': True}, 'network_rule_set': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, 'sku': {'key': 'sku', 'type': 'Sku'}, 'kind': {'key': 'kind', 'type': 'str'}, 'identity': {'key': 'identity', 'type': 'Identity'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'primary_endpoints': {'key': 'properties.primaryEndpoints', 'type': 'Endpoints'}, 'primary_location': {'key': 'properties.primaryLocation', 'type': 'str'}, 'status_of_primary': {'key': 'properties.statusOfPrimary', 'type': 'str'}, 'last_geo_failover_time': {'key': 'properties.lastGeoFailoverTime', 'type': 'iso-8601'}, 'secondary_location': {'key': 'properties.secondaryLocation', 'type': 'str'}, 'status_of_secondary': {'key': 'properties.statusOfSecondary', 'type': 'str'}, 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, 'custom_domain': {'key': 'properties.customDomain', 'type': 'CustomDomain'}, 'secondary_endpoints': {'key': 'properties.secondaryEndpoints', 'type': 'Endpoints'}, 'encryption': {'key': 'properties.encryption', 'type': 'Encryption'}, 'access_tier': {'key': 'properties.accessTier', 'type': 'str'}, 'enable_https_traffic_only': {'key': 'properties.supportsHttpsTrafficOnly', 'type': 'bool'}, 'network_rule_set': {'key':
u=self.library_id, t=self.library_type, i=item.upper() ) return self._build_query(query_string) @retrieve def collection_items(self, collection, **kwargs): """ Get a specific collection's items """ query_string = "/{t}/{u}/collections/{c}/items".format( u=self.library_id, t=self.library_type, c=collection.upper() ) return self._build_query(query_string) @retrieve def collection_items_top(self, collection, **kwargs): """ Get a specific collection's top-level items """ query_string = "/{t}/{u}/collections/{c}/items/top".format( u=self.library_id, t=self.library_type, c=collection.upper() ) return self._build_query(query_string) @retrieve def collection_tags(self, collection, **kwargs): """ Get a specific collection's tags """ query_string = "/{t}/{u}/collections/{c}/tags".format( u=self.library_id, t=self.library_type, c=collection.upper() ) return self._build_query(query_string) @retrieve def collection(self, collection, **kwargs): """ Get user collection """ query_string = "/{t}/{u}/collections/{c}".format( u=self.library_id, t=self.library_type, c=collection.upper() ) return self._build_query(query_string) @retrieve def collections(self, **kwargs): """ Get user collections """ query_string = "/{t}/{u}/collections" return self._build_query(query_string) def all_collections(self, collid=None): """ Retrieve all collections and subcollections. Works for top-level collections or for a specific collection. Works at all collection depths. """ all_collections = [] def subcoll(clct): """ recursively add collections to a flat master list """ all_collections.append(clct) if clct["meta"].get("numCollections", 0) > 0: # add collection to master list & recur with all child # collections [ subcoll(c) for c in self.everything(self.collections_sub(clct["data"]["key"])) ] # select all top-level collections or a specific collection and # children if collid: toplevel = [self.collection(collid)] else: toplevel = self.everything(self.collections_top()) [subcoll(collection) for collection in toplevel] return all_collections @retrieve def collections_top(self, **kwargs): """ Get top-level user collections """ query_string = "/{t}/{u}/collections/top" return self._build_query(query_string) @retrieve def collections_sub(self, collection, **kwargs): """ Get subcollections for a specific collection """ query_string = "/{t}/{u}/collections/{c}/collections".format( u=self.library_id, t=self.library_type, c=collection.upper() ) return self._build_query(query_string) @retrieve def groups(self, **kwargs): """ Get user groups """ query_string = "/users/{u}/groups" return self._build_query(query_string) @retrieve def tags(self, **kwargs): """ Get tags """ query_string = "/{t}/{u}/tags" self.tag_data = True return self._build_query(query_string) @retrieve def item_tags(self, item, **kwargs): """ Get tags for a specific item """ query_string = "/{t}/{u}/items/{i}/tags".format( u=self.library_id, t=self.library_type, i=item.upper() ) self.tag_data = True return self._build_query(query_string) def all_top(self, **kwargs): """ Retrieve all top-level items """ return self.everything(self.top(**kwargs)) @retrieve def follow(self): """ Return the result of the call to the URL in the 'Next' link """ if self.links.get("next"): return self.links.get("next") else: return def iterfollow(self): """ Generator for self.follow() """ # use same criterion as self.follow() while True: if self.links.get("next"): yield self.follow() else: return def makeiter(self, func): """ Return a generator of func's results """ # reset the link. This results in an extra API call, yes self.links["next"] = self.links["self"] return self.iterfollow() def everything(self, query): """ Retrieve all items in the library for a particular query This method will override the 'limit' parameter if it's been set """ try: items = [] items.extend(query) while self.links.get("next"): items.extend(self.follow()) except TypeError: # we have a bibliography object ughh items = copy.deepcopy(query) while self.links.get("next"): items.entries.extend(self.follow().entries) return items def get_subset(self, subset): """ Retrieve a subset of items Accepts a single argument: a list of item IDs """ if len(subset) > 50: raise ze.TooManyItems("You may only retrieve 50 items per call") # remember any url parameters that have been set params = self.url_params retr = [] for itm in subset: retr.extend(self.item(itm)) self.url_params = params # clean up URL params when we're finished self.url_params = None return retr # The following methods process data returned by Read API calls def _json_processor(self, retrieved): """ Format and return data from API calls which return Items """ json_kwargs = {} if self.preserve_json_order: json_kwargs["object_pairs_hook"] = OrderedDict # send entries to _tags_data if there's no JSON try: items = [ json.loads(e["content"][0]["value"], **json_kwargs) for e in retrieved.entries ] except KeyError: return self._tags_data(retrieved) return items def _csljson_processor(self, retrieved): """ Return a list of dicts which are dumped CSL JSON """ items = [] json_kwargs = {} if self.preserve_json_order: json_kwargs["object_pairs_hook"] = OrderedDict for csl in retrieved.entries: items.append(json.loads(csl["content"][0]["value"], **json_kwargs)) self.url_params = None return items def _bib_processor(self, retrieved): """ Return a list of strings formatted as HTML bibliography entries """ items = [] for bib in retrieved.entries: items.append(bib["content"][0]["value"]) self.url_params = None return items def _citation_processor(self, retrieved): """ Return a list of strings formatted as HTML citation entries """ items = [] for cit in retrieved.entries: items.append(cit["content"][0]["value"]) self.url_params = None return items def _tags_data(self, retrieved): """ Format and return data from API calls which return Tags """ self.url_params = None return [t["tag"] for t in retrieved] # The following methods are Write API calls def item_template(self, itemtype, linkmode=None): """ Get a template for a new item """ # if we have a template and it hasn't been updated since we stored it template_name = "{}_{}_{}".format(*["item_template", itemtype, linkmode or ""]) query_string = "/items/new?itemType={i}".format(i=itemtype) if self.templates.get(template_name) and not self._updated( query_string, self.templates[template_name], template_name ): return copy.deepcopy(self.templates[template_name]["tmplt"]) # Set linkMode parameter for API request if itemtype is attachment if itemtype == "attachment": query_string = "{}&linkMode={}".format(query_string, linkmode) # otherwise perform a normal request and cache the response retrieved = self._retrieve_data(query_string) return self._cache(retrieved, template_name) def _attachment_template(self, attachment_type): """ Return a new attachment template of the required type: imported_file imported_url linked_file linked_url """ return self.item_template("attachment&linkMode=" + attachment_type) def _attachment(self, payload, parentid=None): """ Create attachments accepts a list of one or more attachment template dicts and an optional parent Item ID. If this is specified, attachments are created under this ID """ attachment = Zupload(self, payload, parentid) res = attachment.upload() return res @ss_wrap def show_operators(self): """ Show available saved search operators """ return self.savedsearch.operators @ss_wrap def show_conditions(self): """ Show available saved search conditions """ return self.savedsearch.conditions_operators.keys() @ss_wrap def show_condition_operators(self, condition): """ Show available operators for a given saved search condition """ # dict keys of allowed operators for the current condition permitted_operators = self.savedsearch.conditions_operators.get(condition) # transform these into values permitted_operators_list = set( [self.savedsearch.operators.get(op) for op in permitted_operators] ) return permitted_operators_list @ss_wrap def saved_search(self, name, conditions): """ Create a saved search. conditions is a list of dicts containing search conditions, and must contain the following str keys: condition, operator, value """ self.savedsearch._validate(conditions) payload = [{"name": name, "conditions": conditions}] headers = {"Zotero-Write-Token": token()} headers.update(self.default_headers()) self._check_backoff() req = requests.post( url=self.endpoint + "/{t}/{u}/searches".format(t=self.library_type, u=self.library_id), headers=headers, data=json.dumps(payload), ) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(self, req) backoff = self.request.headers.get("backoff") if backoff: self._set_backoff(backoff) return req.json() @ss_wrap def delete_saved_search(self, keys): """ Delete one or more saved searches by passing a list of one or more unique search keys """ headers = {"Zotero-Write-Token": token()} headers.update(self.default_headers()) self._check_backoff() req = requests.delete( url=self.endpoint + "/{t}/{u}/searches".format(t=self.library_type, u=self.library_id), headers=headers, params={"searchKey": ",".join(keys)}, ) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(self, req) backoff = self.request.headers.get("backoff") if backoff: self._set_backoff(backoff) return req.status_code def upload_attachments(self, attachments, parentid=None, basedir=None): """Upload files to the already created (but never uploaded) attachments""" return Zupload(self, attachments, parentid, basedir=basedir).upload() def add_tags(self, item, *tags): """ Add one or more tags to a retrieved item, then update it on the server Accepts a dict, and one or more tags to add to it Returns the updated item from the server """ # Make sure there's a tags field, or add one try: assert item["data"]["tags"] except AssertionError: item["data"]["tags"] = list() for tag in tags: item["data"]["tags"].append({"tag": "%s" % tag}) # make sure everything's OK assert self.check_items([item]) return self.update_item(item) def check_items(self, items): """ Check that items to be created contain no invalid dict keys Accepts a single argument: a list of one or more dicts The retrieved fields are cached and re-used until a 304 call fails """ params = {"locale": self.locale} query_string = "/itemFields" r = Request("GET", self.endpoint + query_string, params=params).prepare() # now split up the URL result = urlparse(r.url) # construct cache key cachekey = result.path + "_" + result.query if self.templates.get(cachekey) and not self._updated( query_string, self.templates[cachekey], cachekey ): template = set(t["field"] for t in self.templates[cachekey]["tmplt"]) else: template = set(t["field"] for t in self.item_fields()) # add fields we know to be OK template = template | set( [ "path", "tags", "notes", "itemType", "creators", "mimeType", "linkMode", "note", "charset", "dateAdded", "version", "collections", "dateModified", "relations", # attachment items "parentItem", "mtime", "contentType", "md5", "filename", "inPublications" ] ) template = template | set(self.temp_keys) for pos, item in enumerate(items): if set(item) == set(["links", "library", "version", "meta", "key", "data"]): # we have an item that was retrieved from
#!/usr/bin/env python """ Run basic notary client tests against a server """ from __future__ import print_function import argparse from getpass import getpass import inspect import json import os import ssl import tempfile import platform import requests from requests.auth import HTTPBasicAuth from shutil import rmtree from subprocess import CalledProcessError, PIPE, Popen, call from tempfile import mkdtemp, mkstemp from textwrap import dedent from time import sleep, time from uuid import uuid4 def reporoot(): """ Get the root of the git repo """ return os.path.dirname( os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # Returns the reponame and server name def parse_args(args=None): """ Parses the command line args for this command """ parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=dedent(""" Tests the notary client against a host. To test against a testing host without auth, just run without any arguments except maybe for the server; a random repo name will be generated. When running against Docker Hub, suggest usage like: python buildscripts/testchangefeed.py \\ -s https://notary.docker.io \\ -r docker.io/username/reponame \\ -u username -p password Note that especially for Docker Hub, the repo has to have been already created, else auth won't succeed. """)) parser.add_argument( '-r', '--reponame', dest="reponame", type=str, help="The name of the repo - will be randomly generated if not provided") parser.add_argument( '-s', '--server', dest="server", type=str, required=True, help="Notary Server to connect to - defaults to https://notary-server:4443") parser.add_argument( '-u', '--username', dest="username", type=str, required=True, help="Username to use to log into the Notary Server") parser.add_argument( '-p', '--password', dest="password", type=str, required=True, help="Password to use to log into the Notary Server") parsed = parser.parse_args(args) return parsed.reponame, parsed.server.rstrip('/'), parsed.username, parsed.password def cleanup(*paths): """ Best effort removal the temporary paths, whether file or directory """ for path in paths: try: os.remove(path) except OSError: pass else: continue try: rmtree(path) except OSError: pass class Client(object): """ Object that will run the notary client with the proper command lines """ def __init__(self, notary_server, ca_file_path, username_passwd=()): self.notary_server = notary_server self.username_passwd = <PASSWORD> self.env = os.environ.copy() self.ca_file_path = ca_file_path self.env.update({ "NOTARY_ROOT_PASSPHRASE": "root_ponies", "NOTARY_TARGETS_PASSPHRASE": "targets_ponies", "NOTARY_SNAPSHOT_PASSPHRASE": "snapshot_ponies", "NOTARY_DELEGATION_PASSPHRASE": "user_ponies", }) if notary_server is None or ca_file_path is None: raise Exception("must provide a notary_server and ca_file_path to Client") else: self.client = [binary(), "-s", notary_server, "--tlscacert", ca_file_path] def run(self, args, trust_dir, stdinput=None, username_passwd=None): """ Runs the notary client in a subprocess, and returns the output """ command = self.client + ["-d", trust_dir] + list(args) print("$ " + " ".join(command)) # username password require newlines - EOF doesn't seem to do it. communicate_input = (tuple((x + "\n" for x in self.username_passwd)) if username_passwd is None else username_passwd) # Input comes before the username/password, and if there is a username # and password, we need a newline after the input. Otherwise, just use # EOF (for instance if we're piping text to verify) if stdinput is not None: if communicate_input: communicate_input = (stdinput + "\n",) + communicate_input else: communicate_input = (stdinput,) _, filename = mkstemp() with open(filename, 'wb') as tempfile: process = Popen(command, env=self.env, stdout=tempfile, stdin=PIPE, universal_newlines=True) # communicate writes once then closes stdin for the process process.communicate("".join(communicate_input)) process.wait() with open(filename) as tempfile: output = tempfile.read() retcode = process.poll() cleanup(filename) print(output) if retcode: raise CalledProcessError(retcode, command, output=output) return output def changefeed(self, gun=None, start=0, pagesize=100): # blackout for rethinkdb sleep(60) if gun is not None: token_url = "{}/auth/token?realm=dtr&service=dtr&scope=repository:{}:pull".format(self.notary_server, gun) changefeed_url = "{}/v2/{}/_trust/changefeed".format(self.notary_server, gun) else: token_url = "{}/auth/token?service=dtr&scope=registry:catalog:*".format(self.notary_server) changefeed_url = "{}/v2/_trust/changefeed".format(self.notary_server) query = [] if start is not None: query.append("change_id="+str(start)) if pagesize is not None: query.append("records="+str(pagesize)) changefeed_url = changefeed_url + "?" + "&".join(query) resp = requests.get(token_url, auth=HTTPBasicAuth(self.username_passwd[0], self.username_passwd[1]), verify=False) token = resp.json()["token"] resp = requests.get(changefeed_url, headers={"Authorization": "Bearer " + token}, verify=False) return resp.json() class Tester(object): """ Thing that runs the test """ def __init__(self, repo_name, client): self.repo_name = repo_name self.client = client self.dir = mkdtemp(suffix="_main") def basic_repo_test(self, tempfile, tempdir): """ Initialize a repo, add a target, ensure the target is readable """ print("---- Initializing a repo, adding a target, and pushing ----\n") self.client.run(["init", self.repo_name], self.dir) self.client.run(["add", self.repo_name, "basic_repo_test", tempfile], self.dir) self.client.run(["publish", self.repo_name], self.dir) print("---- Listing and validating basic repo test targets ----\n") targets1 = self.client.run(["list", self.repo_name], self.dir) targets2 = self.client.run(["list", self.repo_name], tempdir) assert targets1 == targets2, "targets lists not equal: \n{0}\n{1}".format( targets1, targets2) assert "basic_repo_test" in targets1, "missing expected basic_repo_test: {0}".format( targets1) self.client.run( ["verify", self.repo_name, "basic_repo_test", "-i", tempfile, "-q"], self.dir) changes = self.client.changefeed(gun=self.repo_name) assert changes["count"] == 1 assert changes["records"][0]["GUN"] == self.repo_name assert changes["records"][0]["Category"] == "update" def add_delegation_test(self, tempfile, tempdir): """ Add a delegation to the repo - assumes the repo has already been initialized """ print("---- Rotating the snapshot key to server and adding a delegation ----\n") self.client.run(["key", "rotate", self.repo_name, "snapshot", "-r"], self.dir) self.client.run( ["delegation", "add", self.repo_name, "targets/releases", os.path.join(reporoot(), "fixtures", "secure.example.com.crt"), "--all-paths"], self.dir) self.client.run(["publish", self.repo_name], self.dir) print("---- Listing delegations ----\n") delegations1 = self.client.run(["delegation", "list", self.repo_name], self.dir) delegations2 = self.client.run(["delegation", "list", self.repo_name], tempdir) assert delegations1 == delegations2, "delegation lists not equal: \n{0}\n{1}".format( delegations1, delegations2) assert "targets/releases" in delegations1, "targets/releases delegation not added" # add key to tempdir, publish target print("---- Publishing a target using a delegation ----\n") self.client.run( ["key", "import", os.path.join(reporoot(), "fixtures", "secure.example.com.key"), "-r", "targets/releases"], tempdir) self.client.run( ["add", self.repo_name, "add_delegation_test", tempfile, "-r", "targets/releases"], tempdir) self.client.run(["publish", self.repo_name], tempdir) print("---- Listing and validating delegation repo test targets ----\n") targets1 = self.client.run(["list", self.repo_name], self.dir) targets2 = self.client.run(["list", self.repo_name], tempdir) assert targets1 == targets2, "targets lists not equal: \n{0}\n{1}".format( targets1, targets2) expected_target = [line for line in targets1.split("\n") if line.strip().startswith("add_delegation_test") and line.strip().endswith("targets/releases")] assert len(expected_target) == 1, "could not find target added to targets/releases" changes = self.client.changefeed(gun=self.repo_name) assert changes["count"] == 4 for r in changes["records"]: assert r["GUN"] == self.repo_name assert r["Category"] == "update" def root_rotation_test(self, tempfile, tempdir): """ Test root rotation """ print("---- Figuring out what the old keys are ----\n") # update the tempdir self.client.run(["list", self.repo_name], tempdir) output = self.client.run(["key", "list"], self.dir) orig_root_key_info = [line.strip() for line in output.split("\n") if line.strip().startswith('root')] assert len(orig_root_key_info) == 1 # this should be replaced with notary info later with open(os.path.join(tempdir, "tuf", self.repo_name, "metadata", "root.json")) as root: root_json = json.load(root) old_root_num_keys = len(root_json["signed"]["keys"]) old_root_certs = root_json["signed"]["roles"]["root"]["keyids"] assert len(old_root_certs) == 1 print("---- Rotating root key ----\n") # rotate root, check that we have a new key - this is interactive, so pass input self.client.run(["key", "rotate", self.repo_name, "root"], self.dir, stdinput="yes") output = self.client.run(["key", "list"], self.dir) new_root_key_info = [line.strip() for line in output.split("\n") if line.strip().startswith('root') and line.strip() != orig_root_key_info[0]] assert len(new_root_key_info) == 1 # update temp dir and make sure we can download the update self.client.run(["list", self.repo_name], tempdir) with open(os.path.join(tempdir, "tuf", self.repo_name, "metadata", "root.json")) as root: root_json = json.load(root) assert len(root_json["signed"]["keys"]) == old_root_num_keys + 1, ( "expected {0} base keys, but got {1}".format( old_root_num_keys + 1, len(root_json["signed"]["keys"]))) root_certs = root_json["signed"]["roles"]["root"]["keyids"] assert len(root_certs) == 1, "expected 1 valid root key, got {0}".format( len(root_certs)) assert root_certs != old_root_certs, "root key has not been rotated" print("---- Ensuring we can still publish ----\n") # make sure we can still publish from both repos self.client.run( ["key", "import", os.path.join(reporoot(), "fixtures", "secure.example.com.key"), "-r", "targets/releases"], tempdir) self.client.run( ["add", self.repo_name, "root_rotation_test_delegation_add", tempfile, "-r", "targets/releases"], tempdir) self.client.run(["publish", self.repo_name], tempdir) self.client.run(["add", self.repo_name, "root_rotation_test_targets_add", tempfile], self.dir) self.client.run(["publish", self.repo_name], self.dir) targets1 = self.client.run(["list", self.repo_name], self.dir) targets2 = self.client.run(["list", self.repo_name], tempdir) assert targets1 == targets2, "targets lists not equal: \n{0}\n{1}".format( targets1, targets2) lines = [line.strip() for line in targets1.split("\n")] expected_targets = [ line for line in lines if (line.startswith("root_rotation_test_delegation_add") and line.endswith("targets/releases")) or (line.startswith("root_rotation_test_targets_add") and line.endswith("targets"))] assert len(expected_targets) == 2 changes = self.client.changefeed(gun=self.repo_name) assert changes["count"] == 7 for r in changes["records"]: assert r["GUN"] == self.repo_name assert r["Category"] == "update" def changefeed_test(self, tempfile, tempdir): """ Try some of the changefeed filtering options now that the previous tests have populated some data """ changes = self.client.changefeed(gun=self.repo_name, start=0, pagesize=1) assert changes["count"] == 1 all_changes = self.client.changefeed(gun=self.repo_name, start=0, pagesize=1000) assert all_changes["count"] == 7 for r in all_changes["records"]: assert r["GUN"] == self.repo_name assert r["Category"] == "update" self.client.run(["delete", "--remote", self.repo_name], tempdir) changes = self.client.changefeed(gun=self.repo_name, start=-1, pagesize=1) assert changes["count"] == 1 assert changes["records"][0]["Category"] == "deletion" start = all_changes["records"][4]["ID"] changes = self.client.changefeed(start=start, gun=self.repo_name, pagesize=1) assert changes["count"] == 1 assert changes["records"][0]["ID"] == all_changes["records"][5]["ID"] changes = self.client.changefeed(start=start, gun=self.repo_name, pagesize=-1) assert changes["count"] == 1 assert changes["records"][0]["ID"] == all_changes["records"][3]["ID"] def run(self): """ Run tests N.B.
root, dirs, files in os.walk(theDir): for z in files: fn = g.os_path_finalize_join(root, z) junk, ext = g.os_path_splitext(fn) if not extList or ext in extList: result.append(fn) if excludeDirs and dirs: for z in dirs: if z in excludeDirs: dirs.remove(z) else: for ext in extList: result.extend(glob.glob('%s.*%s' % (theDir, ext))) return sorted(list(set(result))) #@+node:ekr.20150525123715.3: *3* pu.get_project_directory def get_project_directory(self, name): # Ignore everything after the first space. i = name.find(' ') if i > -1: name = name[: i].strip() leo_path, junk = g.os_path_split(__file__) d = { # Change these paths as required for your system. 'coverage': r'C:\Python26\Lib\site-packages\coverage-3.5b1-py2.6-win32.egg\coverage', 'leo': r'C:\leo.repo\leo-editor\leo\core', 'lib2to3': r'C:\Python26\Lib\lib2to3', 'pylint': r'C:\Python26\Lib\site-packages\pylint', 'rope': r'C:\Python26\Lib\site-packages\rope-0.9.4-py2.6.egg\rope\base', 'test': g.os_path_finalize_join(g.app.loadDir, '..', 'test-proj'), } dir_ = d.get(name.lower()) # g.trace(name,dir_) if not dir_: g.trace('bad project name: %s' % (name)) if not g.os_path_exists(dir_): g.trace('directory not found:' % (dir_)) return dir_ or '' #@+node:ekr.20171213071416.1: *3* pu.leo_core_files def leo_core_files(self): '''Return all the files in Leo's core.''' trace = False loadDir = g.app.loadDir # Compute directories. commands_dir = g.os_path_finalize_join(loadDir, '..', 'commands') plugins_dir = g.os_path_finalize_join(loadDir, '..', 'plugins') # Compute files. core_files = glob.glob('%s%s%s' % (loadDir, os.sep, '*.py')) for exclude in ['format-code.py',]: core_files = [z for z in core_files if not z.endswith(exclude)] command_files = glob.glob('%s%s%s' % (commands_dir, os.sep, '*.py')) plugins_files = glob.glob('%s%s%s' % (plugins_dir, os.sep, 'qt_*.py')) # Compute the result. files = core_files + command_files + plugins_files files = [z for z in files if not z.endswith('__init__.py')] if trace: g.printList(files) return files #@+node:ekr.20150525123715.4: *3* pu.project_files #@@nobeautify def project_files(self, name, force_all=False): '''Return a list of all files in the named project.''' # Ignore everything after the first space. i = name.find(' ') if i > -1: name = name[: i].strip() leo_path, junk = g.os_path_split(__file__) if name == 'leo': # Get the leo files directly. return self.leo_core_files() else: # Import the appropriate module. try: m = importlib.import_module(name, name) theDir = g.os_path_dirname(m.__file__) except ImportError: g.trace('package not found', name) return [] d = { 'coverage': (['.py'], ['.bzr', 'htmlfiles']), 'lib2to3': (['.py'], ['tests']), 'pylint': (['.py'], ['.bzr', 'test']), 'rope': (['.py'], ['.bzr']), } data = d.get(name.lower()) if not data: g.trace('bad project name: %s' % (name)) return [] extList, excludeDirs = data files = self.files_in_dir(theDir, recursive=True, extList=extList, excludeDirs=excludeDirs, ) if files: if g.app.runningAllUnitTests and len(files) > 1 and not force_all: return [files[0]] if not files: g.trace('no files found for %s in %s' % (name, theDir)) if g.app.runningAllUnitTests and len(files) > 1 and not force_all: return [files[0]] else: return files #@-others #@+node:ekr.20171213155537.1: ** class NewShowData class NewShowData(object): '''The driver class for analysis project.''' assigns_d = {} calls_d = {} classes_d = {} defs_d = {} returns_d = {} #@+others #@+node:ekr.20171213160214.1: *3* sd.analyze def analyze(self, fn, root): ast_d = { ast.Assign: self.assigns_d, ast.AugAssign: self.assigns_d, ast.Call: self.calls_d, ast.ClassDef: self.classes_d, ast.FunctionDef: self.defs_d, ast.Return: self.returns_d, } fn = g.shortFileName(fn) for d in ast_d.values(): d[fn] = [] for node in ast.walk(root): d = ast_d.get(node.__class__) if d is not None: d[fn].append(self.format(node)) #@+node:ekr.20171214040822.1: *3* sd.dump def dump(self, fn, root): suppress = [ 'arg', 'arguments', 'comprehension', 'keyword', 'Attribute', 'BinOp', 'BoolOp', 'Dict', 'IfExp', 'Index', 'Load', 'List', 'ListComp', 'Name', 'NameConstant', 'Num', 'Slice', 'Store', 'Str', 'Subscript', 'Tuple', 'UnaryOp', ] # statements = ['Assign', 'AugAssign', 'Call', 'Expr', 'If', 'Return',] errors = set() fn = g.shortFileName(fn) for node in ast.walk(root): name = node.__class__.__name__ if name not in suppress: try: print('%15s: %s' % (name, self.format(node,strip=False))) except AttributeError: errors.add(name) g.trace('errors', sorted(errors)) # g.printList(sorted(errors)) #@+node:ekr.20171213163216.1: *3* sd.format def format(self, node, strip=True): class Formatter(leoAst.AstFormatter): level = 0 s = Formatter().visit(node) line1 = g.splitLines(s)[0] line1 = line1.strip() if strip else line1.rstrip() return g.truncate(line1, 80) #@+node:ekr.20171213155537.3: *3* sd.run def run(self, files, dump=False, show_results=True): '''Process all files''' t1 = time.time() for fn in files: s, e = g.readFileIntoString(fn) if s: print('=====', g.shortFileName(fn)) s1 = g.toEncodedString(s) root = ast.parse(s1, filename='before', mode='exec') if dump: self.dump(fn, root) else: self.analyze(fn, root) else: g.trace('skipped', g.shortFileName(fn)) t2 = time.time() if show_results: self.show_results() g.trace('done: %s files in %4.1f sec.' % (len(files), (t2 - t1))) #@+node:ekr.20171213155537.7: *3* sd.show_results def show_results(self): '''Print a summary of the test results.''' table = ( ('assignments', self.assigns_d), ('calls', self.calls_d), ('classes', self.classes_d), ('defs', self.defs_d), ('returns', self.returns_d), ) for name, d in table: print('%s...' % name) g.printDict({key: sorted(set(d.get(key))) for key in d}) #@+node:ekr.20171213174732.1: *3* sd.visit def visit(self, node, types): if isinstance(node, types): yield self.format(node) #@-others #@+node:ekr.20150604164113.1: ** class ShowData class ShowData(object): '''The driver class for analysis project.''' #@+others #@+node:ekr.20150604165500.1: *3* ctor def __init__(self, c): '''Ctor for ShowData controller class.''' self.c = c self.files = None # Data. self.assigns_d = {} self.calls_d = {} self.classes_d = {} self.context_stack = [] self.defs_d = {} self.returns_d = {} # Statistics self.n_matches = 0 self.n_undefined_calls = 0 self.tot_lines = 0 self.tot_s = 0 #@+node:ekr.20150604163903.1: *3* run & helpers def run(self, files): '''Process all files''' self.files = files t1 = time.time() for fn in files: s, e = g.readFileIntoString(fn) if s: self.tot_s += len(s) g.trace('%8s %s' % ("{:,}".format(len(s)), g.shortFileName(fn))) # Print len(s), with commas. # Fast, accurate: # 1.9 sec for parsing. # 2.5 sec for Null AstFullTraverer traversal. # 2.7 sec to generate all strings. # 3.8 sec to generate all reports. s1 = g.toEncodedString(s) self.tot_lines += len(g.splitLines(s)) # Adds less than 0.1 sec. node = ast.parse(s1, filename='before', mode='exec') ShowDataTraverser(self, fn).visit(node) # elif 0: # Too slow, too clumsy: 3.3 sec for tokenizing # readlines = g.ReadLinesClass(s).next # for token5tuple in tokenize.generate_tokens(readlines): # pass # else: # Inaccurate. 2.2 sec to generate all reports. # self.scan(fn, s) else: g.trace('skipped', g.shortFileName(fn)) t2 = time.time() # Get the time exlusive of print time. self.show_results() g.trace('done: %4.1f sec.' % (t2 - t1)) #@+node:ekr.20150605054921.1: *3* scan & helpers (a prototype: no longer used) if 0: # The excellent prototype code, fast, easy but inaccurate. # It was a roadmap for the ShowDataTraverser class. # Regex patterns (were defined in the ctor) r_class = r'class[ \t]+([a-z_A-Z][a-z_A-Z0-9]*).*:' r_def = r'def[ \t]+([a-z_A-Z][a-z_A-Z0-9]*)[ \t]*\((.*)\)' r_return = r'(return[ \t].*)$' r_call = r'([a-z_A-Z][a-z_A-Z0-9]*)[ \t]*\(([^)]*)\)' r_all = re.compile('|'.join([r_class, r_def, r_return, r_call,])) def scan(self, fn, s): lines = g.splitLines(s) self.tot_lines += len(lines) for i, s in enumerate(lines): m = re.search(self.r_all, s) if m and not s.startswith('@'): self.match(fn, i, m, s) #@+node:ekr.20150605063318.1: *4* match def match(self, fn, i, m, s): '''Handle the next match.''' trace = False self.n_matches += 1 indent = g.skip_ws(s, 0) # Update the context and enter data. if g.match_word(s, indent, 'def'): self.update_context(fn, indent, 'def', s) for i, name in enumerate(m.groups()): if name: aList = self.defs_d.get(name, []) def_tuple = self.context_stack[: -1], s aList.append(def_tuple) self.defs_d[name] = aList break elif g.match_word(s, indent, 'class'): self.update_context(fn, indent, 'class', s) for i, name in enumerate(m.groups()): if name: aList = self.classes_d.get(name, []) class_tuple = self.context_stack[: -1], s aList.append(class_tuple) self.classes_d[name] = aList elif s.find('return') > -1: context, name = self.context_names() j = s.find('#') if j > -1: s = s[: j] s = s.strip() if s: aList = self.returns_d.get(name, []) return_tuple = context, s aList.append(return_tuple) self.returns_d[name] = aList else: # A call. for i, name in enumerate(m.groups()): if name: context2, context1 = self.context_names() j = s.find('#') if j > -1: s = s[: j] s = s.strip().strip(',').strip() if s: aList = self.calls_d.get(name, []) call_tuple = context2, context1, s aList.append(call_tuple) self.calls_d[name] = aList break if trace: print('%4s %4s %3s %3s %s' % ( self.n_matches, i, len(self.context_stack), indent, s.rstrip())) #@+node:ekr.20150605074749.1: *4* update_context def update_context(self, fn, indent, kind, s): '''Update context info when a class or def is seen.''' trace = False and self.n_matches < 100 while self.context_stack: fn2, kind2, indent2, s2 = self.context_stack[-1] if indent <= indent2: self.context_stack.pop() if trace: g.trace('pop ', len(self.context_stack), indent, indent2, kind2) else: break context_tuple = fn, kind, indent, s self.context_stack.append(context_tuple) if trace: g.trace('push', len(self.context_stack), s.rstrip()) self.context_indent = indent #@+node:ekr.20150604164546.1: *3* show_results & helpers def show_results(self): '''Print a summary of the test results.''' make = True multiple_only = False # True only show defs defined in more than one place. c = self.c result = ['@killcolor\n'] for name in sorted(self.defs_d): aList = self.defs_d.get(name, []) if len(aList) > 1 or not multiple_only: # not name.startswith('__') and ( self.show_defs(name, result) self.show_calls(name,
instances in " f"the training dataset, which is less than the lower limit ({_CAT_LIMIT}), " "so no heterogeneity model will be fit for it. This check can be turned off by " "setting 'skip_cat_limit_checks' to True, but that may result in an inaccurate " "model for this feature.") invalid_inds.append((ind, 'cat_limit')) for (ind, _) in invalid_inds: new_inds.remove(ind) # also remove from train_inds so we don't try to access the result later train_inds.remove(ind) if len(train_inds) == 0: raise ValueError("No features remain; increase the upper_bound_on_cat_expansion and ensure that there " "are several instances of each categorical value so that at least " "one feature model can be trained.") # extract subset of names matching new columns new_feat_names = _safe_indexing(feature_names, new_inds) cache_updates = dict(zip(new_inds, joblib.Parallel( n_jobs=self.n_jobs, verbose=self.verbose )(joblib.delayed(_process_feature)( feat_name, feat_ind, self.verbose, categorical_inds, categories, heterogeneity_inds, min_counts, y, X, self.nuisance_models, self.heterogeneity_model, self.random_state, self._model_y, self.cv, self.mc_iters) for feat_name, feat_ind in zip(new_feat_names, new_inds)))) # track indices where an exception was thrown, since we can't remove from dictionary while iterating inds_to_remove = [] for ind, value in cache_updates.items(): if isinstance(value, Exception): # don't want to cache this failed result inds_to_remove.append(ind) train_inds.remove(ind) invalid_inds.append((ind, value)) for ind in inds_to_remove: del cache_updates[ind] self._cache.update(cache_updates) for ind in train_inds: dict_update, result = self._cache[ind] self._results.append(result) for k in dict_update: self._shared[k] += dict_update[k] invalid_inds.sort() self.untrained_feature_indices_ = invalid_inds self.trained_feature_indices_ = train_inds self.nuisance_models_ = self.nuisance_models self.heterogeneity_model_ = self.heterogeneity_model return self def _format_col(self, ind): if self._has_column_names: return f"Column {ind} ({self.feature_names_[ind]})" else: return f"Column {ind}" # properties to return from effect InferenceResults @staticmethod def _point_props(alpha): return [(_CausalInsightsConstants.PointEstimateKey, 'point_estimate'), (_CausalInsightsConstants.StandardErrorKey, 'stderr'), (_CausalInsightsConstants.ZStatKey, 'zstat'), (_CausalInsightsConstants.PValueKey, 'pvalue'), (_CausalInsightsConstants.ConfidenceIntervalLowerKey, lambda inf: inf.conf_int(alpha=alpha)[0]), (_CausalInsightsConstants.ConfidenceIntervalUpperKey, lambda inf: inf.conf_int(alpha=alpha)[1])] # properties to return from PopulationSummaryResults @staticmethod def _summary_props(alpha): return [(_CausalInsightsConstants.PointEstimateKey, 'mean_point'), (_CausalInsightsConstants.StandardErrorKey, 'stderr_mean'), (_CausalInsightsConstants.ZStatKey, 'zstat'), (_CausalInsightsConstants.PValueKey, 'pvalue'), (_CausalInsightsConstants.ConfidenceIntervalLowerKey, lambda inf: inf.conf_int_mean(alpha=alpha)[0]), (_CausalInsightsConstants.ConfidenceIntervalUpperKey, lambda inf: inf.conf_int_mean(alpha=alpha)[1])] # Converts strings to property lookups or method calls as a convenience so that the # _point_props and _summary_props above can be applied to an inference object @staticmethod def _make_accessor(attr): if isinstance(attr, str): s = attr def attr(o): val = getattr(o, s) if callable(val): return val() else: return val return attr # Create a summary combining all results into a single output; this is used # by the various causal_effect and causal_effect_dict methods to generate either a dataframe # or a dictionary, respectively, based on the summary function passed into this method def _summarize(self, *, summary, get_inference, props, expand_arr, drop_sample): assert hasattr(self, "_results"), "This object has not been fit, so cannot get results" # ensure array has shape (m,y,t) def ensure_proper_dims(arr): if expand_arr: # population summary is missing sample dimension; add it for consistency arr = np.expand_dims(arr, 0) if self._vec_y: # outcome dimension is missing; add it for consistency arr = np.expand_dims(arr, axis=1) assert 2 <= arr.ndim <= 3 # add singleton treatment dimension if missing return arr if arr.ndim == 3 else np.expand_dims(arr, axis=2) # store set of inference results so we don't need to recompute per-attribute below in summary/coalesce infs = [get_inference(res) for res in self._results] # each attr has dimension (m,y) or (m,y,t) def coalesce(attr): """Join together the arrays for each feature""" attr = self._make_accessor(attr) # concatenate along treatment dimension arr = np.concatenate([ensure_proper_dims(attr(inf)) for inf in infs], axis=2) # for dictionary representation, want to remove unneeded sample dimension # in cohort and global results if drop_sample: arr = np.squeeze(arr, 0) return arr return summary([(key, coalesce(val)) for key, val in props]) def _pandas_summary(self, get_inference, *, props, n, expand_arr=False, keep_all_levels=False): """ Summarizes results into a dataframe. Parameters ---------- get_inference : lambda Method to get the relevant inference results from each result object props : list of (string, string or lambda) Set of column names and ways to get the corresponding values from the inference object n : int The number of samples in the dataset expand_arr : boolean, default False Whether to add a synthetic sample dimension to the result arrays when performing internal computations keep_all_levels : boolean, default False Whether to keep all levels, even when they don't take on more than one value; Note that regardless of this argument the "sample" level will only be present if expand_arr is False """ def make_dataframe(props): to_include = OrderedDict([(key, value.reshape(-1)) for key, value in props]) # TODO: enrich outcome logic for multi-class classification when that is supported index = pd.MultiIndex.from_tuples([(i, outcome, res.feature_name, f"{lvl}v{res.feature_baseline}" if res.feature_baseline is not None else lvl) for i in range(n) for outcome in ["y0"] for res in self._results for lvl in res.feature_levels], names=["sample", "outcome", "feature", "feature_value"]) if expand_arr: # There is no actual sample level in this data index = index.droplevel("sample") if not keep_all_levels: for lvl in index.levels: if len(lvl) == 1: if not isinstance(index, pd.MultiIndex): # can't drop only level index = pd.Index([self._results[0].feature_name], name="feature") else: index = index.droplevel(lvl.name) return pd.DataFrame(to_include, index=index) return self._summarize(summary=make_dataframe, get_inference=get_inference, props=props, expand_arr=expand_arr, drop_sample=False) # dropping the sample dimension is handled above instead def _dict_summary(self, get_inference, *, n, props, kind, drop_sample=False, expand_arr=False, row_wise=False): """ Summarizes results into a dictionary. Parameters ---------- get_inference : lambda Method to get the relevant inference results from each result object n : int The number of samples in the dataset props : list of (string, string or lambda) Set of column names and ways to get the corresponding values from the inference object kind : string The kind of inference results to get (e.g. 'global', 'local', or 'cohort') drop_sample : boolean, default False Whether to drop the sample dimension from each array expand_arr : boolean, default False Whether to add an initial sample dimension to the result arrays row_wise : boolean, default False Whether to return a list of dictionaries (one dictionary per row) instead of a dictionary of lists (one list per column) """ def make_dict(props): # should be serialization-ready and contain no numpy arrays res = _get_default_specific_insights(kind) shared = self._shared if row_wise: row_data = {} # remove entries belonging to row data, since we're including them in the list of nested dictionaries for k in _get_data_causal_insights_keys(): del res[k] shared = shared.copy() # copy so that we can modify without affecting shared state # TODO: Note that there's no column metadata for the sample number - should there be? for k in _get_column_causal_insights_keys(): # need to replicate the column info for each sample, then remove from the shared data row_data[k] = shared[k] * n del shared[k] # NOTE: the flattened order has the ouptut dimension before the feature dimension # which may need to be revisited once we support multiclass row_data.update([(key, value.flatten()) for key, value in props]) # get the length of the list corresponding to the first dictionary key # `list(row_data)` gets the keys as a list, since `row_data.keys()` can't be indexed into n_rows = len(row_data[list(row_data)[0]]) res[_CausalInsightsConstants.RowData] = [{key: row_data[key][i] for key in row_data} for i in range(n_rows)] else: res.update([(key, value.tolist()) for key, value in props]) return {**shared, **res} return self._summarize(summary=make_dict, get_inference=get_inference, props=props, expand_arr=expand_arr, drop_sample=drop_sample) def global_causal_effect(self, *, alpha=0.05, keep_all_levels=False): """ Get the global causal effect for each feature as a pandas DataFrame. Parameters ---------- alpha : float, default 0.05 The confidence level of the confidence interval keep_all_levels : bool, default False Whether to keep all levels of the output dataframe ('outcome', 'feature', and 'feature_level') even if there was only a single value for that level; by default single-valued levels are dropped. Returns ------- global_effects : pandas Dataframe DataFrame with the following structure: :Columns: ['point', 'stderr', 'zstat', 'pvalue', 'ci_lower', 'ci_upper'] :Index: ['feature', 'feature_value'] :Rows: For each feature that is numerical, we have an entry with index ['{feature_name}', 'num'], where 'num' is literally the string 'num' and feature_name is the input feature name. For each feature that is categorical, we have an entry with index ['{feature_name}', '{cat}v{base}'] where cat is the category value and base is the category used as baseline. If all features are numerical then the feature_value index is dropped in the dataframe, but not in
"""Manipulating the Sphinx AST with Jupyter objects""" import os import json from pathlib import Path import docutils from docutils.parsers.rst import Directive, directives from docutils.nodes import math_block, image, literal from sphinx.util import parselinenos from sphinx.util.docutils import ReferenceRole from sphinx.addnodes import download_reference from sphinx.transforms import SphinxTransform from sphinx.environment.collectors.asset import ImageCollector from sphinx.errors import ExtensionError import ipywidgets.embed import nbconvert from .utils import strip_latex_delimiters, sphinx_abs_dir from .thebelab import ThebeSourceNode, ThebeOutputNode WIDGET_VIEW_MIMETYPE = "application/vnd.jupyter.widget-view+json" WIDGET_STATE_MIMETYPE = "application/vnd.jupyter.widget-state+json" def csv_option(s): return [p.strip() for p in s.split(",")] if s else [] def load_content(cell, location, logger): if cell.arguments: # As per 'sphinx.directives.code.LiteralInclude' env = cell.state.document.settings.env rel_filename, filename = env.relfn2path(cell.arguments[0]) env.note_dependency(rel_filename) if cell.content: logger.warning( 'Ignoring inline code in Jupyter cell included from "{}"'.format( rel_filename ), location=location, ) try: with Path(filename).open() as f: content = [line.rstrip() for line in f.readlines()] except (IOError, OSError): raise IOError("File {} not found or reading it failed".format(filename)) else: cell.assert_has_content() content = cell.content return content def get_highlights(cell, content, location, logger): # The code fragment is taken from CodeBlock directive almost unchanged: # https://github.com/sphinx-doc/sphinx/blob/0319faf8f1503453b6ce19020819a8cf44e39f13/sphinx/directives/code.py#L134-L148 emphasize_linespec = cell.options.get("emphasize-lines") if emphasize_linespec: nlines = len(content) hl_lines = parselinenos(emphasize_linespec, nlines) if any(i >= nlines for i in hl_lines): logger.warning( "Line number spec is out of range(1-{}): {}".format( nlines, emphasize_linespec ), location=location, ) hl_lines = [i + 1 for i in hl_lines if i < nlines] else: hl_lines = [] return hl_lines class JupyterCell(Directive): """Define a code cell to be later executed in a Jupyter kernel. The content of the directive is the code to execute. Code is not executed when the directive is parsed, but later during a doctree transformation. Arguments --------- filename : str (optional) If provided, a path to a file containing code. Options ------- hide-code : bool If provided, the code will not be displayed in the output. hide-output : bool If provided, the cell output will not be displayed in the output. code-below : bool If provided, the code will be shown below the cell output. linenos : bool If provided, the code will be shown with line numbering. lineno-start: nonnegative int If provided, the code will be show with line numbering beginning from specified line. emphasize-lines : comma separated list of line numbers If provided, the specified lines will be highlighted. raises : comma separated list of exception types If provided, a comma-separated list of exception type names that the cell may raise. If one of the listed execption types is raised then the traceback is printed in place of the cell output. If an exception of another type is raised then we raise a RuntimeError when executing. Content ------- code : str A code cell. """ required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True has_content = True option_spec = { "hide-code": directives.flag, "hide-output": directives.flag, "code-below": directives.flag, "linenos": directives.flag, "lineno-start": directives.nonnegative_int, "emphasize-lines": directives.unchanged_required, "raises": csv_option, "stderr": directives.flag, } def run(self): # This only works lazily because the logger is inited by Sphinx from . import logger location = self.state_machine.get_source_and_line(self.lineno) content = load_content(self, location, logger) try: hl_lines = get_highlights(self, content, location, logger) except ValueError as err: return [self.state.document.reporter.warning(err, line=self.lineno)] # A top-level placeholder for our cell cell_node = JupyterCellNode( execute=True, hide_code=("hide-code" in self.options), hide_output=("hide-output" in self.options), code_below=("code-below" in self.options), emphasize_lines=hl_lines, raises=self.options.get("raises"), stderr=("stderr" in self.options), classes=["jupyter_cell"], ) # Add the input section of the cell, we'll add output at execution time cell_input = CellInputNode(classes=["cell_input"]) cell_input += docutils.nodes.literal_block( text="\n".join(content), linenos=("linenos" in self.options), linenostart=(self.options.get("lineno-start")), ) cell_node += cell_input return [cell_node] class CellInput(Directive): """Define a code cell to be included verbatim but not executed. Arguments --------- filename : str (optional) If provided, a path to a file containing code. Options ------- linenos : bool If provided, the code will be shown with line numbering. lineno-start: nonnegative int If provided, the code will be show with line numbering beginning from specified line. emphasize-lines : comma separated list of line numbers If provided, the specified lines will be highlighted. Content ------- code : str A code cell. """ required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True has_content = True option_spec = { "linenos": directives.flag, "lineno-start": directives.nonnegative_int, "emphasize-lines": directives.unchanged_required, } def run(self): # This only works lazily because the logger is inited by Sphinx from . import logger location = self.state_machine.get_source_and_line(self.lineno) content = load_content(self, location, logger) try: hl_lines = get_highlights(self, content, location, logger) except ValueError as err: return [self.state.document.reporter.warning(err, line=self.lineno)] # A top-level placeholder for our cell cell_node = JupyterCellNode( execute=False, hide_code=False, hide_output=True, code_below=False, emphasize_lines=hl_lines, raises=False, stderr=False, classes=["jupyter_cell"], ) # Add the input section of the cell, we'll add output when jupyter-execute cells are run cell_input = CellInputNode(classes=["cell_input"]) cell_input += docutils.nodes.literal_block( text="\n".join(content), linenos=("linenos" in self.options), linenostart=(self.options.get("lineno-start")), ) cell_node += cell_input return [cell_node] class CellOutput(Directive): """Define an output cell to be included verbatim. Arguments --------- filename : str (optional) If provided, a path to a file containing output. Content ------- code : str An output cell. """ required_arguments = 0 optional_arguments = 1 final_argument_whitespace = True has_content = True option_spec = {} def run(self): # This only works lazily because the logger is inited by Sphinx from . import logger location = self.state_machine.get_source_and_line(self.lineno) content = load_content(self, location, logger) # A top-level placeholder for our cell cell_node = JupyterCellNode( execute=False, hide_code=True, hide_output=False, code_below=False, emphasize_lines=[], raises=False, stderr=False, ) # Add a blank input and the given output to the cell cell_input = CellInputNode(classes=["cell_input"]) cell_input += docutils.nodes.literal_block( text="", linenos=False, linenostart=None, ) cell_node += cell_input content_str = "\n".join(content) cell_output = CellOutputNode(classes=["cell_output"]) cell_output += docutils.nodes.literal_block( text=content_str, rawsource=content_str, language="none", classes=["output", "stream"], ) cell_node += cell_output return [cell_node] class JupyterCellNode(docutils.nodes.container): """Inserted into doctree whever a JupyterCell directive is encountered. Contains code that will be executed in a Jupyter kernel at a later doctree-transformation step. """ class CellInputNode(docutils.nodes.container): """Represent an input cell in the Sphinx AST.""" def __init__(self, rawsource="", *children, **attributes): super().__init__("", **attributes) class CellOutputNode(docutils.nodes.container): """Represent an output cell in the Sphinx AST.""" def __init__(self, rawsource="", *children, **attributes): super().__init__("", **attributes) class CellOutputBundleNode(docutils.nodes.container): """Represent a MimeBundle in the Sphinx AST, to be transformed later.""" def __init__(self, outputs, rawsource="", *children, **attributes): self.outputs = outputs super().__init__("", **attributes) class JupyterKernelNode(docutils.nodes.Element): """Inserted into doctree whenever a JupyterKernel directive is encountered. Used as a marker to signal that the following JupyterCellNodes (until the next, if any, JupyterKernelNode) should be executed in a separate kernel. """ class JupyterWidgetViewNode(docutils.nodes.Element): """Inserted into doctree whenever a Jupyter cell produces a widget as output. Contains a unique ID for this widget; enough information for the widget embedding javascript to render it, given the widget state. For non-HTML outputs this doctree node is rendered generically. """ def __init__(self, rawsource="", *children, **attributes): super().__init__("", view_spec=attributes["view_spec"]) def html(self): return ipywidgets.embed.widget_view_template.format( view_spec=json.dumps(self["view_spec"]) ) class JupyterWidgetStateNode(docutils.nodes.Element): """Appended to doctree if any Jupyter cell produced a widget as output. Contains the state needed to render a collection of Jupyter widgets. Per doctree there is 1 JupyterWidgetStateNode per kernel that produced Jupyter widgets when running. This is fine as (presently) the 'html-manager' Javascript library, which embeds widgets, loads the state from all script tags on the page of the correct mimetype. """ def __init__(self, rawsource="", *children, **attributes): super().__init__("", state=attributes["state"]) def html(self): # TODO: render into a separate file if 'html-manager' starts fully # parsing script tags, and not just grabbing their innerHTML # https://github.com/jupyter-widgets/ipywidgets/blob/master/packages/html-manager/src/libembed.ts#L36 return ipywidgets.embed.snippet_template.format( load="", widget_views="", json_data=json.dumps(self["state"]) ) def cell_output_to_nodes(outputs, data_priority, write_stderr, out_dir, thebe_config, inline=False): """Convert a jupyter cell with outputs and filenames to doctree nodes. Parameters ---------- outputs : a list of outputs from a Jupyter cell data_priority : list of mime types Which media types to prioritize. write_stderr : bool If True include stderr in cell output out_dir : string Sphinx "absolute path" to the output folder, so it is a relative path to the source folder prefixed with ``/``. thebe_config: dict Thebelab configuration object or None inline: False Whether the nodes will be placed in-line with the text. Returns ------- to_add : list of docutils nodes Each output, converted into a docutils node. """ # If we're in `inline` mode, ensure that we don't add block-level nodes if inline: literal_node = docutils.nodes.literal math_node = docutils.nodes.math else:
if (walker_plot_args.get("fig") is not None) and ( walker_plot_args.get("axes") is not None ): self.walker_fig = walkers_fig self.walker_axes = walkers_axes else: try: walkers_fig.savefig( os.path.join(self.outdir, self.label + "_walkers.png") ) plt.close(walkers_fig) except Exception as e: logging.warning( "Failed to save walker plots due to Error {}".format(e) ) def _get_rescale_multiplier_for_key(self, key): """Get the rescale multiplier from the transform_dictionary Can either be a float, a string (in which case it is interpretted as a attribute of the MCMCSearch class, e.g. minStartTime, or non-existent in which case 0 is returned """ if key not in self.transform_dictionary: return 1 if "multiplier" in self.transform_dictionary[key]: val = self.transform_dictionary[key]["multiplier"] if type(val) == str: if hasattr(self, val): multiplier = getattr( self, self.transform_dictionary[key]["multiplier"] ) else: raise ValueError("multiplier {} not a class attribute".format(val)) else: multiplier = val else: multiplier = 1 return multiplier def _get_rescale_subtractor_for_key(self, key): """Get the rescale subtractor from the transform_dictionary Can either be a float, a string (in which case it is interpretted as a attribute of the MCMCSearch class, e.g. minStartTime, or non-existent in which case 0 is returned """ if key not in self.transform_dictionary: return 0 if "subtractor" in self.transform_dictionary[key]: val = self.transform_dictionary[key]["subtractor"] if type(val) == str: if hasattr(self, val): subtractor = getattr( self, self.transform_dictionary[key]["subtractor"] ) else: raise ValueError("subtractor {} not a class attribute".format(val)) else: subtractor = val else: subtractor = 0 return subtractor def _scale_samples(self, samples, theta_keys): """Scale the samples using the transform_dictionary""" for key in theta_keys: if key in self.transform_dictionary: idx = theta_keys.index(key) s = samples[:, idx] subtractor = self._get_rescale_subtractor_for_key(key) s = s - subtractor multiplier = self._get_rescale_multiplier_for_key(key) s *= multiplier samples[:, idx] = s return samples def _get_labels(self, newline_units=False): """Combine the units, symbols and rescaling to give labels""" labels = [] for key in self.theta_keys: values = self.transform_dictionary.get(key, {}) s, label, u = [ values.get(slu_key, None) for slu_key in ["symbol", "label", "unit"] ] if label is None: s = s or self.symbol_dictionary[key].replace( "_{glitch}", r"_\mathrm{glitch}" ) u = u or self.unit_dictionary[key] label = ( f"{s}" + ("\n" if newline_units else " ") + (f"[{u}]" if u != "" else "") ) labels.append(label) return labels def plot_corner( self, figsize=(10, 10), add_prior=False, nstds=None, label_offset=0.4, dpi=300, rc_context={}, tglitch_ratio=False, fig_and_axes=None, save_fig=True, **kwargs, ): """Generate a corner plot of the posterior Using the `corner` package (https://pypi.python.org/pypi/corner/), generate estimates of the posterior from the production samples. Parameters ---------- figsize: tuple (7, 7) Figure size in inches (passed to plt.subplots) add_prior: bool, str If true, plot the prior as a red line. If 'full' then for uniform priors plot the full extent of the prior. nstds: float The number of standard deviations to plot centered on the median. Standard deviation is computed from the samples using `numpy.std`. label_offset: float Offset the labels from the plot: useful to prevent overlapping the tick labels with the axis labels. This option is passed to `ax.[x|y]axis.set_label_coords`. dpi: int Passed to plt.savefig. rc_context: dict Dictionary of rc values to set while generating the figure (see matplotlib rc for more details). tglitch_ratio: bool If true, and tglitch is a parameter, plot posteriors as the fractional time at which the glitch occurs instead of the actual time. fig_and_axes: tuple (fig, axes) tuple to plot on. The axes must be of the right shape, namely (ndim, ndim) save_fig: bool If true, save the figure, else return the fig, axes. **kwargs: Passed to corner.corner. Use "truths" to plot the true parameters of a signal. Returns ------- fig, axes: The matplotlib figure and axes, only returned if save_fig = False. """ if "truths" in kwargs: if not isinstance(kwargs["truths"], dict): raise ValueError("'truths' must be a dictionary.") missing_keys = set(self.theta_keys) - kwargs["truths"].keys() if missing_keys: logging.warning( f"plot_corner(): Missing keys {missing_keys} in 'truths' dictionary," " argument will be ignored." ) kwargs["truths"] = None else: kwargs["truths"] = [kwargs["truths"][key] for key in self.theta_keys] kwargs["truths"] = self._scale_samples( np.reshape(kwargs["truths"], (1, -1)), self.theta_keys ).ravel() if "truth_color" not in kwargs: kwargs["truth_color"] = "black" if self.ndim < 2: with plt.rc_context(rc_context): if fig_and_axes is None: fig, ax = plt.subplots(figsize=figsize) else: fig, ax = fig_and_axes ax.hist(self.samples, bins=50, histtype="stepfilled") ax.set_xlabel(self.theta_symbols[0]) fig.savefig(os.path.join(self.outdir, self.label + "_corner.png"), dpi=dpi) plt.close(fig) return with plt.rc_context(rc_context): if fig_and_axes is None: fig, axes = plt.subplots(self.ndim, self.ndim, figsize=figsize) else: fig, axes = fig_and_axes samples_plt = copy.copy(self.samples) labels = self._get_labels(newline_units=False) samples_plt = self._scale_samples(samples_plt, self.theta_keys) if tglitch_ratio: for j, k in enumerate(self.theta_keys): if k == "tglitch": s = samples_plt[:, j] samples_plt[:, j] = (s - self.minStartTime) / ( self.maxStartTime - self.minStartTime ) labels[j] = r"$R_{\mathrm{glitch}}$" if type(nstds) is int and "range" not in kwargs: _range = [] for j, s in enumerate(samples_plt.T): median = np.median(s) std = np.std(s) _range.append((median - nstds * std, median + nstds * std)) elif "range" in kwargs: _range = kwargs.pop("range") else: _range = None hist_kwargs = kwargs.pop("hist_kwargs", dict()) if "density" not in hist_kwargs: hist_kwargs["density"] = True fig_triangle = corner.corner( samples_plt, labels=labels, fig=fig, bins=50, max_n_ticks=4, plot_contours=True, plot_datapoints=True, label_kwargs={"fontsize": 12}, data_kwargs={"alpha": 0.1, "ms": 0.5}, range=_range, hist_kwargs=hist_kwargs, show_titles=True, fill_contours=True, quantiles=[0.05, 0.95] if "quantiles" not in kwargs else kwargs.pop("quantiles"), verbose=True if "verbose" not in kwargs else kwargs.pop("verbose"), **kwargs, ) axes_list = fig_triangle.get_axes() axes = np.array(axes_list).reshape(self.ndim, self.ndim) plt.draw() for ax in axes[:, 0]: ax.yaxis.set_label_coords(-label_offset, 0.5) for ax in axes[-1, :]: ax.xaxis.set_label_coords(0.5, -label_offset) for ax in axes_list: ax.set_rasterized(True) ax.set_rasterization_zorder(-10) for tick in ax.xaxis.get_major_ticks(): # tick.label1.set_fontsize(8) tick.label1.set_rotation(30) for tick in ax.yaxis.get_major_ticks(): # tick.label1.set_fontsize(8) tick.label1.set_rotation(30) plt.tight_layout() fig.subplots_adjust(hspace=0.1, wspace=0.1) if add_prior: self._add_prior_to_corner(axes, self.samples, add_prior) if save_fig: fig_triangle.savefig( os.path.join(self.outdir, self.label + "_corner.png"), dpi=dpi ) plt.close(fig_triangle) else: return fig, axes def plot_chainconsumer(self, save_fig=True, label_offset=0.25, dpi=300, **kwargs): """Generate a corner plot of the posterior using the `chaniconsumer` package. `chainconsumer` is an optional dependency of PyFstat. See https://samreay.github.io/ChainConsumer/. Parameters are akin to the ones described in MCMCSearch.plot_corner. Only the differing parameters are explicitly described. Parameters ---------- **kwargs: Passed to chainconsumer.plotter.plot. Use "truths" to plot the true parameters of a signal. """ try: import chainconsumer except ImportError: logging.warning( "Could not import 'chainconsumer' package, please install it to use this method." ) return samples_plt = copy.copy(self.samples) labels = self._get_labels(newline_units=True) samples_plt = self._scale_samples(samples_plt, self.theta_keys) if "truth" in kwargs: if not isinstance(kwargs["truth"], dict): raise ValueError("'truth' must be a dictionary.") missing_keys = np.setdiff1d(self.theta_keys, list(kwargs["truth"].keys())) if len(missing_keys) > 0: logging.warning( "plot_chainconsumer(): Missing keys {} in 'truth' dictionary," " argument will be ignored.".format(missing_keys) ) kwargs["truth"] = None else: parameters_in_order = np.array( [kwargs["truth"][key] for key in self.theta_keys] ).reshape((1, -1)) kwargs["truth"] = self._scale_samples( parameters_in_order, self.theta_keys ).ravel() c = chainconsumer.ChainConsumer() c.add_chain(samples_plt, parameters=labels) # We set usetex=False to avoid dependency on 'kpsewhich' TeX tool c.configure(smooth=0, summary=False, sigma2d=True, usetex=False) fig = c.plotter.plot(**kwargs) axes_list = fig.get_axes() axes = np.array(axes_list).reshape(self.ndim, self.ndim) plt.draw() for ax in axes[:, 0]: ax.yaxis.set_label_coords(-label_offset, 0.5) for ax in axes[-1, :]: ax.xaxis.set_label_coords(0.5, -label_offset) for ax in axes_list: ax.set_rasterized(True) ax.set_rasterization_zorder(-10) plt.tight_layout(h_pad=0.0, w_pad=0.0) fig.subplots_adjust(hspace=0.05, wspace=0.05) if save_fig: fig.savefig( os.path.join(self.outdir, self.label + "_chainconsumer_corner.png"), dpi=dpi, ) plt.close(fig) else: return fig, axes def _add_prior_to_corner(self, axes, samples, add_prior): for i, key in enumerate(self.theta_keys): ax = axes[i][i] s = samples[:, i] lnprior = self._generic_lnprior(**self.theta_prior[key]) if add_prior == "full" and self.theta_prior[key]["type"] == "unif": lower = self.theta_prior[key]["lower"] upper = self.theta_prior[key]["upper"] r = upper - lower xlim = [lower - 0.05 * r, upper + 0.05 * r] x = np.linspace(xlim[0], xlim[1], 1000) else: xlim = ax.get_xlim() x = np.linspace(s.min(), s.max(), 1000) multiplier = self._get_rescale_multiplier_for_key(key) subtractor = self._get_rescale_subtractor_for_key(key) ax.plot( (x - subtractor) * multiplier, [np.exp(lnprior(xi)) for xi in x], "-C3", label="prior", ) for j in range(i, self.ndim): axes[j][i].set_xlim(xlim[0], xlim[1]) for k in range(0, i): axes[i][k].set_ylim(xlim[0], xlim[1]) def _get_prior_bounds(self, normal_stds=2): """Get the lower/upper bounds of all priors Parameters ---------- normal_stds: float Number of standard deviations to cut normal (Gaussian) or half-norm distributions at. Returns ------- prior_bounds: dict Dictionary of ["lower","upper"] pairs for each parameter norm_warning: bool A flag that is true if any parameter has a norm or half-norm prior. Caller functions may wish to warn the user that the prior has been truncated at normal_stds. """ prior_bounds = {} norm_trunc_warning = False for key in self.theta_keys: prior_bounds[key] = {} prior_dict = self.theta_prior[key] norm_trunc_warning = "norm" in prior_dict["type"] or norm_trunc_warning
<gh_stars>0 ## Shallow Ensemble of Temporal Hypersphere Reservoirs ## - pre-trains a single reservoir for later inclusion in an ensemble import numpy as np import cupy as cp import chargrams as cg import re import pickle import time from random import shuffle from gensim.models.keyedvectors import KeyedVectors import pydybm.arraymath as amath import pydybm.arraymath.dycupy as dycupy from pydybm.base.sgd32 import ADAM # todo: grab bigram indexes directly from text file instead of loading w2vec library wv = KeyedVectors.load_word2vec_format('/home/user01/dev/wang2vec/embeddings-i3e4-ssg-neg15-s1024w6.txt', binary=False) temp = wv.index2word glist = np.array(temp[1:len(temp)]) glist = [re.sub(r'_', ' ', j) for j in glist] gramindex = {gram:idx for idx, gram in enumerate(glist)} def init(M, N, inweights): v = cp.identity(M, dtype=np.float32) for key in inweights: for m in range(M): inweights[key][:, m] = inweights[key][:, m] - inweights[key][:, m].mean() inweights[key][:, m] = inweights[key][:, m] / cp.linalg.norm(inweights[key][:, m]) return inweights, v def train_kcpa(inweights, v, variables, leak, bs, step, s, cpstates): T = len(s) N = 1024 M = 1024 x1 = cp.zeros(N * layerscales["L1"], dtype=np.float32) # gradient = dict() # softerr1 = 0 # err1 = 0 skipfirst = 1 t = step tm1 = (T - 1 - t - skipfirst) for k in range(skipfirst): current = s[t - step] x1 = (1.0 - leak) * x1 + leak * (inweights["U1"][:, current] + cp.roll(x1, 1)) x1 = x1 / cp.linalg.norm(x1) # wx = cp.dot(variables["W1"], x1) # wx = wx - cp.max(wx) # p = cp.exp(wx) # p1 = p / cp.sum(p) t += 1 for b1 in range(tm1): current = s[t - step] x1 = (1.0 - leak) * x1 + leak * (inweights["U1"][:, current] + cp.roll(x1, 1)) x1 = x1 / cp.linalg.norm(x1) # wx = cp.dot(variables["W1"], x1) # wx = wx - cp.max(wx) # p = cp.exp(wx) # p1 = p / cp.sum(p) cpstates = cp.concatenate((cpstates, x1.reshape((1, N * layerscales["L1"])))) # target = s[t+1] # gradient["W1"] = cp.outer(v[:, target] - p1, x1) # SGD.update_state(gradient) # delta = SGD.get_delta() # SGD.update_with_L1_regularization(variables, delta, L1) t += 1 return variables, cpstates def train(inweights, v, variables, leak, bs, steps, testflag, s, count): T = len(s) N = 1024 M = 1024 x1 = cp.zeros(int(N * layerscales["L1"]), dtype=np.float32) x2 = cp.zeros(int(N * layerscales["L1"]), dtype=np.float32) x3 = cp.zeros(int(N * layerscales["L1"]), dtype=np.float32) gradient = dict() softerr1 = 0 softerr2 = 0 softerr3 = 0 softerrm = 0 err1 = 0 err2 = 0 err3 = 0 errm = 0 skipfirst = 1 t = steps["S2"] tm1 = (T - 1 - t - skipfirst) for k in range(skipfirst): step1 = s[t - steps["S1"]] step2 = s[t - steps["S2"]] x1 = (1.0 - leaks[0]) * x1 + leaks[0] * (inweights["U1"][:, step1] + cp.roll(x1, 1)) x1 = x1 / cp.linalg.norm(x1) x2 = (1.0 - leaks[1]) * x2 + leaks[1] * (inweights["U2"][:, step2] + cp.roll(x2, 1)) x2 = x2 / cp.linalg.norm(x2) t += 1 for b1 in range(tm1): step1 = s[t - steps["S1"]] step2 = s[t - steps["S2"]] x1 = (1.0 - leaks[0]) * x1 + leaks[0] * (inweights["U1"][:, step1] + cp.roll(x1, 1)) x1 = x1 / cp.linalg.norm(x1) wx = cp.dot(variables["W1"], x1) wx = wx - cp.max(wx) p = cp.exp(wx) p1 = p / cp.sum(p) # pred1 = cp.argmax(p1) x2 = (1.0 - leaks[1]) * x2 + leaks[1] * (inweights["U2"][:, step2] + cp.roll(x2, 1)) x2 = x2 / cp.linalg.norm(x2) wx = cp.dot(variables["W2"], x2) wx = wx - cp.max(wx) p = cp.exp(wx) p2 = p / cp.sum(p) # pred2 = cp.argmax(p2) pstack = cp.hstack((p1, p2)) wx = cp.dot(variables["Wm"], pstack) wx = wx - cp.max(wx) p = cp.exp(wx) pm = p / cp.sum(p) meanpred = cp.argmax(pm) target = s[t+1] target_prob1 = p1[target] softerr1 += 1 - target_prob1 # err1 = err1 + (pred1 != target) target_prob2 = p2[target] softerr2 += 1 - target_prob2 # err2 = err2 + (pred2 != target) target_probm = pm[target] errm = errm + (meanpred != target) softerrm += 1 - target_probm if testflag == 0: gradient["W1"] = cp.outer(v[:, target] - p1, x1) # gradient["W2"] = cp.outer(v[:, target] - p2, x2) gradient["Wm"] = cp.outer(v[:, target] - pm, pstack) SGD.update_state(gradient) delta = SGD.get_delta() SGD.update_with_L1_regularization(variables, delta, L1) t += 1 softerrors = dict() prederrors = dict() softerrors["lay1"] = softerr1 / (tm1) softerrors["lay2"] = softerr2 / (tm1) softerrors["laym"] = softerrm / (tm1) # prederrors["lay1"] = err1 * 100.0 / (tm1) # prederrors["lay2"] = err2 * 100.0 / (tm1) prederrors["laym"] = errm * 100.0 / (tm1) return prederrors, softerrors, variables amath.setup(dycupy) chunkfile = '/home/user01/dev/language-model/chunks256.p' train1280 = '/home/user01/dev/language-model/train1280.p' test128 = '/home/user01/dev/language-model/test128.p' chunklist = pickle.load(open(chunkfile, "rb")) layerscales = dict() variables = dict() inweights = dict() L2 = dict() L1 = dict() steps = dict() trainchunks = [] testchunks = [] cp.random.seed(481639) n=2 stride = 1 # leaks = [0.382, 0.5, 0.618] leaks = [0.382, 0.5] # leak = 0.382 N = 1024 M = 1024 layerscales["L1"] = 8 # layerscales["L2"] = 3 # layerscales["L3"] = 2 ## use 1-2-4-7-12-20-33-54-88, the fibonacci numbers look better as ## ## distances between points, rather than as the points themselves ## savedweights = 1 steps["S1"] = 0 steps["S2"] = 2 batchsize = 1 trainsize = 256 testsize = 32 interval = 128 lrate = 0.0001 learningrates = [0.09, 0.03, 0.009, 0.003, 0.0009, 0.0003, 0.0001] SGD = ADAM(alpha=lrate) # SGD = ADAM(alpha=learningrates[0]) variables["W1"] = cp.zeros((M, int(N * layerscales["L1"])), dtype=np.float32) variables["W2"] = cp.zeros((M, int(N * layerscales["L1"])), dtype=np.float32) variables["Wm"] = cp.zeros((M, M*2), dtype=np.float32) inweights["U1"] = cp.random.rand(int(N * layerscales["L1"]), M, dtype=np.float32) inweights["U2"] = cp.random.rand(int(N * layerscales["L1"]), M, dtype=np.float32) allweights = dict() SGD = SGD.set_shape(variables) for key in variables: L1[key] = 0 L2[key] = 0 inweights, v = init(M, N, inweights) layersize1 = str(inweights["U1"].shape[0]) layersize2 = str(inweights["U2"].shape[0]) print("L1: {} L2: {}".format(layersize1, layersize2)) print("steps: {} {}".format(steps["S1"], steps["S2"])) ### load pre integer tokenized dataset of ~1 million characters in size # trainfile = '/home/user01/dev/language-model/train1m.p' # testfile = '/home/user01/dev/language-model/test1m.p' # trainlist = pickle.load(open(trainfile, "rb")) # testlist = pickle.load(open(testfile, "rb")) # # for chunk in trainlist: # intchunk = cp.array(chunk, dtype=np.int16) # trainchunks.append(intchunk) # # for chunk in testlist: # intchunk = cp.array(chunk, dtype=np.int16) # testchunks.append(intchunk) for j in range(trainsize): chunk = chunklist[j] sgi = [] for idx in range(0, len(chunk) - (n - 1), stride): try: sgi.append(gramindex[chunk[idx:idx + n]]) except: print(chunk[idx:idx + n]) intchunk = cp.asarray(sgi, dtype=np.int16) trainchunks.append(intchunk) for k in range(trainsize, trainsize + testsize): chunk = chunklist[k] sgi = [] for idx in range(0, len(chunk) - (n - 1), stride): try: sgi.append(gramindex[chunk[idx:idx + n]]) except: print(chunk[idx:idx + n]) intchunk = cp.asarray(sgi, dtype=np.int16) testchunks.append(intchunk) trainsize = len(trainchunks) testsize = len(testchunks) print("train size:", trainsize, "test size:", testsize) print("Learning rate:", lrate) print(leaks[0], leaks[1]) ### get kernel PCA states # cpstates = cp.empty((0, N * layerscales["L1"]), dtype=np.float32) # npstates = np.empty((0, N * layerscales["L1"]), dtype=np.float32) # totalerr1 = 0 # totalstates = 0 # testflag = 0 # count = 0 # totalstart = time.perf_counter() # # for chunk in trainchunks: # count += 1 # startp = time.perf_counter() # variables, cpstates = train_kcpa(inweights, v, variables, leak, batchsize, step, chunk, cpstates) # npstates = np.concatenate((npstates, cp.asnumpy(cpstates))) # cpstates = cp.empty((0, N * layerscales["L1"]), dtype=np.float32) # totalstates += len(chunk) - 2 # if count % interval == 0: # elapsedp = time.perf_counter() - startp # totalelapsed = time.perf_counter() - totalstart # tm, ts = divmod(totalelapsed, 60) # print("\n", count, elapsedp, "-- {0:.0f}m {1:.0f}s".format(tm, ts)) # print("total states:", totalstates, "npstates:", npstates.shape) # # statefile = '/home/user01/dev/language-model/states' + layersize + "-" + str(step) + ".p" # pickle.dump(npstates, open(statefile, "wb")) # print("total states:", totalstates, "npstates:", npstates.shape) # elapsedp = time.perf_counter() - startp # totalelapsed = time.perf_counter() - totalstart # tm, ts = divmod(totalelapsed, 60) # print("\n", count, elapsedp, "-- {0:.0f}m {1:.0f}s".format(tm, ts)) # shuffle(trainchunks) # print(inweights["U1"], variables["W1"] ) # outweights = '/home/user01/dev/language-model/outweights' + layersize + "-" + str(step) + ".p" # inweights = '/home/user01/dev/language-model/inweights' + layersize + "-" + str(step) + ".p" # saved_outweights = pickle.load(open(outweights, "rb")) # saved_inweights = pickle.load(open(inweights, "rb")) # print(saved_inweights["U1"].shape, type(saved_inweights["U1"])) # print(saved_outweights["W1"].shape, type(saved_outweights["W1"])) # inweights["U1"] = saved_inweights["U1"] # variables["W1"] = saved_outweights["W1"] # print(inweights["U1"], variables["W1"] ) ###################################################################### lay1infile = '/home/user01/dev/language-model/inweights8192-0-382' + ".p" lay2infile = '/home/user01/dev/language-model/inweights8192-2-500' + ".p" lay1outfile = '/home/user01/dev/language-model/outweights8192-0-382' + ".p" lay2outfile = '/home/user01/dev/language-model/outweights8192-2-500' + ".p" # print("U1: {}\nW1: {}\nU2: {}\nW2: {}".format(lay1infile, lay2infile, lay1outfile, lay2outfile)) # lay1_inweights = pickle.load(open(lay1infile, "rb")) # lay1_outweights = pickle.load(open(lay1outfile, "rb")) # lay2_inweights = pickle.load(open(lay2infile, "rb")) # lay2_outweights = pickle.load(open(lay2outfile, "rb")) # inweights["U1"] = lay1_inweights["U1"] # inweights["U2"] = lay2_inweights["U1"] # variables["W1"] = lay1_outweights["W1"] # variables["W2"] = lay2_outweights["W1"] # variables["Wm"] = saved_outweights["Wm"] # print(lay1_inweights["U1"].shape, lay2_outweights["W1"].shape) # lrs = str(lrate) # lrs = "-" + lrs[2:] stepstr = str(steps["S1"]) + str(steps["S2"]) weightfile = '/home/user01/dev/language-model/weights2.' + layersize1 + '.0-2.382-500.p' if savedweights == 1: weightfile = '/home/user01/dev/language-model/weights2.' + layersize1 + '.0-2.382-500.p' print("W: {}".format(weightfile)) saved_weights = pickle.load(open(weightfile, "rb")) inweights["U1"] = saved_weights["U1"] inweights["U2"] = saved_weights["U2"] variables["W1"] = saved_weights["W1"] variables["W2"] = saved_weights["W2"] variables["Wm"] = saved_weights["Wm"] print(saved_weights["U1"].shape, saved_weights["W2"].shape) # shuffle(trainchunks) # shuffle(testchunks) totalstart = time.perf_counter() testflag = 0 count = 0 # for lr in range(7):
<filename>autolens/pipeline/phase.py import logging import os import warnings import numpy as np from astropy import cosmology as cosmo from autofit import conf from autofit.tools import phase from autofit.tools.phase_property import PhasePropertyCollection from autofit.optimize import non_linear from autolens import exc from autolens.data.array import mask as msk from autolens.data.plotters import ccd_plotters from autolens.lens import lens_data as li, lens_fit from autolens.lens import ray_tracing from autolens.lens import sensitivity_fit from autolens.lens.plotters import sensitivity_fit_plotters, ray_tracing_plotters, lens_fit_plotters from autolens.model.galaxy import galaxy as g, galaxy_model as gm, galaxy_fit, galaxy_data as gd from autolens.model.galaxy.plotters import galaxy_fit_plotters logger = logging.getLogger(__name__) logger.level = logging.DEBUG def default_mask_function(image): return msk.Mask.circular(shape=image.shape, pixel_scale=image.pixel_scale, radius_arcsec=3.0) def setup_phase_mask(data, mask, mask_function, inner_circular_mask_radii): if mask_function is not None: mask = mask_function(image=data.image) elif mask is None and mask_function is None: mask = default_mask_function(image=data.image) if inner_circular_mask_radii is not None: inner_mask = msk.Mask.circular(shape=mask.shape, pixel_scale=mask.pixel_scale, radius_arcsec=inner_circular_mask_radii, invert=True) mask = mask + inner_mask return mask class ResultsCollection(list): def __init__(self, results): super().__init__(results) @property def last(self): if len(self) > 0: return self[-1] return None @property def first(self): if len(self) > 0: return self[0] return None class AbstractPhase(phase.AbstractPhase): def __init__(self, phase_name, optimizer_class=non_linear.MultiNest, cosmology=cosmo.Planck15, auto_link_priors=False): """ A phase in an lens pipeline. Uses the set non_linear optimizer to try to fit models and hyper passed to it. Parameters ---------- optimizer_class: class The class of a non_linear optimizer phase_name: str The name of this phase """ self.optimizer = optimizer_class(name=phase_name) self.cosmology = cosmology self.phase_name = phase_name self.auto_link_priors = auto_link_priors @property def constant(self): """ Convenience method Returns ------- ModelInstance A model instance comprising all the constant objects in this lens """ return self.optimizer.constant @property def variable(self): """ Convenience method Returns ------- ModelMapper A model mapper comprising all the variable (prior) objects in this lens """ return self.optimizer.variable @property def galaxy_model_tuples(self): """ Returns ------- galaxy_model_tuples: [(String, GalaxyModel)] A list of tuples containing galaxy model names and instances. """ return [tup for tup in self.optimizer.variable.prior_model_tuples if isinstance(tup.prior_model, gm.GalaxyModel)] def match_instance_to_models(self, instance): """ Matches named galaxies associated with the instance to named galaxies associated with this phase. Parameters ---------- instance: ModelInstance An instance with named galaxy attributes. Returns ------- tuples: [(String, Galaxy, GalaxyModel)] A list of tuples associating galaxy instances from the model instance object with galaxy models in this phase. """ galaxy_dict = dict(instance.name_instance_tuples_for_class(g.Galaxy)) return [(key, galaxy_dict[key], value) for key, value in self.galaxy_model_tuples if key in galaxy_dict] def fit_priors(self, instance, fitting_function): """ Update the priors in this phase by fitting each galaxy model to a galaxy with the same name from a previous phase if such a galaxy exists. Parameters ---------- instance: ModelInstance An object with named galaxy attributes fitting_function: (Galaxy, GalaxyModel) -> GalaxyModel A function that takes a galaxy and a galaxy model and returns a GalaxyModel produced by combining a best fit between the original galaxy and galaxy model with prior widths given by the configuration. """ tuples = self.match_instance_to_models(instance) for t in tuples: name = t[0] galaxy = t[1] galaxy_model = t[2] new_galaxy_model = fitting_function(galaxy, galaxy_model) for phase_property_collection in self.phase_property_collections: if hasattr(phase_property_collection, name): setattr(phase_property_collection, name, new_galaxy_model) def fit_priors_with_results(self, results, fitting_function): """ Update the priors in this phase by fitting each galaxy model to a galaxy with the same name from a previous phase if such a galaxy exists. Results later in the list take precedence, with the last instance of any galaxies that share a name being kept. Parameters ---------- results: [Results] A list of results from previous phases. fitting_function: (Galaxy, GalaxyModel) -> GalaxyModel A function that takes a galaxy and a galaxy model and returns a GalaxyModel produced by combining a best fit between the original galaxy and galaxy model with prior widths given by the configuration. """ if results is not None and len(results) > 0: instances = [r.constant for r in results] instance = instances[0] for next_instance in instances[1:]: instance += next_instance self.fit_priors(instance, fitting_function) @property def phase_property_collections(self): """ Returns ------- phase_property_collections: [PhasePropertyCollection] A list of phase property collections associated with this phase. This is used in automated prior passing and should be overridden for any phase that contains its own PhasePropertyCollections. """ return [] @property def path(self): return self.optimizer.path @property def doc(self): if self.__doc__ is not None: return self.__doc__.replace(" ", "").replace("\n", " ") def pass_priors(self, previous_results): """ Perform any prior or constant passing. This could involve setting model attributes equal to priors or constants from a previous phase. Parameters ---------- previous_results: ResultsCollection The result of the previous phase """ pass # noinspection PyAbstractClass class Analysis(non_linear.Analysis): def __init__(self, cosmology, phase_name, previous_results=None): """ An lens object Parameters ---------- phase_name: str The name of the phase to which this analysis belongs previous_results: ResultsCollection The results of all previous phases """ self.previous_results = previous_results self.cosmology = cosmology self.phase_name = phase_name self.phase_output_path = "{}/{}".format(conf.instance.output_path, self.phase_name) log_file = conf.instance.general.get('output', 'log_file', str) if not len(log_file.replace(" ", "")) == 0: log_path = "{}/{}".format(self.phase_output_path, log_file) logger.handlers = [logging.FileHandler(log_path)] logger.propagate = False self.position_threshold = conf.instance.general.get('positions', 'position_threshold', float) self.plot_count = 0 self.output_image_path = "{}/image/".format(self.phase_output_path) make_path_if_does_not_exist(path=self.output_image_path) self.output_fits_path = "{}/image/fits/".format(self.phase_output_path) make_path_if_does_not_exist(path=self.output_fits_path) @property def last_results(self): if self.previous_results is not None: return self.previous_results.last def tracer_for_instance(self, instance): raise NotImplementedError() def padded_tracer_for_instance(self, instance): raise NotImplementedError() def fit_for_tracers(self, tracer, padded_tracer): raise NotImplementedError() def figure_of_merit_for_fit(self, tracer): raise NotImplementedError() def make_result(self, result, analysis): return self.__class__.Result(constant=result.constant, figure_of_merit=result.figure_of_merit, variable=result.variable, analysis=analysis, optimizer=self.optimizer) class Result(non_linear.Result): def __init__(self, constant, figure_of_merit, variable, analysis, optimizer): """ The result of a phase """ super(Phase.Result, self).__init__(constant=constant, figure_of_merit=figure_of_merit, variable=variable) self.analysis = analysis self.optimizer = optimizer @property def most_likely_tracer(self): return self.analysis.tracer_for_instance(instance=self.constant) @property def most_likely_padded_tracer(self): return self.analysis.padded_tracer_for_instance(instance=self.constant) @property def most_likely_fit(self): return self.analysis.fit_for_tracers(tracer=self.most_likely_tracer, padded_tracer=self.most_likely_padded_tracer) @property def unmasked_model_image(self): return self.most_likely_fit.unmasked_model_image @property def unmasked_model_image_of_planes(self): return self.most_likely_fit.unmasked_model_image_of_planes @property def unmasked_model_image_of_planes_and_galaxies(self): return self.most_likely_fit.unmasked_model_image_of_planes_and_galaxies class Phase(AbstractPhase): def run(self, image, previous_results=None, mask=None): raise NotImplementedError() # noinspection PyAbstractClass class Analysis(AbstractPhase.Analysis): def __init__(self, cosmology, phase_name, previous_results=None): super(Phase.Analysis, self).__init__(cosmology=cosmology, phase_name=phase_name, previous_results=previous_results) self.should_plot_mask = \ conf.instance.general.get('output', 'plot_mask_on_images', bool) self.extract_array_from_mask = \ conf.instance.general.get('output', 'extract_images_from_mask', bool) self.zoom_around_mask = \ conf.instance.general.get('output', 'zoom_around_mask_of_images', bool) self.should_plot_positions = \ conf.instance.general.get('output', 'plot_positions_on_images', bool) self.plot_units = \ conf.instance.general.get('output', 'plot_units', str).strip() self.plot_ray_tracing_all_at_end_png = \ conf.instance.general.get('output', 'plot_ray_tracing_all_at_end_png', bool) self.plot_ray_tracing_all_at_end_fits = \ conf.instance.general.get('output', 'plot_ray_tracing_all_at_end_fits', bool) self.plot_ray_tracing_as_subplot = \ conf.instance.general.get('output', 'plot_ray_tracing_as_subplot', bool) self.plot_ray_tracing_image_plane_image = \ conf.instance.general.get('output', 'plot_ray_tracing_image_plane_image', bool) self.plot_ray_tracing_source_plane = \ conf.instance.general.get('output', 'plot_ray_tracing_source_plane_image', bool) self.plot_ray_tracing_surface_density = \ conf.instance.general.get('output', 'plot_ray_tracing_surface_density', bool) self.plot_ray_tracing_potential = \ conf.instance.general.get('output', 'plot_ray_tracing_potential', bool) self.plot_ray_tracing_deflections = \ conf.instance.general.get('output', 'plot_ray_tracing_deflections', bool) class PhasePositions(AbstractPhase): lens_galaxies = PhasePropertyCollection("lens_galaxies") @property def phase_property_collections(self): return [self.lens_galaxies] def __init__(self, phase_name, lens_galaxies=None, optimizer_class=non_linear.MultiNest, cosmology=cosmo.Planck15, auto_link_priors=False): super().__init__(optimizer_class=optimizer_class, cosmology=cosmology, phase_name=phase_name, auto_link_priors=auto_link_priors) self.lens_galaxies = lens_galaxies def run(self, positions, pixel_scale, previous_results=None): """ Run this phase. Parameters ---------- pixel_scale positions previous_results: ResultsCollection An object describing the results of the last phase or None if no phase has been executed Returns ------- result: AbstractPhase.Result A result object comprising the best fit model and other hyper. """ analysis = self.make_analysis(positions=positions, pixel_scale=pixel_scale, previous_results=previous_results) result = self.run_analysis(analysis) return self.make_result(result, analysis) def make_analysis(self, positions, pixel_scale, previous_results=None): """ Create an lens object. Also calls the prior passing and lens_data modifying functions to allow child classes to change the behaviour of the phase. Parameters ---------- pixel_scale positions previous_results: ResultsCollection The result from the previous phase Returns ------- lens: Analysis An lens object that the non-linear optimizer calls to determine the fit of a set of values """ self.pass_priors(previous_results) analysis = self.__class__.Analysis(positions=positions, pixel_scale=pixel_scale, cosmology=self.cosmology, phase_name=self.phase_name, previous_results=previous_results) return analysis # noinspection PyAbstractClass class Analysis(Phase.Analysis): def __init__(self, positions, pixel_scale, cosmology, phase_name, previous_results=None): super().__init__(cosmology=cosmology, phase_name=phase_name, previous_results=previous_results) self.positions = list(map(lambda position_set: np.asarray(position_set), positions)) self.pixel_scale = pixel_scale def visualize(self, instance, suffix, during_analysis): pass def fit(self, instance): """ Determine the fit of a lens galaxy and source galaxy to the lens_data in this lens. Parameters ---------- instance A model instance with attributes Returns ------- fit: Fit A fractional value indicating how well this model fit and the model lens_data itself """ tracer = self.tracer_for_instance(instance) fit = self.fit_for_tracer(tracer) return fit.figure_of_merit def tracer_for_instance(self, instance): return ray_tracing.TracerImageSourcePlanesPositions(lens_galaxies=instance.lens_galaxies, image_plane_positions=self.positions, cosmology=self.cosmology) def fit_for_tracer(self, tracer): return lens_fit.LensPositionFit(positions=tracer.source_plane.positions, noise_map=self.pixel_scale) @classmethod def log(cls, instance): logger.debug( "\nRunning lens lens for... \n\nLens Galaxy::\n{}\n\n".format(instance.lens_galaxies)) class PhaseImaging(Phase): def __init__(self, phase_name, optimizer_class=non_linear.MultiNest, sub_grid_size=2, image_psf_shape=None, pixelization_psf_shape=None, use_positions=False, mask_function=None, inner_circular_mask_radii=None, cosmology=cosmo.Planck15, auto_link_priors=False): """ A phase in an lens pipeline. Uses the set non_linear optimizer to try to fit models and hyper passed to it. Parameters ---------- optimizer_class: class The class of
> w: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r)) image = cv2.resize(image, dim, interpolation=inter) return image # --------------- def __draw_rectangle_on_mouse_drag(event, x, y, flags, param): """ draws rectangle with mouse events """ global __coords__, __drawing__ if event == cv2.EVENT_LBUTTONDOWN: __coords__ = [(x, y)] __drawing__ = True elif event == 0 and __drawing__: __coords__[1:] = [(x, y)] im = image.copy() cv2.rectangle(im, __coords__[0], __coords__[1], (255, 0, 0), 2) cv2.imshow(window_name, im) elif event == cv2.EVENT_LBUTTONUP: # __coords__.append((x, y)) __coords__[1:] = [(x, y)] __drawing__ = False # PREVENT POSSIBLE OUT OF IMAGE RECTANGLES if(__coords__[0][0] and __coords__[1][0] > 0 and __coords__[0][0] and __coords__[1][0] < max_windows_size[0]): if(__coords__[0][1] and __coords__[1][1] > 0 and __coords__[0][1] and __coords__[1][1] < max_windows_size[1]): cv2.rectangle(image, __coords__[0], __coords__[1], (255, 0, 0), 2) # add points points.append(((label),__coords__[0],__coords__[1])) elif event == cv2.EVENT_RBUTTONDOWN: pass def __save_annotations_to_file(image_path, yolo_labels_lists, write_mode): """ saves yolo annnotations lists to annotations file list of lists:[[0,1,1,1,1],[1,0,0,0,0]] returns annotation_file_path """ # prepare the annotations yolo_labels = [] for yolo_labels_list in yolo_labels_lists: yolo_labels.append("{0} {1:.6} {2:.6} {3:.6} {4:.6}".format(yolo_labels_list[0], yolo_labels_list[1], yolo_labels_list[2], yolo_labels_list[3], yolo_labels_list[4])) image_name, image_extension = os.path.splitext(image_path) annotation_file_path = "{0}.txt".format(image_name) # if last character of the file is not \n we cant append directly we should add another line # since __write_to_file function writes lists to line inserting an empty string automatically creates a new line if(os.path.exists(annotation_file_path)): temp_file_content = __read_from_file(annotation_file_path) if(temp_file_content): if(temp_file_content[-1][-1] != "\n"): yolo_labels.insert(0,"") # write prepared annotations to file __write_to_file(yolo_labels, annotation_file_path, write_mode=write_mode) return annotation_file_path def __load_annotations_from_file(image_path): """ loads an images annotations with using that images path returns none if annotation is not exists """ # checking if the annotation file exists if exists read it image_name, image_extension = os.path.splitext(image_path) annotation_file_path = "{0}.txt".format(image_name) if os.path.exists(annotation_file_path): annotations = __read_from_file(annotation_file_path) annotations = annotations.split("\n") annotations = filter(None, annotations) # delete empty lists annotations = [annotation.split() for annotation in annotations] # convert annotations to float and label to int # yolo annotation structure: (0 0.8 0.8 0.5 0.5) for annotation in annotations: annotation[0] = int(annotation[0]) annotation[1] = float(annotation[1]) annotation[2] = float(annotation[2]) annotation[3] = float(annotation[3]) annotation[4] = float(annotation[4]) return annotations else: return None def __draw_bounding_boxes_to_image(image_path, class_names): """ draw annotations if file is exists """ # loading annotation file if exists annotations = __load_annotations_from_file(image_path) if(not annotations): return None, 0 # loading image image = cv2.imread(image_path) # get dimensions of image image_height = np.size(image, 0) image_width = np.size(image, 1) # convert points opencv_points = __convert_annotations_yolo_to_opencv(image_width, image_height, annotations) # draw the rectangles using converted points for opencv_point in opencv_points: # give error if an annoted file has impossible class value if(opencv_point[0] > len(class_names)-1): raise ValueError("this txt file has an annotation that has bigger class number than current selected class file") cv2.rectangle(image, (opencv_point[1], opencv_point[2]), (opencv_point[3], opencv_point[4]), (0,200,100), 2) cv2.line(image, (opencv_point[1], opencv_point[2]), (opencv_point[3], opencv_point[4]), (255, 0, 0), 1) if(show_labels): cv2.putText(image, "{0}".format(class_names[opencv_point[0]]), (opencv_point[1], opencv_point[2]), cv2.FONT_HERSHEY_SIMPLEX, 1.5, color=(0, 0, 0), thickness=2) return image, len(annotations) def __refresh_image(image_index, label): """ if annotation file exists draw the rectangles resize and return the image if not just return the resized image also draw information to the image """ image, annoted_object_count = __draw_bounding_boxes_to_image(images[image_index], class_names) if(image is None): image = cv2.imread(images[image_index]) # image = __resize_with_aspect_ratio(image, max_windows_size[0], max_windows_size[1]) image = cv2.resize(image, max_windows_size) if(annoted_object_count == 0): __save_annotations_to_file(images[image_index], [], "w") # show some info with puttext and print _, image_name = os.path.split(images[image_index]) cv2.putText(image, "{0}/{1} {2} objs:{3} lbl:{4}".format(len(images), image_index+1, image_name, annoted_object_count, class_names[label]), (0, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color=(0, 200, 100), thickness=2) print("{0}/{1} objects: {2} label: {3} image: {4}".format(len(images), image_index+1, annoted_object_count, class_names[label], images[image_index])) return image points = [] image_index = 0 label_temp = 0 global __drawing__ __drawing__ = False window_name = "Yolo annotation tool" image = images[0] show_labels = True # create window and set it up cv2.namedWindow(window_name) cv2.moveWindow(window_name, 40,30) cv2.setMouseCallback(window_name, __draw_rectangle_on_mouse_drag,image) cv2.createTrackbar('label', window_name, 0, len(class_names)-1, __on__trackbar_change) image = __refresh_image(image_index, 0) # gui loop while(True): label = cv2.getTrackbarPos('label', window_name) # bu ne salak yontem lan kafan mi iyidi yaparken if(label != label_temp): image = __refresh_image(image_index, label) label_temp = label points = [] # dont refresh the original frame while drawing if(not __drawing__): cv2.imshow(window_name, image) key = cv2.waitKey(30) # save selected annotations to a file if(key == ord("s")): if(len(points) > 0): image_height = np.size(image, 0) image_width = np.size(image, 1) # convert and save annotations to file yolo_labels_lists = __convert_annotations_opencv_to_yolo(image_width,image_height,points) __save_annotations_to_file(images[image_index], yolo_labels_lists, "a") # reset points and refresh image image = __refresh_image(image_index, label) points = [] print("annotation saved {0}".format(yolo_labels_lists)) # move backward if(key == ord("a")): if(image_index > 0): image_index -= 1 image = __refresh_image(image_index, label) points = [] # move forward if(key == ord("d")): if(image_index < len(images)-1): image_index += 1 image = __refresh_image(image_index, label) points = [] # delete last annotation if(key == ord("z")): # load annotations yolo_labels_lists = __load_annotations_from_file(images[image_index]) if(yolo_labels_lists): # delete last one yolo_labels_lists.pop() # save new annotations (last one deleted) annotation_file_path = __save_annotations_to_file(images[image_index], yolo_labels_lists, "w") image =__refresh_image(image_index, label) points = [] # # if file is empty delete it # if(len(yolo_labels_lists) == 0): # os.remove(annotation_file_path) # refresh current image if(key == ord("r")): image =__refresh_image(image_index, label) points = [] # clear annotations if(key == ord("c")): __save_annotations_to_file(images[image_index], [], "w") image = __refresh_image(image_index, label) points = [] # hide show labels if(key == ord("h")): if(show_labels): show_labels = False else: show_labels = True image = __refresh_image(image_index, label) points = [] # if window is closed break this has to be after waitkey if (cv2.getWindowProperty(window_name, 0) < 0): # cv2.destroyAllWindows() break # quit on esc if(key == 27): break cv2.destroyAllWindows() def make_prediction_from_directory_yolo(images_path, darknet_path, save_path = "detection_results", darknet_command = "./darknet detector test cfg/coco.data cfg/yolov3.cfg yolov3.weights {0} -i 0 -thresh 0.2 -dont_show", files_to_exclude = [".DS_Store",""]): """ makes prediction for multiple images from directory it uses shell command to execute darknet """ save_path = os.path.join(darknet_path, save_path) # make the dir if not os.path.exists(save_path): os.makedirs(save_path) images = os.listdir(images_path) images.sort() # remove excluded files for exclude in files_to_exclude: if exclude in images: images.remove(exclude) image_count = len(images) for index, image in enumerate(images): abs_path = os.path.join(images_path, image) __run_shell_command("cd {0} && {1}".format(darknet_path,darknet_command.format(abs_path))) copyfile(os.path.join(darknet_path, "predictions.jpg"), os.path.join(save_path, "predictions{0}.jpg".format(index))) print("File name: {0} - {1}/{2}".format(image, index+1, image_count), end="\r") print("\nAll images saved to {0}".format(save_path)) def draw_bounding_boxes(images_path_file, class_names_file, save_path = "annoted_images"): """ Draws bounding boxes of images # input images_path_file: a file that consists of image paths class_names_file: class names for bounding boxes save_path:("annoted_images") save path of the new images """ import cv2 import numpy as np image_paths = __read_from_file(images_path_file) image_paths = image_paths.split() class_names = __read_from_file(class_names_file) class_names = class_names.split() # make the dir if not os.path.exists(save_path): os.makedirs(save_path) for image_path in image_paths: image = cv2.imread(image_path) # set up save loaction and get annotation file image_name, image_extension = os.path.splitext(image_path) new_file_name = "{0}(objects){1}".format(image_name, image_extension) new_file_save_path = os.path.join(save_path, os.path.basename(new_file_name)) annotation_file_path = "{0}.txt".format(image_name) # parse annotation file if os.path.exists(annotation_file_path): annotations = __read_from_file(annotation_file_path) annotations = annotations.split("\n") annotations = filter(None, annotations) # delete empty lists annotations = [annotation.split() for annotation in annotations] # convert annotations to float and label to int # yolo annotation structure: (0 0.8 0.8 0.5 0.5) for annotation in annotations: annotation[0] = int(annotation[0]) annotation[1] = float(annotation[1]) annotation[2] = float(annotation[2]) annotation[3] = float(annotation[3]) annotation[4] = float(annotation[4]) else: continue # get dimensions of image image_height = np.size(image, 0) image_width = np.size(image, 1) # convert points opencv_points = __convert_annotations_yolo_to_opencv(image_width, image_height, annotations) # draw the rectangles using converted points for opencv_point in opencv_points: # give error if an annoted file has impossible class value if(opencv_point[0] > len(class_names)-1): raise ValueError("this image file has an annotation that has bigger class number than current selected class file") cv2.rectangle(image, (opencv_point[1], opencv_point[2]), (opencv_point[3], opencv_point[4]), (0,200,100), 2) cv2.line(image, (opencv_point[1], opencv_point[2]), (opencv_point[3], opencv_point[4]), (255, 0, 0), 1) cv2.putText(image, "{0}".format(class_names[opencv_point[0]]), (opencv_point[1], opencv_point[2]), cv2.FONT_HERSHEY_SIMPLEX, 1.5, color=(0, 0, 0), thickness=2) cv2.imwrite(new_file_save_path, image) print("Image saved: {0}".format(new_file_save_path)) def count_classes_from_annotation_files(class_path, names_path, include_zeros = False): """ Counts individual class appearances in a folder. # Arguments: class_path:
nn.Linear(d_model, d_ff), nn.ReLU(), nn.Dropout(dropouth), nn.Linear(d_ff, d_model) ) self.droph = nn.Dropout(dropouth) self.dropa = nn.Dropout(dropouta) self.norm_in = nn.LayerNorm(d_model) self.norm_inter = nn.LayerNorm(d_model) self.reset_parameters() def reset_parameters(self): """Reinitialize learnable parameters.""" for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) def forward(self, x, mem, lengths_x, lengths_mem): """ Compute multi-head self-attention. Parameters ---------- x : torch.Tensor The input tensor used to compute queries. mem : torch.Tensor The memory tensor used to compute keys and values. lengths_x : list The array of node numbers, used to segment x. lengths_mem : list The array of node numbers, used to segment mem. """ batch_size = len(lengths_x) max_len_x = max(lengths_x) max_len_mem = max(lengths_mem) device = x.device lengths_x = th.tensor(lengths_x, dtype=th.int64, device=device) lengths_mem = th.tensor(lengths_mem, dtype=th.int64, device=device) queries = self.proj_q(x).view(-1, self.num_heads, self.d_head) keys = self.proj_k(mem).view(-1, self.num_heads, self.d_head) values = self.proj_v(mem).view(-1, self.num_heads, self.d_head) # padding to (B, max_len_x/mem, num_heads, d_head) queries = F.pad_packed_tensor(queries, lengths_x, 0) keys = F.pad_packed_tensor(keys, lengths_mem, 0) values = F.pad_packed_tensor(values, lengths_mem, 0) # attention score with shape (B, num_heads, max_len_x, max_len_mem) e = th.einsum('bxhd,byhd->bhxy', queries, keys) # normalize e = e / np.sqrt(self.d_head) # generate mask mask = _gen_mask(lengths_x, lengths_mem, max_len_x, max_len_mem) e = e.masked_fill(mask == 0, -float('inf')) # apply softmax alpha = th.softmax(e, dim=-1) # the following line addresses the NaN issue, see # https://github.com/dmlc/dgl/issues/2657 alpha = alpha.masked_fill(mask == 0, 0.) # sum of value weighted by alpha out = th.einsum('bhxy,byhd->bxhd', alpha, values) # project to output out = self.proj_o( out.contiguous().view(batch_size, max_len_x, self.num_heads * self.d_head)) # pack tensor out = F.pack_padded_tensor(out, lengths_x) # intra norm x = self.norm_in(x + out) # inter norm x = self.norm_inter(x + self.ffn(x)) return x class SetAttentionBlock(nn.Module): r"""SAB block from `Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks <https://arxiv.org/abs/1810.00825>`__ Parameters ---------- d_model : int The feature size (input and output) in Multi-Head Attention layer. num_heads : int The number of heads. d_head : int The hidden size per head. d_ff : int The inner hidden size in the Feed-Forward Neural Network. dropouth : float The dropout rate of each sublayer. dropouta : float The dropout rate of attention heads. Notes ----- This module was used in SetTransformer layer. """ def __init__(self, d_model, num_heads, d_head, d_ff, dropouth=0., dropouta=0.): super(SetAttentionBlock, self).__init__() self.mha = MultiHeadAttention(d_model, num_heads, d_head, d_ff, dropouth=dropouth, dropouta=dropouta) def forward(self, feat, lengths): """ Compute a Set Attention Block. Parameters ---------- feat : torch.Tensor The input feature. lengths : list The array of node numbers, used to segment feat tensor. """ return self.mha(feat, feat, lengths, lengths) class InducedSetAttentionBlock(nn.Module): r"""ISAB block from `Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks <https://arxiv.org/abs/1810.00825>`__ Parameters ---------- m : int The number of induced vectors. d_model : int The feature size (input and output) in Multi-Head Attention layer. num_heads : int The number of heads. d_head : int The hidden size per head. d_ff : int The inner hidden size in the Feed-Forward Neural Network. dropouth : float The dropout rate of each sublayer. dropouta : float The dropout rate of attention heads. Notes ----- This module was used in SetTransformer layer. """ def __init__(self, m, d_model, num_heads, d_head, d_ff, dropouth=0., dropouta=0.): super(InducedSetAttentionBlock, self).__init__() self.m = m if m == 1: dgl_warning("if m is set to 1, the parameters corresponding to query and key " "projections would not get updated during training.") self.d_model = d_model self.inducing_points = nn.Parameter( th.FloatTensor(m, d_model) ) self.mha = nn.ModuleList([ MultiHeadAttention(d_model, num_heads, d_head, d_ff, dropouth=dropouth, dropouta=dropouta) for _ in range(2)]) self.reset_parameters() def reset_parameters(self): """Reinitialize learnable parameters.""" nn.init.xavier_uniform_(self.inducing_points) def forward(self, feat, lengths): """ Compute an Induced Set Attention Block. Parameters ---------- feat : torch.Tensor The input feature. lengths : list The array of node numbers, used to segment feat tensor. Returns ------- torch.Tensor The output feature """ batch_size = len(lengths) query = self.inducing_points.repeat(batch_size, 1) memory = self.mha[0](query, feat, [self.m] * batch_size, lengths) return self.mha[1](feat, memory, lengths, [self.m] * batch_size) def extra_repr(self): """Set the extra representation of the module. which will come into effect when printing the model. """ shape_str = '({}, {})'.format(self.inducing_points.shape[0], self.inducing_points.shape[1]) return 'InducedVector: ' + shape_str class PMALayer(nn.Module): r"""Pooling by Multihead Attention from `Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks <https://arxiv.org/abs/1810.00825>`__ Parameters ---------- k : int The number of seed vectors. d_model : int The feature size (input and output) in Multi-Head Attention layer. num_heads : int The number of heads. d_head : int The hidden size per head. d_ff : int The kernel size in FFN (Positionwise Feed-Forward Network) layer. dropouth : float The dropout rate of each sublayer. dropouta : float The dropout rate of attention heads. Notes ----- This module was used in SetTransformer layer. """ def __init__(self, k, d_model, num_heads, d_head, d_ff, dropouth=0., dropouta=0.): super(PMALayer, self).__init__() self.k = k if k == 1: dgl_warning("if k is set to 1, the parameters corresponding to query and key " "projections would not get updated during training.") self.d_model = d_model self.seed_vectors = nn.Parameter( th.FloatTensor(k, d_model) ) self.mha = MultiHeadAttention(d_model, num_heads, d_head, d_ff, dropouth=dropouth, dropouta=dropouta) self.ffn = nn.Sequential( nn.Linear(d_model, d_ff), nn.ReLU(), nn.Dropout(dropouth), nn.Linear(d_ff, d_model) ) self.reset_parameters() def reset_parameters(self): """Reinitialize learnable parameters.""" nn.init.xavier_uniform_(self.seed_vectors) def forward(self, feat, lengths): """ Compute Pooling by Multihead Attention. Parameters ---------- feat : torch.Tensor The input feature. lengths : list The array of node numbers, used to segment feat tensor. Returns ------- torch.Tensor The output feature """ batch_size = len(lengths) query = self.seed_vectors.repeat(batch_size, 1) return self.mha(query, self.ffn(feat), [self.k] * batch_size, lengths) def extra_repr(self): """Set the extra representation of the module. which will come into effect when printing the model. """ shape_str = '({}, {})'.format(self.seed_vectors.shape[0], self.seed_vectors.shape[1]) return 'SeedVector: ' + shape_str class SetTransformerEncoder(nn.Module): r"""The Encoder module from `Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks <https://arxiv.org/pdf/1810.00825.pdf>`__ Parameters ---------- d_model : int The hidden size of the model. n_heads : int The number of heads. d_head : int The hidden size of each head. d_ff : int The kernel size in FFN (Positionwise Feed-Forward Network) layer. n_layers : int The number of layers. block_type : str Building block type: 'sab' (Set Attention Block) or 'isab' (Induced Set Attention Block). m : int or None The number of induced vectors in ISAB Block. Set to None if block type is 'sab'. dropouth : float The dropout rate of each sublayer. dropouta : float The dropout rate of attention heads. Examples -------- >>> import dgl >>> import torch as th >>> from dgl.nn import SetTransformerEncoder >>> >>> g1 = dgl.rand_graph(3, 4) # g1 is a random graph with 3 nodes and 4 edges >>> g1_node_feats = th.rand(3, 5) # feature size is 5 >>> g1_node_feats tensor([[0.8948, 0.0699, 0.9137, 0.7567, 0.3637], [0.8137, 0.8938, 0.8377, 0.4249, 0.6118], [0.5197, 0.9030, 0.6825, 0.5725, 0.4755]]) >>> >>> g2 = dgl.rand_graph(4, 6) # g2 is a random graph with 4 nodes and 6 edges >>> g2_node_feats = th.rand(4, 5) # feature size is 5 >>> g2_node_feats tensor([[0.2053, 0.2426, 0.4111, 0.9028, 0.5658], [0.5278, 0.6365, 0.9990, 0.2351, 0.8945], [0.3134, 0.0580, 0.4349, 0.7949, 0.3891], [0.0142, 0.2709, 0.3330, 0.8521, 0.6925]]) >>> >>> set_trans_enc = SetTransformerEncoder(5, 4, 4, 20) # create a settrans encoder. Case 1: Input a single graph >>> set_trans_enc(g1, g1_node_feats) tensor([[ 0.1262, -1.9081, 0.7287, 0.1678, 0.8854], [-0.0634, -1.1996, 0.6955, -0.9230, 1.4904], [-0.9972, -0.7924, 0.6907, -0.5221, 1.6211]], grad_fn=<NativeLayerNormBackward>) Case 2: Input a batch of graphs Build a batch of DGL graphs and concatenate all graphs' node features into one tensor. >>> batch_g = dgl.batch([g1, g2]) >>> batch_f = th.cat([g1_node_feats, g2_node_feats]) >>> >>> set_trans_enc(batch_g, batch_f) tensor([[ 0.1262, -1.9081, 0.7287, 0.1678, 0.8854], [-0.0634, -1.1996, 0.6955, -0.9230, 1.4904], [-0.9972, -0.7924, 0.6907, -0.5221, 1.6211], [-0.7973, -1.3203, 0.0634, 0.5237, 1.5306], [-0.4497, -1.0920, 0.8470, -0.8030, 1.4977], [-0.4940, -1.6045, 0.2363, 0.4885, 1.3737], [-0.9840, -1.0913, -0.0099, 0.4653, 1.6199]], grad_fn=<NativeLayerNormBackward>) See Also -------- SetTransformerDecoder Notes ----- SetTransformerEncoder is not a readout layer, the tensor it returned is nodewise representation instead out graphwise representation, and the SetTransformerDecoder would return a graph readout tensor. """ def __init__(self, d_model, n_heads, d_head, d_ff, n_layers=1, block_type='sab', m=None, dropouth=0., dropouta=0.):
it can de-queue the request. Raises: RuntimeError: An object other than an RDFValue was passed for sending. """ if not isinstance(rdf_value, rdfvalue.RDFValue): raise RuntimeError("Sending objects other than RDFValues not supported.") message = rdf_flows.GrrMessage( session_id=session_id, task_id=task_id, name=name, response_id=response_id, request_id=request_id, require_fastpoll=require_fastpoll, ttl=ttl, type=message_type) if rdf_value is not None: message.payload = rdf_value serialized_message = message.SerializeToString() self.ChargeBytesToSession(session_id, len(serialized_message)) if message.type == rdf_flows.GrrMessage.Type.STATUS: rdf_value.network_bytes_sent = self.sent_bytes_per_flow[session_id] del self.sent_bytes_per_flow[session_id] message.payload = rdf_value try: self.QueueResponse(message, blocking=blocking) except queue.Full: # In the case of a non blocking send, we reraise the exception to notify # the caller that something went wrong. if not blocking: raise # There is nothing we can do about it here - we just lose the message and # keep going. logging.info("Queue is full, dropping messages.") @utils.Synchronized def ChargeBytesToSession(self, session_id, length, limit=0): self.sent_bytes_per_flow.setdefault(session_id, 0) self.sent_bytes_per_flow[session_id] += length # Check after incrementing so that sent_bytes_per_flow goes over the limit # even though we don't send those bytes. This makes sure flow_runner will # die on the flow. if limit and self.sent_bytes_per_flow[session_id] > limit: self.SendClientAlert("Network limit exceeded.") raise actions.NetworkBytesExceededError( "Action exceeded network send limit.") def HandleMessage(self, message): """Entry point for processing jobs. Args: message: The GrrMessage that was delivered from the server. Raises: RuntimeError: The client action requested was not found. """ self._is_active = True try: action_cls = actions.ActionPlugin.classes.get(message.name) if action_cls is None: raise RuntimeError("Client action %r not known" % message.name) action = action_cls(grr_worker=self) # Write the message to the transaction log. self.transaction_log.Write(message) # Heartbeat so we have the full period to work on this message. action.Progress() action.Execute(message) # If we get here without exception, we can remove the transaction. self.transaction_log.Clear() finally: self._is_active = False # We want to send ClientStats when client action is complete. self.stats_collector.RequestSend() def MemoryExceeded(self): """Returns True if our memory footprint is too large.""" rss_size = self.proc.memory_info().rss return rss_size // 1024 // 1024 > config.CONFIG["Client.rss_max"] def IsActive(self): """Returns True if worker is currently handling a message.""" return self._is_active def SendNannyMessage(self): # We might be monitored by Fleetspeak. if not self.nanny_controller: return msg = self.nanny_controller.GetNannyMessage() if msg: self.SendReply( rdf_protodict.DataBlob(string=msg), session_id=rdfvalue.FlowSessionID(flow_name="NannyMessage"), require_fastpoll=False) self.nanny_controller.ClearNannyMessage() def SendClientAlert(self, msg): self.SendReply( rdf_protodict.DataBlob(string=msg), session_id=rdfvalue.FlowSessionID(flow_name="ClientAlert"), require_fastpoll=False) def Sleep(self, timeout): """Sleeps the calling thread with heartbeat.""" if self.nanny_controller: self.nanny_controller.Heartbeat() # Split a long sleep interval into 1 second intervals so we can heartbeat. while timeout > 0: time.sleep(min(1., timeout)) timeout -= 1 # If the output queue is full, we are ready to do a post - no # point in waiting. if self._out_queue.Full(): return if self.nanny_controller: self.nanny_controller.Heartbeat() def OnStartup(self): """A handler that is called on client startup.""" # We read the transaction log and fail any requests that are in it. If there # is anything in the transaction log we assume its there because we crashed # last time and let the server know. last_request = self.transaction_log.Get() if last_request: status = rdf_flows.GrrStatus( status=rdf_flows.GrrStatus.ReturnedStatus.CLIENT_KILLED, error_message="Client killed during transaction") if self.nanny_controller: nanny_status = self.nanny_controller.GetNannyStatus() if nanny_status: status.nanny_status = nanny_status self.SendReply( status, request_id=last_request.request_id, response_id=1, session_id=last_request.session_id, message_type=rdf_flows.GrrMessage.Type.STATUS) self.transaction_log.Clear() # Inform the server that we started. action = admin.SendStartupInfo(grr_worker=self) action.Run(None, ttl=1) def run(self): """Main thread for processing messages.""" self.OnStartup() try: while True: message = self._in_queue.get() # A message of None is our terminal message. if message is None: break try: self.HandleMessage(message) # Catch any errors and keep going here except Exception as e: # pylint: disable=broad-except logging.warn("%s", e) self.SendReply( rdf_flows.GrrStatus( status=rdf_flows.GrrStatus.ReturnedStatus.GENERIC_ERROR, error_message=utils.SmartUnicode(e)), request_id=message.request_id, response_id=1, session_id=message.session_id, task_id=message.task_id, message_type=rdf_flows.GrrMessage.Type.STATUS) if flags.FLAGS.debug: pdb.post_mortem() except Exception as e: # pylint: disable=broad-except logging.error("Exception outside of the processing loop: %r", e) finally: # There's no point in running the client if it's broken out of the # processing loop and it should be restarted shortly anyway. logging.fatal("The client has broken out of its processing loop.") # The binary (Python threading library, perhaps) has proven in tests to be # very persistent to termination calls, so we kill it with fire. os.kill(os.getpid(), signal.SIGKILL) class SizeLimitedQueue(object): """A Queue which limits the total size of its elements. The standard Queue implementations uses the total number of elements to block on. In the client we want to limit the total memory footprint, hence we need to use the total size as a measure of how full the queue is. """ def __init__(self, heart_beat_cb, maxsize=1024): self._queue = collections.deque() self._lock = threading.Lock() self._total_size = 0 self._maxsize = maxsize self._heart_beat_cb = heart_beat_cb def Put(self, message, block=True, timeout=1000): """Put a message on the queue, blocking if it is too full. Blocks when the queue contains more than the threshold. Args: message: rdf_flows.GrrMessage The message to put. block: bool If True, we block and wait for the queue to have more space. Otherwise, if the queue is full, we raise. timeout: int Maximum time (in seconds, with 1 sec resolution) we spend waiting on the queue. Raises: queue.Full: if the queue is full and block is False, or timeout is exceeded. """ # We only queue already serialized objects so we know how large they are. message = message.SerializeToString() if not block: if self.Full(): raise queue.Full else: t0 = time.time() while self.Full(): time.sleep(1) self._heart_beat_cb() if time.time() - t0 > timeout: raise queue.Full with self._lock: self._queue.appendleft(message) self._total_size += len(message) def _Generate(self): """Yields messages from the queue. Lock should be held by the caller.""" while self._queue: yield self._queue.pop() def GetMessages(self, soft_size_limit=None): """Retrieves and removes the messages from the queue. Args: soft_size_limit: int If there is more data in the queue than soft_size_limit bytes, the returned list of messages will be approximately this large. If None (default), returns all messages currently on the queue. Returns: rdf_flows.MessageList A list of messages that were .Put on the queue earlier. """ with self._lock: ret = rdf_flows.MessageList() ret_size = 0 for message in self._Generate(): self._total_size -= len(message) ret.job.append(rdf_flows.GrrMessage.FromSerializedString(message)) ret_size += len(message) if soft_size_limit is not None and ret_size > soft_size_limit: break return ret def Size(self): return self._total_size def Full(self): return self._total_size >= self._maxsize class GRRHTTPClient(object): """A class which abstracts away HTTP communications. To create a new GRR HTTP client, instantiate this class and generate its Run() method. The HTTP client starts up by loading a communicator which will read the client's public key (or create a new random key). Since the client ID is based on the key (its a hash of the public key), the communicator controls the client name. The client worker is then created - this will be the main thread for executing server messages. The client then creates a HTTPManager() instance to control communication with the front end over HTTP, and a Timer() instance to control polling policy. The HTTP client simply reads pending messages from the client worker queues and makes POST requests to the server. The POST request may return the following error conditions: - A successful POST is signified by a status of 200: The client worker is given any requests the server has sent. - A status code of 406 means that the server is unable to communicate with the client. The client will then prepare an enrollment request CSR and send that. Enrollment requests are throttled to a maximum of one every 10 minutes. - A status code of 500 is an error, the messages are re-queued and the client waits and retries to send them later. """ http_manager_class = HTTPManager def __init__(self, ca_cert=None, worker_cls=None, private_key=None): """Constructor. Args: ca_cert: String representation of a CA certificate to use for checking server certificate. worker_cls: The client worker class to use. Defaults to GRRClientWorker. private_key: The private key for this client. Defaults to config Client.private_key. """ self.ca_cert = ca_cert if private_key is None: private_key = config.CONFIG.Get("Client.private_key", default=None) # The server's PEM encoded certificate. self.server_certificate = None # This manages our HTTP connections. Note: The comms thread is allowed to # block indefinitely since the worker thread is responsible for # heart-beating the nanny. We assume that HTTP requests can not block #
<gh_stars>1-10 import abc import base64 from datetime import date, datetime import dataclasses as dc from typing import Type as PyType, Any, Dict, Optional import marshmallow as ma import pickle import pluggy import statey as st from statey.syms import types, utils, Object class Encoder(abc.ABC): """ An encoder encodes data of some with possibly native types info some format """ type: types.Type @abc.abstractmethod def encode(self, value: Any) -> Any: """ Given some _non-validated_ value, convert it to a serializable value """ raise NotImplementedError @abc.abstractmethod def decode(self, value: Any) -> Any: """ Given a freshly deserialized dictionary, potentially apply some post-processing or wrap it in a native type """ raise NotImplementedError class EncoderHooks: """ Hooks to wrap encoder functionality """ @st.hookspec(firstresult=True) def encode(self, value: Any) -> Any: """ Optionally apply some logic to encode the given value. return None if the given value is not handled. """ @st.hookspec(firstresult=True) def decode(self, value: Any) -> Any: """ Opposite of the encode() hook """ def create_encoder_plugin_manager(): """ Factory function to create the default plugin manager for encoders """ pm = st.create_plugin_manager() pm.add_hookspecs(EncoderHooks) return pm class HookHandlingEncoder(Encoder): """ Handles hooks properly in encode() and decode() """ def encode(self, value: Any) -> Any: result = self.pm.hook.encode(value=value) return value if result is None else result def decode(self, value: Any) -> Any: result = self.pm.hook.decode(value=value) return value if result is None else result @dc.dataclass(frozen=True) class DefaultEncoder(HookHandlingEncoder, utils.Cloneable): """ The default encoder just handles hooks properly, doesn't do any actual encoding """ type: types.Type pm: pluggy.PluginManager = dc.field( init=False, default_factory=create_encoder_plugin_manager, compare=False, repr=False, ) @classmethod @st.hookimpl def get_encoder( cls, type: types.Type, registry: "Registry", serializable: bool ) -> Encoder: """ The basic encoder behavior just calls hooks, but we should pass through plugins too. """ if serializable: return None inst = cls(type) for plugin in type.meta.get("plugins", []): inst.pm.register(plugin) return inst @dc.dataclass(frozen=True) class MarshmallowEncoder(HookHandlingEncoder): """ Encodeable helper to get all functionality from a field factory """ type: types.Type registry: "Registry" pm: pluggy.PluginManager = dc.field( init=False, compare=False, repr=False, default_factory=create_encoder_plugin_manager, ) @abc.abstractmethod def base_marshmallow_field(self, encoding: bool) -> ma.fields.Field: """ Return the marshmallow field for this type """ raise NotImplementedError def marshmallow_field(self, encoding: bool) -> ma.fields.Field: kws = self._marshmallow_field_kws(self.type.nullable, self.type.meta) base = self.base_marshmallow_field(encoding) return utils.PossiblySymbolicField(base, self.type, self.registry, **kws) def encode(self, data: Any) -> Any: # Allow pre-encoding hooks data = super().encode(data) field = self.marshmallow_field(True) with utils.reraise_ma_validation_error(): # This does the validation data = field.deserialize(data) # This allows us to leverage marshmallow to do things like encoding # dates as strings w/ symmetrical encoding/decoding logic return field.serialize("tmp", {"tmp": data}) def decode(self, data: Any) -> Any: with utils.reraise_ma_validation_error(): value = self.marshmallow_field(False).deserialize(data) # Allow post-decoding hooks return super().decode(value) @staticmethod def _marshmallow_field_kws(nullable: bool, meta: Dict[str, Any]) -> Dict[str, Any]: default = meta.get("default", utils.MISSING) validate = meta.get("validator", utils.MISSING) if nullable: kws = { "required": False, "default": None if utils.is_missing(default) else default, "missing": None if utils.is_missing(default) else default, "allow_none": True, } elif utils.is_missing(default): kws = {"required": True} else: kws = {"missing": default, "default": default} if not utils.is_missing(validate): kws["validate"] = validate return kws class MarshmallowValueEncoder(MarshmallowEncoder): """ Simple marshmallow encoder for value types """ base_field: ma.fields.Field type_cls: PyType[types.Type] serializable: bool def base_marshmallow_field(self, encoding: bool) -> ma.fields.Field: return self.base_field @classmethod @st.hookimpl def get_encoder( cls, type: types.Type, registry: "Registry", serializable: bool ) -> Encoder: if serializable and not cls.serializable: return None if isinstance(type, cls.type_cls): instance = cls(type, registry) for plugin in type.meta.get("plugins", []): instance.pm.register(plugin) return instance return None @dc.dataclass(frozen=True) class IntegerEncoder(MarshmallowValueEncoder): type_cls = types.IntegerType base_field = ma.fields.Int() serializable = True @dc.dataclass(frozen=True) class FloatEncoder(MarshmallowValueEncoder): type_cls = types.FloatType base_field = ma.fields.Float() serializable = True @dc.dataclass(frozen=True, repr=False) class BooleanEncoder(MarshmallowValueEncoder): type_cls = types.BooleanType base_field = ma.fields.Bool() serializable = True @dc.dataclass(frozen=True, repr=False) class StringEncoder(MarshmallowValueEncoder): type_cls = types.StringType base_field = ma.fields.Str() serializable = True class DateLikeFuzzyDeserialize: """""" def _deserialize(self, value, attr, data, **kwargs): error = None try: return super()._deserialize(value, attr, data, **kwargs) except ma.ValidationError as err: error = err fmt = self.format try: for new_fmt, func in self.DESERIALIZATION_FUNCS.items(): self.format = new_fmt try: return super()._deserialize(value, attr, data, **kwargs) except ma.ValidationError: pass finally: self.format = fmt raise error class DateField(DateLikeFuzzyDeserialize, ma.fields.Date): """""" def from_date(value: Any) -> date: if isinstance(value, date): return value raise ma.ValidationError("Not a valid date.") def from_datetime(value: Any) -> date: if isinstance(value, datetime): return value.date() raise ma.ValidationError("Not a valid date.") DESERIALIZATION_FUNCS = { **ma.fields.Date.DESERIALIZATION_FUNCS, "date": from_date, "datetime": from_datetime, } class DateTimeField(DateLikeFuzzyDeserialize, ma.fields.DateTime): """""" def from_datetime(value: Any) -> datetime: if isinstance(value, datetime): return value raise ma.ValidationError("Not a valid datetime.") def from_date(value: Any) -> datetime: if isinstance(value, date): return datetime(value.year, value.month, value.day) raise ma.ValidationError("Not a valid datetime.") DESERIALIZATION_FUNCS = { **ma.fields.DateTime.DESERIALIZATION_FUNCS, "datetime": from_datetime, "date": from_date, } @dc.dataclass(frozen=True, repr=False) class DateEncoder(MarshmallowValueEncoder): type_cls = types.DateType base_field = DateField() serializable = True @dc.dataclass(frozen=True, repr=False) class DateTimeEncoder(MarshmallowValueEncoder): type_cls = types.DateTimeType base_field = DateTimeField() serializable = True @dc.dataclass(frozen=True, repr=False) class ArrayEncoder(MarshmallowEncoder): """ An array with some element type """ element_encoder: Encoder def base_marshmallow_field(self, encoding: bool) -> ma.fields.Field: kws = self._marshmallow_field_kws( self.element_encoder.type.nullable, self.element_encoder.type.meta ) if encoding: kws["serialize"] = lambda x: x kws["deserialize"] = self.element_encoder.encode else: kws["serialize"] = lambda x: x kws["deserialize"] = self.element_encoder.decode element_field = utils.SingleValueFunction(**kws) return ma.fields.List(element_field) @classmethod @st.hookimpl def get_encoder( cls, type: types.Type, registry: "Registry", serializable: bool ) -> Encoder: if not isinstance(type, types.ArrayType): return None element_encoder = registry.get_encoder(type.element_type, serializable) instance = cls(type, registry, element_encoder) for plugin in type.meta.get("plugins", []): instance.pm.register(plugin) return instance @dc.dataclass(frozen=True, repr=False) class StructEncoder(MarshmallowEncoder): field_encoders: Dict[str, Encoder] def base_marshmallow_field(self, encoding: bool) -> ma.fields.Field: return ma.fields.Nested(self.marshmallow_schema(encoding)) def marshmallow_schema(self, encoding: bool) -> ma.Schema: fields = {} for name, encoder in self.field_encoders.items(): kws = self._marshmallow_field_kws(encoder.type.nullable, encoder.type.meta) if encoding: kws["serialize"] = lambda x: x kws["deserialize"] = encoder.encode else: kws["serialize"] = lambda x: x kws["deserialize"] = encoder.decode fields[name] = utils.SingleValueFunction(**kws) return type("StructSchema", (ma.Schema,), fields)() @classmethod @st.hookimpl def get_encoder( cls, type: types.Type, registry: "Registry", serializable: bool ) -> Encoder: if not isinstance(type, types.StructType): return None encoders = {} for field in type.fields: encoders[field.name] = registry.get_encoder(field.type, serializable) instance = cls(type, registry, encoders) for plugin in type.meta.get("plugins", []): instance.pm.register(plugin) return instance @dc.dataclass(frozen=True) class NativeFunctionEncoder(StructEncoder): """ Encoder for native python functions """ module: Any = pickle def encode(self, value: Any) -> Any: if isinstance(value, Object) or value is None: return super().encode(value) serialized_bytes = self.module.dumps(value.func) converted = { "serialized": base64.b64encode(serialized_bytes), "name": value.name, } return super().encode(converted) def decode(self, value: Any) -> Any: from statey.syms import func value = super().decode(value) if isinstance(value, Object) or value is None: return value function_ob = self.module.loads(base64.b64decode(value["serialized"])) return func.NativeFunction(self.type, function_ob, value["name"]) @classmethod @st.hookimpl def get_encoder( cls, type: types.Type, registry: "Registry", serializable: bool ) -> Encoder: if not isinstance(type, types.NativeFunctionType): return None as_struct = types.StructType(type.fields, type.nullable, type.meta) struct_encoder = registry.get_encoder(as_struct, serializable) return cls(type, registry, struct_encoder.field_encoders) @dc.dataclass(frozen=True, repr=False) class MapEncoder(MarshmallowEncoder): """ An array with some element type """ key_encoder: Encoder value_encoder: Encoder def base_marshmallow_field(self, encoding: bool) -> ma.fields.Field: key_kws = self._marshmallow_field_kws( self.key_encoder.type.nullable, self.key_encoder.type.meta ) if encoding: key_kws["serialize"] = lambda x: x key_kws["deserialize"] = self.key_encoder.encode else: key_kws["serialize"] = lambda x: x key_kws["deserialize"] = self.key_encoder.decode key_field = utils.SingleValueFunction(**key_kws) value_kws = self._marshmallow_field_kws( self.value_encoder.type.nullable, self.value_encoder.type.meta ) if encoding: value_kws["serialize"] = lambda x: x value_kws["deserialize"] = self.value_encoder.encode else: value_kws["serialize"] = lambda x: x value_kws["deserialize"] = self.value_encoder.decode value_field = utils.SingleValueFunction(**value_kws) return ma.fields.Dict(keys=key_field, values=value_field) @classmethod @st.hookimpl def get_encoder( cls, type: types.Type, registry: "Registry", serializable: bool ) -> Encoder: if not isinstance(type, types.MapType): return None key_encoder = registry.get_encoder(type.key_type, serializable) value_encoder = registry.get_encoder(type.value_type, serializable) instance = cls(type, registry, key_encoder, value_encoder) for plugin in type.meta.get("plugins", []): instance.pm.register(plugin) return instance @dc.dataclass(frozen=True) class TypeEncoder(HookHandlingEncoder): """ encodes a types.TypeType """ type: types.Type registry: "Registry" pm: pluggy.PluginManager = dc.field( init=False, compare=False, repr=False, default_factory=create_encoder_plugin_manager, ) def encode(self, value: Any) -> Any: super_encoded = super().encode(value) if value is None: if self.type.nullable: return None raise st.exc.InputValidationError({"_schema": ["Invalid input type."]}) if isinstance(value, dict): return value try: type_serializer = self.registry.get_type_serializer(value) except st.exc.NoTypeSerializerFound as err: raise st.exc.InputValidationError( {"_schema": ["Unable to find type serializer."]} ) return type_serializer.serialize(value) def decode(self, value: Any) -> Any: if value is None: if self.type.nullable: return super().decode(value) raise st.exc.InputValidationError({"_schema": ["Invalid input type."]}) if isinstance(value, types.Type): return super().decode(value) try: type_serializer = self.registry.get_type_serializer_from_data(value) except st.exc.NoTypeSerializerFound as err: raise st.exc.InputValidationError( {"_schema": ["Unable to find type serializer."]} ) typ = type_serializer.deserialize(value) return super().decode(typ) @classmethod @st.hookimpl def get_encoder( cls, type: types.Type, registry: "Registry", serializable: bool ) -> Encoder: if not isinstance(type, types.TypeType): return None instance = cls(type, registry) for plugin in
Pink Polar": 0xD8C9CC, "Light Pink Tone": 0xFAD9DA, "Light Pistachio Tang": 0xE2DEC8, "Light Placid Blue": 0xC8D8E8, "Light Pollinate": 0xEBE1CB, "Light Poolside": 0xBEE0E2, "Light Porcelain": 0xE7DAD7, "Light Powder Blue": 0xC4D9EF, "Light Powdered Granite": 0xD1D6EB, "Light Pre School": 0xC5D0D9, "Light Pretty Pale": 0xEAD4E0, "Light Puffball": 0xD9CED5, "Light Pumpkin Brown": 0xC2A585, "Light Pure Blue": 0xC2D2D8, "Light Purity": 0xE0D5E9, "Light Quaver": 0xCDDED7, "Light Quilt": 0xFDE1D4, "Light Radar": 0xC6D5EA, "Light Rattan": 0xD1C1AA, "Light Raw Cotton": 0xECDFCA, "Light Red": 0xF3D3D9, "Light Relax": 0xCADDDE, "Light Ridge Light": 0xC3D5E5, "Light Roast": 0x615544, "Light Rose": 0xF4D4D6, "Light Rose Beige": 0xF9EBE4, "Light Rose Romantic": 0xF3DCD8, "Light Saffron Orange": 0xFFCCA5, "Light Sage": 0xB3B0A3, "Light Salome": 0xCCF1E3, "Light Salt Spray": 0xBBD3DA, "Light Sandbank": 0xDEDCC6, "Light Sandy Day": 0xE1DACF, "Light Sea Breeze": 0xB7CDD9, "Light Sea Cliff": 0xB9D4E7, "Light Sea Spray": 0xABD6DE, "Light Sea-Foam": 0xA0FEBF, "Light Seafoam Green": 0xA7FFB5, "Light Security": 0xE0E9D0, "Light Shell Haven": 0xF1E8CE, "Light Shell Tint": 0xFCE0D6, "Light Shetland Lace": 0xE7DCCF, "Light Shimmer": 0xA3D4EF, "Light Short Phase": 0xCBE8DF, "Light Shutterbug": 0xCEF2E4, "Light Silver Grass": 0xD4DBD1, "Light Silverton": 0xCEE3D9, "Light Sky Babe": 0xA1D0E2, "Light Sky Bus": 0xAFCFE0, "Light Sky Chase": 0xBAD7DC, "Light Skyway": 0xC2E3E8, "Light Slipper Satin": 0xCFD1D8, "Light Soft Celadon": 0xCEDCD4, "Light Soft Fresco": 0xCFE0D7, "Light Soft Kind": 0xDCDDCC, "Light Spearmint Ice": 0xCFDED7, "Light Spirit": 0xC3CAD3, "Light Spirited": 0xD8EEE7, "Light Sprig Muslin": 0xE0CFD2, "Light Spring Burst": 0xD6E8D5, "Light Sprinkle": 0xE3E3D7, "Light Stargate": 0xC7D2DD, "Light Starlight": 0xCBD0D7, "Light Stately Frills": 0xD2CCD1, "Light Steel Blue": 0xB0C4DE, "Light Stone": 0xDCD1CC, "Light Subpoena": 0xE4DAD3, "Light Supernova": 0xCDE5E2, "Light Tactile": 0xDEEDD4, "Light Taupe": 0xB19D8D, "Light Taupe White": 0xD5D0CB, "Light Teal": 0xB1CCC5, "Light Template": 0xBBD6EA, "Light Terracotta": 0xDF9B81, "Light Thought": 0xE2D8D4, "Light Tidal Foam": 0xBCD6E9, "Light Time Travel": 0xC5D2DF, "Light Tinge Of Mauve": 0xDFD2D9, "Light Tip Toes": 0xE1D0D8, "Light Tomato": 0xD0756F, "Light Topaz Ochre": 0xB08971, "Light Topaz Soft Blue": 0xB5CDD7, "Light Touch": 0xF5ECDF, "Light Turquoise": 0x7EF4CC, "Light Vandamint": 0xBFE7EA, "Light Vanilla Ice": 0xB8CED9, "Light Vanilla Quake": 0xD8D5D0, "Light Violet": 0xD6B4FC, "Light Vision": 0xDCD9EB, "Light Wallis": 0xD4CCCE, "Light Washed Blue": 0xACDCE7, "Light Water Wash": 0xBFD5EB, "Light Water Wings": 0xC2F0E6, "Light Watermark": 0xB7DADD, "Light Watermelon Milk": 0xE6DAD6, "Light Wavecrest": 0xB5D1DF, "Light Weathered Hide": 0xE0D4D0, "Light Whimsy": 0x99D0E7, "Light White Box": 0xCEDCD6, "Light Year": 0xBFBFB4, "Light Yellow": 0xFFFE7A, "Light Yellowish Green": 0xC2FF89, "Light Youth": 0xEAD7D5, "Light Zen": 0xD1DBD2, "Lighter Green": 0x75FD63, "Lighter Mint": 0xDFEBDD, "Lighter Purple": 0xA55AF4, "Lightest Sky": 0xE4EADF, "Lighthearted": 0xF7E0E1, "Lighthearted Pink": 0xEDD5DD, "Lighthearted Rose": 0xC7A1A9, "Lighthouse": 0xF3F4F4, "Lighthouse Glow": 0xF8D568, "Lighthouse View": 0xD9DCD5, "Lightish Blue": 0x3D7AFD, "Lightish Green": 0x61E160, "Lightish Purple": 0xA552E6, "Lightish Red": 0xFE2F4A, "Lightning Bolt": 0xE5EBE6, "Lightning Bolt Blue": 0x93B9DF, "Lightning Bug": 0xEFDE74, "Lightning White": 0xF8EDD1, "Lightning Yellow": 0xF7A233, "Lights of Shibuya": 0xF8F2DE, "Lights Out": 0x3D474B, "Lightsaber Blue": 0x15F2FD, "Lightweight Beige": 0xF6E5C5, "Lignum Vitœ Foliage": 0x67765B, "Ligonier Tan": 0xD2B18F, "Likeable Sand": 0xD1B7A8, "Lilac": 0xCEA2FD, "Lilac Ash": 0xD7CDCD, "Lilac Bisque": 0xC6CDE0, "Lilac Bloom": 0xAFABB8, "Lilac Blossom": 0x9A93A9, "Lilac Blue": 0x8293AC, "Lilac Breeze": 0xB3A0C9, "Lilac Bush": 0x9470C4, "Lilac Champagne": 0xDFE1E6, "Lilac Chiffon": 0xDE9BC4, "Lilac Cotton Candy": 0xCDD7EC, "Lilac Crystal": 0xCBC5D9, "Lilac Fields": 0x8F939D, "Lilac Flare": 0xB2BADB, "Lilac Fluff": 0xC8A4BF, "Lilac Frost": 0xE8DEEA, "Lilac Geode": 0xBB88FF, "Lilac Grey": 0x9896A4, "Lilac Haze": 0xD5B6D4, "Lilac Hint": 0xD0D0DA, "Lilac Intuition": 0x9A7EA7, "Lilac Light": 0xD7C1BA, "Lilac Lotion": 0xFF3388, "Lilac Lust": 0xC3B9D8, "Lilac Luster": 0xAE98AA, "Lilac Marble": 0xC3BABF, "Lilac Mauve": 0xD6D0D6, "Lilac Mist": 0xE4E4E7, "Lilac Murmur": 0xE5E6EA, "Lilac Paradise": 0xDCBBBA, "Lilac Pink": 0xC09DC8, "Lilac Purple": 0xA183C0, "Lilac Rose": 0xBD4275, "Lilac Sachet": 0xABB6D7, "Lilac Scent Soft Blue": 0x9EABD0, "Lilac Smoke": 0xB6A3A0, "Lilac Snow": 0xE0C7D7, "Lilac Spring": 0x8822CC, "Lilac Suede": 0xBA9B97, "Lilac Tan": 0xD4C7C4, "Lilac Time": 0xA4ABBF, "Lilac Violet": 0x754A80, "Lilacs in Spring": 0xE9CFE5, "Lilas": 0xB88995, "Lilás": 0xCC99FF, "Liliac": 0xC48EFD, "Lilliputian Lime": 0x88DD55, "Lilting Laughter": 0xFCEBD8, "Lily": 0xC19FB3, "Lily Green": 0xC5CF98, "Lily Lavender": 0xE6E6E8, "Lily Legs": 0xEEC7D6, "Lily of the Nile": 0x9191BB, "Lily of The Valley White": 0xE2E3D6, "Lily Pad": 0x818F84, "Lily Pads": 0x6DB083, "Lily Pond": 0xDEEAD8, "Lily Pond Blue": 0x55707F, "Lily Scent Green": 0xE6E6BC, "Lily The Pink": 0xF5DEE2, "Lily White": 0xF0E7D3, "Lilylock": 0xE0E1C1, "Lima": 0xA9F971, "Lima Bean": 0xE1D590, "Lima Bean Green": 0x88BE69, "Lima Green": 0xB1B787, "Lima Sombrio": 0x7AAC21, "Limbert Leather": 0x988870, "Lime": 0xAAFF32, "Lime Acid": 0xAFFF01, "Lime Blossom": 0xF4F2D3, "Lime Bright": 0xF1E4B0, "Lime Cake": 0xDAE3D0, "Lime Candy Pearl": 0xAAFF00, "Lime Chalk": 0xE5DDC8, "Lime Coco Cake": 0xE6EFCC, "Lime Cream": 0xD7E8BC, "Lime Daiquiri": 0xDDE6D7, "Lime Dream": 0xC2ECBC, "Lime Fizz": 0xCFE838, "Lime Flip": 0xD2E3CC, "Lime Glow": 0xE1ECD9, "Lime Granita": 0xDCE1B8, "Lime Green": 0x9FC131, "Lime Hawk Moth": 0xCDAEA5, "Lime Ice": 0xD1DD86, "Lime Jelly": 0xE3FF00, "Lime Juice": 0xE7E4D3, "Lime Juice Green": 0xE5E896, "Lime Lightning": 0xBEFD73, "Lime Lizard": 0xABD35D, "Lime Lollipop": 0xB4BD7A, "Lime Meringue": 0xE6ECD6, "Lime Mist": 0xDDFFAA, "Lime Parfait": 0x95C577, "Lime Peel": 0xC6C191, "Lime Pink": 0xB6848C, "Lime Pop": 0xCCCB2F, "Lime Popsicle": 0xC0DB3A, "Lime Punch": 0xC0D725, "Lime Rasp": 0xB5CE08, "Lime Rickey": 0xAFB96A, "Lime Sherbet": 0xCDD78A, "Lime Shot": 0x1DF914, "Lime Slice": 0xF0FDED, "Lime Soap": 0x7AF9AB, "Lime Sorbet": 0xBEE5BE, "Lime Sorbet Green": 0xC6CD7D, "Lime Splash": 0xCFDB8D, "Lime Spritz": 0xDAE1CF, "Lime Taffy": 0xBAD1B5, "Lime Time": 0xEBE734, "Lime Tree": 0xD8D06B, "Lime Twist": 0xC6D624, "Lime Wash": 0xDFE3D0, "Lime Yellow": 0xD0FE1D, "Lime Zest": 0xDDFF00, "Limeade": 0x5F9727, "Limed Ash": 0x747D63, "Limed Oak": 0xAC8A56, "Limed Spruce": 0x394851, "Limed White": 0xCFC9C0, "Limelight": 0xF0E87D, "Limeño Limón": 0xF8B109, "Limerick": 0x76857B, "Limescent": 0xE0D4B7, "Limesicle": 0xF2EABF, "Limestone": 0xDCD8C7, "Limestone Green": 0xA5AF9D, "Limestone Mauve": 0xD6D7DB, "Limestone Quarry": 0xF9F6DB, "Limestone Slate": 0xC5E0BD, "Limetta": 0x8E9A21, "Limewash": 0xDBD5CB, "Limited Lime": 0xEAECB9, "Limitless": 0xF0DDB8, "Limo-Scene": 0x4B4950, "Limoge Pink": 0xF3E0DB, "Limoges": 0x243F6C, "Limón Fresco": 0xCEBC55, "Limonana": 0x11DD66, "Limoncello": 0xBFFF00, "Limone": 0xD6C443, "Limonite": 0xBE7F51, "Limonite Brown": 0x4B4433, "Limousine Grey Blue": 0x535F62, "Limousine Leather": 0x3B3C3B, "Limpet Shell": 0x98DDDE, "Limpid Light": 0xCDC2CA, "Limuyi Yellow": 0xFEFC7E, "Lincoln Green": 0x195905, "Lincolnshire Sausage": 0xE3E6DA, "Linden Green": 0xC4BF71, "Linden Spear": 0x8E9985, "Linderhof Garden": 0x229922, "Lindworm Green": 0x172808, "Line Dried Sheets": 0xF5EDED, "Lineage": 0x4C3430, "Linear": 0x164975, "Linen": 0xFAF0E6, "Linen Grey": 0x466163, "Linen Ruffle": 0xEFEBE3, "Linen White": 0xE9DCD1, "Lingering Lilac": 0xE6DEF0, "Lingonberry": 0xFF255C, "Lingonberry Punch": 0xA95657, "Lingonberry Red": 0xCE4458, "Link": 0x778290, "Link Gray": 0x7F7E72, "Link Green": 0x01A049, "Link to the Past": 0xD2B48C, "Link Water": 0xC7CDD8, "Link's Awakening": 0x3EAF76, "Linnet": 0xC3BCB3, "Linnet Egg Red": 0xFFCCDD, "Linoleum Blue": 0x427C9D, "Linoleum Green": 0x3AA372, "Linseed": 0xB0A895, "Lint": 0xB6BA99, "Lion": 0xC19A62, "Lion Cub": 0xF9CDA4, "Lion King": 0xDD9933, "Lion Mane": 0xBA8E4F, "Lion of Menecrates": 0xEEAA66, "Lion's Lair": 0x81522E, "Lion's Mane": 0xE8AF49, "Lion's Mane Blonde": 0x946B41, "Lioness": 0xE0AF47, "Lionfish Red": 0xE03C28, "Lionhead": 0xD5B60A, "Lionheart": 0xCC2222, "Lip Gloss": 0xDFCDC7, "Lippie": 0xD16A68, "Lips of Apricot": 0xFBCEB1, "Lipstick": 0xC95B83, "Lipstick Pink": 0xBD7F8A, "Lipstick Red": 0xC0022F, "Liqueur Red": 0x61394B, "Liquid Blue": 0x55B7CE, "Liquid Gold": 0xFDC675, "Liquid Green Stuff": 0x3B7A5F, "Liquid Lime": 0xCDF80C, "Liquid Mercury": 0x757A80, "Liquid Nitrogen": 0xF3F3F4, "Liquorice": 0x0A0502, "Liquorice Black": 0x352D32, "Liquorice Green": 0x2A4041, "Liquorice Red": 0x740900, "Liquorice Root": 0x222200, "Lira": 0xE2C28D, "Lisbon Brown": 0x423921, "Lisbon Lemon": 0xFFFB00, "Liselotte Syrup": 0xDD5511, "Liseran Purple": 0xDE6FA1, "Lit": 0xFFFED8, "Lit'L Buoy Blew": 0xD6E8E1, "Lite Cocoa": 0xB59A8D, "Lite Lavender": 0xE0DADF, "Lithic Sand": 0x53626E, "Litmus": 0x9895C5, "Little Baby Girl": 0xF8B9D4, "Little Bear": 0x604B42, "Little Beaux Blue": 0xB6D3C5, "Little Black Dress": 0x43484B, "Little Blue Box": 0x8AC5BA, "Little Blue Heron": 0x3C4378, "Little Bow Pink": 0xD37C99, "Little Boy Blu": 0xC7D8DB, "Little Boy Blue": 0x6CA0DC, "Little Dipper": 0xE4E6EA, "Little Dove": 0xEBE0CE, "Little Lamb": 0xEAE6D7, "Little League": 0x6A9A8E, "Little Lilac": 0xE0D8DF, "Little Mermaid": 0x2D454A, "Little Pinky": 0xF4EFED, "Little Pond": 0xA6D1EB, "Little Princess": 0xE6AAC1, "Little Red Corvette": 0xE50102, "Little Smile": 0xF8D0E8, "Little Sun Dress": 0xF7C85F, "Little Theater": 0x73778F, "Little Touch": 0xE7CFE8, "Little Valley": 0xA4A191, "Live Jazz": 0x87819B, "Liveable Green": 0xCECEBD, "Liveliness": 0xFFDFB9, "Lively Coral": 0xE67C7A, "Lively Ivy": 0xB3AE87, "Lively Laugh": 0xE1DD8E, "Lively Lavender": 0x816F7A, "Lively Light": 0xA18899, "Lively Lilac": 0x9096B7, "Lively Tune": 0xC8D8E5, "Lively White": 0xF7F3E0, "Lively Yellow": 0xFFE9B1, "Liver": 0x534B4F, "Liver Brown": 0x513E32, "Liver Chestnut": 0x987456, "Livery Green": 0xA8D275, "Livid": 0x6688CC, "Livid Brown": 0x312A29, "Livid Lime": 0xB8E100, "Living Coral": 0xFF6F61, "Living Large": 0xC87163, "Living Stream": 0x37708C, "Livingston": 0xA39880, "Livingstone": 0xCBCBBB, "Lizard": 0x71643E, "Lizard Belly": 0xCCCC33, "Lizard Breath": 0xEDBB32, "Lizard Brown": 0x795419, "Lizard Green": 0x81826E, "Lizard Legs": 0x7F6944, "Llama Wool": 0x917864, "Loafer": 0xDBD9C2, "Lobaria Lichen": 0x9FC8B2, "Lobby Lilac": 0xA780B2, "Lobelia": 0x7498BE, "Loblolly": 0xB3BBB7, "Lobster": 0xBB240C, "Lobster Bisque": 0xDD9289, "Lobster
db_ele is 12 or db_ele is 22: element = 'INT' if db_ele is 3 or db_ele is 13 or db_ele is 23: element = 'STR' if db_ele is 4 or db_ele is 14 or db_ele is 24: element = 'PHY' rewards.append(element + ' ' + database.fetch(ver + '.db', 'cards', 'id=' + str(x['card_id']))[1] + ' [' + database.fetch(ver + '.db', 'leader_skills', 'id=' + str(database.fetch(ver + '.db', 'cards', 'id=' + str(x['card_id']))[24]))[1] + '] x1') except: rewards.append('card x1') if 'awakening_items' in data: for x in data['awakening_items']: try: rewards.append(database.fetch(ver + '.db', 'awakening_items', 'id=' + str(x['awakening_item_id']))[1] + ' x' + str(x['quantity'])) except: rewards.append('medal x' + str(x['quantity'])) if 'potential_items' in data: for x in data['potential_items']: try: rewards.append(database.fetch(ver + '.db', 'potential_items', 'id=' + str(x['potential_item_id']))[1] + ' x' + str(x['quantity'])) except: rewards.append('orb x' + str(x['quantity'])) print(Fore.CYAN + ',\n'.join(rewards)) def gift(ver, os, token, secret): store = ingame.gifts(ver, os, token, secret) if 'error' not in store: presents = [] for i in store['gifts']: presents.append(i['id']) if len(presents) != 0: store2 = ingame.acceptGifts(ver, os, token, secret, presents) if 'error' not in store2: print(Fore.GREEN + 'accepted ' + str(len(presents)) + ' gifts.') else: print(store2) else: print('no gifts to accept!') else: print(store) def mission(ver, os, token, secret): store = ingame.missions(ver, os, token, secret) if 'error' not in store: missions = [] db_ids = [] accepted = [] for i in store['missions']: if i['completed_at'] != None: missions.append(i['id']) db_ids.append(i['mission_id']) if len(missions) != 0: store2 = ingame.acceptMissions(ver, os, token, secret, missions) if 'error' not in store2: print(Fore.GREEN + 'claimed ' + str(len(missions)) + ' missions.') for i in db_ids: try: accepted.append(database.fetch(ver + '.db', 'missions', 'id='+str(i))[3] + '\n' + database.fetch(ver + '.db', 'mission_rewards', 'id='+str(i))[3] + ' x' + str(database.fetch(ver + '.db', 'mission_rewards', 'id='+str(i))[4])) except: accepted.append('unknown mission ID: ' + str(i)) print(Fore.CYAN + ',\n'.join(accepted)) else: print(store2) if 'already_accepted_mission_rewards' in store2['error']['code']: print('you\'ve ready claimed.') else: print('no missions to claim!') else: print(store) def summon(ver, os, token, secret, id, course): store = ingame.summon(ver, os, token, secret, id, course) if 'error' not in store: cards = [] element = '?' rarity = '?' for i in store['gasha_items']: try: db_ele = database.fetch(ver + '.db', 'cards', 'id=' + str(i['item_id']))[13] if db_ele is 0 or db_ele is 10 or db_ele is 20: element = Fore.CYAN + 'AGL' if db_ele is 1 or db_ele is 11 or db_ele is 21: element = Fore.GREEN + 'TEQ' if db_ele is 2 or db_ele is 12 or db_ele is 22: element = Fore.MAGENTA + 'INT' if db_ele is 3 or db_ele is 13 or db_ele is 23: element = Fore.RED + 'STR' if db_ele is 4 or db_ele is 14 or db_ele is 24: element = Fore.YELLOW + 'PHY' if database.fetch(ver + '.db', 'cards', 'id=' + str(i['item_id']))[6] is 0: rarity = 'N' if database.fetch(ver + '.db', 'cards', 'id=' + str(i['item_id']))[6] is 1: rarity = 'R' if database.fetch(ver + '.db', 'cards', 'id=' + str(i['item_id']))[6] is 2: rarity = 'SR' if database.fetch(ver + '.db', 'cards', 'id=' + str(i['item_id']))[6] is 3: rarity = 'SSR' if database.fetch(ver + '.db', 'cards', 'id=' + str(i['item_id']))[6] is 4: rarity = 'UR' if database.fetch(ver + '.db', 'cards', 'id=' + str(i['item_id']))[6] is 5: rarity = 'LR' cards.append(element + ' ' + rarity + ' ' + database.fetch(ver + '.db', 'cards', 'id=' + str(i['item_id']))[1] + ' [' + database.fetch(ver + '.db', 'leader_skills', 'id=' + str(database.fetch(ver + '.db', 'cards', 'id=' + str(i['item_id']))[24]))[1] + '] x' + str(i['quantity'])) except: cards.append('unknown (' + str(i['item_id']) + ') x' + str(i['quantity'])) print(',\n'.join(cards)) else: print(store) def complete_stage(ver, os, token, secret, stage, difficulty, kagi, iden): if stage != None and difficulty != None: # fetch area & stage name try: if len(stage) >= 6: area = database.fetch(ver + '.db', 'areas', 'id=' + str(stage[0:3]))[4] name = database.fetch(ver + '.db', 'quests', 'id=' + str(stage)[0:6])[2] else: if len(stage) == 5: area = database.fetch(ver + '.db', 'areas', 'id=' + str(stage[0:2]))[4] name = database.fetch(ver + '.db', 'quests', 'id=' + str(stage)[0:5])[2] else: area = database.fetch(ver + '.db', 'areas', 'id=' + str(stage[0:1]))[4] name = database.fetch(ver + '.db', 'quests', 'id=' + str(stage)[0:4])[2] match = str(area) + ' - ' + str(name) + ' (' + str(stage) + ':' + str(difficulty) + ')' except: area = 'unknown' name = 'unknown' match = str(name) + ' (' + str(stage) + ':' + str(difficulty) + ')' print(Fore.LIGHTYELLOW_EX + match) # pre define paces = [] defeated = [] # support unit store = ingame.getSupports(ver, os, token, secret, stage, difficulty) if 'error' not in store: difficulties = ['normal', 'hard', 'very_hard', 'super_hard1', 'super_hard2', 'super_hard3'] if 'cpu_supporters' in store: if str(difficulties[int(difficulty)]) in store['cpu_supporters']: if store['cpu_supporters'][str(difficulties[int(difficulty)])]['is_cpu_only'] == True: if len(store['cpu_supporters'][str(difficulties[int(difficulty)])]['cpu_friends']) >= 1: friend = store['cpu_supporters'][str(difficulties[int(difficulty)])]['cpu_friends'][0]['id'] friend_card = store['cpu_supporters'][str(difficulties[int(difficulty)])]['cpu_friends'][0]['card_id'] else: #use friend supports if no CPUs friend = store['supporters'][0]['id'] friend_card = store['supporters'][0]['leader']['card_id'] else: #use friend supports if CPUs not allowed friend = store['supporters'][0]['id'] friend_card = store['supporters'][0]['leader']['card_id'] else: #use friend supports if there's no CPUs in list friend = store['supporters'][0]['id'] friend_card = store['supporters'][0]['leader']['card_id'] else: #use friend supports if no CPU supports period friend = store['supporters'][0]['id'] friend_card = store['supporters'][0]['leader']['card_id'] # time stage clear timer_start = int(round(time.time(), 0)) # start stage store = ingame.startStage(ver, os, token, secret, stage, difficulty, friend, friend_card) if 'error' not in store: data = crypto.decrypt_sign(store['sign']) stoken = data['token'] for i in data['sugoroku']['events']: paces.append(int(i)) if 'battle_info' in data['sugoroku']['events'][i]['content']: for j in data['sugoroku']['events'][i]['content']['battle_info']: defeated.append(j['round_id']) # finish stage store = ingame.finishStage(ver, os, token, secret, stage, difficulty, paces, defeated, stoken) if 'error' not in store: timer_finish = int(round(time.time(), 0)) timer_total = timer_finish - timer_start print(Fore.GREEN + 'completed: ' + name + ' in ' + str(timer_total) + ' seconds.') data = crypto.decrypt_sign(store['sign']) rewards(ver, os, token, secret, data) #sell(ver, os, token, secret) else: print('finish - ' + str(store)) else: print('start - ' + str(store)) if 'act_is_not_enough' in store['error']['code']: restore(ver, os, token, secret) complete_stage(ver, os, token, secret, stage, difficulty, kagi, crypto.basic(iden.replace('\n', ''))) if 'the_number_of_cards_must_be_less_than_or_equal_to_the_capacity' in store['error']['code']: sell(ver, os, token, secret) complete_stage(ver, os, token, secret, stage, difficulty, kagi, crypto.basic(iden.replace('\n', ''))) if 'no_condition_to_try_the_quest_is_fulfilled' in store['error']['code']: print('this area is not unlocked or found!') if 'invalid_area_conditions_potential_releasable' in store['error']['code']: print(Fore.LIGHTRED_EX + 'potential isn\'t unlocked!') if 'active_record/record_not_found' in store['error']['code']: print(Fore.LIGHTRED_EX + 'stage not active or found!') else: print('support - ' + str(store)) if 'invalid_token' in store['error']: commands.refresh() token = commands.farm[0][3] secret = commands.farm[0][4] complete_stage(ver, os, token, secret, stage, difficulty, kagi, crypto.basic(iden.replace('\n', ''))) def complete_zstage(ver, os, token, secret, eza, level, iden): if len(str(eza)) >= 1: try: area = database.fetch(ver + '.db', 'z_battle_stage_views', 'z_battle_stage_id=' + str(eza))[3] except: area = 'unknown #' + str(eza) print(Fore.LIGHTYELLOW_EX + str(area) + ' EZA - Level ' + str(level)) em_hp = [] em_atk = 0 # support unit store = ingame.zSupports(ver, os, token, secret, eza) if 'error' not in store: friend = store['supporters'][0]['id'] friend_card = store['supporters'][0]['leader']['card_id'] timer_start = int(round(time.time(), 0)) # start stage store = ingame.zStart(ver, os, token, secret, eza, level, friend, friend_card) if 'error' not in store: dec_sign = crypto.decrypt_sign(store['sign']) for i in dec_sign['enemies'][0]: em_hp.append(i['hp']) em_atk = int(em_atk) + int(i['attack']) stoken = dec_sign['token'] # finish stage store = ingame.zFinish(ver, os, token, secret, eza, level, stoken, em_atk, em_hp) if 'error' not in store: timer_finish = int(round(time.time(), 0)) timer_total = timer_finish - timer_start print(Fore.GREEN + 'completed level: ' + str(level) + ' in ' + str(timer_total) + ' seconds.') dec_sign = crypto.decrypt_sign(store['sign']) zRewards(ver, os, token, secret, dec_sign['user_items']) else: print('finish - ' + str(store)) else: print('start - ' + str(store)) if 'z_battle_check_point_does_not_exist' in store['error']['code']: print(Fore.LIGHTRED_EX + 'you haven\'t reached this level yet!') else: print('support - ' + str(store)) if 'invalid_token' in store['error']: commands.refresh() token = commands.farm[0][3] secret = commands.farm[0][4] complete_zstage(ver, os, token, secret, eza, level, iden) def complete_unfinished_quests(ver, os, token, secret, iden): store = ingame.user(ver, os, token, secret, False) if 'error' not in store: if int(store['user']['stone']) >= 1: areas = ingame.quests(ver, os, token, secret) # user_areas -> area_id -> user_sugoroku_maps -> sugoroku_map_id, cleared_count maps = [] for i in areas['user_areas']: if i['area_id'] <= 27: for j in i['user_sugoroku_maps']: if j['cleared_count'] == 0: maps.append(j['sugoroku_map_id']) if len(maps) == 0: print('no quests to complete.') else: if len(maps) == 15: f = open('quests.txt',
'O3120X0', 'O3120X1', 'O3120X2', 'O3120X3', 'O3120X4', 'O3120X5', 'O3120X9', 'O3121X0', 'O3121X1', 'O3121X2', 'O3121X3', 'O3121X4', 'O3121X5', 'O3121X9', 'O3122X0', 'O3122X1', 'O3122X2', 'O3122X3', 'O3122X4', 'O3122X5', 'O3122X9', 'O3123X0', 'O3123X1', 'O3123X2', 'O3123X3', 'O3123X4', 'O3123X5', 'O3123X9', 'O3130X0', 'O3130X1', 'O3130X2', 'O3130X3', 'O3130X4', 'O3130X5', 'O3130X9', 'O3131X0', 'O3131X1', 'O3131X2', 'O3131X3', 'O3131X4', 'O3131X5', 'O3131X9', 'O3132X0', 'O3132X1', 'O3132X2', 'O3132X3', 'O3132X4', 'O3132X5', 'O3132X9', 'O3133X0', 'O3133X1', 'O3133X2', 'O3133X3', 'O3133X4', 'O3133X5', 'O3133X9', 'O318X10', 'O318X11', 'O318X12', 'O318X13', 'O318X14', 'O318X15', 'O318X19', 'O318X20', 'O318X21', 'O318X22', 'O318X23', 'O318X24', 'O318X25', 'O318X29', 'O318X30', 'O318X31', 'O318X32', 'O318X33', 'O318X34', 'O318X35', 'O318X39', 'O318X90', 'O318X91', 'O318X92', 'O318X93', 'O318X94', 'O318X95', 'O318X99', 'O320XX0', 'O320XX1', 'O320XX2', 'O320XX3', 'O320XX4', 'O320XX5', 'O320XX9', 'O321XX0', 'O321XX1', 'O321XX2', 'O321XX3', 'O321XX4', 'O321XX5', 'O321XX9', 'O322XX0', 'O322XX1', 'O322XX2', 'O322XX3', 'O322XX4', 'O322XX5', 'O322XX9', 'O323XX0', 'O323XX1', 'O323XX2', 'O323XX3', 'O323XX4', 'O323XX5', 'O323XX9', 'O324XX0', 'O324XX1', 'O324XX2', 'O324XX3', 'O324XX4', 'O324XX5', 'O324XX9', 'O326XX0', 'O326XX1', 'O326XX2', 'O326XX3', 'O326XX4', 'O326XX5', 'O326XX9', 'O328XX0', 'O328XX1', 'O328XX2', 'O328XX3', 'O328XX4', 'O328XX5', 'O328XX9', 'O329XX0', 'O329XX1', 'O329XX2', 'O329XX3', 'O329XX4', 'O329XX5', 'O329XX9', 'O330', 'O331', 'O332', 'O333XX0', 'O333XX1', 'O333XX2', 'O333XX3', 'O333XX4', 'O333XX5', 'O333XX9', 'O334XX0', 'O334XX1', 'O334XX2', 'O334XX3', 'O334XX4', 'O334XX5', 'O334XX9', 'O335XX0', 'O335XX1', 'O335XX2', 'O335XX3', 'O335XX4', 'O335XX5', 'O335XX9', 'O336XX0', 'O336XX1', 'O336XX2', 'O336XX3', 'O336XX4', 'O336XX5', 'O336XX9', 'O337XX0', 'O337XX1', 'O337XX2', 'O337XX3', 'O337XX4', 'O337XX5', 'O337XX9', 'O338', 'O339', 'O3400', 'O3401', 'O3402', 'O3403', 'O3410', 'O3411', 'O3412', 'O3413', 'O34211', 'O34212', 'O34219', 'O3429', 'O3430', 'O3431', 'O3432', 'O3433', 'O3440', 'O3441', 'O3442', 'O3443', 'O34511', 'O34512', 'O34513', 'O34519', 'O34521', 'O34522', 'O34523', 'O34529', 'O34531', 'O34532', 'O34533', 'O34539', 'O34591', 'O34592', 'O34593', 'O34599', 'O3460', 'O3461', 'O3462', 'O3463', 'O3470', 'O3471', 'O3472', 'O3473', 'O3480', 'O3481', 'O3482', 'O3483', 'O3490', 'O3491', 'O3492', 'O3493', 'O350XX0', 'O350XX1', 'O350XX2', 'O350XX3', 'O350XX4', 'O350XX5', 'O350XX9', 'O351XX0', 'O351XX1', 'O351XX2', 'O351XX3', 'O351XX4', 'O351XX5', 'O351XX9', 'O352XX0', 'O352XX1', 'O352XX2', 'O352XX3', 'O352XX4', 'O352XX5', 'O352XX9', 'O353XX0', 'O353XX1', 'O353XX2', 'O353XX3', 'O353XX4', 'O353XX5', 'O353XX9', 'O354XX0', 'O354XX1', 'O354XX2', 'O354XX3', 'O354XX4', 'O354XX5', 'O354XX9', 'O355XX0', 'O355XX1', 'O355XX2', 'O355XX3', 'O355XX4', 'O355XX5', 'O355XX9', 'O356XX0', 'O356XX1', 'O356XX2', 'O356XX3', 'O356XX4', 'O356XX5', 'O356XX9', 'O357XX0', 'O357XX1', 'O357XX2', 'O357XX3', 'O357XX4', 'O357XX5', 'O357XX9', 'O358XX0', 'O358XX1', 'O358XX2', 'O358XX3', 'O358XX4', 'O358XX5', 'O358XX9', 'O359XX0', 'O359XX1', 'O359XX2', 'O359XX3', 'O359XX4', 'O359XX5', 'O359XX9', 'O360110', 'O360111', 'O360112', 'O360113', 'O360114', 'O360115', 'O360119', 'O360120', 'O360121', 'O360122', 'O360123', 'O360124', 'O360125', 'O360129', 'O360130', 'O360131', 'O360132', 'O360133', 'O360134', 'O360135', 'O360139', 'O360190', 'O360191', 'O360192', 'O360193', 'O360194', 'O360195', 'O360199', 'O360910', 'O360911', 'O360912', 'O360913', 'O360914', 'O360915', 'O360919', 'O360920', 'O360921', 'O360922', 'O360923', 'O360924', 'O360925', 'O360929', 'O360930', 'O360931', 'O360932', 'O360933', 'O360934', 'O360935', 'O360939', 'O360990', 'O360991', 'O360992', 'O360993', 'O360994', 'O360995', 'O360999', 'O361110', 'O361111', 'O361112', 'O361113', 'O361114', 'O361115', 'O361119', 'O361120', 'O361121', 'O361122', 'O361123', 'O361124', 'O361125', 'O361129', 'O361130', 'O361131', 'O361132', 'O361133', 'O361134', 'O361135', 'O361139', 'O361190', 'O361191', 'O361192', 'O361193', 'O361194', 'O361195', 'O361199', 'O361910', 'O361911', 'O361912', 'O361913', 'O361914', 'O361915', 'O361919', 'O361920', 'O361921', 'O361922', 'O361923', 'O361924', 'O361925', 'O361929', 'O361930', 'O361931', 'O361932', 'O361933', 'O361934', 'O361935', 'O361939', 'O361990', 'O361991', 'O361992', 'O361993', 'O361994', 'O361995', 'O361999', 'O3620X0', 'O3620X1', 'O3620X2', 'O3620X3', 'O3620X4', 'O3620X5', 'O3620X9', 'O3621X0', 'O3621X1', 'O3621X2', 'O3621X3', 'O3621X4', 'O3621X5', 'O3621X9', 'O3622X0', 'O3622X1', 'O3622X2', 'O3622X3', 'O3622X4', 'O3622X5', 'O3622X9', 'O3623X0', 'O3623X1', 'O3623X2', 'O3623X3', 'O3623X4', 'O3623X5', 'O3623X9', 'O364XX0', 'O364XX1', 'O364XX2', 'O364XX3', 'O364XX4', 'O364XX5', 'O364XX9', 'O365110', 'O365111', 'O365112', 'O365113', 'O365114', 'O365115', 'O365119', 'O365120', 'O365121', 'O365122', 'O365123', 'O365124', 'O365125', 'O365129', 'O365130', 'O365131', 'O365132', 'O365133', 'O365134', 'O365135', 'O365139', 'O365190', 'O365191', 'O365192', 'O365193', 'O365194', 'O365195', 'O365199', 'O365910', 'O365911', 'O365912', 'O365913', 'O365914', 'O365915', 'O365919', 'O365920', 'O365921', 'O365922', 'O365923', 'O365924', 'O365925', 'O365929', 'O365930', 'O365931', 'O365932', 'O365933', 'O365934', 'O365935', 'O365939', 'O365990', 'O365991', 'O365992', 'O365993', 'O365994', 'O365995', 'O365999', 'O3660X0', 'O3660X1', 'O3660X2', 'O3660X3', 'O3660X4', 'O3660X5', 'O3660X9', 'O3661X0', 'O3661X1', 'O3661X2', 'O3661X3', 'O3661X4', 'O3661X5', 'O3661X9', 'O3662X0', 'O3662X1', 'O3662X2', 'O3662X3', 'O3662X4', 'O3662X5', 'O3662X9', 'O3663X0', 'O3663X1', 'O3663X2', 'O3663X3', 'O3663X4', 'O3663X5', 'O3663X9', 'O3670X0', 'O3670X1', 'O3670X2', 'O3670X3', 'O3670X4', 'O3670X5', 'O3670X9', 'O3671X0', 'O3671X1', 'O3671X2', 'O3671X3', 'O3671X4', 'O3671X5', 'O3671X9', 'O3672X0', 'O3672X1', 'O3672X2', 'O3672X3', 'O3672X4', 'O3672X5', 'O3672X9', 'O3673X0', 'O3673X1', 'O3673X2', 'O3673X3', 'O3673X4', 'O3673X5', 'O3673X9', 'O368120', 'O368121', 'O368122', 'O368123', 'O368124', 'O368125', 'O368129', 'O368130', 'O368131', 'O368132', 'O368133', 'O368134', 'O368135', 'O368139', 'O368190', 'O368191', 'O368192', 'O368193', 'O368194', 'O368195', 'O368199', 'O368210', 'O368211', 'O368212', 'O368213', 'O368214', 'O368215', 'O368219', 'O368220', 'O368221', 'O368222', 'O368223', 'O368224', 'O368225', 'O368229', 'O368230', 'O368231', 'O368232', 'O368233', 'O368234', 'O368235', 'O368239', 'O368290', 'O368291', 'O368292', 'O368293', 'O368294', 'O368295', 'O368299', 'O368910', 'O368911', 'O368912', 'O368913', 'O368914', 'O368915', 'O368919', 'O368920', 'O368921', 'O368922', 'O368923', 'O368924', 'O368925', 'O368929', 'O368930', 'O368931', 'O368932', 'O368933', 'O368934', 'O368935', 'O368939', 'O368990', 'O368991', 'O368992', 'O368993', 'O368994', 'O368995', 'O368999', 'O3690X0', 'O3690X1', 'O3690X2', 'O3690X3', 'O3690X4', 'O3690X5', 'O3690X9', 'O3691X0', 'O3691X1', 'O3691X2', 'O3691X3', 'O3691X4', 'O3691X5', 'O3691X9', 'O3692X0', 'O3692X1', 'O3692X2', 'O3692X3', 'O3692X4', 'O3692X5', 'O3692X9', 'O3693X0', 'O3693X1', 'O3693X2', 'O3693X3', 'O3693X4', 'O3693X5', 'O3693X9', 'O401XX0', 'O401XX1', 'O401XX2', 'O401XX3', 'O401XX4', 'O401XX5', 'O401XX9', 'O402XX0', 'O402XX1', 'O402XX2', 'O402XX3', 'O402XX4', 'O402XX5', 'O402XX9', 'O403XX0', 'O403XX1', 'O403XX2', 'O403XX3', 'O403XX4', 'O403XX5', 'O403XX9', 'O409XX0', 'O409XX1', 'O409XX2', 'O409XX3', 'O409XX4', 'O409XX5', 'O409XX9', 'O4100X0', 'O4100X1', 'O4100X2', 'O4100X3', 'O4100X4', 'O4100X5', 'O4100X9', 'O4101X0', 'O4101X1', 'O4101X2', 'O4101X3', 'O4101X4', 'O4101X5', 'O4101X9', 'O4102X0', 'O4102X1', 'O4102X2', 'O4102X3', 'O4102X4', 'O4102X5', 'O4102X9', 'O4103X0', 'O4103X1', 'O4103X2', 'O4103X3', 'O4103X4', 'O4103X5', 'O4103X9', 'O411010', 'O411011', 'O411012', 'O411013', 'O411014', 'O411015', 'O411019', 'O411020', 'O411021', 'O411022', 'O411023', 'O411024', 'O411025', 'O411029', 'O411030', 'O411031', 'O411032', 'O411033', 'O411034', 'O411035', 'O411039', 'O411090', 'O411091', 'O411092', 'O411093', 'O411094', 'O411095', 'O411099', 'O411210', 'O411211', 'O411212', 'O411213', 'O411214', 'O411215', 'O411219', 'O411220', 'O411221', 'O411222', 'O411223', 'O411224', 'O411225', 'O411229', 'O411230', 'O411231', 'O411232', 'O411233', 'O411234', 'O411235', 'O411239', 'O411290', 'O411291', 'O411292', 'O411293', 'O411294', 'O411295', 'O411299', 'O411410', 'O411411', 'O411412', 'O411413', 'O411414', 'O411415', 'O411419', 'O411420', 'O411421', 'O411422', 'O411423', 'O411424', 'O411425', 'O411429', 'O411430', 'O411431', 'O411432', 'O411433', 'O411434', 'O411435', 'O411439', 'O411490', 'O411491', 'O411492', 'O411493', 'O411494', 'O411495', 'O411499', 'O418X10', 'O418X11', 'O418X12', 'O418X13', 'O418X14', 'O418X15', 'O418X19', 'O418X20', 'O418X21', 'O418X22', 'O418X23', 'O418X24', 'O418X25', 'O418X29', 'O418X30', 'O418X31', 'O418X32', 'O418X33', 'O418X34', 'O418X35', 'O418X39', 'O418X90', 'O418X91', 'O418X92', 'O418X93', 'O418X94', 'O418X95', 'O418X99', 'O4190X0', 'O4190X1', 'O4190X2', 'O4190X3', 'O4190X4', 'O4190X5', 'O4190X9', 'O4191X0', 'O4191X1', 'O4191X2', 'O4191X3', 'O4191X4', 'O4191X5', 'O4191X9', 'O4192X0', 'O4192X1', 'O4192X2', 'O4192X3', 'O4192X4', 'O4192X5', 'O4192X9', 'O4193X0', 'O4193X1', 'O4193X2', 'O4193X3', 'O4193X4', 'O4193X5', 'O4193X9', 'O4200', 'O42011', 'O42012', 'O42013', 'O42019', 'O4202', 'O4210', 'O42111', 'O42112', 'O42113', 'O42119', 'O4212', 'O4290', 'O42911', 'O42912', 'O42913', 'O42919', 'O4292', 'O43011', 'O43012', 'O43013', 'O43019', 'O43021', 'O43022', 'O43023', 'O43029', 'O43101', 'O43102', 'O43103', 'O43109', 'O43111', 'O43112', 'O43113', 'O43119', 'O43121', 'O43122', 'O43123', 'O43129', 'O43191', 'O43192', 'O43193', 'O43199', 'O43211', 'O43212', 'O43213', 'O43219', 'O43221', 'O43222', 'O43223', 'O43229', 'O43231', 'O43232', 'O43233', 'O43239', 'O43811', 'O43812', 'O43813', 'O43819', 'O43891', 'O43892', 'O43893', 'O43899', 'O4390', 'O4391', 'O4392', 'O4393', 'O4400', 'O4401', 'O4402', 'O4403', 'O4410', 'O4411', 'O4412', 'O4413', 'O4420', 'O4421', 'O4422', 'O4423', 'O4430', 'O4431', 'O4432', 'O4433', 'O4440', 'O4441', 'O4442', 'O4443', 'O4450', 'O4451', 'O4452', 'O4453', 'O45001', 'O45002', 'O45003', 'O45009', 'O45011', 'O45012', 'O45013', 'O45019', 'O45021', 'O45022', 'O45023', 'O45029', 'O45091', 'O45092', 'O45093', 'O45099', 'O458X1', 'O458X2', 'O458X3', 'O458X9', 'O4590', 'O4591', 'O4592', 'O4593', 'O46001', 'O46002', 'O46003', 'O46009', 'O46011', 'O46012', 'O46013', 'O46019', 'O46021', 'O46022', 'O46023', 'O46029', 'O46091', 'O46092', 'O46093', 'O46099', 'O468X1', 'O468X2', 'O468X3', 'O468X9', 'O4690', 'O4691', 'O4692', 'O4693', 'O4700', 'O4702', 'O4703', 'O471', 'O479', 'O480', 'O481', 'O6000', 'O6002', 'O6003', 'O7100', 'O7102', 'O7103', 'O88011', 'O88012', 'O88013', 'O88019', 'O88111', 'O88112', 'O88113', 'O88119', 'O88211', 'O88212', 'O88213', 'O88219', 'O88311', 'O88312', 'O88313', 'O88319', 'O88811', 'O88812', 'O88813', 'O88819', 'O903', 'O91011', 'O91012', 'O91013', 'O91019', 'O91111', 'O91112', 'O91113', 'O91119', 'O91211', 'O91212', 'O91213', 'O91219', 'O92011', 'O92012', 'O92013', 'O92019', 'O92111', 'O92112', 'O92113', 'O92119', 'O9220', 'O9229', 'O98011', 'O98012', 'O98013', 'O98019', 'O98111', 'O98112', 'O98113', 'O98119', 'O98211', 'O98212', 'O98213', 'O98219', 'O98311', 'O98312', 'O98313', 'O98319', 'O98411', 'O98412', 'O98413', 'O98419', 'O98511', 'O98512', 'O98513', 'O98519', 'O98611', 'O98612', 'O98613', 'O98619', 'O98711', 'O98712', 'O98713', 'O98719', 'O98811', 'O98812', 'O98813', 'O98819', 'O98911', 'O98912', 'O98913', 'O98919', 'O99011', 'O99012', 'O99013', 'O99019', 'O99111', 'O99112', 'O99113', 'O99119', 'O99210', 'O99211', 'O99212', 'O99213', 'O99280', 'O99281', 'O99282', 'O99283', 'O99310', 'O99311', 'O99312', 'O99313', 'O99320', 'O99321', 'O99322', 'O99323', 'O99330', 'O99331', 'O99332', 'O99333', 'O99340', 'O99341', 'O99342', 'O99343', 'O99350', 'O99351', 'O99352', 'O99353', 'O99411', 'O99412', 'O99413', 'O99419', 'O99511', 'O99512', 'O99513', 'O99519', 'O99611', 'O99612', 'O99613', 'O99619', 'O99711', 'O99712', 'O99713', 'O99719', 'O99810', 'O99820', 'O99830', 'O99840', 'O99841', 'O99842', 'O99843', 'O9989', 'O9A111', 'O9A112', 'O9A113', 'O9A119', 'O9A211', 'O9A212', 'O9A213', 'O9A219', 'O9A311', 'O9A312', 'O9A313', 'O9A319', 'O9A411', 'O9A412', 'O9A413', 'O9A419', 'O9A511', 'O9A512', 'O9A513', 'O9A519', 'Z331', 'Z333', 'Z3400', 'Z3401', 'Z3402', 'Z3403', 'Z3480', 'Z3481', 'Z3482', 'Z3483', 'Z3490', 'Z3491', 'Z3492', 'Z3493' } SNOMEDCT = { '10231000132102', '102872000', '102873005', '102875003', '11082009', '127364007', '134781000119106', '14080002', '14418008', '16356006', '16836261000119107', '16836351000119100', '16836391000119105', '16836891000119104', '169560008', '169561007', '169562000', '169563005', '169564004', '169565003', '169566002', '169567006', '169568001', '17285009', '198624007', '198626009', '198627000', '199064003', '199306007', '22281000119101', '237233002', '237238006', '237239003', '237240001', '237241002', '237242009', '237244005', '237254009', '248985009', '276367008', '276881003', '281307002', '314204000', '31601007', '34801009', '35381000119101', '35656003', '36801000119105', '38720006', '41587001', '41991004', '429187001', '43990006', '442478007', '444661007', '44782008', '45307008', '457811000124103', '457821000124106', '459167000', '459169002', '459170001', '47200007', '472321009', '57630001', '58532003', '59466002', '60000008', '60810003', '64254006', '65147003', '65727000', '713575004', '713576003', '72892002', '77386006', '786067000', '79290002', '79586000', '80997009', '82661006', '83074005', '87527008', '87605005', '90968009', '9279009',
doc.create(Tabular(tab_spec, pos='htb')) as table: write_header_tabular(table, variable, tab_spec.count('c')) if tab_spec == '|cc|ccc|': write_data_only_tabular(table, variable, kwargs['cur_mean'], kwargs['cur_min'], kwargs['cur_max'], kwargs['cur_min_time'], kwargs['cur_max_time']) elif tab_spec == '|cc|c|cccc|c|': write_qc_only_tabular(table, kwargs['sum_good'], kwargs['sum_prob_good'], kwargs['sum_prob_bad'], kwargs['sum_bad'], kwargs['sum_spike'], kwargs['sum_nan'], kwargs['percent_good'], kwargs['percent_rest'], kwargs['percent_nan']) elif tab_spec == '|cc|c|cccc|c|c|ccc|': write_data_and_qc_tabular(table, variable, kwargs['sum_good'], kwargs['sum_prob_good'], kwargs['sum_prob_bad'], kwargs['sum_bad'], kwargs['sum_spike'], kwargs['sum_nan'], kwargs['cur_mean'], kwargs['cur_min'], kwargs['cur_max'], kwargs['percent_good'], kwargs['percent_rest'], kwargs['percent_nan'], kwargs['cur_min_time'], kwargs['cur_max_time']) elif tab_spec == '|c|c|c|c|c|': write_specific_statistics_tabular(table, variable, kwargs['v_mean'], kwargs['v_std'], kwargs['v_min'], kwargs['v_max'], kwargs['v_good_percent']) else: logger.warning('Undefined tabular specification.') table.add_hline() t.add_caption('Data Summary for ' + get_standard_name(variable) + ' in ' + month_str + ' ' + str(year) + '.') doc.append(NoEscape(r'\end{center}')) def get_time_str_from_converted_time_idx(idx, converted_time): return md.num2date(converted_time[idx]).strftime("%Y-%m-%d %H:%M:%S") def get_mean_min_max(data, time_ref=None): if time_ref is None: # Makes only sense for timeless data. pass else: cur_mean = np.nanmean(data) mean_time_str = '' cur_min = np.nanmin(data) cur_min_idx = np.where(data == cur_min) min_time_str = get_time_str_from_converted_time_idx(cur_min_idx[0][0], time_ref) cur_max = np.nanmax(data) cur_max_idx = np.where(data == cur_max) max_time_str = get_time_str_from_converted_time_idx(cur_max_idx[0][0], time_ref) return cur_mean, mean_time_str, cur_min, min_time_str, cur_max, max_time_str def plot_histogram_radial_files(doc, stations_end_time, stations_bins): with doc.create(Figure(position='htbp')) as plot: plt.figure(figsize=(11,5)) galf_bar = plt.bar(stations_end_time[0:len(stations_end_time)/2], stations_bins['GALF'], color='cornflowerblue', align='center', width=8) form_bar = plt.bar(stations_end_time[0:len(stations_end_time)/2], stations_bins['FORM'], color='lightcoral', align='center', bottom=stations_bins['GALF'], width=8) ax = plt.gca() ax.set_xticks(stations_end_time[0:len(stations_end_time)/2]) x_labels = [] for dt in stations_end_time[0:len(stations_end_time)/2]: x_labels.append(str(dt.day) + '.' + str(dt.month) + '.' + str(dt.year)) ax.set_xticklabels(x_labels, rotation=45, horizontalalignment='right', rotation_mode='anchor') ax.tick_params(direction='out', axis='y', pad=15) ax.set_ylim([0, 600]) plt.title('Number of radial files per 10 days.') plt.xticks(stations_end_time[0:len(stations_end_time)/2]) plt.legend((galf_bar, form_bar), ('GALF', 'FORM')) plt.tight_layout() plot.add_plot(width=NoEscape(r'1\textwidth')) plot.add_caption('Number of radial files') plt.clf() plt.close('all') def plot_threshold_graph(doc, x_data, y_data, lower_threshold, upper_threshold, variable, year, month_str, x_limits=None): if x_limits is None: x_limits = [x_data[0], x_data[-1]] try: title_name = variable.long_name + ' (' + variable.name + ')' except AttributeError: logger.info(variable.name + ' has no long name.') try: title_name = variable.standard_name + ' (' + variable.name + ')' except AttributeError: logger.info(variable.name + ' has no standard name.') title_name = variable.name with doc.create(Figure(position='htbp')) as plot: plt.figure() plt.plot(x_data, y_data, 'k', linewidth=1, ) if lower_threshold is not None: lower_line = np.ones((1, len(x_data)))[0] * lower_threshold plt.fill_between(x_data, lower_line, y_data, facecolor='gray', alpha=0.5) # plt.plot(x_data, lower_line, '-r', linewidth=1, ) if upper_threshold is not None: upper_line = np.ones((1, len(x_data)))[0] * upper_threshold # plt.plot(x_data, upper_line, '-r', linewidth=1, ) plt.fill_between(x_data, y_data, upper_line, facecolor='gray', alpha=0.5) data_axis = plt.gca() data_axis.xaxis.set_major_formatter(c.settings.xfmt) if variable.units == '1': cur_units = '' else: cur_units = variable.units data_axis.set_ylabel(cur_units, rotation=0, horizontalalignment='right') data_axis.grid(b=False, which='major', color='k', linestyle='--', linewidth=0.25) # data_axis.set_ylim([data_axis.get_ylim()[0] - 5, data_axis.get_ylim()[1] + 5]) plt.margins(y=0.1) data_axis.set_xlim(x_limits) data_axis.get_yaxis().get_major_formatter().set_useOffset(False) plt.title('\n'.join(wrap(title_name, 70))) plt.gcf().autofmt_xdate() plt.gcf().set_size_inches(11, 3) data_axis.set_xticks(np.arange(x_limits[0], x_limits[1]+1, 5.0)) data_axis.locator_params(axis='y', nbins=6) plt.tight_layout() plt.subplots_adjust(top=0.8) plot.add_plot(width=NoEscape(r'1\textwidth')) plot.add_caption('Evolution of ' + title_name + ' and indicating valid thresholds in ' + month_str + ' ' + str(year) + '.') plt.clf() plt.close('all') def get_hf_simple_statistics(data, data_qc=None): data_mean = np.nanmean(data) data_std = np.nanstd(data) data_min = np.nanmin(data) data_max = np.nanmax(data) if data_qc is None: good_percent = None else: good_idx = data_qc == 1 good_amount = np.where(good_idx == 1)[0] good_percent = float(len(good_amount))/len(data_qc)*100 return data_mean, data_std, data_min, data_max, good_percent def get_hf_radial_site_file_size(dir_path, elements, threshold): file_counter = 0 good_counter = 0 for e in elements: if e[0:4] == 'RDLi': continue file_counter += 1 cur_path = dir_path + '' + e cur_size = os.stat(cur_path) cur_size = cur_size.st_size/1024.0 if cur_size > threshold: good_counter += 1 good_percent = float(good_counter)/file_counter*100 return good_percent, file_counter, good_counter def get_hf_radial_sites_file_sizes(galf_path, galf_elements, form_path, form_elements, totals_path, totals_elements, galf_threshold, form_threshold, total_threshold): galf_good_percent, _, _ = get_hf_radial_site_file_size(galf_path, galf_elements, galf_threshold) form_good_percent, _, _ = get_hf_radial_site_file_size(form_path, form_elements, form_threshold) totals_good_percent, _, _ = get_hf_radial_site_file_size(totals_path, totals_elements, total_threshold) logger.info('Galfi good percent: ' + str(galf_good_percent)) logger.info('Formentera good percent: ' + str(form_good_percent)) logger.info('Total good percent: ' + str(totals_good_percent)) return galf_good_percent, form_good_percent, totals_good_percent def plot_temporal_and_spatial_availability(doc, temporal_avail_percent, non_zero_sorted_spatial_avail, temp_avail): red_x = np.arange(0, 100, 0.01) red_y = np.zeros((1, 10000))[0] red_y[0:8000] = 80 red_x[8001] = red_x[7999] cur_x = temporal_avail_percent cur_x = np.append(cur_x, [100.]) cur_y = non_zero_sorted_spatial_avail cur_y = np.append(cur_y, [0.]) f = interpolate.interp1d(cur_x, cur_y) interpolated_temporal_data = np.arange(0, 100, 0.01) interpolated_spatial_data = f(interpolated_temporal_data) idx = interpolated_temporal_data <= 80 with doc.create(Figure(position='htbp')) as plot: plt.figure() plt.plot(interpolated_temporal_data, interpolated_spatial_data) plt.plot(red_x, red_y, color='red') plt.fill_between(interpolated_temporal_data, interpolated_spatial_data, red_y, where=red_y >= interpolated_spatial_data, facecolor='salmon', interpolate=True) data_axis = plt.gca() data_axis.set_ylabel('%', rotation=0, horizontalalignment='right') data_axis.set_xlabel('%') data_axis.grid(b=False, which='major', color='k', linestyle='--', linewidth=0.25) data_axis.get_yaxis().get_major_formatter().set_useOffset(False) cur_title = 'Spatial vs Temporal Availability' if np.all(interpolated_spatial_data[idx]>=80): cur_title += '. The MARACOOS metric for long range data coverage and availability has surpassed the 80% coverage 80% of the time during this period.' plt.title('\n'.join(wrap(cur_title, 90))) plt.gcf().set_size_inches(11, 3) data_axis.locator_params(axis='y', nbins=6) plt.tight_layout() plt.subplots_adjust(top=0.8) plot.add_plot(width=NoEscape(r'1\textwidth')) plot.add_caption('Spatial (x-axis) vs Temporal (y-axis) Availability') plt.clf() plt.close('all') def plot_spatial_availability(doc, lon2, lat2, masked_array, basemap1): mycmap = mp.cm.Greens mycmap.set_bad('w', 0.0) lon2, lat2 = basemap1(lon2, lat2) with doc.create(Figure(position='htbp')) as plot: plt.figure() basemap1.drawcoastlines(linewidth=.25, zorder=3) basemap1.drawmapboundary(fill_color='white') basemap1.drawparallels(np.arange(30., 40., 1.), labels=[True, False, True, False], zorder=2) basemap1.drawmeridians(np.arange(-10., 2., 1.), labels=[False, True, False, True], zorder=2) q = basemap1.pcolor(lon2, lat2, masked_array, cmap=mycmap, zorder=4) plt.clim(0, 100) divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", size="5%", pad=0.05) bounds = np.linspace(0,100,11) norm = mp.colors.BoundaryNorm(bounds, mycmap.N) # cb = plt.colorbar(q, cax=cax) cb = mp.colorbar.ColorbarBase(cax, cmap=mycmap, norm=norm, spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i') cb.set_label(r'%', rotation=0, labelpad=15) plot.add_plot(width=NoEscape(r'1\textwidth')) plot.add_caption('Gridded Availabilty of Data') plt.clf() plt.close('all') def plot_hf_temporal_availability(doc, form_path, galf_path, hf_time, year, month): form_elements = sorted(os.listdir(form_path)) galf_elements = sorted(os.listdir(galf_path)) logger.info('Formentera ' + str(len(form_elements)) + ' entries. Galfi ' + str(len(galf_elements)) + '.') pattern_search = str(year) + '_' + str(month).zfill(2) + '_' last_day = 1 last_hour = 0 form_missing_times = get_missing_times(form_elements, pattern_search, last_day, last_hour, year, month) galf_missing_times = get_missing_times(galf_elements, pattern_search, last_day, last_hour, year, month) non_nan_hf_time_form = np.asarray(md.date2num([datetime.fromtimestamp(ts, tz=pytz.utc) for ts in np.copy(hf_time)])) non_nan_hf_time_galf = np.asarray(md.date2num([datetime.fromtimestamp(ts, tz=pytz.utc) for ts in np.copy(hf_time)])) for m_t in form_missing_times: if m_t in hf_time: temp_idx = np.where(hf_time == m_t)[0] non_nan_hf_time_form[temp_idx] = np.nan ibiz_nan_idx = np.isnan(non_nan_hf_time_form) for m_t in galf_missing_times: if m_t in hf_time: temp_idx = np.where(hf_time == m_t)[0] non_nan_hf_time_galf[temp_idx] = np.nan data_form = np.ones((len(non_nan_hf_time_form), 1)) - 0.5 data_galf = np.ones((len(non_nan_hf_time_galf), 1)) plot_horizontal_fat_lines(doc, non_nan_hf_time_form, data_form, non_nan_hf_time_galf, data_galf) return np.logical_or(ibiz_nan_idx, np.isnan(non_nan_hf_time_galf)) def plot_horizontal_fat_lines(doc, time_one, data_one, time_two, data_two, x_limits=None): if x_limits is None: if np.nanmin(time_one) < np.nanmin(time_two): start_time = np.nanmin(time_one) else: start_time = np.nanmin(time_two) if np.nanmax(time_one) > np.nanmax(time_two): end_time = np.nanmax(time_one) else: end_time = np.nanmax(time_two) x_limits = [start_time, end_time] with doc.create(Figure(position='htbp')) as plot: f = plt.figure() plt.plot(time_one, data_one, color='k', linewidth=4.0) plt.plot(time_two, data_two, color='g', linewidth=4.0) data_axis = plt.gca() data_axis.xaxis.set_major_formatter(c.settings.xfmt) data_axis.set_ylabel('', rotation=0, horizontalalignment='right') data_axis.set_xlim(x_limits) plt.title('\n'.join(wrap('Temporal availability', 70))) f.set_size_inches(11, 3) f.autofmt_xdate() plt.yticks([0.5, 1], ['Form', 'Galf']) plt.ylim([0, 1.5]) plt.grid() data_axis.set_xticks(np.arange(x_limits[0], x_limits[1] + 1, 5.0)) plt.tight_layout() plot.add_plot(width=NoEscape(r'1\textwidth')) plot.add_caption('Form and Galf temporal availability') plt.clf() plt.close('all') def totimestamp(dt, epoch=datetime(1970, 1, 1)): td = dt - epoch return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 def get_missing_times(elements, pattern, last_day, last_hour, year, month): missing_times = [] for cur_file in elements: if last_hour == 23: last_hour = 0 last_day += 1 else: last_hour += 1 temp_idx = cur_file.find(pattern) if temp_idx == -1: # fix invalid file name logger.info('Invalid file found {0}'.format(cur_file)) continue cur_day_hour = cur_file[temp_idx + len(pattern):-4] cur_day = int(cur_day_hour[0:2]) cur_hour = int(cur_day_hour[3:-2]) if (cur_hour != last_hour) and (cur_day != last_day): day_difference = cur_day - last_day hour_difference = day_difference * 24 + cur_hour - last_hour missing_times.extend(create_missing_times(year, month, last_day, last_hour, hour_difference)) last_day = cur_day last_hour = cur_hour return np.unique(missing_times) def create_missing_times(year, month, start_day, start_hour, hour_difference): temp_times = [] for i in range(1, hour_difference + 1): if start_hour == 24: start_day += 1 start_hour = 0 temp_times.append(totimestamp(datetime(year, month, start_day, start_hour))) start_hour += 1 return temp_times def compare_angles(data1, data2): return (data2 - data1 + 180) % 360 - 180 def plot_overlapping_1d_graphs(doc, cur_time, data_one, data_two, year, month_str, x_limits=None, title_str=None, y_label=None, is_degree_0_360_y_limit=False): if x_limits is None: x_limits = [cur_time[0], cur_time[-1]] if y_label is None: y_label == '' elif y_label == '1': y_label = '' if title_str is None: title_str = '' with doc.create(Figure(position='htbp')) as plot: plt.figure() plt.plot(cur_time, data_one, color='k', linewidth=0.5) plt.plot(cur_time, data_two, color='b', linewidth=0.5) data_axis = plt.gca() data_axis.xaxis.set_major_formatter(c.settings.xfmt) y_label = transform_y_label(y_label) data_axis.set_ylabel(y_label, rotation=0, horizontalalignment='right') data_axis.grid(b=False, which='major', color='k', linestyle='--', linewidth=0.25) data_axis.set_xlim(x_limits) data_axis.get_yaxis().get_major_formatter().set_useOffset(False) plt.title('\n'.join(wrap(title_str, 80))) plt.gcf().autofmt_xdate() plt.gcf().set_size_inches(11, 3) data_axis.set_xticks(np.arange(x_limits[0], x_limits[1]+1, 5.0)) has_set_ticks = False if is_degree_0_360_y_limit: data_axis.set_ylim([0, 360]) data_axis.set_yticks([0, 90, 180, 270, 360]) has_set_ticks = True if not has_set_ticks: data_axis.yaxis.set_major_locator(mp.ticker.MaxNLocator(nbins=6, trim=False)) # data_axis.locator_params(axis='y', nbins=6) plt.tight_layout() plt.subplots_adjust(top=0.8) plot.add_plot(width=NoEscape(r'1\textwidth')) plot.add_caption(title_str + ' in ' + month_str + ' ' + str(year) + '.') plt.clf() plt.close('all') def get_idx_closest_grid_point(lat_1d_vector, lon_1d_vector, reference_lat, reference_lon): return np.searchsorted(lat_1d_vector, reference_lat), np.searchsorted(lon_1d_vector, reference_lon) - 1 def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100): new_cmap = mp.colors.LinearSegmentedColormap.from_list( 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval), cmap(np.linspace(minval, maxval, n))) return new_cmap def hf_monthly_mean_direction_plot(doc, u_mean, v_mean, np_longrid, np_latgrid, basemap, buoy_lat,
<filename>model_zoo/model_networks.py import numpy as np import cv2 import torch import torch.nn as nn import torch.nn.functional as F from torch import autograd import math import random import time from tensorboardX import SummaryWriter from model_base_layers import PixelwiseNormalization, TruncationTrick from model_blocks import GeneratorMappingBlock, GeneratorSynthesisInputBlock, GeneratorSynthesisBlock, \ DiscriminatorBlock, DiscriminatorLastBlock, ConvLayer # from model_loss import # from dataset import Dataset ################################################################################################### ### Sub Networks: Generator Mapping and Synthesis ### ################################################################################################### class GeneratorMapping(nn.Module): def __init__(self, resolution=1024, latent_size=512, dlatent_size=512, mapping_layers=8, mapping_fmaps=512, mapping_lr=0.01, mapping_nonlinearity='lrelu', normalize_latents=True, **_kwargs): """ Mapping network used in the StyleGAN paper. latent_size: Latent vector(Z) dimensionality. dlatent_size: Disentangled latent (W) dimensionality. mapping_layers: Number of mapping layers. mapping_fmaps: Number of activations in the mapping layers. mapping_lr: Learning rate for the mapping layers. mapping_nonlinearity: Activation function: 'relu', 'lrelu'. normalize_latents: Normalize latent vectors (Z) before feeding them to the mapping layers? **_kwargs: Ignore unrecognized keyword args. """ super().__init__() self.latent_size = latent_size self.dlatent_size = dlatent_size self.mapping_fmaps = mapping_fmaps self.normalize_latents = normalize_latents self.resolution_log2 = int(np.log2(resolution)) self.n_latent = self.resolution_log2 * 2 - 2 layers = [] # build a first layer for pixel wise normalization layers.append(PixelwiseNormalization()) # build intermediate layers for layer_idx in range(0, mapping_layers): in_fmaps = self.latent_size if layer_idx==0 else self.mapping_fmaps out_fmaps = self.dlatent_size if layer_idx==0 else self.mapping_fmaps layers.append(GeneratorMappingBlock(in_fmaps=in_fmaps, out_fmaps=out_fmaps)) # build a last layer for truncation trick layers.append(TruncationTrick(num_target=10, threshold=1.0, out_num=self.n_latent, dlatent_size=512)) # threshold=0.7 self.blocks = nn.ModuleList(layers) # # display layers # print('Generator Mapping Network: ') # print(self.model) def forward(self, latents_in): """ Args: latents_in: First input: Latent vectors (Z) [minibatch, latent_size]. ex, [4, 512] dlatents_out: Latent vectors (W) [N 18, D] = [4, 18, 512] """ x = latents_in for i in range(len(self.blocks)): x = self.blocks[i](x) dlatents_out = x return dlatents_out class GeneratorSynthesis(nn.Module): def __init__(self, dlatent_size=512, num_channels=3, resolution=1024, fmap_base=16 << 10, fmap_decay=1.0, fmap_min=1, fmap_max=512, randomize_noise=True, architecture='skip', **_kwargs): """ Args: dlatent_size: Disentangled latent (W) dimensionality. num_channels: Number of output color channels. resolution: Output resolution. fmap_base: Overall multiplier for the number of feature maps. fmap_decay: log2 feature map reduction when doubling the resolution. fmap_min: Minimum number of feature maps in any layer. fmap_max: Maximum number of feature maps in any layer. randomize_noise: True = randomize noise inputs every time (non-deterministic), False = read noise inputs from variables. architecture: 'orig', 'skip', 'resnet'. **_kwargs: Ignore unrecognized keyword args.): """ super().__init__() resolution_log2 = int(np.log2(resolution)) assert resolution == 2 ** resolution_log2 and resolution >= 4 assert architecture in ['orig', 'skip', 'resnet'] self.architecture = architecture self.resolution_log2 = resolution_log2 self.randomize_noise = randomize_noise def nf(stage): return np.clip(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_min, fmap_max) # build early layers # nf(1) = 512 self.init_block = GeneratorSynthesisInputBlock(dlatent_size=dlatent_size, num_channels=num_channels, in_fmaps=nf(1), out_fmaps=nf(1), use_noise=randomize_noise) # build all the remaining layers # blocks / in / out # 0 512 512 # 1 512 512 # 2 512 512 # 3 512 512 # 4 512 256 # 5 256 128 # 6 128 64 # 7 64 32 blocks = [GeneratorSynthesisBlock(dlatent_size=dlatent_size, num_channels=num_channels, res=res, in_fmaps=nf(res - 2), out_fmaps=nf(res - 1), use_noise=randomize_noise) for res in range(3, resolution_log2 + 1)] self.blocks = nn.ModuleList(blocks) def forward(self, dlatents_in): """ Args: dlatents_in: Input: Disentangled latents (W) [minibatch, num_layers, dlatent_size]. ex. [4, 18, 512] Returns: images """ x, skip = self.init_block(dlatents_in) for block in self.blocks: x, skip = block(x, dlatents_in, skip) images = skip return images ################################################################################################### ### Main Networks: Generator and Discriminator ### ################################################################################################### class Generator(nn.Module): def __init__(self, resolution=1024, latent_size=512, dlatent_size=512, **_kwargs): """ Args: latent_size: Latent vector(Z) dimensionality. dlatent_size: Disentangled latent (W) dimensionality. """ super().__init__() self.resolution_log2 = int(np.log2(resolution)) self.n_latent = self.resolution_log2 * 2 - 2 ## synthetic rate for synthetic images / do not use this time # self.register_buffer('style_mixing_rate', torch.zeros((1,))) # set up sub networks self.mapping_network = GeneratorMapping( resolution=resolution, latent_size=latent_size, dlatent_size=dlatent_size, **_kwargs ) self.synthesis_network = GeneratorSynthesis(resolution=resolution, **_kwargs) def forward(self,latents_in, return_dlatents=False): """ Args: latents_in: First input: Latent vectors (Z) [minibatch, latent_size]. ([4, 512], [4, 512]) or [[4, 512]] return_dlatents: Return dlatents in addition to the images? (labels_in: Second input: Conditioning labels [minibatch, label_size].) Returns: images """ dlatents_out = [self.mapping_network(latent) for latent in latents_in] if len(dlatents_out) < 2: dlatents_in = dlatents_out[0] else: inject_id = random.randint(1, self.n_latent - 1) dlatents_out1 = dlatents_out[0][:, :inject_id] dlatents_out2 = dlatents_out[1][:, inject_id:] dlatents_in = torch.cat([dlatents_out1, dlatents_out2], 1) imgs_out = self.synthesis_network(dlatents_in) if return_dlatents: noise = torch.randn_like(imgs_out) / math.sqrt(imgs_out.shape[2] * imgs_out.shape[3]) grad, = autograd.grad(outputs=(imgs_out * noise).sum(), inputs=dlatents_in, create_graph=True) return imgs_out, dlatents_in, grad else: return imgs_out class Discriminator(nn.Module): def __init__(self, num_channels=3, resolution=1024, fmap_base=16 << 10, fmap_decay=1.0, fmap_min=1, fmap_max=512, architecture='resnet', nonlinearity='lrelu', mbstd_group_size=4, mbstd_num_features=1, resample_kernel=None, **_kwargs): """ Args: num_channels: Number of input color channels. Overridden based on dataset. resolution: Input resolution. Overridden based on dataset. label_size: Dimensionality of the labels, 0 if no labels. Overridden based on dataset. fmap_base: Overall multiplier for the number of feature maps. fmap_decay: log2 feature map reduction when doubling the resolution. fmap_min: Minimum number of feature maps in any layer. fmap_max: Maximum number of feature maps in any layer. architecture: Architecture: 'orig', 'skip', 'resnet'. nonlinearity: Activation function: 'relu', 'lrelu', etc. mbstd_group_size: Group size for the minibatch standard deviation layer, 0 = disable. mbstd_num_features: Number of features for the minibatch standard deviation layer. resample_kernel: Low-pass filter to apply when resampling activations. None = no filtering. **_kwargs: Ignore unrecognized keyword args.): """ super().__init__() resolution_log2 = int(np.log2(resolution)) assert resolution == 2 ** resolution_log2 and resolution >= 4 assert architecture in ['orig', 'skip', 'resnet'] # we use skip in this implementation self.architecture = architecture self.resolution_log2 = resolution_log2 self.nonlinearity = nonlinearity def nf(stage): return np.clip(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_min, fmap_max) # blocks / in / out # 0 32 64 # 1 64 128 # 2 128 256 # 3 256 512 # 4 512 512 # 5 512 512 # 6 512 512 # 7 512 512 # build a first layer for images [N, 3, 1024, 1024] self.init_conv = ConvLayer(in_channels=3, out_channels=nf(resolution_log2 - 1), kernel_size=1) # build main layers blocks = [DiscriminatorBlock(in_fmaps=nf(res - 1), out_fmaps=nf(res - 2)) for res in range(resolution_log2, 2, -1)] self.blocks = nn.ModuleList(blocks) # build a last layer self.last_block = DiscriminatorLastBlock(in_fmaps=nf(1), in_fmaps_fc=nf(0), mbstd_group_size=mbstd_group_size, mbstd_num_features=mbstd_num_features) def forward(self, imgs_in): out = self.init_conv(imgs_in) for block in self.blocks: out = block(out) out = self.last_block(out) return out if __name__ == '__main__': # ## mapping_network # g_mapping = GeneratorMapping().to('cuda:0') # print(g_mapping) # noise = torch.randn(4, 512).to('cuda:0') # test_dlatents_out = g_mapping(noise) # print('dlatents_out: {}'.format(test_dlatents_out.shape)) # [N 18, D] = [4, 18, 512] # # check params # params_0 = 0 # for p in g_mapping.parameters(): # if p.requires_grad: # params_0 += p.numel() # print('params_0: {}'.format(params_0)) # # synthesis_network # g_synthesis = GeneratorSynthesis().to('cuda:0') # print(g_synthesis) # test_dlatents_in = torch.randn(4, 18, 512).to('cuda:0') # test_imgs_out = g_synthesis(test_dlatents_in) # print('imgs_out: {}'.format(test_imgs_out.shape)) # [4, 3, 1024, 1024] # # check params # params_1 = 0 # for p in g_synthesis.parameters(): # if p.requires_grad: # params_1 += p.numel() # print('params_0: {}'.format(params_1)) def mixing_noise(batch_size, latent_size, prob, device): if prob > 0 and random.random() < prob: noises = torch.randn(2, batch_size, latent_size, device=device).unbind(0) return noises else: noise = torch.randn(batch_size, latent_size, device=device) # 16, 512 return [noise] # torch.tensor in list, [(torch.tensor), (torch.tensor), ...] # generator_network Gen = Generator(resolution=1024, latent_size=512).to('cuda:0') print(Gen) path_batch_size = max(1, 4 // 2) noise = mixing_noise(path_batch_size, 512, 0.9, 'cuda:0') fake_imgs, dlatents = Gen(noise, return_dlatents=True) noise = torch.randn_like(fake_imgs) / math.sqrt(fake_imgs.shape[2] * fake_imgs.shape[3]) grad, = autograd.grad(outputs=(fake_imgs * noise).sum(), inputs=dlatents, create_graph=True) print(grad) # print('imgs_out: {}'.format(test_imgs_out.shape)) # [4, 3, 1024, 1024] # # check params # params_Gen = 0 # for p in Gen.parameters(): # if p.requires_grad: # params_Gen += p.numel() # print('params_Gen: {}'.format(params_Gen)) # # discriminator_network # Dis = Discriminator().to('cuda:0') # print(Dis) # test_imgs_in = torch.randn(4, 3, 1024, 1024).to('cuda:0') # print(test_imgs_in.shape) # out = Dis(test_imgs_in) # print('out: {}'.format(out.shape)) # # check params # params_Dis = 0 # for p in Dis.parameters(): # if p.requires_grad: # params_Dis += p.numel() # print('params_Dis: {}'.format(params_Dis)) # # check fmaps # fmap_base=16 << 10 # fmap_decay=1.0 # fmap_min=1 # fmap_max=512 # resolution = 1024 # resolution_log2 = int(np.log2(resolution)) # def nf(stage): # return np.clip(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_min, fmap_max) # for res
<reponame>jeppeter/py-obcode #! /usr/bin/env python import random import json import logging import re import sys import os ##importdebugstart sys.path.append(os.path.abspath(os.path.dirname(__file__))) from strparser import * ##importdebugend ##extractcode_start class Utf8Encode(object): def __dict_utf8(self,val): newdict =dict() for k in val.keys(): newk = self.__encode_utf8(k) newv = self.__encode_utf8(val[k]) newdict[newk] = newv return newdict def __list_utf8(self,val): newlist = [] for k in val: newk = self.__encode_utf8(k) newlist.append(newk) return newlist def __encode_utf8(self,val): retval = val if sys.version[0]=='2' and isinstance(val,unicode): retval = val.encode('utf8') elif isinstance(val,dict): retval = self.__dict_utf8(val) elif isinstance(val,list): retval = self.__list_utf8(val) return retval def __init__(self,val): self.__val = self.__encode_utf8(val) return def __str__(self): return self.__val def __repr__(self): return self.__val def get_val(self): return self.__val def format_line(l, tab=0): retstr = '' retstr += format_tabs(tab) retstr += '%s\n'%(l) return retstr def format_comment_line(l): s = '' idx = 0 while idx < len(l): if l[idx] == '*': s += '\\*' elif l[idx] == '/': s += '\\/' else: s += l[idx] idx += 1 return s def format_debug_line(l,tab=0,debug=0): rets = '' if debug >= 3: rets += format_line('/* %s */'%(format_comment_line(l)), tab) return rets def format_xor_encode_function(nameprefix='prefix',namelen=10,tabs=0,debug=0): funcstr = '' funcname = '%s_%s'%(nameprefix,get_random_name(namelen)) if debug >= 3: funcstr += format_line('/*********************************************',tabs) funcstr += format_line('* to make xor encoded functions', tabs) funcstr += format_line('* it will be simple ,may be it will give more complex', tabs) funcstr += format_line('*********************************************/',tabs) funcstr += format_debug_line('variable:namelen %d variable:prefix [%s]'%(namelen,nameprefix), tabs,debug) funcstr += format_line('int %s(unsigned char* pbuf,int size,unsigned char* pxorcode, int xorsize)'%(funcname),tabs) funcstr += format_line('{',tabs) funcstr += format_line('int i,curi;',tabs+1) funcstr += format_line('',tabs) funcstr += format_line('for (i=0;i<size;i++){', tabs + 1) funcstr += format_line('curi = (i % xorsize);',tabs + 2) funcstr += format_line('pbuf[i] = (unsigned char)(pbuf[i] ^ pxorcode[curi]);', tabs + 2) funcstr += format_line('}', tabs + 1) funcstr += format_line('', tabs) funcstr += format_line('return size;',tabs + 1) funcstr += format_line('}',tabs) return funcstr,funcname def format_xor_decode_function(nameprefix='prefix_',namelen=10, tabs=0, debug=0): funcstr = '' funcname = '%s_%s'%(nameprefix,get_random_name(namelen)) if debug >= 3: funcstr += format_line('/*********************************************',tabs) funcstr += format_line('* to make xor decoded functions', tabs) funcstr += format_line('* it will be simple ,may be it will give more complex', tabs) funcstr += format_line('*********************************************/',tabs) funcstr += format_debug_line('variable:namelen %d variable:prefix [%s]'%(namelen,nameprefix), tabs,debug) funcstr += format_line('int %s(unsigned char* pbuf,int size,unsigned char* pxorcode, int xorsize)'%(funcname),tabs) funcstr += format_line('{',tabs) funcstr += format_line('int i,curi;',tabs+1) funcstr += format_line('',tabs) funcstr += format_line('for (i=0;i<size;i++){', tabs + 1) funcstr += format_line('curi = (i % xorsize);',tabs + 2) funcstr += format_line('pbuf[i] = (unsigned char)(pbuf[i] ^ pxorcode[curi]);', tabs + 2) funcstr += format_line('}', tabs + 1) funcstr += format_line('', tabs) funcstr += format_line('return size;',tabs + 1) funcstr += format_line('}',tabs) return funcstr,funcname def get_xor_code(cnum=16): xorcode = [] for i in range(cnum): xorcode.append(random.randint(0,255)) return xorcode def format_key_ctr_function(xorcode,nameprefix='prefix', namelen=10, numturns=30, tabs=0,debug=0): funcstr = '' funcname = '%s_%s'%(nameprefix,get_random_name(namelen)) presentxor = [] funcstr += format_line('int %s(unsigned char* pbuf,int size)'%(funcname),tabs) funcstr += format_line('{',tabs) codestr = '' for i in range(len(xorcode)): if i > 0: codestr += ',' codestr += '0x%02x'%(xorcode[i]) funcstr += format_debug_line('keys %s size %d'%(codestr,len(xorcode)), tabs + 1 , debug) funcstr += format_line('',tabs) for i in range(len(xorcode)): if (i%5) == 0: funcstr += format_line('',tabs) curnum = random.randint(0, 255) funcstr += format_line('if ( %d < size) {'%(i), tabs + 1) funcstr += format_line('pbuf[%d] = %d;'%(i,curnum), tabs + 2) funcstr += format_line('}',tabs + 1) presentxor.append(curnum) funcstr += format_line('',tabs) funcstr += format_debug_line('variable:numturns %d'%(numturns), tabs + 1, debug) for i in range(numturns): if (i%5) == 0 and i > 0: funcstr += format_line('',tabs) curi = random.randint(0, len(xorcode)-1) curj = random.randint(0, len(xorcode)-1) funcstr += format_line('if (%d < size && %d < size){'%(curi,curj), tabs + 1) funcstr += format_debug_line('%d = %d ^ %d'%((presentxor[curi] ^ presentxor[curj]) & 0xff, presentxor[curi],presentxor[curj]), tabs + 2,debug) presentxor[curi] = (presentxor[curi] ^ presentxor[curj]) & 0xff funcstr += format_line('pbuf[%d] = (unsigned char)(pbuf[%d] ^ pbuf[%d]);'%(curi, curi, curj),tabs + 2) funcstr += format_line('}', tabs + 1) for i in range(len(xorcode)): if (i%3) == 0: funcstr += format_line('', tabs) curi = random.randint(0, len(xorcode)-1) curv = presentxor[i] ^ presentxor[curi] curv = xorcode[i] ^ curv funcstr += format_line('if (%d < size){'%(curi), tabs + 1) funcstr += format_debug_line('%d = %d ^ %d'%((presentxor[curi] ^ presentxor[curj]) & 0xff, presentxor[curi],presentxor[curj]), tabs + 2,debug) presentxor[i] = (presentxor[i] ^ presentxor[curi]) & 0xff funcstr += format_debug_line('%d = %d ^ %d'%((presentxor[i] ^ curv) & 0xff, presentxor[curi],curv), tabs + 2,debug) presentxor[i] = (presentxor[i] ^ curv) & 0xff assert(presentxor[i] == xorcode[i]) funcstr += format_line('pbuf[%d] = (unsigned char)(pbuf[%d] ^ pbuf[%d]);'%(i ,i,curi), tabs+2) funcstr += format_line('pbuf[%d] = (unsigned char)(pbuf[%d] ^ %d);'%(i,i,curv), tabs+2) funcstr += format_line('}', tabs + 1) funcstr += format_line('',tabs) funcstr += format_line('return %d < size ? %d : size;'%(len(xorcode),len(xorcode)), tabs+1) funcstr += format_line('}',tabs) return funcstr,funcname def format_key_dtr_function(xorcode,nameprefix='prefix', namelen=10, numturns=30, tabs=0,debug=0): funcstr = '' funcname = '%s_%s'%(nameprefix,get_random_name(namelen)) funcstr += format_line('void %s(unsigned char* pbuf,int size)'%(funcname),tabs) funcstr += format_line('{',tabs) funcstr += format_debug_line('variable:nameprefix %s variable:namelen %d variable:numturns %d'%(nameprefix,namelen,numturns), tabs+1,debug) funcstr += format_line('',tabs) storecode = [] for x in xorcode: storecode.append(x) for i in range(numturns): if (i%5) == 0: funcstr += format_line('',tabs) curi = random.randint(0, len(xorcode)-1) curj = random.randint(0, len(xorcode)-1) funcstr += format_line('if (%d < size && %d < size){'%(curi,curj), tabs+1) funcstr += format_debug_line('%d = %d ^ %d'%((storecode[curi] ^ storecode[curj]),storecode[curi],storecode[curj]), tabs + 2, debug) funcstr += format_line('pbuf[%d] = (unsigned char)(pbuf[%d] ^ pbuf[%d]);'%(curi, curi, curj),tabs + 2) funcstr += format_line('}',tabs + 1) funcstr += format_line('',tabs) funcstr += format_line('return;',tabs + 1) funcstr += format_line('}',tabs) return funcstr,funcname def format_printf_func(l,tabs): #return format_line(l,tabs) return '' def format_bytes_set_function(sbyte,nameprefix='prefix', namelen=10, numturns=30, tabs=0,debug=0,line=None): funcname = '%s_%s'%(nameprefix,get_random_name(namelen)) funcstr = '' funcstr += format_line('int %s(unsigned char* pbuf, int size)'%(funcname),tabs) funcstr += format_line('{', tabs) funcstr += format_printf_func('int i;', tabs + 1) if line is not None: funcstr += format_debug_line('first at line [%d]'%(line), tabs + 1 , debug) funcstr += format_debug_line('variable:nameprefix %s variable:namelen %d variable:numturns %d length(%d)'%(nameprefix,namelen,numturns,len(sbyte)), tabs + 1, debug) ss = '' for c in sbyte: if len(ss) > 0: ss += ',0x%02x'%(c) else: ss += 'sbyte [0x%02x'%(c) ss += ']' funcstr += format_debug_line('%s'%(ss), tabs + 1, debug) funcstr += format_printf_func('for (i=0;i<size;i++){', tabs + 1) funcstr += format_printf_func('printf("[%d]=[%d:0x%x]\\n",i,pbuf[i],pbuf[i]);', tabs + 2) funcstr += format_printf_func('}', tabs + 1) clbits = [] leastmask = [] for i in range(len(sbyte)): clbits.append(random.randint(0,255)) leastmask.append(0) ss = '' for c in clbits: if len(ss) > 0: ss += ',0x%x:%d'%(c,c) else: ss += 'clbits [0x%x:%d'%(c,c) ss += ']' funcstr += format_printf_func('/* %s */'%(ss), tabs+1) for i in range(len(sbyte)): curnum = clear_bit(sbyte[i], clbits[i]) funcstr += format_line('',tabs+1) funcstr += format_debug_line('pbuf[%d] & 0x%x ?=> 0x%x'%(i,curnum,sbyte[i]), tabs + 1, debug) funcstr += format_line('if (size > %d){'%(i), tabs + 1) funcstr += format_printf_func('printf("[%d][%%d:0x%%x] & [%%d:0x%%x] = [%%d:0x%%x] [target:0x%x:%d]\\n",pbuf[%d], pbuf[%d], %d,%d, (pbuf[%d] & %d), (pbuf[%d] & %d));'%(i,sbyte[i],sbyte[i],i,i,curnum,curnum,i,curnum,i,curnum), tabs+2) funcstr += format_line('pbuf[%d] = (unsigned char)(pbuf[%d] & 0x%x);'%(i,i,curnum), tabs + 2) funcstr += format_line('}',tabs + 1) # we need not to set the number directly ,but just used for i in range(numturns): cidx = random.randint(0, len(sbyte) - 1) cbit = random.randint(0, 255) if random.randint(0,1) == 1: cnum = clear_bit(sbyte[cidx], cbit) leastmask[cidx] = leastmask[cidx] | cnum funcstr += format_line('', tabs + 1) funcstr += format_line('if ( size > %d){'%(cidx), tabs + 1) funcstr += format_printf_func('printf("||[%d][%%d:0x%%x] | [%%d:0x%%x] = [%%d:0x%%x] [target:0x%x:%d]\\n",pbuf[%d],pbuf[%d],%d,%d,(pbuf[%d] | %d), (pbuf[%d] | %d));'%(cidx,sbyte[cidx],sbyte[cidx],cidx,cidx,cnum,cnum,cidx,cnum,cidx,cnum), tabs + 2) funcstr += format_line('pbuf[%d] = (unsigned char)(pbuf[%d] | 0x%x);'%(cidx,cidx, cnum), tabs + 2) funcstr += format_line('}', tabs + 1) else: cnum = expand_bit(sbyte[cidx], cbit) funcstr += format_line('', tabs + 1) funcstr += format_line('if ( size > %d){'%(cidx), tabs + 1) funcstr += format_printf_func('printf("&&[%d][%%d:0x%%x] & [%%d:0x%%x] = [%%d:0x%%x] [target:0x%x:%d]\\n",pbuf[%d],pbuf[%d],%d,%d,(pbuf[%d] & %d), (pbuf[%d] & %d));'%(cidx,sbyte[cidx],sbyte[cidx],cidx,cidx,cnum,cnum,cidx,cnum,cidx,cnum), tabs + 2) funcstr += format_line('pbuf[%d] = (unsigned char)(pbuf[%d] & 0x%x);'%(cidx,cidx, cnum), tabs + 2) funcstr += format_line('}', tabs + 1) # now we should filled the number for i in range(len(sbyte)): cnum = sbyte[i] & (~leastmask[i]) if cnum > 0: funcstr += format_line('',tabs+1) funcstr += format_debug_line('pbuf[%d] | 0x%x ?=> 0x%x'%(i,cnum, sbyte[i]), tabs + 1, debug) funcstr += format_line('if (size > %d){'%(i), tabs + 1) funcstr += format_printf_func('printf("[%d] [%%d:0x%%x] | [%%d:0x%%x] = [%%d:0x%%x] [target:0x%x:%d]\\n", pbuf[%d], pbuf[%d], %d ,%d , (pbuf[%d] | %d), (pbuf[%d] | %d));'%(i,sbyte[i],sbyte[i],i,i,cnum,cnum,i,cnum,i,cnum), tabs + 2) funcstr += format_line('pbuf[%d] = (unsigned char)(pbuf[%d] | 0x%x);'%(i,i,cnum), tabs + 2) funcstr += format_line('}',tabs + 1) funcstr += format_line('', tabs + 1) funcstr += format_line('return size;', tabs + 1) funcstr += format_line('}',
<gh_stars>100-1000 """ parsr is a library for building parsers based on `parsing expression grammars or PEGs <http://bford.info/pub/lang/peg.pdf>`_. You build a parser by making subparsers to match simple building blocks like numbers, strings, symbols, etc. and then composing them to reflect the higher level structure of your language. Some means of combination are like those of regular expressions: sequences, alternatives, repetition, optional matching, etc. However, matching is always greedy. parsr also allows recursive definitions and the ability to transform the match of any subparser with a function. The parser can recognize and interpret its input at the same time. Here's an example that evaluates arithmetic expressions. .. code-block:: python from insights.parsr import EOF, Forward, InSet, Many, Number, WS def op(args): ans, rest = args for op, arg in rest: if op == "+": ans += arg elif op == "-": ans -= arg elif op == "*": ans *= arg else: ans /= arg return ans LP = Char("(") RP = Char(")") expr = Forward() # Forward declarations allow recursive structure factor = WS >> (Number | (LP >> expr << RP)) << WS term = (factor + Many(InSet("*/") + factor)).map(op) # Notice the funny assignment of Forward definitions. expr <= (term + Many(InSet("+-") + term)).map(op) evaluate = expr << EOF """ from __future__ import print_function import functools import logging import os import string import traceback from bisect import bisect_left from six import StringIO, with_metaclass log = logging.getLogger(__name__) class Node(object): """ Node is the base class of all parsers. It's a generic tree structure with each instance containing a list of its children. Its main purpose is to simplify pretty printing. """ def __init__(self): self.children = [] def add_child(self, child): self.children.append(child) return self def set_children(self, children): self.children = [] for c in children: self.add_child(c) return self def __repr__(self): return self.__class__.__name__ def text_format(tree): """ Converts a PEG into a pretty printed string. """ out = StringIO() tab = " " * 2 seen = set() def inner(cur, prefix): print(prefix + str(cur), file=out) if cur in seen: return seen.add(cur) next_prefix = prefix + tab for c in cur.children: inner(c, next_prefix) inner(tree, "") out.seek(0) return out.read() def render(tree): """ Pretty prints a PEG. """ print(text_format(tree)) def _debug_hook(func): """ _debug_hook wraps the process function of every parser. It maintains a stack of active parsers during evaluation to help with error reporting and prints diagnostic messages for parsers with debug enabled. """ @functools.wraps(func) def inner(self, pos, data, ctx): if ctx.function_error is not None: # no point in continuing... raise Exception() ctx.parser_stack.append(self) if self._debug: line = ctx.line(pos) + 1 col = ctx.col(pos) + 1 log.debug("Trying {0} at line {1} col {2}".format(self, line, col)) try: res = func(self, pos, data, ctx) if self._debug: log.debug("Result: {0}".format(res[1])) return res except: if self._debug: ps = "-> ".join([str(p) for p in ctx.parser_stack]) log.debug("Failed: {0}".format(ps)) raise finally: ctx.parser_stack.pop() return inner class Backtrack(Exception): """ Mapped or Lifted functions should Backtrack if they want to fail without causing parsing to fail. """ def __init__(self, msg): super(Backtrack, self).__init__(msg) class Context(object): """ An instance of Context is threaded through the process call to every parser. It stores an indention stack to track hanging indents, a tag stack for grammars like xml or apache configuration, the active parser stack for error reporting, and accumulated errors for the farthest position reached. """ def __init__(self, lines, src=None): self.pos = -1 self.indents = [] self.tags = [] self.src = src self.lines = [i for i, x in enumerate(lines) if x == "\n"] self.parser_stack = [] self.errors = [] self.function_error = None def set(self, pos, msg): """ Every parser that encounters an error calls set with the current position and a message. If the error is at the farthest position reached by any other parser, the active parser stack and message are accumulated onto a list of errors for that position. If the position is beyond any previous errors, the error list is cleared before the active stack and new error are recorded. This is the "farthest failure heurstic." """ if pos > self.pos: self.errors = [] if pos >= self.pos: self.pos = pos self.errors.append((list(self.parser_stack), msg)) def line(self, pos): return bisect_left(self.lines, pos) def col(self, pos): p = self.line(pos) if p == 0: return pos return (pos - self.lines[p - 1] - 1) class _ParserMeta(type): """ ParserMeta wraps every parser subclass's process function with the ``_debug_hook`` decorator. """ def __init__(cls, name, bases, clsdict): orig = getattr(cls, "process") setattr(cls, "process", _debug_hook(orig)) class Parser(with_metaclass(_ParserMeta, Node)): """ Parser is the common base class of all Parsers. """ def __init__(self): super(Parser, self).__init__() self.name = None self._debug = False def debug(self, d=True): """ Set to ``True`` to enable diagnostic messages before and after the parser is invoked. """ self._debug = d return self @staticmethod def _accumulate(first, rest): results = [first] if first else [] if rest: results.extend(rest) return results def sep_by(self, sep): """ Return a parser that matches zero or more instances of the current parser separated by instances of the parser sep. """ return Lift(self._accumulate) * Opt(self) * Many(sep >> self) def until(self, pred): """ Return an :py:class:`Until` parser that matches zero or more instances of the current parser until the pred parser succeeds. """ return Until(self, pred) def map(self, func): """ Return a :py:class:`Map` parser that transforms the results of the current parser with the function func. """ return Map(self, func) def __add__(self, other): """ Return a :py:class:`Sequence` that requires the current parser to be followed by the other parser. Additional calls to ``+`` on the returned parser will cause it to accumulate "other" onto itself instead of creating new Sequences. This has the desirable effect of causing sequence matches to be represented as flat lists instead of trees, but it can also have unintended consequences if a sequence is used in multiple parts of a grammar as the initial element of another sequence. :py:class:`Choice`s also accumulate and can lead to similar surprises. """ return Sequence([self, other]) def __or__(self, other): """ Return a :py:class:`Choice` that requires the current parser or the other parser to match. Additional calls to ``|`` on the returned parser will cause it to accumulate "other" onto itself instead of creating new Choices. This has the desirable effect of making choices more efficient, but it can also have unintended consequences if a choice is used in multiple parts of a grammar as the initial element of another :py:class:`Choice`. """ return Choice([self, other]) def __lshift__(self, other): """ Return a parser that requires the current parser and the other parser but ignores the other parser's result. Both parsers consume input. """ return KeepLeft(self, other) def __rshift__(self, other): """ Return a parser that requires the current parser and the other parser but ignores the current parser's result. Both parsers consume input. """ return KeepRight(self, other) def __and__(self, other): """ Return a parser that requires the current parser and the other parser but ignores the current parser's result. Only the current parser consumes input. """ return FollowedBy(self, other) def __truediv__(self, other): """ Return a parser that requires the current parser but requires the other parser to fail. Only the current parser consumes input. """ return NotFollowedBy(self, other) def __mod__(self, name): """ Gives the current parser a human friendly name for display in error messages and PEG rendering. """ self.name = name return self def process(self, pos, data, ctx): raise NotImplementedError() def __call__(self, data, src=None, Ctx=Context): """ Invoke the parser like a function on a regular string of characters. Optinally provide an arbitrary external object that will be made available to the Context instance. You also can provide a Context subclass if your parsers have particular needs not covered by the default implementation that provides significant indent and tag stacks. """ data = list(data) data.append(None) # add a terminal so we don't overrun ctx = Ctx(data, src=src) try: _, ret = self.process(0, data, ctx) return ret except Exception: pass if ctx.function_error is not None: pos, msg = ctx.function_error lineno = ctx.line(pos) + 1 colno = ctx.col(pos) + 1
# coding: utf-8 """ UpgradeApi.py Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient class UpgradeApi(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): config = Configuration() if api_client: self.api_client = api_client else: if not config.api_client: config.api_client = ApiClient() self.api_client = config.api_client def create_cluster_add_remaining_node(self, cluster_add_remaining_node, **kwargs): """ Let system absorb any remaining or new nodes inside the existing upgrade. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_cluster_add_remaining_node(cluster_add_remaining_node, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Empty cluster_add_remaining_node: (required) :return: Empty If the method is called asynchronously, returns the request thread. """ all_params = ['cluster_add_remaining_node'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_cluster_add_remaining_node" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'cluster_add_remaining_node' is set if ('cluster_add_remaining_node' not in params) or (params['cluster_add_remaining_node'] is None): raise ValueError("Missing the required parameter `cluster_add_remaining_node` when calling `create_cluster_add_remaining_node`") resource_path = '/platform/3/upgrade/cluster/add_remaining_nodes'.replace('{format}', 'json') path_params = {} query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None if 'cluster_add_remaining_node' in params: body_params = params['cluster_add_remaining_node'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = ['basic_auth'] response = self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Empty', auth_settings=auth_settings, callback=params.get('callback')) return response def create_cluster_archive_item(self, cluster_archive_item, **kwargs): """ Start an archive of an upgrade. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_cluster_archive_item(cluster_archive_item, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param ClusterArchiveItem cluster_archive_item: (required) :return: Empty If the method is called asynchronously, returns the request thread. """ all_params = ['cluster_archive_item'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_cluster_archive_item" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'cluster_archive_item' is set if ('cluster_archive_item' not in params) or (params['cluster_archive_item'] is None): raise ValueError("Missing the required parameter `cluster_archive_item` when calling `create_cluster_archive_item`") resource_path = '/platform/3/upgrade/cluster/archive'.replace('{format}', 'json') path_params = {} query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None if 'cluster_archive_item' in params: body_params = params['cluster_archive_item'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = ['basic_auth'] response = self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Empty', auth_settings=auth_settings, callback=params.get('callback')) return response def create_cluster_assess_item(self, cluster_assess_item, **kwargs): """ Start upgrade assessment on cluster. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_cluster_assess_item(cluster_assess_item, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param ClusterAssessItem cluster_assess_item: (required) :return: Empty If the method is called asynchronously, returns the request thread. """ all_params = ['cluster_assess_item'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_cluster_assess_item" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'cluster_assess_item' is set if ('cluster_assess_item' not in params) or (params['cluster_assess_item'] is None): raise ValueError("Missing the required parameter `cluster_assess_item` when calling `create_cluster_assess_item`") resource_path = '/platform/3/upgrade/cluster/assess'.replace('{format}', 'json') path_params = {} query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None if 'cluster_assess_item' in params: body_params = params['cluster_assess_item'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = ['basic_auth'] response = self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Empty', auth_settings=auth_settings, callback=params.get('callback')) return response def create_cluster_commit_item(self, cluster_commit_item, **kwargs): """ Commit the upgrade of a cluster. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_cluster_commit_item(cluster_commit_item, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Empty cluster_commit_item: (required) :return: Empty If the method is called asynchronously, returns the request thread. """ all_params = ['cluster_commit_item'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_cluster_commit_item" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'cluster_commit_item' is set if ('cluster_commit_item' not in params) or (params['cluster_commit_item'] is None): raise ValueError("Missing the required parameter `cluster_commit_item` when calling `create_cluster_commit_item`") resource_path = '/platform/3/upgrade/cluster/commit'.replace('{format}', 'json') path_params = {} query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None if 'cluster_commit_item' in params: body_params = params['cluster_commit_item'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = ['basic_auth'] response = self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Empty', auth_settings=auth_settings, callback=params.get('callback')) return response def create_cluster_firmware_assess_item(self, cluster_firmware_assess_item, **kwargs): """ Start firmware upgrade assessment on cluster. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_cluster_firmware_assess_item(cluster_firmware_assess_item, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Empty cluster_firmware_assess_item: (required) :return: Empty If the method is called asynchronously, returns the request thread. """ all_params = ['cluster_firmware_assess_item'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_cluster_firmware_assess_item" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'cluster_firmware_assess_item' is set if ('cluster_firmware_assess_item' not in params) or (params['cluster_firmware_assess_item'] is None): raise ValueError("Missing the required parameter `cluster_firmware_assess_item` when calling `create_cluster_firmware_assess_item`") resource_path = '/platform/3/upgrade/cluster/firmware/assess'.replace('{format}', 'json') path_params = {} query_params = {} header_params = {} form_params = [] local_var_files = {} body_params = None if 'cluster_firmware_assess_item' in params: body_params = params['cluster_firmware_assess_item'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = ['basic_auth'] response = self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Empty', auth_settings=auth_settings, callback=params.get('callback')) return response def create_cluster_firmware_upgrade_item(self, cluster_firmware_upgrade_item, **kwargs): """ The settings necessary to start a firmware upgrade. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_cluster_firmware_upgrade_item(cluster_firmware_upgrade_item, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param ClusterFirmwareUpgradeItem cluster_firmware_upgrade_item: (required) :return: Empty If the
index(request): return redirect("search") # View for provider.html def provider(request): # currentUser gets the userInfo table information for the template (may not be used?). currentUser = userInfo.objects.filter(user=(request.user.userinfo.id - 1)) # Get the user's programs. myEventList = Program.objects.filter(user_id=request.user.userinfo.id) if request.method == "POST": if request.POST.get("changeemail") and ( request.user.username != request.POST["changeemail"] ): if UserAccount.objects.filter( username=request.POST["changeemail"] ).exists(): context = { "config": settings.CONFIG, "currentUser": currentUser, "myEventList": myEventList, "user_exists": True, } return render(request, "provider.html", context) else: change_username( request.user.username, request.POST.get("changeemail"), request ) if request.POST.get("changename"): u = userInfo.objects.get(pk=request.user.id) u.org_name = request.POST["changename"] u.save() rebuild_index.rebuildWhooshIndex() if request.POST.get("current") and ( request.POST.get("new") == request.POST.get("confirm") ): current = request.POST["current"] new = request.POST["new"] if request.user.check_password(current): request.user.set_password(new) request.user.save() currentUser = userInfo.objects.filter( user=(request.user.userinfo.id - 1) ) myEventList = Program.objects.filter(user_id=request.user.userinfo.id) update_session_auth_hash(request, request.user) else: currentUser = userInfo.objects.filter( user=(request.user.userinfo.id - 1) ) myEventList = Program.objects.filter(user_id=request.user.userinfo.id) context = { "config": settings.CONFIG, "currentUser": currentUser, "myEventList": myEventList, "incorrect_password": True, } return render(request, "provider.html", context) if request.POST.get("delete"): deleteEvent(request.POST.get("delete")) if ( request.user.is_authenticated and not request.user.userinfo.isAdmin and not request.user.userinfo.isPending ): currentUser = userInfo.objects.filter(user=(request.user.userinfo.id - 1)) myEventList = Program.objects.filter(user_id=request.user.userinfo.id) context = { "config": settings.CONFIG, "currentUser": currentUser, "myEventList": myEventList, } return render(request, "provider.html", context) if ( request.user.is_authenticated and request.user.userinfo.isAdmin and not request.user.userinfo.isPending ): return HttpResponseRedirect(reverse("admin_page")) else: return HttpResponseRedirect(reverse("login_page")) # View for register.html. def register(request): if request.method == "POST" and request.POST["current"] == request.POST["confirm"]: emailAddr = request.POST["emailAddr"] orgName = request.POST["orgName"] current = request.POST["current"] contact_name = request.POST["contact_name"] contact_email = request.POST["contact_email"] contact_phone = request.POST["contact_phone"] # Check for Duplicate Email Entry (Email Already in Database) checkInfo = UserAccount.objects.filter(email=emailAddr) if checkInfo.count() >= 1: context = { "config": settings.CONFIG, "emailTaken": True, } return render(request, "register.html", context) else: # Create Django user. newUser = UserAccount.objects.create_user(emailAddr, emailAddr, current) # Create userInfo table entry. This is linked to the Django user system. uInfo = userInfo( user=newUser, org_name=orgName, contact_name=contact_name, contact_email=contact_email, contact_phone=contact_phone, ) uInfo.save() return redirect("login_page") else: context = { "config": settings.CONFIG, "emailTaken": False, } return render(request, "register.html", context) context = { "config": settings.CONFIG, "emailTaken": False, } return render(request, "register.html", context) # View for resetPW.html (the page to put an email address in) def resetpw(request): if request.method == "POST": # Check for if the account exists. if UserAccount.objects.filter(username=request.POST["emailAddr"]).exists(): try: # This line attempts to delete any existing entry in the reset URL table for the user so the user cannot generate multiple reset links. resetPWURLs.objects.get(user_ID=request.POST["emailAddr"]).delete() # If there is no entry in the table, let the app continue withiut throwing an error. except resetPWURLs.DoesNotExist: pass # Create reset link, a 15 characrer string, then write to table, # alomg with the associated user, and the exiration time. reset_link = "".join( [random.choice(string.ascii_letters + string.digits) for n in range(15)] ) resetPWURL = resetPWURLs( user_ID=request.POST["emailAddr"], reset_string=reset_link, expiry_time=(datetime.now() + timedelta(minutes=60)), ) resetPWURL.save() # Add reset link to the contt to be used in the email. email_context = { "config": settings.CONFIG, "reset_link": reset_link, } send_email( [request.POST["emailAddr"]], render_to_string("messaging/reset_password_subject.txt"), render_to_string( "messaging/reset_password_mail.txt", context=email_context ), ) # If the email is sent correctly, set email_submitted to true to display the appropriate message in the template. return render(request, "resetPW.html", context={"email_submitted": True}) else: return render(request, "resetPW.html") # View for resetPWForm.html/<reset_string>. def resetPWForm(request, reset_string): try: # Check if the current time is greater than the timestamp in the table (which is 60 minutes after submission) if datetime.now() > datetime.strptime( resetPWURLs.objects.get(reset_string=reset_string).expiry_time, "%Y-%m-%d %H:%M:%S.%f", ): # If so, show the expired message, hide the form. context = {"expired": True, "valid_string": False} # Then delete the associated table entry that's out of date. resetPWURLs.objects.get(reset_string=reset_string).delete() return render(request, "resetPWForm.html", context) # This is the most typical situation, where the form has a reset_string with a valid time. else: # The form should be showing if valid. context = {"valid_string": True} # If a post went through (check for the time again!), and the input was valid, change the password. if request.method == "POST": if request.POST.get("new") == request.POST.get("confirm"): print(reset_string) username = resetPWURLs.objects.get(reset_string=reset_string) user = UserAccount.objects.get(username=username.user_ID) user.set_password(request.POST["<PASSWORD>"]) user.save() resetPWURLs.objects.get(reset_string=reset_string).delete() return redirect("login_page") else: # If the inputted passwords do not match, bring up the "confirm match" message, and continue to show the form. context = {"pwdmatch": True, "valid_string": True} return render(request, "resetPWForm.html", context) return render(request, "resetPWForm.html", context) except resetPWURLs.DoesNotExist: # If the entry is not found, hide the resetPW form and show the "link expired message". context = {"expired": True, "valid_string": False} return render(request, "resetPWForm.html", context) # This is only triggered when no reset string is present. Note that this situation cannot happen without editing the URL file. return render(request, "resetPWForm.html") # Functional views, post only, need to be logged in admin, self defining names # View for <url>/approve_user/userID. def approveUser(request, userID): """Function to approve new users. Takes the indicated userID, and makes it so that user can log in. Args: request: The Django request, which is used to determine whether the currently authenticated user is an admin. userID: An integer indicating which user to approve. Returns: Redirects the user to the admin page. However, if the user is not authenticated, or not the admin, the page redirects to the login page, with the expectation that the admin will log in. """ if ( request.user.is_authenticated and request.user.userinfo.isAdmin and not request.user.userinfo.isPending ): # Set ispending to false, save he user. This will allow the user to log in. u = userInfo.objects.get(pk=userID) u.isPending = False u.save() # Send emails to the provider and alt. contact addresss. email_context = { "config": settings.CONFIG, "user": u, } send_email( [str(u.user)], render_to_string("messaging/provider_account_approval_subject.txt"), render_to_string( "messaging/provider_account_approval_mail.txt", context=email_context ), ) send_email( [str(u.contact_email)], render_to_string("messaging/alternate_contact_confirm_subject.txt"), render_to_string( "messaging/alternate_contact_confirm_mail.txt", context=email_context ), ) return redirect("admin_page") else: return redirect("login_page") def denyUser(request, userID, deny_user_reason): """Function to deny new users. Takes the indicated userID, and removes that user from the Django users and userInfo table. Also takes the reason for the denial from the modal, and sends that reason to the provider email. Args: request: The Django request, which is used to determine whether the currently authenticated user is an admin. userID: An integer indicating which user to delete. deny_user_reason: A string from the modal, which is sent to the provider account's email address. Returns: Redirects the user to the admin page. However, if the user is not authenticated, or not the admin, the page redirects to the login page, with the expectation that the admin will log in. No changes are made to the accounts if this is the case. """ if ( request.user.is_authenticated and request.user.userinfo.isAdmin and not request.user.userinfo.isPending ): u = userInfo.objects.get(pk=userID) v = UserAccount.objects.get(id=userID) send_email( [str(u.user)], render_to_string("messaging/provider_account_denied_subject.txt"), render_to_string( "messaging/provider_account_denied_mail.txt", context={ "config": settings.CONFIG, "denied_reason": deny_user_reason, "user": u, }, ), ) # Delete both the Django and userInfo user entries. u.delete() v.delete() rebuild_index.rebuildWhooshIndex() return redirect("admin_page") else: return redirect("login_page") # Function to delete an existing user. def deleteUser(request, userID): """Function to delete existing users, usually via the allAdmins or allUsers page. Takes the indicated userID, and removes that user from the Django and userInfo tables. Also removes all events associated with the deleted user. No reason for the deletion is collected. Args: request: The Django request, which is used to determine whether the currently authenticated user is an admin. userID: An integer indicating which user to delete. Returns: Redirects the user to the admin page. However, if the user is not authenticated, or not the admin, the page redirects to the login page, with the expectation that the admin will log in. No changes are made to the accounts if this is the case. """ if ( request.user.is_authenticated and request.user.userinfo.isAdmin and not request.user.userinfo.isPending ): u = userInfo.objects.get(pk=userID) v = UserAccount.objects.get(id=userID) # Delete the user from the Django and userInfo tables. This also removes any associated events. u.delete() v.delete() # Rebuild the index to update search results. rebuild_index.rebuildWhooshIndex() return redirect("admin_page") else: return redirect("login_page") # View for <url>/approve_event/<eventID> def approveEvent(request, eventID): """Function to approve pending events. Takes the indicated eventID, and sets the event's isPending to False. This makes is so the event shows up in search results. Args: request: The Django request, which is used to determine whether the currently authenticated user is an admin. eventID: An integer indicating which
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from typing import Union, List import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from qiskit.exceptions import QiskitError from qiskit.ignis.measurement.discriminator.discriminators import \ BaseDiscriminationFitter from qiskit.pulse import PulseError from qiskit.result import Result from qiskit.pulse.schedule import Schedule try: from matplotlib import pyplot as plt HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False class IQDiscriminationFitter(BaseDiscriminationFitter): """ Abstract discriminator that implements the data formatting for IQ level 1 data. """ def __init__(self, cal_results: Union[Result, List[Result]], qubit_mask: List[int], expected_states: List[str] = None, standardize: bool = False, schedules: Union[List[str], List[Schedule]] = None): """ Args: cal_results (Union[Result, List[Result]]): calibration results, Result or list of Result used to fit the discriminator. qubit_mask (List[int]): determines which qubit's level 1 data to use in the discrimination process. expected_states (List[str]): a list that should have the same length as schedules. All results in cal_results are used if schedules is None. expected_states must have the corresponding length. standardize (bool): if true the discriminator will standardize the xdata using the internal method _scale_data. schedules (Union[List[str], List[Schedule]]): The schedules or a subset of schedules in cal_results used to train the discriminator. The user may also pass the name of the schedules instead of the schedules. If schedules is None, then all the schedules in cal_results are used. """ BaseDiscriminationFitter.__init__(self, cal_results, qubit_mask, expected_states, standardize, schedules) def get_xdata(self, results: Union[Result, List[Result]], schedule_type_to_get: int, schedules: Union[List[str], List[Schedule]] = None) \ -> List[List[float]]: """ Retrieves feature data (xdata) for the discriminator. Args: results (Union[Result, List[Result]]): the get_memory() method is used to retrieve the level 1 data. If result is a list of Result, then the first Result in the list that returns the data of schedule (through get_memory(schedule)) is used. schedule_type_to_get (int): use to specify if we should return data corresponding to: 0: calibration data only 1: non-calibration data 2: both calibration and non-calibration data schedules (Union[List[str], List[Schedule]]): Either the names of the schedules or the schedules themselves. Returns (List[List[float]]): data as a list of features. Each feature is a list. """ xdata = [] if schedules is None: schedules = self._get_schedules(results, schedule_type_to_get) for schedule in schedules: iq_data = None if isinstance(results, list): for result in results: try: iq_data = result.get_memory(schedule) except QiskitError: pass else: iq_data = results.get_memory(schedule) if iq_data is None: raise PulseError('Could not find IQ data for %s' % schedule) xdata.extend(self.format_iq_data(iq_data)) return self._scale_data(xdata) def get_ydata(self, results: Union[Result, List[Result]], schedule_type_to_get: int, schedules: Union[List[str], List[Schedule]] = None): """ Args: results (Union[Result, List[Result]]): results for which to retrieve the y data (i.e. expected states). schedule_type_to_get (int): use to specify if we should return data corresponding to: 0: calibration data only 1: non-calibration data 2: both calibration and non-calibration data schedules (Union[List[str], List[Schedule]]): the schedules for which to get the y data. Returns (List[str]): the y data, i.e. expected states. get_ydata is designed to produce y data with the same length as the x data. """ ydata = [] if schedules is None: schedules = self._get_schedules(results, schedule_type_to_get) for schedule in schedules: if isinstance(schedule, Schedule): shed_name = schedule.name else: shed_name = schedule if isinstance(results, Result): results = [results] for result in results: try: iq_data = result.get_memory(schedule) n_shots = iq_data.shape[0] ydata.extend([self._expected_state[shed_name]]*n_shots) except QiskitError: pass return ydata def format_iq_data(self, iq_data: np.ndarray) -> List[List[float]]: """ Takes IQ data obtained from get_memory(), applies the qubit mask and formats the data as a list of lists. Each sub list is IQ data where the first half of the list is the I data and the second half of the list is the Q data. Args: iq_data (np.ndarray): data obtained from get_memory(). Returns (List[List[float]]): A list of shots where each entry is a list of IQ points. """ xdata = [] if len(iq_data.shape) == 2: # meas_return 'single' case for shot in iq_data[:, self._qubit_mask]: shot_i = list(np.real(shot)) shot_q = list(np.imag(shot)) xdata.append(shot_i + shot_q) elif len(iq_data.shape) == 1: # meas_return 'avg' case avg_i = list(np.real(iq_data[self._qubit_mask])) avg_q = list(np.imag(iq_data[self._qubit_mask])) xdata.append(avg_i + avg_q) else: raise PulseError('Unknown measurement return type.') return xdata def plot(self, axs=None, show_boundary: bool = False, show_fitting_data: bool = True, flag_misclassified: bool = False, qubits_to_plot: list = None, title: bool = True): """ Creates a plot of the data used to fit the discriminator. Args: axs (Union[np.ndarray, axes]): the axis to use for the plot. If it is none, the plot method will create its own axis instance. If the number of axis instances provided is less than the number of qubits then only the data for the first len(axs) qubits will be plotted. show_boundary (bool): plot the decision regions if true. Some discriminators may put additional constraints on whether the decision regions are plotted or not. show_fitting_data (bool): if True the x data and labels used to fit the discriminator are shown in the plot. flag_misclassified (bool): plot the misclassified training data points if true. qubits_to_plot (list): each qubit in this list will receive its own plot. The qubits in qubits to plot must be in the qubit mask. If qubits_to_plot is None then the qubit mask will be used. title (bool): adds a title to each subplot with the number of the qubit. Returns: (Union[List[axes], axes], figure): the axes object used for the plot as well as the figure handle. The figure handle returned is not None only when the figure handle is created by the discriminator's plot method. """ if not HAS_MATPLOTLIB: raise QiskitError('please install matplotlib') if qubits_to_plot is None: qubits_to_plot = self._qubit_mask else: for q in qubits_to_plot: if q not in self._qubit_mask: raise QiskitError('Qubit %i is not in discriminators ' 'qubit mask' % q) if axs is None: fig, axs = plt.subplots(len(qubits_to_plot), 1) else: fig = None if not isinstance(axs, np.ndarray): axs = np.asarray(axs) axs = axs.flatten() if len(axs) < len(qubits_to_plot): raise QiskitError('Not enough axis instances supplied. ' 'Please provide one per qubit discriminated.') # If only one qubit is present then draw the discrimination region. if show_boundary and len(self._qubit_mask) != 1: raise QiskitError('Background can only be plotted for individual ' 'qubit discriminators. Qubit mask has length ' '%i != 1' % len(self._qubit_mask)) x_data = np.array(self._xdata) y_data = np.array(self._ydata) if show_boundary and len(self._qubit_mask) == 1: try: xx, yy = self._get_iq_grid(x_data) zz = self.discriminate(np.c_[xx.ravel(), yy.ravel()]) zz = np.array(zz).astype(float).reshape(xx.shape) axs[0].contourf(xx, yy, zz, alpha=.2) except ValueError: raise QiskitError('Cannot convert expected state labels to ' 'float.') n_qubits = len(self._qubit_mask) if show_fitting_data: for idx, q in enumerate(qubits_to_plot): q_idx = self._qubit_mask.index(q) ax = axs[idx] # Different results may have the same expected state. # First merge all the data with the same expected state. data = {} for _, exp_state in self.expected_states.items(): if exp_state not in data: data[exp_state] = {'I': [], 'Q': []} dat = x_data[y_data == exp_state] data[exp_state]['I'].extend(dat[:, q_idx]) data[exp_state]['Q'].extend(dat[:, n_qubits + q_idx]) # Plot the data by expected state. for exp_state in data: ax.scatter(data[exp_state]['I'], data[exp_state]['Q'], label=exp_state, alpha=0.5) if flag_misclassified: y_disc = np.array(self.discriminate(self._xdata)) misclassified = x_data[y_disc != y_data] ax.scatter(misclassified[:, q_idx], misclassified[:, n_qubits + q_idx], color='r', alpha=0.5, marker='x') ax.legend(frameon=True) if title: for idx, q in enumerate(qubits_to_plot): axs[idx].set_title('Qubit %i' % q) for ax in axs: ax.set_xlabel('I (arb. units)') ax.set_ylabel('Q (arb. units)') return axs, fig @staticmethod def _get_iq_grid(x_data: np.array) -> (np.meshgrid, np.meshgrid): """ Create mesh grids used to plot the decision boundary. Args: x_data (np.array): IQ data. Returns: xx (np.meshgrid): xx meshgrid for plotting discriminator boundary yy (np.meshgrid): yy meshgrid for plotting discriminator boundary """ max_i = np.max(x_data[:, 0]) min_i = np.min(x_data[:, 0]) max_q = np.max(x_data[:, 1]) min_q = np.min(x_data[:, 1]) spacing = (max_i - min_i) / 100.0 xx, yy = np.meshgrid( np.arange(min_i
the figure plt.colorbar() # plt.axis() plt.show() # plt.savefig("relXtarget_%d_%d.jpg" % (lim_l, lim_r)) def plotRelXTarget(target, relative, lim_l=0, lim_r=500, particle=""): ''' Plots the relative energy difference against the target energy. :parameter target: array of energy targets (true value label). :type target: numpy.ndarray :parameter relative: array of the relative energy differences. :type relative: numpy.ndarray. :parameter lim_l: minimum value in the x axis. :type lim_l: float :parameter lim_r: defines the maximum value in the x axis. :type lim_r: float :parameter particle: name of the particle in the dataset, for the title. :type particle: str ''' plt.figure(figsize=(5, 5)) plt.xlabel("Target energy (GeV)") plt.ylabel("Relative energy difference (%)") plt.title("%s \n Relative energy difference X True energy" % particle) plt.scatter(target, relative, color='g', alpha=0.5) plt.xlim(lim_l, lim_r) plt.ylim(-100, 100) plt.legend() plt.show() # plt.savefig("relXtarget_%d_%d.jpg" % (lim_l, lim_r)) def plotMeanXEnergy(target, predicted, lim_y=0.14, lim_l=0, lim_r=520, limit=False): ''' Not so useful. Plots the prediction error. (Mean of the distribution of the difference between the target and the predicted energy, divided by the prediction energy, against the target energy). :parameter target: array of energy targets (true value label). :type target: numpy.ndarray :parameter predicted: array of predictions from testing. :type predicted: numpy.ndarray :parameter lim_y: maximum value for the y axis. :type lim_y: float :parameter lim_l: minimum energy value, x axis. :type lim_l: float :parameter lim_r: maximum energy value, x axis. :type lim_r: float :parameter limit: whether to limit the axes. :type limit: bool ''' plt.figure(figsize=(5, 5)) plt.xlabel("True energy (GeV)") plt.ylabel("Energy difference mean / Predicted energy") plt.title("Mean. \n Energies between %d and %d GeV." % (lim_l, lim_r)) #plt.title("Mean") plt.scatter(target, np.mean(_dif(target, predicted)) / predicted, color='g', alpha=0.5) if (limit): plt.xlim(lim_l, lim_r) plt.ylim(0, lim_y) plt.legend() plt.show() # plt.savefig("meanXenergy_%d_%d.jpg" % (lim_l, lim_r)) def plotStdXEnergy(target, predicted, lim_y=2.7, lim_l=0, lim_r=520, limit=False): ''' Not so useful. Plots the prediction deviation depending on the true energy. (Standard deviation of the distribution of the difference between the target and the predicted energy, divided by the predicted energy, against the target energy). :parameter target: array of energy targets (true value label). :type target: numpy.ndarray :parameter predicted: array of predictions from testing. :type predicted: numpy.ndarray :parameter lim_y: maximum value for the y axis. :type lim_y: float :parameter lim_l: minimum energy value, x axis. :type lim_l: float :parameter lim_r: maximum energy value, x axis :type lim_r: float :parameter limit: whether or not to limit the axes. :type limit: bool ''' plt.figure(figsize=(5, 5)) plt.xlabel("True energy (GeV)") plt.ylabel("Standard deviation of the energy difference / Predicted energy") plt.title("Standard deviation \n Energies between %d and %d GeV" % (lim_l, lim_r)) #plt.title("Standard deviation") plt.scatter(target, np.std(_dif(target, predicted)) / predicted, color='g', alpha=0.5) if limit: plt.xlim(lim_l, lim_r) plt.ylim(0, lim_y) plt.legend() plt.show() # plt.savefig("stdXenergy_%d_%d.jpg" % (lim_l, lim_r)) def binning(nbins, label, pred, plot=False): ''' Divides the data into n bins containing energy ranges of the same size. :parameter nbins: number of bins. :type nbins: int :parameter label: array of energy targets (true value label). :type label: numpy.ndarray :parameter pred: array of predictions from testing. :type pred: numpy.ndarray :parameter plot: whether to plot Predicted X Target and histogram for each energy bin. :type plot: bool :return: arrays of means, relative means, standard deviations, relative standard deviations, size of the bins, and energy resolution. :rtype: array, array, array, array, array, array. ''' #if __package__ is None: # sys.path.append(os.path.realpath("/data/shared/Software/CMS_Deep_Learning")) #from CMS_Deep_Learning.io import gen_from_data, retrieve_data #from CMS_Deep_Learning.postprocessing.metrics import distribute_to_bins out, x, y = distribute_to_bins(label, [label, pred], nb_bins=nbins, equalBins=True) # x -> true energy # y -> pred energy iSize = 500 / nbins means = [] rMeans = [] # normalized means stds = [] rStds = [] # normalized standard deviations sizes = [] # number of events in the bins res= [] # calorimeter energy resolution for i in range(0, nbins): sizes.append(len(x[i])) if (plot == True): #plotPredictedXTarget(x[i], y[i], i * iSize, (i + 1) * iSize) PredictedTarget(x[i], y[i], i * iSize, (i + 1) * iSize) # histEDif(x[i], y[i], nbins=200, lim=20, lim_l=i*iSize, lim_r=(i+1)*iSize) histRelDif(x[i], y[i], nbins=150, lim=15, lim_l=i*iSize, lim_r=(i+1)*iSize) difference = _dif(x[i], y[i]) relDiff = _rDif_pctg(x[i], y[i]) mean = np.mean(difference) means.append(mean) rMean = np.mean(relDiff) rMeans.append(rMean) std = np.std(difference) stds.append(std) rStd = np.std(relDiff) rStds.append(rStd) eRes = std / np.mean(x[i]) res.append(eRes) return x, y, means, rMeans, stds, rStds, sizes, res def plotN(inp, stds, sizes, what, particle=""): ''' TOO LONG AND COMPLICATED. CHECK METHODS BELOW. Plots the means or stds (normalized or not) for the bins of energy. :param inp: array containing the data to be plotted (means, rMeans, stds or rStds). :type inp: array :param stds: stds array to calculate the error. :type stds: array :param sizes: array containing the number of samples in each bin, to calculate the error. :type sizes: array :param what: what is plotted (means, rMeans, stds or rStds), for the legend. :type what: str :parameter particle: name of the particle in the dataset, for the title. :type particle: str ''' plt.figure(figsize=(5, 5)) plt.xlabel("Energy", size=16) n = len(inp) # print(n) iSize = 500 / n if what == "means": for i in range(0, n): x_axis = (i * iSize + (i + 1) * iSize) / 2 error = stds[i] / np.sqrt(sizes[i]) plt.scatter(x_axis, inp[i], color='purple', alpha=0.5 # , label='%d to %d GeV' % (i * iSize, (i + 1) * iSize) ) plt.errorbar(x_axis, inp[i], yerr=error, color='black') plt.ylabel("$\mu_{\Delta E}$ (GeV)", size=19) plt.title("%s Means" % particle, size=16) elif what == "rMeans": for i in range(0, n): energy = (i * iSize + (i + 1) * iSize) / 2 error = stds[i] / np.sqrt(sizes[i]) plt.scatter(energy, inp[i], color='pink', alpha=0.8 # , label='%d to %d GeV' % (i * iSize, (i + 1) * iSize) ) plt.errorbar(energy, inp[i], yerr=error, color='purple') plt.ylabel(r"$\mu_{\frac{\Delta E}{E}}$ (%)", size=19) plt.title("%s Relative means" % particle, size=16) elif what == "stds": for i in range(0, n): energy = (i * iSize + (i + 1) * iSize) / 2 plt.scatter(energy, inp[i], color='blue', alpha=0.5 # , label='%d to %d GeV' % (i * iSize, (i + 1) * iSize) ) plt.ylabel("$\sigma_{\Delta E}$ (GeV)", size=19) plt.title("%s Standard deviations" % particle, size=16) elif what == "rStds": for i in range(0, n): energy = (i * iSize + (i + 1) * iSize) / 2 plt.scatter(energy, inp[i], color='orange', alpha=0.5 # , label='%d to %d GeV' % (i * iSize, (i + 1) * iSize) ) plt.ylabel(r"$\sigma_{\frac{\Delta E}{E}}$ (%)", size=19) plt.title("%s Relative standard deviations" % particle, size=16) elif what == "res": for i in range(0, n): energy = (i * iSize + (i + 1) * iSize) / 2 plt.scatter(energy, inp[i], color='blue', alpha=0.5 # , label='%d to %d GeV' % (i * iSize, (i + 1) * iSize) ) plt.ylabel(r"$\frac{\sigma({\Delta E})}{E_{mean}}$ (GeV)", size=19) plt.title("%s Energy resolution" % particle, size=16) else: raise ValueError("'what' should be 'means', 'stds', 'rMeans', 'rStds', or 'res'. ") plt.xlim(0, 500) plt.legend(loc='best', bbox_to_anchor=(1.52, 0.9)) plt.show() # plt.savefig("means.jpg") def means(means, stds, sizes, particle ="", col='purple'): ''' Plots the absolute mean for each bin of energy. :param means: array containing the means to be plotted. :type means: array :param stds: stds array to calculate the error. :type stds: array :param sizes: array containing the number of samples in each bin, to calculate the error. :type sizes: array :parameter particle: name of the particle in the dataset, for the title. :type particle: str ''' plt.figure(figsize=(5, 5)) n = len(means) # print(n) iSize = 500 / n for i in range(0, n): x_axis = (i * iSize + (i + 1) * iSize) / 2 error = stds[i] / np.sqrt(sizes[i]) plt.scatter(x_axis, means[i], color=col, alpha=0.5 # , label='%d to %d GeV' % (i * iSize, (i + 1) * iSize) ) plt.errorbar(x_axis, means[i], yerr=error, color='black') plt.xlabel("Energy (GeV)", size=16) plt.ylabel("$\mu(\Delta E)$ (GeV)", size=19) plt.title("%s Means" % particle, size=16) plt.xlim(0, 500) #plt.legend(loc='best', bbox_to_anchor=(1.52, 0.9)) plt.show() # plt.savefig("means.jpg") def rMeans(rMeans, stds, sizes, particle ="", col='pink'): ''' Plots the relative mean for each bin of energy. :param rMeans: array containing the relative means. :type rMeans: array :param stds: stds array to calculate the error. :type stds: array :param sizes: array containing
#!/usr/bin/env python ## @file # # Plot a PEMap. The PEMap is generated by running matmul with the # --print-PEMap command line option. # # @author <NAME> <<EMAIL>> # @author <NAME> <<EMAIL>> import math import re import subprocess import sys import tempfile import pdb try: import numpy as np except ImportError as e: print("can not import numpy: " + str(e)) sys.exit(0) try: import argparse except ImportError as e: print("can not import argparse: " + str(e)) sys.exit(0) ############################################## ## Print a line in the POVRay script. # # @param line The line to print. def script (line): global script_file global python_version if python_version.major == 2: script_file.write(line) else: script_file.write(bytes(line, "UTF-8")) ## Open a script file. # # @param iteration The current iteration. # @param suffix The script filename suffix. def openScriptFile (iteration, suffix): global basename global script_file if basename != None: script_file = open("{:s}.{:d}.{:s}".format( basename, iteration, suffix), "w+b") else: script_file = tempfile.NamedTemporaryFile( suffix = ".{:d}.{:s}".format(iteration, suffix), delete = False) print("writing script into {:s}".format(script_file.name)) ## Get a color vector given a PE. # # @param value The value of the PE. # @param N The total number of PEs. # # @return The color vector as RGB values between [ 0, 1 ]. def getColor (value, N): return [ math.cos(value/float(N-1)*math.pi/2.), math.sin(value/float(N-1)*math.pi/2.), 0 ] ## Call POVRay to render the PEMaps. # # @param iteration The current iteration. # @param filename The filename of the POVRay script. def render (iteration, filename): try: cmd = [ "povray", "-d", "Verbose=false", "+OPEMap_{:d}.png".format(iteration), "+H1080", "+W1920", filename ] povray = subprocess.Popen( cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE) povray.wait() except subprocess.CalledProcessError as e: print("error spawning povray using: " + e.cmd) if povray.returncode != 0: print("POVRAY: " + cmd.__str__()) for line in povray.stdout: print("POVRAY: " + line.rstrip().decode()) for line in povray.stderr: print("POVRAY: " + line.rstrip().decode()) ## POVRay helper. Open a box. # # @param xmin Lower corner. # @param ymin Lower corner. # @param zmin Lower corner. # @param xmax Upper corner. # @param ymax Upper corner. # @param zmax Upper corner. def box_open (xmin, ymin, zmin, xmax, ymax, zmax): script("box {\n") script(" < {:f}, {:f}, {:f} >, < {:f}, {:f}, {:f} >\n".format( xmin, ymin, zmin, xmax, ymax, zmax)) ## POVRay helper. Draw a wire. # # @param xmin Starting point. # @param ymin Starting point. # @param zmin Starting point. # @param xmax End point. # @param ymax End point. # @param zmax End point. def wire (xmin, ymin, zmin, xmax, ymax, zmax): script("cylinder {\n") script(" < {:f}, {:f}, {:f} >, < {:f}, {:f}, {:f} >, {:f}\n".format( xmin, ymin, zmin, xmax, ymax, zmax, 0.1)) script(" pigment { color White }\n") script("}\n") return ## Print a label. # # @param text The text to print. # @param x The x offset. # @param y The y offset. # @param z The z offset. def label (text, x, y, z): script("text {\n") script(" ttf \"/usr/share/fonts/droid/DroidSans.ttf\" \"{:s}\" 0.5, 0\n".format(text)) script(" translate < {:f}, {:f}, {:f} >\n".format(x, y, z)) script(" pigment { White }\n") script("}\n") ## Generate a POVRay script and render it. # # @param iteration The current iteration. # @param numPEs The total number of PEs. # @param PEMap_A The PEMap for matrix A. # @param PEMap_C The PEMap for matrix C. # @param PEMap_convolution The PEMap for the convolution. # @param norms_convolution The product norms of the convolution. def generatePOVRay ( iteration, numPEs, PEMap_A, PEMap_C, PEMap_convolution, norms_convolution): global script_file openScriptFile(iteration, "pov") ( N, _ ) = PEMap_A.shape script("/* Automatically generated... */\n") script("#include \"colors.inc\"\n") # Place the camera. script("camera {\n") script(" location < {:e}, {:e}, {:e} >\n".format( 2*N/1.5, 2*N, 2*N)) script(" look_at < 0, 0, 0 >\n") script("}\n") # Add a few light sources. script("light_source {\n") script(" < {:d}, {:d}, {:d} >, White\n".format(2*N, 2*N, 2*N)) script(" parallel\n") script(" point_at < 0, 0, 0 >\n") script("}\n") script("light_source {\n") script(" < {:f}, {:f}, {:f} >, White\n".format(2*N, 2*N, N/2.)) script(" parallel\n") script(" point_at < {:f}, {:f}, {:f} >\n".format(2*N, 2*N, 0)) script("}\n") script("light_source {\n") script(" < {:f}, {:f}, {:f} >, White\n".format(2*N, N/2., 2*N)) script(" parallel\n") script(" point_at < {:f}, {:f}, {:f} >\n".format(2*N, 0, 2*N)) script("}\n") script("light_source {\n") script(" < {:f}, {:f}, {:f} >, White\n".format(N/2., 2*N, 2*N)) script(" parallel\n") script(" point_at < {:f}, {:f}, {:f} >\n".format(0, 2*N, 2*N)) script("}\n") # Plot axes. wire(0, -N/2., -N/2., N, -N/2., -N/2.) label("X-axis", N+1, -N/2., -N/2.) wire(-N/2., 0, -N/2., -N/2., N, -N/2.) label("Y-axis", -N/2., N+1, -N/2.) wire(-N/2., -N/2., 0, -N/2., -N/2., N) label("Z-axis", -N/2., -N/2., N+1) # Plot A map on x-y plane. box_open(0, 0, -N/2., N, N, -N/2.) script(" pigment { color White }\n") script("}\n") for i in range(N): for j in range(N): box_open(0.1+i, 0.1+j, -N/2.+0.1, 0.9+i, 0.9+j, -N/2.+0.1) color_vector = getColor(PEMap_A[i, j], numPEs) script(" pigment {{ color red {:f} green {:f} blue {:f} }}\n".format( color_vector[0], color_vector[1], color_vector[2])) script("}\n") # Plot B map on x-z plane. box_open(0, -N/2., 0, N, -N/2., N) script(" pigment { color White }\n") script("}\n") for i in range(N): for j in range(N): box_open(0.1+i, -N/2.+0.1, 0.1+j, 0.9+i, -N/2.+0.1, 0.9+j) color_vector = getColor(PEMap_A[i, j], numPEs) script(" pigment {{ color red {:f} green {:f} blue {:f} }}\n".format( color_vector[0], color_vector[1], color_vector[2])) script("}\n") # Plot C map on y-z plane. box_open(-N/2., 0, 0, -N/2., N, N) script(" pigment { color White }\n") script("}\n") for i in range(N): for j in range(N): box_open(-N/2.+0.1, 0.1+i, 0.1+j, -N/2.+0.1, 0.9+i, 0.9+j) color_vector = getColor(PEMap_C[i, j], numPEs) script(" pigment {{ color red {:f} green {:f} blue {:f} }}\n".format( color_vector[0], color_vector[1], color_vector[2])) script("}\n") # Plot convolution. maxNorm = np.amax(norm_convolution) for i in range(N): for j in range(N): for k in range(N): if PEMap_convolution[i, j, k] >= 0: box_open(0.1+i, 0.1+j, 0.1+k, 0.9+i, 0.9+j, 0.9+k) color_vector = getColor( PEMap_convolution[i, j, k], numPEs) script(" pigment {{ color red {:f} green {:f} blue {:f} ".format( color_vector[0], color_vector[1], color_vector[2])) script("transmit {:f} }}\n".format(1-norm_convolution[i,j,k]/maxNorm)) script(" finish { metallic 0.4 }\n") script(" hollow\n") script("}\n") script_file.close() render(iteration, script_file.name) ## Generate a POVRay script and render it. # # @param iteration The current iteration. # @param numPEs The total number of PEs. # @param PEMap_A The PEMap for matrix A. # @param PEMap_C The PEMap for matrix C. # @param PEMap_convolution The PEMap for the convolution. # @param norms_convolution The product norms of the convolution. def generateBlender ( iteration, numPEs, PEMap_A, PEMap_C, PEMap_convolution, norms_convolution): global script_file openScriptFile(iteration, "py") script("import bpy\n") script("bpy.ops.object.select_all(action = 'SELECT')\n") script("bpy.ops.object.delete()\n"); script("bpy.ops.object.camera_add(" + "location = ({:d}, {:d}, {:d}))\n".format(N, N, N)) script("bpy.ops.mesh.primitive_plane_add(radius = {:d}, ".format(N) + "location = ({:d}, {:d}, {:d}))\n".format(0, 0, 0)) for i in range(N): for j in range(N): for k in range(N): if PEMap_convolution[i, j, k] >= 0: script("bpy.ops.mesh.primitive_cube_add(radius=0.45, " + "location=({:d}, {:d}, {:d}))\n".format(i, j, k)) script("bpy.ops.material.new()\n") script_file.close() ## Generate a Mathematica script. # # @param iteration The current iteration. # @param numPEs The total number of PEs. # @param PEMap_A The PEMap for matrix A. # @param PEMap_C The PEMap for matrix C. # @param PEMap_convolution The PEMap for the convolution. # @param norms_convolution The product norms of the convolution. def generateMathematica ( iteration, numPEs, PEMap_A, PEMap_C, PEMap_convolution, norms_convolution): global script_file openScriptFile(iteration, "nb") # Plot convolution. maxNorm = np.amax(norm_convolution) script("Graphics3D[ {\n"); for i in range(N): for j in range(N): for k in range(N): if PEMap_convolution[i, j, k] >= 0: color_vector = getColor( PEMap_convolution[i, j, k], numPEs) script(" RGBColor[ {:f}, {:f}, {:f} ], ".format( color_vector[0], color_vector[1], color_vector[2])) script("Opacity[ {:f} ], Cuboid[".format( norm_convolution[i,j,k]/maxNorm)) script("{{ {:f}, {:f}, {:f} }}, ".format(0.1+i, 0.1+j, 0.1+k)) script("{{ {:f}, {:f}, {:f} }} ],\n".format(0.9+i, 0.9+j, 0.9+k)) script("} ]\n") script_file.close() ## Print the communication complexity. def print_load (N, numPEs, PEMap): communication_complexity = 0 max_communication_complexity = 0 computational_load = np.zeros(numPEs, dtype = "int") for i in range(N): for j in range(N): for k in range(N): if PEMap["convolution"][i, j, k] >= 0: computational_load[PEMap["convolution"][i, j, k]] += 1 if PEMap["convolution"][i, j, k] != PEMap["matrix P"][i, k]: communication_complexity += 2 max_communication_complexity += 2 if PEMap["convolution"][i, j, k] != PEMap["matrix P"][k, j]: communication_complexity += 2 max_communication_complexity += 2 if PEMap["convolution"][i, j, k] != PEMap["matrix P2"][i, j]: communication_complexity += 1 max_communication_complexity += 1 print("communication complexity: {:d} out of {:d}".format( communication_complexity, max_communication_complexity)) print("computational load: {:d}".format(np.max(computational_load))) ## The main program. def main (): ## The python version. global python_version python_version = sys.version_info if python_version.major == 2 and python_version.minor < 7: print("need at least python 2.7 (running {:d}.{:d})".format( python_version.major, python_version.minor)) sys.exit(1) ## The parser object. parser = argparse.ArgumentParser() parser.add_argument("FILE", help = "The file to plot. A missing FILE means reading from standard input.", nargs = "?", type = argparse.FileType("r"), default = sys.stdin) parser.add_argument("--output",
import cv2 as cv # opencv import copy # for deepcopy on images import numpy as np # numpy from random import randint # for random values import threading # for deamon processing from pathlib import Path # for directory information import os # for directory information from constants import constants # constants class PlantDetector: """Dynamically apply detection algorithms to source images All images are sourced from and follow naming standard from the KOMATSUNA dataset http://limu.ait.kyushu-u.ac.jp/~agri/komatsuna/ METHODS __init__(self, src='multi_plant', labels='multi_label') [void] prepares the images and labels for display initializes windows and trackbars runs background subtraction on plant group images on_low_H_thresh_trackbar(self, val) on_high_H_thresh_trackbar(self, val) on_low_S_thresh_trackbar(self, val) on_high_S_thresh_trackbar(self, val) on_low_V_thresh_trackbar(self, val) on_high_V_thresh_trackbar(self, val) HSV trackbar triggers prepare_plant_collection(self, src, labelsrc) returns [plants, plant_groups, labels] constructor helper function for loading plant images parse(self, auto_inc=False, mode=0) [void] main function dynamically applies HSV inRange filters watershed algorithm to the currently displayed image based on selected HSV trackbar values six modes are displayable: mode: window1 + window2 0 : original (fallback) + original 1 : HSV filter range + original 2 : bare watershed masks + labels 3 : watershed masks w/ bg + original 4 : sequential bg sub + original 5 : seq bg sub w/ watersh + original additionally, the user is allowed control key | function m | next image n | prev image s | save selected image in the selected mode z | save all images in selected mode esc | exit the program d | dynamically calculate dice f | show dice data based on saved images 1-5 | select the respective mode parse is also used for saving all images parse is run for all images in the given mode either in parrallel or in place save_one(self, mode, image, filename) [void] saves the image in the appropriate mode folder with filename HSV_filtering_and_watershed(self, input_im) [mask, input_im, im_threshold] image is filtered through HSV inRange according to trackbar values image is prepared (threshold) for watershed algorithm watershed algorithm is applied markers are applied to image dicify_wrapper(self, image_id) [void] runs dice summary in background dicify_summary(self, image_id) [void] prints summary of dice values for image, plant, dateset note: based on saved images dicify_one(self, image_id) [dice] returns the dice value for the given image_id based on saved segmentation and label images dicify_one_dynamic(self, mask, image_id) [dice] returns dice value for the given image_id based on given mask (current) and saved label image dicify_plant(self, plant_id) [mean, min, max] returns mean, min and max dice values for images in plant group dicify_all(self) [mean, min, max] returns mean, min and max dice values for images in dataset and for each plant """ def __init__(self, src='multi_plant', labels='multi_label'): self.c = constants() self.window1 = self.c.window.window1 self.window2 = self.c.window.window2 cv.namedWindow(self.window1) cv.namedWindow(self.window2) cv.moveWindow(self.window2, 550, 90) cv.createTrackbar( self.c.HSV.low_H_name, self.window1, self.c.HSV.low_H, self.c.HSV.max_value_H, self.on_low_H_thresh_trackbar) cv.createTrackbar( self.c.HSV.high_H_name, self.window1, self.c.HSV.high_H, self.c.HSV.max_value_H, self.on_high_H_thresh_trackbar) cv.createTrackbar( self.c.HSV.low_S_name, self.window1, self.c.HSV.low_S, self.c.HSV.max_value, self.on_low_S_thresh_trackbar) cv.createTrackbar( self.c.HSV.high_S_name, self.window1, self.c.HSV.high_S, self.c.HSV.max_value, self.on_high_S_thresh_trackbar) cv.createTrackbar( self.c.HSV.low_V_name, self.window1, self.c.HSV.low_V, self.c.HSV.max_value, self.on_low_V_thresh_trackbar) cv.createTrackbar( self.c.HSV.high_V_name, self.window1, self.c.HSV.high_V, self.c.HSV.max_value, self.on_high_V_thresh_trackbar) self.plants, self.plant_groups, self.labels = self.prepare_plant_collection(src, labels) # source https://docs.opencv.org/3.4/d1/dc5/tutorial_background_subtraction.html for key in self.plant_groups: if self.c.bgsub.mod == 'MOG2': backSub = cv.createBackgroundSubtractorMOG2(history=60, detectShadows=True) elif self.c.bgsub.mod == 'KNN': backSub = cv.createBackgroundSubtractorKNN() fgMask = None for i, image in enumerate(self.plant_groups[key]): fgMask = backSub.apply(image) self.plant_groups[key][i] = fgMask def on_low_H_thresh_trackbar(self, val): self.c.HSV.low_H = val self.c.HSV.low_H = min(self.c.HSV.high_H-1, self.c.HSV.low_H) cv.setTrackbarPos( self.c.HSV.low_H_name, self.window1, self.c.HSV.low_H) def on_high_H_thresh_trackbar(self, val): self.c.HSV.high_H = val self.c.HSV.high_H = max(self.c.HSV.high_H, self.c.HSV.low_H+1) cv.setTrackbarPos( self.c.HSV.high_H_name, self.window1, self.c.HSV.high_H) def on_low_S_thresh_trackbar(self, val): self.c.HSV.low_S = val self.c.HSV.low_S = min(self.c.HSV.high_S-1, self.c.HSV.low_S) cv.setTrackbarPos( self.c.HSV.low_S_name, self.window1, self.c.HSV.low_S) def on_high_S_thresh_trackbar(self, val): self.c.HSV.high_S = val self.c.HSV.high_S = max(self.c.HSV.high_S, self.c.HSV.low_S+1) cv.setTrackbarPos( self.c.HSV.high_S_name, self.window1, self.c.HSV.high_S) def on_low_V_thresh_trackbar(self, val): self.c.HSV.low_V = val self.c.HSV.low_V = min(self.c.HSV.high_V-1, self.c.HSV.low_V) cv.setTrackbarPos( self.c.HSV.low_V_name, self.window1, self.c.HSV.low_V) def on_high_V_thresh_trackbar(self, val): self.c.HSV.high_V = val self.c.HSV.high_V = max(self.c.HSV.high_V, self.c.HSV.low_V+1) cv.setTrackbarPos( self.c.HSV.high_V_name, self.window1, self.c.HSV.high_V) def prepare_plant_collection(self, src, labelsrc): plants = [] plant_groups = dict() files = os.listdir(src) files.sort() for fl in files: input_im = cv.imread(src + '/' + fl, cv.IMREAD_COLOR) if (input_im is None): exit() plants.append({ 'p': input_im, 'n': fl }) group_id = f'{fl.split("_")[1]}{fl.split("_")[2]}' if group_id not in plant_groups: plant_groups[group_id] = [] plant_groups[group_id].append(input_im) labels = [] files = os.listdir(labelsrc) files.sort() for fl in files: input_im = cv.imread(labelsrc + '/' + fl) if (input_im is None): exit() labels.append(input_im) return plants, plant_groups, labels def parse(self, auto_inc=False, mode=0): key = 0 i = 0 l_tog = False while key != self.c.cntr.exit_k: if auto_inc and i == len(self.plants): break image = copy.deepcopy(self.plants[i]['p']) group_id = f'{self.plants[i]["n"].split("_")[1]}{self.plants[i]["n"].split("_")[2]}' mask, markers, im_threshold = self.HSV_filtering_and_watershed(image) _, bgfgSegMarkers, _ = self.HSV_filtering_and_watershed( cv.cvtColor(self.plant_groups[group_id][i % 60], cv.COLOR_GRAY2BGR) ) if mode == 5: alt = bgfgSegMarkers text = f'Watershed new areas w/ fg/bg segm. {self.plants[i]["n"]}' tcol = (255, 255, 255) elif mode == 4: alt = copy.deepcopy(self.plant_groups[group_id][i % 60]) text = f'FG/BG segmentation {self.plants[i]["n"]}' tcol = (255, 255, 255) elif mode == 3: alt = markers text = f'Watershed algorithm areas w/ bg {self.plants[i]["n"]}' tcol = (0, 0, 0) elif mode == 2: alt = mask text = f'Watershed algorithm areas bare {self.plants[i]["n"]}' tcol = (255, 255, 255) elif mode == 1: alt = im_threshold text = f'HSV inRange threshold {self.plants[i]["n"]}' tcol = (255, 255, 255) else: alt = copy.deepcopy(self.plants[i]['p']) text = f'Original {self.plants[i]["n"]}' tcol = (0, 0, 0) if self.c.asth.text: cv.putText(alt, text, (0, 20), self.c.asth.font, .5, tcol, 1) cv.imshow(self.window1, alt) if l_tog: cv.imshow(self.window2, self.labels[i]) else: cv.imshow(self.window2, self.plants[i]['p']) key = cv.waitKey(10) if key == self.c.cntr.prev_k and i > 0: i -= 1 if key == self.c.cntr.next_k and i < len(self.plants) - 1: i += 1 if key == self.c.cntr.save or auto_inc: self.save_one(mode, alt, self.plants[i]["n"]) if key == self.c.cntr.save_all: self.parse(True, mode) if key == self.c.cntr.dice: print(self.dicify_one_dynamic(mask, self.plants[i]['n'])) if key == self.c.cntr.dice_more: self.dicify_wrapper(self.plants[i]['n']) if key == self.c.cntr.m1_k: mode = 1 l_tog = False elif key == self.c.cntr.m2_k: mode = 2 l_tog = True elif key == self.<KEY>: mode = 3 l_tog = False elif key == self.<KEY>: mode = 4 l_tog = False elif key == self.<KEY>: mode = 5 l_tog = False if auto_inc: i += 1 def save_one(self, mode, image, filename): Path(f'formatted/{self.c.cntr.modes[mode]}').mkdir(parents=True, exist_ok=True) cv.imwrite(f'formatted/{self.c.cntr.modes[mode]}/{filename}', image) def HSV_filtering_and_watershed(self, input_im): im_threshold = cv.inRange( cv.cvtColor(input_im, cv.COLOR_BGR2HSV), (self.c.HSV.low_H, self.c.HSV.low_S, self.c.HSV.low_V), (self.c.HSV.high_H, self.c.HSV.high_S, self.c.HSV.high_V) ) # source https://docs.opencv.org/master/d3/db4/tutorial_py_watershed.html kernel = np.ones((3, 3), np.uint8) opening = cv.morphologyEx(im_threshold, cv.MORPH_OPEN, kernel, iterations=5) sure_bg = cv.dilate(opening, kernel, iterations=7) dist_transform = cv.distanceTransform(opening, cv.DIST_L2, 5) _, sure_fg = cv.threshold(dist_transform, 0.3*dist_transform.max(), 255, 0) sure_fg = np.uint8(sure_fg) unknown = cv.subtract(sure_bg, sure_fg) _, markers = cv.connectedComponents(sure_fg) markers = markers + 1 markers[unknown == 255] = 0 markers = cv.watershed(input_im, markers) input_im[markers == -1] = [255, 0, 0] for i in range(2, markers.max() + 1): input_im[markers == i] = [ randint(0, 255), randint(0, 255), randint(0, 255) ] if self.c.xtra.disco else [ (40 + i * 40) % 255, (i * 40) % 255, (50 + i * 40) % 255 ] mask = copy.deepcopy(input_im) mask[markers < 2] = [0, 0, 0] return mask, input_im, im_threshold def dicify_wrapper(self, image_id): thread = threading.Thread(target=self.dicify_summary, args=(image_id,), daemon=True) thread.start() def dicify_summary(self, image_id): print(self.dicify_all()) def dicify_one(self, image_id): # Source: https://github.com/Kornelos/CV_MINI_1/blob/master/process_plants.py img = cv.imread(f'multi_label/label_{image_id.split("_", 1)[1]}') img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) _, gt = cv.threshold(img, 1, 255, cv.THRESH_BINARY) img = cv.imread(f'formatted/ws_mask/{image_id}') img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) _, rt = cv.threshold(img, 1, 255, cv.THRESH_BINARY) k = 255 dice = np.sum(rt[gt == k]) * 2.0 / (np.sum(rt[rt == k]) + np.sum(gt[gt == k])) return dice def dicify_one_dynamic(self, mask, image_id): img = cv.imread(f'multi_label/label_{image_id.split("_", 1)[1]}') img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) _, gt = cv.threshold(img, 1, 255, cv.THRESH_BINARY) img = cv.cvtColor(mask, cv.COLOR_BGR2GRAY) _, rt = cv.threshold(img, 1, 255, cv.THRESH_BINARY) k = 255 dice = np.sum(rt[gt == k]) * 2.0 / (np.sum(rt[rt == k]) + np.sum(gt[gt == k])) return dice def dicify_plant(self, plant_id): vals = [] for im_data in [ t for t in self.plants if t['n'].split('_')[2] == plant_id ]: vals.append(self.dicify_one(im_data['n'])) return [np.mean(vals), min(vals), max(vals)] def dicify_all(self): means = [] mins = [] maxs = [] summ = "id | mean | min | max" for i in range(0, 5): plant = self.dicify_plant(f'0{str(i)}') means.append(plant[0])
'option': 0, 'original': 'unsplitsuperlong', 'normalized': 'un split shorter', 'map': [0, 1, 2, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 15] } ] assert self.assert_map('tokenizer_split_replace_for_map.xml', testcases) == True, 'Something is wrong.' def test_tokenizer_map_split_replace_to_nothing(self): testcases = [ { 'word_separator': ' ', 'option': 0, 'original': 'unsplitnothing.', 'normalized': 'un split .', 'map': [0, 1, 2, 2, 3, 4, 5, 6, 14, 14] }, { 'word_separator': ' ', 'option': 0, 'original': 'unsplitnothing', 'normalized': 'un split', 'map': [0, 1, 2, 2, 3, 4, 5, 13] } ] assert self.assert_map('tokenizer_split_replace_for_map.xml', testcases) == True, 'Something is wrong.' def test_tokenizer_map_split_replace_character(self): testcases = [ { 'word_separator': ' ', 'option': 0, 'original': 'unsplity.', 'normalized': 'un split x .', 'map': [0, 1, 2, 2, 3, 4, 5, 6, 7, 7, 8, 8] }, { 'word_separator': ' ', 'option': 0, 'original': 'unsplity', 'normalized': 'un split x', 'map': [0, 1, 2, 2, 3, 4, 5, 6, 7, 7] } ] assert self.assert_map('tokenizer_split_replace_for_map.xml', testcases) == True, 'Something is wrong.' def test_tokenizer_map_option_list(self): testcases = [ { 'word_separator': ' ', 'option': 1, 'original': 'ABC123def-ghi-jkl.', 'normalized': '- - . 123 abc def ghi jkl', 'map': [] } ] assert self.assert_map('tokenizer_basic_ci.xml', testcases) == True, 'Something is wrong.' def test_tokenizer_map_option_set(self): testcases = [ { 'word_separator': ' ', 'option': 2, 'original': 'ABC123def-ghi-jkl.', 'normalized': '- . 123 abc def ghi jkl', 'map': [] } ] assert self.assert_map('tokenizer_basic_ci.xml', testcases) == True, 'Something is wrong.' def test_tokenizer_default(self): builder = sic.Builder() worker = builder.build_normalizer() testcase = 'Abc123def-ghdeLtai456-jkl' expected = 'abc 123 def - gh delta i 456 - jkl' tokenized = worker.normalize(testcase) assert tokenized == expected, 'Unexpected tokenization result for default config: "%s" => "%s" (expected "%s")' % (testcase, tokenized, expected) def test_tokenizer_map_nothing(self): testcases = [ { 'word_separator': ' ', 'option': 0, 'original': 'nothing.', 'normalized': '.', 'map': [7] }, { 'word_separator': ' ', 'option': 0, 'original': 'nothing', 'normalized': '', 'map': [] } ] assert self.assert_map('tokenizer_split_replace_for_map.xml', testcases) == True, 'Something is wrong.' def test_tokenizer_plurals_left(self): testcases = [ { 'original': 'plurals plurals', 'expected': { 'normal': 'lurals lurals', 'list': 'lurals lurals', 'set': 'lurals' } } ] assert self.assert_normalization('tokenizer_plurals_left.xml', 'test_plurals', testcases) == True, 'Something is wrong.' def test_tokenizer_plurals_middle(self): testcases = [ { 'original': 'plurals plurals', 'expected': { 'normal': 'plu als plu als', 'list': 'als als plu plu', 'set': 'als plu' } } ] assert self.assert_normalization('tokenizer_plurals_middle.xml', 'test_plurals', testcases) == True, 'Something is wrong.' def test_tokenizer_plurals_right(self): testcases = [ { 'original': 'plurals plurals', 'expected': { 'normal': 'plural plural', 'list': 'plural plural', 'set': 'plural' } } ] assert self.assert_normalization('tokenizer_plurals_right.xml', 'test_plurals', testcases) == True, 'Something is wrong.' def test_tokenizer_plurals_all(self): testcases = [ { 'original': 'plurals plurals', 'expected': { 'normal': 'lu al lu al', 'list': 'al al lu lu', 'set': 'al lu' } } ] assert self.assert_normalization('tokenizer_plurals_all.xml', 'test_plurals', testcases) == True, 'Something is wrong.' def test_tokenizer_no_plurals_right(self): testcases = [ { 'original': 'plurals plurals', 'expected': { 'normal': 'plurals plurals', 'list': 'plurals plurals', 'set': 'plurals' } } ] assert self.assert_normalization('tokenizer_no_plurals_right.xml', 'test_plurals', testcases) == True, 'Something is wrong.' def test_implicit_default_normalize(self): sic.reset() result = sic.normalize('nfkappab') expected = 'nf kappa b' if isinstance(sic.result, dict): result_map = sic.result else: result_map = sic.result() expected_map = { 'original': 'nfkappab', 'normalized': 'nf kappa b', 'map': [0, 1, 7, 2, 3, 4, 5, 6, 7, 7], 'r_map': [[0, 0], [1, 1], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [2, 9]] } assert result == expected, 'Expected "%s", got "%s".' % (expected, result) assert result_map == expected_map, 'Expected "%s", got "%s".' % (str(expected_map), str(result_map)) def test_implicit_normalize_with_parameters(self): result = [ sic.normalize('abc,Def123ghi', tokenizer_config='%s/tokenizer_basic_ci.xml' % (self.assets_dir)), sic.normalize('abc,Def123ghi', tokenizer_config='%s/tokenizer_basic_cs.xml' % (self.assets_dir)), sic.normalize('abc,Def123ghi', tokenizer_config='%s/tokenizer_basic_ci.xml' % (self.assets_dir), word_separator='|'), sic.normalize('abc,Def123ghi', tokenizer_config='%s/tokenizer_basic_cs.xml' % (self.assets_dir), word_separator='|'), sic.normalize('abc,Def123ghi', tokenizer_config='%s/tokenizer_basic_ci.xml' % (self.assets_dir), normalizer_option=1), sic.normalize('abc,Def123ghi', tokenizer_config='%s/tokenizer_basic_cs.xml' % (self.assets_dir), normalizer_option=1), sic.normalize('abc,Def123ghi', tokenizer_config='%s/tokenizer_basic_ci.xml' % (self.assets_dir), word_separator='|', normalizer_option=1), sic.normalize('abc,Def123ghi', tokenizer_config='%s/tokenizer_basic_cs.xml' % (self.assets_dir), word_separator='|', normalizer_option=1) ] expected = [ 'abc , def 123 ghi', 'abc , Def 123 ghi', 'abc|,|def|123|ghi', 'abc|,|Def|123|ghi', ', 123 abc def ghi', ', 123 Def abc ghi', ',|123|abc|def|ghi', ',|123|Def|abc|ghi' ] for i in range(0, len(result)-1): assert result[i] == expected[i], 'Test case #%d: expected "%s", got "%s".' % (i, expected[i], result[i]) def test_implicit_build_normalize(self): result, expected = [], [] sic.build_normalizer('%s/tokenizer_basic_ci.xml' % (self.assets_dir)) result.append(sic.normalize('abc,Def123ghi')) expected.append('abc , def 123 ghi') sic.build_normalizer('%s/tokenizer_basic_cs.xml' % (self.assets_dir)) result.append(sic.normalize('abc,Def123ghi')) expected.append('abc , Def 123 ghi') result.append(sic.normalize('abc,Def123ghi', tokenizer_config='%s/tokenizer_basic_ci.xml' % (self.assets_dir))) expected.append('abc , def 123 ghi') result.append(sic.normalize('abc,Def123ghi')) expected.append('abc , Def 123 ghi') for i in range(0, len(result)-1): assert result[i] == expected[i], 'Test case #%d: expected "%s", got "%s".' % (i, expected[i], result[i]) def test_ad_hoc_model_empty(self): model = sic.Model() model.case_sensitive = False expected = 'set\tcs\t0\n' result = str(model) assert result == expected, 'Expected "%s", got "%s".' % (expected, result) def test_ad_hoc_model_add_rule(self): model = sic.Model() model.case_sensitive = False model.add_rule(sic.ReplaceToken('bad', 'good')) expected = 'set\tcs\t0\nr\tgood\tbad\n' result = str(model) assert result == expected, 'Expected "%s", got "%s".' % (expected, result) def test_ad_hoc_model_remove_rule(self): model = sic.Model() model.case_sensitive = False model.add_rule(sic.ReplaceToken('bad', 'good')) model.add_rule(sic.ReplaceToken('worse', 'better')) model.remove_rule(sic.ReplaceToken('bad', 'good')) expected = 'set\tcs\t0\nr\tbetter\tworse\n' result = str(model) assert result == expected, 'Expected "%s", got "%s".' % (expected, result) def test_ad_hoc_model_direct(self): model = sic.Model() model.case_sensitive = False model.add_rule(sic.SplitToken('beta', 'lmr')) normalizer = sic.Normalizer(None) normalizer.make_tokenizer(str(model)) expected = 'a beta z' result = normalizer.normalize('abetaz') assert result == expected, 'Expected "%s", got "%s".' % (expected, result) def test_ad_hoc_model_builder(self): builder = sic.Builder() model = sic.Model() model.add_rule(sic.SplitToken('beta', 'lmr')) normalizer = builder.build_normalizer(model) expected = 'a beta z' result = normalizer.normalize('abetaz') assert result == expected, 'Expected "%s", got "%s".' % (expected, result) def test_ad_hoc_model_implicit(self): model = sic.Model() model.add_rule(sic.SplitToken('beta', 'lmr')) sic.build_normalizer(model) expected = 'a beta z' result = sic.normalize('abetaz') assert result == expected, 'Expected "%s", got "%s".' % (expected, result) def test_save_load_compiled_save_explicit_load_explicit(self): test_string = 'original string, transformed string' expected = 'transformed string , transformed string' pickled_path = '%s/test_save_load_compiled_save_explicit_load_explicit.pic' % (self.assets_dir) builder = sic.Builder() normalizer1 = builder.build_normalizer('%s/tokenizer_replace_token.xml' % (self.assets_dir)) normalized1 = normalizer1.normalize(test_string) normalizer1.save(pickled_path) normalizer2 = sic.Normalizer() normalizer2.load(pickled_path) os.remove(pickled_path) normalized2 = normalizer2.normalize(test_string) assert expected == normalized1, 'Expected "%s", got "%s".' % (expected, normalized1) assert expected == normalized2, 'Expected "%s", got "%s".' % (expected, normalized2) def test_save_load_compiled_save_explicit_load_implicit(self): test_string = 'original string, transformed string' expected = 'transformed string , transformed string' pickled_path = '%s/test_save_load_compiled_save_explicit_load_implicit.pic' % (self.assets_dir) builder = sic.Builder() normalizer1 = builder.build_normalizer('%s/tokenizer_replace_token.xml' % (self.assets_dir)) normalized1 = normalizer1.normalize(test_string) normalizer1.save(pickled_path) sic.load(pickled_path) os.remove(pickled_path) normalized2 = sic.normalize(test_string) assert expected == normalized1, 'Expected "%s", got "%s".' % (expected, normalized1) assert expected == normalized2, 'Expected "%s", got "%s".' % (expected, normalized2) def test_save_load_compiled_save_implicit_load_explicit(self): test_string = 'original string, transformed string' expected = 'transformed string , transformed string' pickled_path = '%s/test_save_load_compiled_save_implicit_load_explicit.pic' % (self.assets_dir) sic.build_normalizer('%s/tokenizer_replace_token.xml' % (self.assets_dir)) normalized1 = sic.normalize(test_string) sic.save(pickled_path) normalizer2 = sic.Normalizer() normalizer2.load(pickled_path) os.remove(pickled_path) normalized2 = normalizer2.normalize(test_string) assert expected == normalized1, 'Expected "%s", got "%s".' % (expected, normalized1) assert expected == normalized2, 'Expected "%s", got "%s".' % (expected, normalized2) def test_save_load_compiled_save_implicit_load_implicit(self): test_string = 'original string, transformed string' expected = 'transformed string , transformed string' pickled_path = '%s/test_save_load_compiled_save_implicit_load_implicit.pic' % (self.assets_dir) sic.build_normalizer('%s/tokenizer_replace_token.xml' % (self.assets_dir)) normalized1 = sic.normalize(test_string) sic.save(pickled_path) sic.reset() sic.load(pickled_path) os.remove(pickled_path) normalized2 = sic.normalize(test_string) assert expected == normalized1, 'Expected "%s", got "%s".' % (expected, normalized1) assert expected == normalized2, 'Expected "%s", got "%s".' % (expected, normalized2) def test_decode_rule(self): rule = sic.ReplaceCharacter('f', 't') decoded = rule.decode() expected = 'c\tt\tf\n' assert expected == decoded, 'Expected "%s", got "%s".' % (expected, decoded) def test_updated_compiled_normalizer(self): builder = sic.Builder() worker = builder.build_normalizer('%s/tokenizer_replace_token.xml' % (self.assets_dir)) rules = [sic.ReplaceCharacter('t', 'n')] decoded = ''.join([x.decode() for x in rules]) worker.make_tokenizer(decoded, update=True) test_string = 'original string, transformed string' normalized = worker.normalize(test_string) expected = 'transformed snring , nransformed snring' assert expected == normalized, 'Expected "%s", got "%s".' % (expected, normalized) def test_expanded_tokenizer(self): builder = sic.Builder() worker = builder.build_normalizer('%s/tokenizer_expanded.xml' % (self.assets_dir)) test_string1 = '123abc456mmm' test_string2 = '123def456mmm' test_string3 = '123ghi456mmm' expected1 = '123 jkl 456 nnn' test_string4 = '123xyz456 nnn' expected2 = '123 www 456 nnn' test_string5 = '123qwe456' test_string6 = '123rty456' expected3 = '123 uiop 456' normalized1 = worker.normalize(test_string1) normalized2 = worker.normalize(test_string2) normalized3 = worker.normalize(test_string3) normalized4 = worker.normalize(test_string4) normalized5 = worker.normalize(test_string5) normalized6 = worker.normalize(test_string6) assert expected1 == normalized1, 'Expected "%s", got "%s".' % (expected1, normalized1) assert expected1 == normalized2, 'Expected "%s", got "%s".' % (expected1, normalized2) assert
#!/usr/bin/env python2 import argparse import cmd import os import sys import struct import json from functools import wraps import bmpy_utils as utils from bm_runtime.standard import Standard from bm_runtime.standard.ttypes import * try: from bm_runtime.simple_pre import SimplePre except: pass try: from bm_runtime.simple_pre_lag import SimplePreLAG except: pass def enum(type_name, *sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.iteritems()) @staticmethod def to_str(x): return reverse[x] enums['to_str'] = to_str @staticmethod def from_str(x): return enums[x] enums['from_str'] = from_str return type(type_name, (), enums) PreType = enum('PreType', 'None', 'SimplePre', 'SimplePreLAG') MeterType = enum('MeterType', 'packets', 'bytes') TableType = enum('TableType', 'simple', 'indirect', 'indirect_ws') def bytes_to_string(byte_array): form = 'B' * len(byte_array) return struct.pack(form, *byte_array) def table_error_name(x): return TableOperationErrorCode._VALUES_TO_NAMES[x] def get_parser(): class ActionToPreType(argparse.Action): def __init__(self, option_strings, dest, nargs=None, **kwargs): if nargs is not None: raise ValueError("nargs not allowed") super(ActionToPreType, self).__init__(option_strings, dest, **kwargs) def __call__(self, parser, namespace, values, option_string=None): assert(type(values) is str) setattr(namespace, self.dest, PreType.from_str(values)) parser = argparse.ArgumentParser(description='BM runtime CLI') # One port == one device !!!! This is not a multidevice CLI parser.add_argument('--thrift-port', help='Thrift server port for table updates', type=int, action="store", default=9090) parser.add_argument('--thrift-ip', help='Thrift IP address for table updates', type=str, action="store", default='localhost') parser.add_argument('--json', help='JSON description of P4 program', type=str, action="store", required=False) parser.add_argument('--pre', help='Packet Replication Engine used by target', type=str, choices=['None', 'SimplePre', 'SimplePreLAG'], default=PreType.SimplePre, action=ActionToPreType) return parser TABLES = {} ACTION_PROFS = {} ACTIONS = {} METER_ARRAYS = {} COUNTER_ARRAYS = {} REGISTER_ARRAYS = {} CUSTOM_CRC_CALCS = {} class MatchType: EXACT = 0 LPM = 1 TERNARY = 2 VALID = 3 RANGE = 4 @staticmethod def to_str(x): return {0: "exact", 1: "lpm", 2: "ternary", 3: "valid", 4: "range"}[x] @staticmethod def from_str(x): return {"exact": 0, "lpm": 1, "ternary": 2, "valid": 3, "range": 4}[x] class Table: def __init__(self, name, id_): self.name = name self.id_ = id_ self.match_type_ = None self.actions = {} self.key = [] self.default_action = None self.type_ = None self.support_timeout = False self.action_prof = None TABLES[name] = self def num_key_fields(self): return len(self.key) def key_str(self): return ",\t".join([name + "(" + MatchType.to_str(t) + ", " + str(bw) + ")" for name, t, bw in self.key]) def table_str(self): ap_str = "implementation={}".format( "None" if not self.action_prof else self.action_prof.name) return "{0:30} [{1}, mk={2}]".format(self.name, ap_str, self.key_str()) class ActionProf: def __init__(self, name, id_): self.name = name self.id_ = id_ self.with_selection = False self.actions = {} self.ref_cnt = 0 ACTION_PROFS[name] = self def action_prof_str(self): return "{0:30} [{1}]".format(self.name, self.with_selection) class Action: def __init__(self, name, id_): self.name = name self.id_ = id_ self.runtime_data = [] ACTIONS[name] = self def num_params(self): return len(self.runtime_data) def runtime_data_str(self): return ",\t".join([name + "(" + str(bw) + ")" for name, bw in self.runtime_data]) def action_str(self): return "{0:30} [{1}]".format(self.name, self.runtime_data_str()) class MeterArray: def __init__(self, name, id_): self.name = name self.id_ = id_ self.type_ = None self.is_direct = None self.size = None self.binding = None self.rate_count = None METER_ARRAYS[name] = self def meter_str(self): return "{0:30} [{1}, {2}]".format(self.name, self.size, MeterType.to_str(self.type_)) class CounterArray: def __init__(self, name, id_): self.name = name self.id_ = id_ self.is_direct = None self.size = None self.binding = None COUNTER_ARRAYS[name] = self def counter_str(self): return "{0:30} [{1}]".format(self.name, self.size) class RegisterArray: def __init__(self, name, id_): self.name = name self.id_ = id_ self.width = None self.size = None REGISTER_ARRAYS[name] = self def register_str(self): return "{0:30} [{1}]".format(self.name, self.size) def reset_config(): TABLES.clear() ACTION_PROFS.clear() ACTIONS.clear() METER_ARRAYS.clear() COUNTER_ARRAYS.clear() REGISTER_ARRAYS.clear() CUSTOM_CRC_CALCS.clear() def load_json_str(json_str): def get_header_type(header_name, j_headers): for h in j_headers: if h["name"] == header_name: return h["header_type"] assert(0) def get_field_bitwidth(header_type, field_name, j_header_types): for h in j_header_types: if h["name"] != header_type: continue for t in h["fields"]: # t can have a third element (field signedness) f, bw = t[0], t[1] if f == field_name: return bw assert(0) reset_config() json_ = json.loads(json_str) def get_json_key(key): return json_.get(key, []) for j_action in get_json_key("actions"): action = Action(j_action["name"], j_action["id"]) for j_param in j_action["runtime_data"]: action.runtime_data += [(j_param["name"], j_param["bitwidth"])] for j_pipeline in get_json_key("pipelines"): if "action_profiles" in j_pipeline: # new JSON format for j_aprof in j_pipeline["action_profiles"]: action_prof = ActionProf(j_aprof["name"], j_aprof["id"]) action_prof.with_selection = "selector" in j_aprof for j_table in j_pipeline["tables"]: table = Table(j_table["name"], j_table["id"]) table.match_type = MatchType.from_str(j_table["match_type"]) table.type_ = TableType.from_str(j_table["type"]) table.support_timeout = j_table["support_timeout"] for action in j_table["actions"]: table.actions[action] = ACTIONS[action] if table.type_ in {TableType.indirect, TableType.indirect_ws}: if "action_profile" in j_table: action_prof = ACTION_PROFS[j_table["action_profile"]] else: # for backward compatibility assert("act_prof_name" in j_table) action_prof = ActionProf(j_table["act_prof_name"], table.id_) action_prof.with_selection = "selector" in j_table action_prof.actions.update(table.actions) action_prof.ref_cnt += 1 table.action_prof = action_prof for j_key in j_table["key"]: target = j_key["target"] match_type = MatchType.from_str(j_key["match_type"]) if match_type == MatchType.VALID: field_name = target + "_valid" bitwidth = 1 elif target[1] == "$valid$": field_name = target[0] + "_valid" bitwidth = 1 else: field_name = ".".join(target) header_type = get_header_type(target[0], json_["headers"]) bitwidth = get_field_bitwidth(header_type, target[1], json_["header_types"]) table.key += [(field_name, match_type, bitwidth)] for j_meter in get_json_key("meter_arrays"): meter_array = MeterArray(j_meter["name"], j_meter["id"]) if "is_direct" in j_meter and j_meter["is_direct"]: meter_array.is_direct = True meter_array.binding = j_meter["binding"] else: meter_array.is_direct = False meter_array.size = j_meter["size"] meter_array.type_ = MeterType.from_str(j_meter["type"]) meter_array.rate_count = j_meter["rate_count"] for j_counter in get_json_key("counter_arrays"): counter_array = CounterArray(j_counter["name"], j_counter["id"]) counter_array.is_direct = j_counter["is_direct"] if counter_array.is_direct: counter_array.binding = j_counter["binding"] else: counter_array.size = j_counter["size"] for j_register in get_json_key("register_arrays"): register_array = RegisterArray(j_register["name"], j_register["id"]) register_array.size = j_register["size"] register_array.width = j_register["bitwidth"] for j_calc in get_json_key("calculations"): calc_name = j_calc["name"] if j_calc["algo"] == "crc16_custom": CUSTOM_CRC_CALCS[calc_name] = 16 elif j_calc["algo"] == "crc32_custom": CUSTOM_CRC_CALCS[calc_name] = 32 class UIn_Error(Exception): def __init__(self, info=""): self.info = info def __str__(self): return self.info class UIn_ResourceError(UIn_Error): def __init__(self, res_type, name): self.res_type = res_type self.name = name def __str__(self): return "Invalid %s name (%s)" % (self.res_type, self.name) class UIn_MatchKeyError(UIn_Error): def __init__(self, info=""): self.info = info def __str__(self): return self.info class UIn_RuntimeDataError(UIn_Error): def __init__(self, info=""): self.info = info def __str__(self): return self.info class CLI_FormatExploreError(Exception): def __init__(self): pass class UIn_BadParamError(UIn_Error): def __init__(self, info=""): self.info = info def __str__(self): return self.info class UIn_BadIPv4Error(UIn_Error): def __init__(self): pass class UIn_BadIPv6Error(UIn_Error): def __init__(self): pass class UIn_BadMacError(UIn_Error): def __init__(self): pass def ipv4Addr_to_bytes(addr): if not '.' in addr: raise CLI_FormatExploreError() s = addr.split('.') if len(s) != 4: raise UIn_BadIPv4Error() try: return [int(b) for b in s] except: raise UIn_BadIPv4Error() def macAddr_to_bytes(addr): if not ':' in addr: raise CLI_FormatExploreError() s = addr.split(':') if len(s) != 6: raise UIn_BadMacError() try: return [int(b, 16) for b in s] except: raise UIn_BadMacError() def ipv6Addr_to_bytes(addr): from ipaddr import IPv6Address if not ':' in addr: raise CLI_FormatExploreError() try: ip = IPv6Address(addr) except: raise UIn_BadIPv6Error() try: return [ord(b) for b in ip.packed] except: raise UIn_BadIPv6Error() def int_to_bytes(i, num): byte_array = [] while i > 0: byte_array.append(i % 256) i = i / 256 num -= 1 if num < 0: raise UIn_BadParamError("Parameter is too large") while num > 0: byte_array.append(0) num -= 1 byte_array.reverse() return byte_array def parse_param(input_str, bitwidth): if bitwidth == 32: try: return ipv4Addr_to_bytes(input_str) except CLI_FormatExploreError: pass except UIn_BadIPv4Error: raise UIn_BadParamError("Invalid IPv4 address") elif bitwidth == 48: try: return macAddr_to_bytes(input_str) except CLI_FormatExploreError: pass except UIn_BadMacError: raise UIn_BadParamError("Invalid MAC address") elif bitwidth == 128: try: return ipv6Addr_to_bytes(input_str) except CLI_FormatExploreError: pass except UIn_BadIPv6Error: raise UIn_BadParamError("Invalid IPv6 address") try: input_ = int(input_str, 0) except: raise UIn_BadParamError( "Invalid input, could not cast to integer, try in hex with 0x prefix" ) try: return int_to_bytes(input_, (bitwidth + 7) / 8) except UIn_BadParamError: raise def parse_runtime_data(action, params): def parse_param_(field, bw): try: return parse_param(field, bw) except UIn_BadParamError as e: raise UIn_RuntimeDataError( "Error while parsing %s - %s" % (field, e) ) bitwidths = [bw for( _, bw) in action.runtime_data] byte_array = [] for input_str, bitwidth in zip(params, bitwidths): byte_array += [bytes_to_string(parse_param_(input_str, bitwidth))] return byte_array _match_types_mapping = { MatchType.EXACT : BmMatchParamType.EXACT, MatchType.LPM : BmMatchParamType.LPM, MatchType.TERNARY : BmMatchParamType.TERNARY, MatchType.VALID : BmMatchParamType.VALID, MatchType.RANGE : BmMatchParamType.RANGE, } def parse_match_key(table, key_fields): def parse_param_(field, bw): try: return parse_param(field, bw) except UIn_BadParamError as e: raise UIn_MatchKeyError( "Error while parsing %s - %s" % (field, e) ) params = [] match_types = [t for (_, t, _) in table.key] bitwidths = [bw for (_, _, bw) in table.key] for idx, field in enumerate(key_fields): param_type = _match_types_mapping[match_types[idx]] bw = bitwidths[idx] if param_type == BmMatchParamType.EXACT: key = bytes_to_string(parse_param_(field, bw)) param = BmMatchParam(type = param_type, exact = BmMatchParamExact(key)) elif param_type == BmMatchParamType.LPM: try: prefix, length = field.split("/") except ValueError: raise UIn_MatchKeyError( "Invalid LPM value {}, use '/' to separate prefix " "and length".format(field)) key = bytes_to_string(parse_param_(prefix, bw)) param = BmMatchParam(type = param_type, lpm = BmMatchParamLPM(key, int(length))) elif param_type == BmMatchParamType.TERNARY: try: key, mask = field.split("&&&") except ValueError: raise UIn_MatchKeyError( "Invalid ternary value {}, use
<reponame>pjaos/rpi_ogsolar<filename>ogsolar/libs/tracer.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import json class EPSolarTracer(object): """@brief Provides an interface to the EPsolar Tracer series MPPT Solar controller.""" READ = "R" READ_WRITE = "R/W" COIL_READ_WRITE = "C_R/W" DISCRETE_READ = "D_R" CHARGE_STATUS = "CHARGE_STATUS" CHARGE_STATE_UNKNOWN = "UNKNOWN" CHARGE_STATE_NOT_CHARGING = "Not Charging" CHARGE_STATE_BOOST = "Boost" CHARGE_STATE_FLOAT = "Float" CHARGE_STATE_EQUALISATION = "Equalisation" #Register sets. Each entry defines a consecutive number of registers. # The ID number 0,1,2 etc defines a set. # Each set holds a dict with # start: The start address of the registers set. # size: The number of consecutive 16 bit registers in the set. # access: R, R/W, CR/W REG_SETS = { 0: {"start": 0x3000, "size": 9, "access": READ}, 1: {"start": 0x300E, "size": 1, "access": READ}, 2: {"start": 0x3100, "size": 8, "access": READ}, 3: {"start": 0x310C, "size": 7, "access": READ}, 4: {"start": 0x311a, "size": 2, "access": READ}, 5: {"start": 0x311d, "size": 1, "access": READ}, 6: {"start": 0x3200, "size": 2, "access": READ}, 7: {"start": 0x3300, "size": 22, "access": READ}, 8: {"start": 0x331b, "size": 4 , "access": READ}, 9: {"start": 0x331b, "size": 4 , "access": READ}, 10: {"start": 0x9000, "size": 15 , "access": READ_WRITE}, 11: {"start": 0x9013, "size": 15 , "access": READ_WRITE}, 12: {"start": 0x903d, "size": 3 , "access": READ_WRITE}, 13: {"start": 0x9042, "size": 12 , "access": READ_WRITE}, 14: {"start": 0x9065, "size": 1 , "access": READ_WRITE}, 15: {"start": 0x9067, "size": 1 , "access": READ_WRITE}, 16: {"start": 0x9069, "size": 1 , "access": READ_WRITE}, 17: {"start": 0x906a, "size": 5 , "access": READ_WRITE}, 18: {"start": 0x9070, "size": 1 , "access": READ_WRITE}, 19: {"start": 0x2, "size": 1 , "access": COIL_READ_WRITE}, 20: {"start": 0x5, "size": 2 , "access": COIL_READ_WRITE}, 21: {"start": 0x2000, "size": 1, "access": DISCRETE_READ}, 22: {"start": 0x200c, "size": 1, "access": DISCRETE_READ}, } def __init__(self, serialPort, jsonDebugFile=None): """@brief Constructor @param serialPort The seiral port to whch the EPSolar Tracer unit is connected. @param jsonDebugFile If defined then the json file is read rather than the Tracer serial port. This is for debug purposes only when testing without a EPSolar Tracer unit connected to a serial port.""" self._serialPort = serialPort self._jsonDebugFile = jsonDebugFile self._tracerClient = None self._createAddrIndexDict() def _createAddrIndexDict(self): #We create a dict that has all the Tracer registers. # Rather than the key being the register name the key is the register address. self._addrKeyTracerRegDict = {} for regKey in TRACER_REG_DICT: register = TRACER_REG_DICT[regKey] register.setRegName(regKey) #Add the name of the register to the register to ease identification. self._addrKeyTracerRegDict[register.getAddress()] = register def getRegLines(self): """@brief Return lines of text that details the state of all registers.""" addrList = list( self._addrKeyTracerRegDict.keys() ) addrList.sort() lines = [] for addr in addrList: lines.append(self._addrKeyTracerRegDict[addr]) return lines def connect(self, simTracer=False): """@brief connect to the tracer serial port. @param simTracer If True then simulate an EPSolar tracer unit.""" self._simTracer=simTracer if not self._simTracer: # Import here so that the modbus module is not imported unless an attempt to connect to a modbus device is attempted. # The alternative is to use the debug file. from pymodbus.client.sync import ModbusSerialClient as ModbusClient self._tracerClient = ModbusClient(method='rtu', port=self._serialPort, baudrate=115200, stopbits=1, bytesize=8, timeout=1) self._tracerClient.connect() def disconnect(self): """@brief Disconnect from the tracer unit if connected.""" if self._tracerClient: self._tracerClient.close() self._tracerClient = None def readRegList(self, tracerRegList): """@brief Read a single EPSoler Tracer register. @param tracerRegList A list of Register instances. @return None""" if self._jsonDebugFile: # If in debug mode read registers from the file. self.readAll() else: for tracerReg in tracerRegList: baseAddress = tracerReg.getAddress() size = 1 access = tracerReg.getAccess() if access == EPSolarTracer.READ: rr = self._tracerClient.read_input_registers(baseAddress, size, unit=1) elif access == EPSolarTracer.READ_WRITE: rr = self._tracerClient.read_holding_registers(baseAddress, size, unit=1) elif access == EPSolarTracer.COIL_READ_WRITE: rr = self._tracerClient.read_coils(baseAddress, size, unit=1) elif access == EPSolarTracer.DISCRETE_READ: rr = self._tracerClient.read_discrete_inputs(baseAddress, size, unit=1) for index in range(0, size): regAddress = (baseAddress + index) if tracerReg.getAccess() == EPSolarTracer.COIL_READ_WRITE: value = rr.getBit(regAddress) elif tracerReg.getAccess() == EPSolarTracer.DISCRETE_READ: value = rr.getBit(0) else: value = rr.getRegister(index) self._addrKeyTracerRegDict[regAddress].setRawValue(value) tracerReg.setRawValue(value) #Update the value of a register from its raw value tracerReg.process() def writeRegList(self, registerList): """@brief Write the state of a register. @param registerList A list of registers to write to. The rawValue in the register is the value that will be written. @param value The value to be written.""" for register in registerList: if register.getAccess() == COILS_READ_WRITE: self._tracerClient.write_coil( register.getAddress(), register.getRawValue() ) elif register.getAccess() == READ_WRITE: self._tracerClient.write_register(register.getAddress(), register.getRawValue()) else: raise Exception("{} register is not writeable.".format(register.getAddress())) def readAllRegs(self): """@brief Read all registers from the EPSolar Tracer unit.""" # If in debug mode read the register data from a json file if self._jsonDebugFile: if os.path.isfile(self._jsonDebugFile): fd = open(self._jsonDebugFile, 'r') fileContents = fd.read() fd.close() self._addrKeyTracerRegDict = json.loads( fileContents ) else: raise Exception("{} file not found.".format(self._jsonDebugFile)) else: #Read data from an EPSolar Tracer unit connected to the serial port. regSets = list( EPSolarTracer.REG_SETS.keys() ) regSets.sort() for regSet in regSets: baseAddress = EPSolarTracer.REG_SETS[regSet]["start"] size = EPSolarTracer.REG_SETS[regSet]["size"] access = EPSolarTracer.REG_SETS[regSet]["access"] if access == EPSolarTracer.READ: rr = self._tracerClient.read_input_registers(baseAddress, size, unit=1) elif access == EPSolarTracer.READ_WRITE: rr = self._tracerClient.read_holding_registers(baseAddress, size, unit=1) elif access == EPSolarTracer.COIL_READ_WRITE: rr = self._tracerClient.read_coils(baseAddress, size, unit=1) elif access == EPSolarTracer.DISCRETE_READ: rr = self._tracerClient.read_discrete_inputs(baseAddress, size, unit=1) for index in range(0, size): regAddress = (baseAddress + index) if EPSolarTracer.REG_SETS[regSet]["access"] == EPSolarTracer.COIL_READ_WRITE: value = rr.getBit(regAddress) elif EPSolarTracer.REG_SETS[regSet]["access"] == EPSolarTracer.DISCRETE_READ: value = rr.getBit(0) else: value = rr.getRegister(index) self._addrKeyTracerRegDict[regAddress].setRawValue( value ) #Update the value of a register from its raw value for addr in self._addrKeyTracerRegDict: self._addrKeyTracerRegDict[addr].process() def getJSON(self): """@brief Get the reg dict in JSON format.""" dictList = [] for key in TRACER_REG_DICT: dictList.append(TRACER_REG_DICT[key].toDict()) return json.dumps(dictList, indent=4, sort_keys=True) def setJSON(self, jsonStr): """@brief Set the Register state from a JSON str. @param jsonStr The JSON str.""" theDict = json.loads(jsonStr) for regDict in theDict: reg = Register(None, None, None, None, None) reg.fromDict(regDict) TRACER_REG_DICT[regDict[Register.REG_NAME]] = reg self._createAddrIndexDict() def writeReg(self, register, value): """@brief Write the state of a register. @param register The register to write to. @param value The value to be written. This is not the raw value of the register but the unit value.""" register.setValue(value) self.writeRegList( (register,) ) def readReg(self, address): """@brief Read a single register. @param address The address of the register.""" if address not in self._addrKeyTracerRegDict: raise Exception("0x{:04x}/{} is an invalid register address.".format(address, address)) register = self._addrKeyTracerRegDict[address] self.readRegList( (register,) ) return register.getValue() def getRegister(self, address): """@brief Get the register instance given the register address. @param address The address of the register.""" if address not in self._addrKeyTracerRegDict: raise Exception("0x{:04x}/{} is an invalid register address.".format(address, address)) return self._addrKeyTracerRegDict[address] def isValidAddress(self, address): """@brief Check if an address is valid @param address The register address to check @return True if the address is a valid register address.""" addrList = list(self._addrKeyTracerRegDict) validAddr = False if address in addrList: validAddr = True return validAddr def getRegisterByName(self, name): """@brief Get a single register instance. @param name The register name. @return The Regitser instance.""" if name not in TRACER_REG_DICT: raise Exception("{} is an unknown register name.".format(name)) return TRACER_REG_DICT[name] def getChargeStatus(self): """@brief Get the string indicating the tracer battery charge state. The CHARGING_EQUIPMENT_STATUS register must be updated (read from the unit) before this method is called.""" chargeStatusReg = TRACER_REG_DICT[CHARGING_EQUIPMENT_STATUS] chargeStatus = (int(chargeStatusReg.getValue())>>2)&0x03 chargeStatusStr=EPSolarTracer.CHARGE_STATE_UNKNOWN if chargeStatus == 0: chargeStatusStr = EPSolarTracer.CHARGE_STATE_NOT_CHARGING elif chargeStatus == 1: chargeStatusStr = EPSolarTracer.CHARGE_STATE_FLOAT elif chargeStatus == 2: chargeStatusStr = EPSolarTracer.CHARGE_STATE_BOOST elif chargeStatus == 3: chargeStatusStr = EPSolarTracer.CHARGE_STATE_EQUALISATION return chargeStatusStr # Unit types UNDEFINED_UNIT_TYPE = "UNDEFINED" VOLTS = "V" AMPS = "A" WATTS = "W" CELSIUS = "C" KWH = "KWH" TON = "TON" AH = "AH" MV_C_2V = "MV_C_2V" MILLIOHM = "milliohm" MIN = "Min" SECOND = "second" MINUTE = "minute" HOUR = "hour" PERCENTAGE = "%" READ_WRITE = EPSolarTracer.READ_WRITE READ = EPSolarTracer.READ COILS_READ_WRITE = EPSolarTracer.COIL_READ_WRITE DISCRETE_READ = EPSolarTracer.DISCRETE_READ # The following is a list of keys of the TracerregDict. They are taken from the # 1733_modbus_protocol.pdf document. # Read registers CHARGING_EQUIPMENT_RATED_INPUT_VOLTAGE = "Charging equipment rated input voltage" CHARGING_EQUIPMENT_RATED_INPUT_CURRENT = "Charging equipment rated input current" CHARGING_EQUIPMENT_RATED_INPUT_POWER = "Charging equipment rated input power" CHARGING_EQUIPMENT_RATED_INPUT_POWER_L =
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' def accept_portfolio_share(AcceptLanguage=None, PortfolioId=None): """ Accepts an offer to share a portfolio. See also: AWS API Documentation :example: response = client.accept_portfolio_share( AcceptLanguage='string', PortfolioId='string' ) :type AcceptLanguage: string :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows: 'en' (English) 'jp' (Japanese) 'zh' (Chinese) If no code is specified, 'en' is used as the default. :type PortfolioId: string :param PortfolioId: [REQUIRED] The portfolio identifier. :rtype: dict :return: {} :returns: (dict) -- """ pass def associate_principal_with_portfolio(AcceptLanguage=None, PortfolioId=None, PrincipalARN=None, PrincipalType=None): """ Associates the specified principal ARN with the specified portfolio. See also: AWS API Documentation :example: response = client.associate_principal_with_portfolio( AcceptLanguage='string', PortfolioId='string', PrincipalARN='string', PrincipalType='IAM' ) :type AcceptLanguage: string :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows: 'en' (English) 'jp' (Japanese) 'zh' (Chinese) If no code is specified, 'en' is used as the default. :type PortfolioId: string :param PortfolioId: [REQUIRED] The portfolio identifier. :type PrincipalARN: string :param PrincipalARN: [REQUIRED] The ARN representing the principal (IAM user, role, or group). :type PrincipalType: string :param PrincipalType: [REQUIRED] The principal type. Must be IAM :rtype: dict :return: {} :returns: (dict) -- """ pass def associate_product_with_portfolio(AcceptLanguage=None, ProductId=None, PortfolioId=None, SourcePortfolioId=None): """ Associates a product with a portfolio. See also: AWS API Documentation :example: response = client.associate_product_with_portfolio( AcceptLanguage='string', ProductId='string', PortfolioId='string', SourcePortfolioId='string' ) :type AcceptLanguage: string :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows: 'en' (English) 'jp' (Japanese) 'zh' (Chinese) If no code is specified, 'en' is used as the default. :type ProductId: string :param ProductId: [REQUIRED] The product identifier. :type PortfolioId: string :param PortfolioId: [REQUIRED] The portfolio identifier. :type SourcePortfolioId: string :param SourcePortfolioId: The identifier of the source portfolio to use with this association. :rtype: dict :return: {} :returns: (dict) -- """ pass def can_paginate(operation_name=None): """ Check if an operation can be paginated. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(**kwargs), if the create_foo operation can be paginated, you can use the call client.get_paginator('create_foo'). """ pass def create_constraint(AcceptLanguage=None, PortfolioId=None, ProductId=None, Parameters=None, Type=None, Description=None, IdempotencyToken=None): """ Creates a new constraint. See also: AWS API Documentation :example: response = client.create_constraint( AcceptLanguage='string', PortfolioId='string', ProductId='string', Parameters='string', Type='string', Description='string', IdempotencyToken='string' ) :type AcceptLanguage: string :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows: 'en' (English) 'jp' (Japanese) 'zh' (Chinese) If no code is specified, 'en' is used as the default. :type PortfolioId: string :param PortfolioId: [REQUIRED] The portfolio identifier. :type ProductId: string :param ProductId: [REQUIRED] The product identifier. :type Parameters: string :param Parameters: [REQUIRED] The constraint parameters. :type Type: string :param Type: [REQUIRED] The type of the constraint. :type Description: string :param Description: The text description of the constraint. :type IdempotencyToken: string :param IdempotencyToken: [REQUIRED] A token to disambiguate duplicate requests. You can create multiple resources using the same input in multiple requests, provided that you also specify a different idempotency token for each request. This field is autopopulated if not provided. :rtype: dict :return: { 'ConstraintDetail': { 'ConstraintId': 'string', 'Type': 'string', 'Description': 'string', 'Owner': 'string' }, 'ConstraintParameters': 'string', 'Status': 'AVAILABLE'|'CREATING'|'FAILED' } """ pass def create_portfolio(AcceptLanguage=None, DisplayName=None, Description=None, ProviderName=None, Tags=None, IdempotencyToken=None): """ Creates a new portfolio. See also: AWS API Documentation :example: response = client.create_portfolio( AcceptLanguage='string', DisplayName='string', Description='string', ProviderName='string', Tags=[ { 'Key': 'string', 'Value': 'string' }, ], IdempotencyToken='string' ) :type AcceptLanguage: string :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows: 'en' (English) 'jp' (Japanese) 'zh' (Chinese) If no code is specified, 'en' is used as the default. :type DisplayName: string :param DisplayName: [REQUIRED] The name to use for display purposes. :type Description: string :param Description: The text description of the portfolio. :type ProviderName: string :param ProviderName: [REQUIRED] The name of the portfolio provider. :type Tags: list :param Tags: Tags to associate with the new portfolio. (dict) --Key/value pairs to associate with this provisioning. These tags are entirely discretionary and are propagated to the resources created in the provisioning. Key (string) -- [REQUIRED]The ProvisioningArtifactParameter.TagKey parameter from DescribeProvisioningParameters . Value (string) -- [REQUIRED]The esired value for this key. :type IdempotencyToken: string :param IdempotencyToken: [REQUIRED] A token to disambiguate duplicate requests. You can create multiple resources using the same input in multiple requests, provided that you also specify a different idempotency token for each request. This field is autopopulated if not provided. :rtype: dict :return: { 'PortfolioDetail': { 'Id': 'string', 'ARN': 'string', 'DisplayName': 'string', 'Description': 'string', 'CreatedTime': datetime(2015, 1, 1), 'ProviderName': 'string' }, 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } """ pass def create_portfolio_share(AcceptLanguage=None, PortfolioId=None, AccountId=None): """ Creates a new portfolio share. See also: AWS API Documentation :example: response = client.create_portfolio_share( AcceptLanguage='string', PortfolioId='string', AccountId='string' ) :type AcceptLanguage: string :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows: 'en' (English) 'jp' (Japanese) 'zh' (Chinese) If no code is specified, 'en' is used as the default. :type PortfolioId: string :param PortfolioId: [REQUIRED] The portfolio identifier. :type AccountId: string :param AccountId: [REQUIRED] The account ID with which to share the portfolio. :rtype: dict :return: {} :returns: (dict) -- """ pass def create_product(AcceptLanguage=None, Name=None, Owner=None, Description=None, Distributor=None, SupportDescription=None, SupportEmail=None, SupportUrl=None, ProductType=None, Tags=None, ProvisioningArtifactParameters=None, IdempotencyToken=None): """ Creates a new product. See also: AWS API Documentation :example: response = client.create_product( AcceptLanguage='string', Name='string', Owner='string', Description='string', Distributor='string', SupportDescription='string', SupportEmail='string', SupportUrl='string', ProductType='CLOUD_FORMATION_TEMPLATE', Tags=[ { 'Key': 'string', 'Value': 'string' }, ], ProvisioningArtifactParameters={ 'Name': 'string', 'Description': 'string', 'Info': { 'string': 'string' }, 'Type': 'CLOUD_FORMATION_TEMPLATE' }, IdempotencyToken='string' ) :type AcceptLanguage: string :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows: 'en' (English) 'jp' (Japanese) 'zh' (Chinese) If no code is specified, 'en' is used as the default. :type Name: string :param Name: [REQUIRED] The name of the product. :type Owner: string :param Owner: [REQUIRED] The owner of the product. :type Description: string :param Description: The text description of the product. :type Distributor: string :param Distributor: The distributor of the product. :type SupportDescription: string :param SupportDescription: Support information about the product. :type SupportEmail: string :param SupportEmail: Contact email for product support. :type SupportUrl: string :param SupportUrl: Contact URL for product support. :type ProductType: string :param ProductType: [REQUIRED] The type of the product to create. :type Tags: list :param Tags: Tags to associate with the new product. (dict) --Key/value
from struct import unpack_from, calcsize LOG_GNSS_POSITION_REPORT = 0x1476 LOG_GNSS_GPS_MEASUREMENT_REPORT = 0x1477 LOG_GNSS_CLOCK_REPORT = 0x1478 LOG_GNSS_GLONASS_MEASUREMENT_REPORT = 0x1480 LOG_GNSS_BDS_MEASUREMENT_REPORT = 0x1756 LOG_GNSS_GAL_MEASUREMENT_REPORT = 0x1886 LOG_GNSS_OEMDRE_MEASUREMENT_REPORT = 0x14DE LOG_GNSS_OEMDRE_SVPOLY_REPORT = 0x14E1 LOG_GNSS_ME_DPO_STATUS = 0x1838 LOG_GNSS_CD_DB_REPORT = 0x147B LOG_GNSS_PRX_RF_HW_STATUS_REPORT = 0x147E LOG_CGPS_SLOW_CLOCK_CLIB_REPORT = 0x1488 LOG_GNSS_CONFIGURATION_STATE = 0x1516 glonass_measurement_report = """ uint8_t version; uint32_t f_count; uint8_t glonass_cycle_number; uint16_t glonass_number_of_days; uint32_t milliseconds; float time_bias; float clock_time_uncertainty; float clock_frequency_bias; float clock_frequency_uncertainty; uint8_t sv_count; """ glonass_measurement_report_sv = """ uint8_t sv_id; int8_t frequency_index; uint8_t observation_state; // SVObservationStates uint8_t observations; uint8_t good_observations; uint8_t hemming_error_count; uint8_t filter_stages; uint16_t carrier_noise; int16_t latency; uint8_t predetect_interval; uint16_t postdetections; uint32_t unfiltered_measurement_integral; float unfiltered_measurement_fraction; float unfiltered_time_uncertainty; float unfiltered_speed; float unfiltered_speed_uncertainty; uint32_t measurement_status; uint8_t misc_status; uint32_t multipath_estimate; float azimuth; float elevation; int32_t carrier_phase_cycles_integral; uint16_t carrier_phase_cycles_fraction; float fine_speed; float fine_speed_uncertainty; uint8_t cycle_slip_count; uint32_t pad; """ gps_measurement_report = """ uint8_t version; uint32_t f_count; uint16_t week; uint32_t milliseconds; float time_bias; float clock_time_uncertainty; float clock_frequency_bias; float clock_frequency_uncertainty; uint8_t sv_count; """ gps_measurement_report_sv = """ uint8_t sv_id; uint8_t observation_state; // SVObservationStates uint8_t observations; uint8_t good_observations; uint16_t parity_error_count; uint8_t filter_stages; uint16_t carrier_noise; int16_t latency; uint8_t predetect_interval; uint16_t postdetections; uint32_t unfiltered_measurement_integral; float unfiltered_measurement_fraction; float unfiltered_time_uncertainty; float unfiltered_speed; float unfiltered_speed_uncertainty; uint32_t measurement_status; uint8_t misc_status; uint32_t multipath_estimate; float azimuth; float elevation; int32_t carrier_phase_cycles_integral; uint16_t carrier_phase_cycles_fraction; float fine_speed; float fine_speed_uncertainty; uint8_t cycle_slip_count; uint32_t pad; """ position_report = """ uint8 u_Version; /* Version number of DM log */ uint32 q_Fcount; /* Local millisecond counter */ uint8 u_PosSource; /* Source of position information */ /* 0: None 1: Weighted least-squares 2: Kalman filter 3: Externally injected 4: Internal database */ uint32 q_Reserved1; /* Reserved memory field */ uint16 w_PosVelFlag; /* Position velocity bit field: (see DM log 0x1476 documentation) */ uint32 q_PosVelFlag2; /* Position velocity 2 bit field: (see DM log 0x1476 documentation) */ uint8 u_FailureCode; /* Failure code: (see DM log 0x1476 documentation) */ uint16 w_FixEvents; /* Fix events bit field: (see DM log 0x1476 documentation) */ uint32 _fake_align_week_number; uint16 w_GpsWeekNumber; /* GPS week number of position */ uint32 q_GpsFixTimeMs; /* GPS fix time of week of in milliseconds */ uint8 u_GloNumFourYear; /* Number of Glonass four year cycles */ uint16 w_GloNumDaysInFourYear; /* Glonass calendar day in four year cycle */ uint32 q_GloFixTimeMs; /* Glonass fix time of day in milliseconds */ uint32 q_PosCount; /* Integer count of the number of unique positions reported */ uint64 t_DblFinalPosLatLon[2]; /* Final latitude and longitude of position in radians */ uint32 q_FltFinalPosAlt; /* Final height-above-ellipsoid altitude of position */ uint32 q_FltHeadingRad; /* User heading in radians */ uint32 q_FltHeadingUncRad; /* User heading uncertainty in radians */ uint32 q_FltVelEnuMps[3]; /* User velocity in east, north, up coordinate frame. In meters per second. */ uint32 q_FltVelSigmaMps[3]; /* Gaussian 1-sigma value for east, north, up components of user velocity */ uint32 q_FltClockBiasMeters; /* Receiver clock bias in meters */ uint32 q_FltClockBiasSigmaMeters; /* Gaussian 1-sigma value for receiver clock bias in meters */ uint32 q_FltGGTBMeters; /* GPS to Glonass time bias in meters */ uint32 q_FltGGTBSigmaMeters; /* Gaussian 1-sigma value for GPS to Glonass time bias uncertainty in meters */ uint32 q_FltGBTBMeters; /* GPS to BeiDou time bias in meters */ uint32 q_FltGBTBSigmaMeters; /* Gaussian 1-sigma value for GPS to BeiDou time bias uncertainty in meters */ uint32 q_FltBGTBMeters; /* BeiDou to Glonass time bias in meters */ uint32 q_FltBGTBSigmaMeters; /* Gaussian 1-sigma value for BeiDou to Glonass time bias uncertainty in meters */ uint32 q_FltFiltGGTBMeters; /* Filtered GPS to Glonass time bias in meters */ uint32 q_FltFiltGGTBSigmaMeters; /* Filtered Gaussian 1-sigma value for GPS to Glonass time bias uncertainty in meters */ uint32 q_FltFiltGBTBMeters; /* Filtered GPS to BeiDou time bias in meters */ uint32 q_FltFiltGBTBSigmaMeters; /* Filtered Gaussian 1-sigma value for GPS to BeiDou time bias uncertainty in meters */ uint32 q_FltFiltBGTBMeters; /* Filtered BeiDou to Glonass time bias in meters */ uint32 q_FltFiltBGTBSigmaMeters; /* Filtered Gaussian 1-sigma value for BeiDou to Glonass time bias uncertainty in meters */ uint32 q_FltSftOffsetSec; /* SFT offset as computed by WLS in seconds */ uint32 q_FltSftOffsetSigmaSec; /* Gaussian 1-sigma value for SFT offset in seconds */ uint32 q_FltClockDriftMps; /* Clock drift (clock frequency bias) in meters per second */ uint32 q_FltClockDriftSigmaMps; /* Gaussian 1-sigma value for clock drift in meters per second */ uint32 q_FltFilteredAlt; /* Filtered height-above-ellipsoid altitude in meters as computed by WLS */ uint32 q_FltFilteredAltSigma; /* Gaussian 1-sigma value for filtered height-above-ellipsoid altitude in meters */ uint32 q_FltRawAlt; /* Raw height-above-ellipsoid altitude in meters as computed by WLS */ uint32 q_FltRawAltSigma; /* Gaussian 1-sigma value for raw height-above-ellipsoid altitude in meters */ uint32 align_Flt[14]; uint32 q_FltPdop; /* 3D position dilution of precision as computed from the unweighted uint32 q_FltHdop; /* Horizontal position dilution of precision as computed from the unweighted least-squares covariance matrix */ uint32 q_FltVdop; /* Vertical position dilution of precision as computed from the unweighted least-squares covariance matrix */ uint8 u_EllipseConfidence; /* Statistical measure of the confidence (percentage) associated with the uncertainty ellipse values */ uint32 q_FltEllipseAngle; /* Angle of semimajor axis with respect to true North, with increasing angles moving clockwise from North. In units of degrees. */ uint32 q_FltEllipseSemimajorAxis; /* Semimajor axis of final horizontal position uncertainty error ellipse. In units of meters. */ uint32 q_FltEllipseSemiminorAxis; /* Semiminor axis of final horizontal position uncertainty error ellipse. In units of meters. */ uint32 q_FltPosSigmaVertical; /* Gaussian 1-sigma value for final position height-above-ellipsoid altitude in meters */ uint8 u_HorizontalReliability; /* Horizontal position reliability 0: Not set 1: Very Low 2: Low 3: Medium 4: High */ uint8 u_VerticalReliability; /* Vertical position reliability */ uint16 w_Reserved2; /* Reserved memory field */ uint32 q_FltGnssHeadingRad; /* User heading in radians derived from GNSS only solution */ uint32 q_FltGnssHeadingUncRad; /* User heading uncertainty in radians derived from GNSS only solution */ uint32 q_SensorDataUsageMask; /* Denotes which additional sensor data were used to compute this position fix. BIT[0] 0x00000001 <96> Accelerometer BIT[1] 0x00000002 <96> Gyro 0x0000FFFC - Reserved A bit set to 1 indicates that certain fields as defined by the SENSOR_AIDING_MASK were aided with sensor data*/ uint32 q_SensorAidMask; /* Denotes which component of the position report was assisted with additional sensors defined in SENSOR_DATA_USAGE_MASK BIT[0] 0x00000001 <96> Heading aided with sensor data BIT[1] 0x00000002 <96> Speed aided with sensor data BIT[2] 0x00000004 <96> Position aided with sensor data BIT[3] 0x00000008 <96> Velocity aided with sensor data 0xFFFFFFF0 <96> Reserved */ uint8 u_NumGpsSvsUsed; /* The number of GPS SVs used in the fix */ uint8 u_TotalGpsSvs; /* Total number of GPS SVs detected by searcher, including ones not used in position calculation */ uint8 u_NumGloSvsUsed; /* The number of Glonass SVs used in the fix */ uint8 u_TotalGloSvs; /* Total number of Glonass SVs detected by searcher, including ones not used in position calculation */ uint8 u_NumBdsSvsUsed; /* The number of BeiDou SVs used in the fix */ uint8 u_TotalBdsSvs; /* Total number of BeiDou SVs detected by searcher, including ones not used in position calculation */ """ def name_to_camelcase(nam): ret = [] i = 0 while i < len(nam): if nam[i] == "_": ret.append(nam[i+1].upper()) i += 2 else: ret.append(nam[i]) i += 1 return ''.join(ret) def parse_struct(ss): st = "<" nams = [] for l in ss.strip().split("\n"): typ, nam = l.split(";")[0].split() #print(typ, nam) if typ == "float" or '_Flt' in nam: st += "f" elif typ == "double" or '_Dbl' in nam: st += "d" elif typ in ["uint8", "uint8_t"]: st += "B" elif typ in ["int8", "int8_t"]: st += "b" elif typ in ["uint32", "uint32_t"]: st += "I" elif typ in ["int32", "int32_t"]: st += "i" elif typ in ["uint16", "uint16_t"]: st += "H" elif typ in ["int16", "int16_t"]: st += "h" elif typ == "uint64": st += "Q" else: print("unknown type", typ) assert False if '[' in nam: cnt = int(nam.split("[")[1].split("]")[0]) st += st[-1]*(cnt-1) for i in range(cnt): nams.append("%s[%d]" % (nam.split("[")[0], i)) else: nams.append(nam) return st, nams def dict_unpacker(ss, camelcase = False): st, nams = parse_struct(ss) if camelcase: nams = [name_to_camelcase(x) for x in nams] sz = calcsize(st) return
directly from pandas DataFrame via `df[hdr]`; no objects removed using nonzero flag values and no quality cuts performed. realization_number (int) -- Allowed values: 0 1 2 None. Refers to Balrog injection and None refers to a one-realization run. Returns: 0 """ if NORMALIZE: num_1sig = one_sigma_counter(norm_delta_mag=delta_mag, clean_magnitude1=clean_magnitude1, bins=bins, hax_mag=hax_mag) # Record number of objects plotted within 1sigma # FD_1SIG.write('Number of objects within 1sigma for tile ' + str(tile_name) + ', filter ' + str(filter_name) + ', type ' + str(RUN_TYPE) + ', realization ' + str(realization_number) + ' : ' + str(num_1sig) + ' / ' + str(len(clean_magnitude1)) + ' = ' + str(float(num_1sig) / len(clean_magnitude1)) + '\n') # Record number of objects plotted (nop) # FD_NOP.write('Number of objects plotted after flag cuts for tile ' + str(tile_name) + ', filter ' + str(filter_name) + ', type ' + str(RUN_TYPE) + ', realization ' + str(realization_number) + ' : ' + str(len(clean_magnitude1)) + ' / ' + str(len(full_magnitude1)) + ' = ' + str(float(len(clean_magnitude1)) / len(full_magnitude1)) + '\n') return 0 def get_colorbar_value(df, cm_t_hdr, cm_t_err_hdr, idx_good, clean_magnitude1, clean_magnitude2, axlabel, inj): """Get data that will be used for the colorbar of plot. Args: df (pandas DataFrame) *_hdr (str) -- Headers refer to columns in the matched catalog. inj (bool) Returns: cbar_val -- Values used to make colorbar. cbar_idx_list -- Can be None cbar_bins -- Can be None cbar_axlabel (str) -- Label for the colorbar. """ if 'true' in axlabel: sys.exit('ERROR. Colorbars should describe measured catalog values, not truth catalog values.') if CM_T_S2N_COLORBAR: cbar_idx_list, cbar_bins, cbar_val = calculate_and_bin_cm_T_signal_to_noise(cm_t_hdr=cm_t_hdr, cm_t_err_hdr=cm_t_err_hdr, df=df, idx_good=idx_good, clean_magnitude1=clean_magnitude1, clean_magnitude2=clean_magnitude2) cbar_axlabel = 'cm_T_s2n_'+str(AXLABEL) if CM_T_ERR_COLORBAR: # For measured catalog, cuts performed on truth catalogs # cbar_val = get_good_data(df=df, hdr=cm_t_err_hdr, idx_good=idx_good, magnitude=False, filter_name=None) cbar_axlabel = str(cm_t_err_hdr[:-2]) + '_' + str(AXLABEL) cbar_idx_list, cbar_bins = None, None if CM_T_COLORBAR: cbar_val = get_good_data(df=df, hdr=cm_t_hdr, idx_good=idx_good, magnitude=False, filter_name=None) cbar_axlabel = str(cm_t_hdr[:-2]) + '_' + str(AXLABEL) cbar_idx_list, cbar_bins = None, None if CM_T_S2N_COLORBAR is False and CM_T_ERR_COLORBAR is False and CM_T_COLORBAR is False: cbar_val, cbar_idx_list, cbar_bins, cbar_axlabel = None, None, None, None if inj and cbar_axlabel is not None: cbar_axlabel = 'inj_' + cbar_axlabel return cbar_val, cbar_idx_list, cbar_bins, cbar_axlabel def get_errors(mag_err_hdr1, mag_err_hdr2, df, filter_name, idx_good): """Get errors for plot. Args: *_hdr (str ) -- Headers refer to columns in the matched catalog. Can be None. df (pandas DataFrame) Returns: err1, err2 (list of floats) -- Will be None if PLOT_1SIG is False. """ if PLOT_1SIG: if mag_err_hdr1 is None: err1 = calculate_total_fractional_magnitude_error(df=df, flux_hdr=CM_FLUX_HDR1, cov_hdr=CM_FLUX_COV_HDR1, filter_name=filter_name, idx_good=idx_good) if mag_err_hdr1 is not None: if MATCH_CAT1 == 'coadd': err1 = get_floats_from_string(df=df, hdr=mag_err_hdr1, filter_name=filter_name) if MATCH_CAT1 == 'star_truth': err1 = df[str(mag_err_hdr1[:-2]) + '_' + filter_name.upper() + str(mag_err_hdr1[-2:])] if mag_err_hdr2 is None: err2 = calculate_total_fractional_magnitude_error(df=df, flux_hdr=CM_FLUX_HDR2, cov_hdr=CM_FLUX_COV_HDR2, filter_name=filter_name, idx_good=idx_good) if mag_err_hdr2 is not None: if MATCH_CAT2 == 'coadd': err2 = get_floats_from_string(df=df, hdr=mag_err_hdr2, filter_name=filter_name) if MATCH_CAT2 == 'star_truth': err2 = df[str(mag_err_hdr2[:-2]) + '_' + filter_name.upper() + str(mag_err_hdr2[-2:])] if PLOT_1SIG is False: print 'WARNING: Not plotting 1-sigma curve so log file will FALSELY report that ZERO objects are within 1sigma ...\n' err1, err2 = None, None return err1, err2 def get_good_data(df, hdr, idx_good, magnitude, filter_name): """Get the data corresponding to good indices (no flags or post quality cuts). Args: df (pandas DataFrame) hdr (str) -- Header for the DataFrame. idx_good (list of floats) -- Safe indices magnitude (bool) -- Get data for magnitudes? filter_name (str) -- Only used if magnitude is True. """ if magnitude: full_data = get_floats_from_string(df=df, hdr=hdr, filter_name=filter_name) if magnitude is False: full_data = df[hdr] clean_data = np.array(full_data)[idx_good] return clean_data def get_plot_variables(filter_name, df, mag_hdr1, mag_hdr2, mag_err_hdr1, mag_err_hdr2, realization_number, tile_name, mag_axlabel1, mag_axlabel2): """Get quantities needed for plotter() and subplotter(). Args: df (pandas DataFrame) *_hdr (str) -- Can be None. Returns: """ # Rewrite mag_axlabels. Transform, for example, cm_mag_true to cm_mag_{filter}_true or psf_mag_meas to psf_mag_{filter}_meas # if RUN_TYPE is None: mag_axlabel1 = str(mag_hdr1[:-2]) + '_' + str(AXLABEL1) if RUN_TYPE is not None: mag_axlabel1 = str(mag_hdr1) + '_' + str(AXLABEL1) mag_axlabel2 = str(mag_hdr2[:-2]) + '_' + str(AXLABEL2) # Transform, for example, cm_mag_true to cm_mag_{filter}_true, or psf_mag_meas to psf_mag_{filter}_meas # mag_axlabel1 = mag_axlabel1[:-4] + str(filter_name) + '_' + mag_axlabel1[-4:] mag_axlabel2 = mag_axlabel2[:-4] + str(filter_name) + '_' + mag_axlabel2[-4:] if INJ1: mag_axlabel1 = 'inj_' + mag_axlabel1 if INJ2: mag_axlabel2 = 'inj_' + mag_axlabel2 # Coadd catalogs. Combined to get '(m_g, m_r, m_i, m_z)' then matched. # if MATCH_CAT1 == 'coadd': mag_axlabel1 = 'MAG_AUTO_'+ str(AXLABEL1) if MATCH_CAT2 == 'coadd': mag_axlabel2 = 'MAG_AUTO_'+ str(AXLABEL2) if CM_T_HDR1 is not None: cm_t_axlabel1 = str(CM_T_HDR1[:-2]) + '_' + str(AXLABEL1) if CM_T_HDR2 is not None: cm_t_axlabel2 = str(CM_T_HDR2[:-2]) + '_' + str(AXLABEL2) if CM_T_ERR_HDR1 is not None: cm_t_err_axlabel1 = str(CM_T_ERR_HDR1[:-2]) + '_' + str(AXLABEL1) if CM_T_ERR_HDR2 is not None: cm_t_err_axlabel2 = str(CM_T_ERR_HDR2[:-2]) + '_' + str(AXLABEL2) ### Define variables ### # Get magnitude1 # fullmag1 = get_floats_from_string(df=df, hdr=mag_hdr1, filter_name=filter_name) # Get magnitude2 # fullmag2 = get_floats_from_string(df=df, hdr=mag_hdr2, filter_name=filter_name) ### Clean the data: removed flags and/or perform quality cuts ### if EH_CUTS: idx_good = get_good_index_using_quality_cuts(df, full_magnitude1=fullmag1, full_magnitude2=fullmag2, cm_flag_hdr1=CM_FLAGS_HDR1, cm_flag_hdr2=CM_FLAGS_HDR2, flag_hdr1=FLAGS_HDR1, flag_hdr2=FLAGS_HDR2)[0] if EH_CUTS is False: idx_good = get_good_index_using_primary_flags(df=df, full_magnitude1=fullmag1, full_magnitude2=fullmag2, cm_flag_hdr1=CM_FLAGS_HDR1, cm_flag_hdr2=CM_FLAGS_HDR2, flag_hdr1=FLAGS_HDR1, flag_hdr2=FLAGS_HDR2)[0] cleanmag1 = get_good_data(df=df, hdr=mag_hdr1, idx_good=idx_good, magnitude=True, filter_name=filter_name) cleanmag2 = get_good_data(df=df, hdr=mag_hdr2, idx_good=idx_good, magnitude=True, filter_name=filter_name) # Some variables set to None because must pass to plotter() # cbar_val, cbar_idx_list, cbar_bins, cbar_axlabel = get_colorbar_value(df=df, cm_t_hdr=CM_T_HDR2, cm_t_err_hdr=CM_T_ERR_HDR2, idx_good=idx_good, clean_magnitude1=cleanmag1, clean_magnitude2=cleanmag2, axlabel=AXLABEL2, inj=INJ2) ### Define errors ### err1, err2 = get_errors(mag_err_hdr1=mag_err_hdr1, mag_err_hdr2=mag_err_hdr2, df=df, filter_name=filter_name, idx_good=idx_good) ### Write flags to file ### if LOG_FLAGS: for i in np.arange(0, len(FLAG_HDR_LIST), 2): # Bad index # temp_idx = handle_flags(df=df, filter_name=f, realization_number=realization_number, flag_hdr1=FLAG_HDR_LIST[i], flag_hdr2=FLAG_HDR_LIST[i+1], full_magnitude1=fullmag1, full_magnitude2=fullmag2, tile_name=tile_name)[1] #flag_idx.append(temp_idx) FLAG_HDR_LIST.extend(temp_idx) if SHOW_PLOT is False and SAVE_PLOT is False: # Reset to avoid errors # counter_subplot = 1 ### Print out the type() for each flag ### if SHOW_FLAG_TYPE: get_flag_type(df=df, k=counter_flag_type_printout) counter_flag_type_printout += 1 return cbar_val, cbar_idx_list, cbar_bins, err1, err2, cleanmag1, cleanmag2, idx_good, cbar_axlabel, fullmag1, mag_axlabel1, mag_axlabel2 def plotter(mag_hdr1, mag_hdr2, cbar_val, error1, error2, filter_name, clean_magnitude1, full_magnitude1, mag_axlabel1, clean_magnitude2, mag_axlabel2, plot_title, realization_number, tile_name, idx_list, bins, cbar_axlabel, plot_name): """Plot a single magnitude versus delta-magnitude plot. Args: full_magnitude1, full_magnitude2 (numpy.ndarray if directly from `df` OR list of floats if from `get_floats_from_string()`) -- Values read directly from pandas DataFrame via `df[hdr]`; no objects removed using nonzero flag values and no quality cuts performed. realization_number (str) -- Allowed values: 0 1 2 None. Refers to Balrog injection and None refers to a one-realization run. Returns: 0 """ ### Get labels for vertical and horizontal axes. ### ''' # Rewrite mag_axlabels. Transform, for example, cm_mag_true to cm_mag_{filter}_true or psf_mag_meas to psf_mag_{filter}_meas # if RUN_TYPE is None: mag_axlabel1 = str(mag_hdr1[:-2]) + '_' + str(AXLABEL1) if RUN_TYPE is not None: mag_axlabel1 = str(mag_hdr1) + '_' + str(AXLABEL1) mag_axlabel2 = str(mag_hdr2[:-2]) + '_' + str(AXLABEL2) # Transform, for example, cm_mag_true to cm_mag_{filter}_true, or psf_mag_meas to psf_mag_{filter}_meas # mag_axlabel1 = mag_axlabel1[:-4] + str(filter_name) + '_' + mag_axlabel1[-4:] mag_axlabel2 = mag_axlabel2[:-4] + str(filter_name) + '_' + mag_axlabel2[-4:] if INJ1: mag_axlabel1 = 'inj_' + mag_axlabel1 if INJ2: mag_axlabel2 = 'inj_' + mag_axlabel2 ''' ### Values to plot for normalized plot ### if NORMALIZE: # Args needed to call normalize_plot() # norm_dm_list, bins, hax_mag_list = normalize_plot_maintain_bin_structure(clean_magnitude1=clean_magnitude1, clean_magnitude2=clean_magnitude2, error1=error1, error2=error2, filter_name=filter_name) PLOT_68P, PLOT_34P_SPLIT = True, True if PLOT_1SIG: ### Plot 1-sigma curve according to error calculation ### plt.axhline(y=1.0, color='red', linestyle='--', linewidth=0.7, label='$1 \sigma_{mag\_meas}$') plt.axhline(y=-1.0, color='red', linestyle='--', linewidth=0.7) # Line width for top and sides of 68th percentile bins # lwt = 1.1; lws = 0.7 if PLOT_34P_SPLIT: ### Plot the 68th percentile calculated from np.percentile() ### vax_68percentile_list, bins, neg_vax_34percentile, pos_vax_34percentile = get_68percentile_from_normalized_data(norm_dm_list=norm_dm_list, bins=bins, hax_mag_list=hax_mag_list) counter_legend1 = 0; color1 = 'cyan' for b in np.arange(0, len(neg_vax_34percentile)-1): # Horizontal bar bounds # x_hbound = np.array([bins[b], bins[b+1]]) x_vbound1 = np.array([bins[b], bins[b]]) x_vbound2 = np.array([bins[b+1], bins[b+1]]) if neg_vax_34percentile[b] is not None: # Horizontal bar bounds # neg_y_hbound = np.array([neg_vax_34percentile[b], neg_vax_34percentile[b]]) # Vertical bar bounds # y_vbound = np.array([neg_vax_34percentile[b], 0]) # Plot # # Plot legend once # if counter_legend1 == 0: plt.plot(x_hbound, neg_y_hbound, color=color1, linewidth=lwt, label='$\pm P_{34}$') counter_legend1 = 1 if counter_legend1 == 1: plt.plot(x_hbound, neg_y_hbound, color=color1) plt.plot(x_vbound1, y_vbound, color=color1, linewidth=lws, linestyle=':') plt.plot(x_vbound2, y_vbound, color=color1, linewidth=lws, linestyle=':') if pos_vax_34percentile[b] is not None: # Horizontal bar bounds # pos_y_hbound = np.array([pos_vax_34percentile[b], pos_vax_34percentile[b]]) # Vertical bar bounds # y_vbound = np.array([0, pos_vax_34percentile[b]]) # Plot # plt.plot(x_hbound, pos_y_hbound, color=color1, linewidth=lwt) plt.plot(x_vbound1, y_vbound, color=color1, linewidth=lws, linestyle=':') plt.plot(x_vbound2, y_vbound, color=color1, linewidth=lws, linestyle=':') if PLOT_68P: counter_legend2 = 0; color2 = 'fuchsia' for b in np.arange(0, len(vax_68percentile_list)-1): if vax_68percentile_list[b] is not None: # Horizontal bar bounds # x_hbound = np.array([bins[b], bins[b+1]]) y_hbound = np.array([vax_68percentile_list[b], vax_68percentile_list[b]]) # Vertical bar bounds # x_vbound1, x_vbound2 = np.array([bins[b], bins[b]]), np.array([bins[b+1], bins[b+1]]) y_vbound = np.array([-1*vax_68percentile_list[b], vax_68percentile_list[b]]) # Plot legend once # if counter_legend2 == 0: plt.plot(x_hbound, y_hbound, color=color2, label='$P_{68}$', linewidth=lwt) counter_legend2 += 1 if counter_legend2 == 1: # Horizontal bar # plt.plot(x_hbound, y_hbound, color=color2, linewidth=lwt) plt.plot(x_hbound, -1.0*y_hbound, color=color2, linewidth=lwt) # Vertical bar # plt.plot(x_vbound1, y_vbound, color=color2, linewidth=lws, linestyle=':') plt.plot(x_vbound2, y_vbound, color=color2, linewidth=lws,
from json import loads, JSONDecodeError from uuid import UUID import re from .exceptions.error import EmptyApiKeyError, FileError, ParameterError, \ UnparsableApiResponseError from .models.response import ResponseCreate, ResponseRecords, ResponseRequests from .net.http import ApiRequester class Client: __default_url = 'https://www.whoisxmlapi.com/BulkWhoisLookup/bulkServices' _api_requester: ApiRequester or None _api_key: str _re_api_key = re.compile(r'^at_[a-z0-9]{29}$', re.IGNORECASE) _PARSABLE_FORMAT = 'json' _PATH_CREATE = '/bulkWhois' _PATH_DOWNLOAD = '/download' _PATH_REQUESTS = '/getUserRequests' _PATH_RECORDS = '/getRecords' JSON_FORMAT = 'json' XML_FORMAT = 'xml' SEARCH_ALL = 'all' SEARCH_NO_ERROR = 'noerror' def __init__(self, api_key: str, **kwargs): """ :param api_key: str: Your API key :key base_url: str: (optional) API endpoint URL :key timeout: float: (optional) API call timeout in seconds """ self._api_key = '' self.api_key = api_key if 'base_url' not in kwargs: kwargs['base_url'] = Client.__default_url self.api_requester = ApiRequester(**kwargs) @property def api_key(self) -> str: return self._api_key @api_key.setter def api_key(self, value: str): self._api_key = Client._validate_api_key(value) @property def api_requester(self) -> ApiRequester or None: return self._api_requester @api_requester.setter def api_requester(self, value: ApiRequester): self._api_requester = value @property def base_url(self) -> str: return self._api_requester.base_url @base_url.setter def base_url(self, value: str or None): if value is None: self._api_requester.base_url = Client.__default_url else: self._api_requester.base_url = value @property def timeout(self) -> float: return self._api_requester.timeout @timeout.setter def timeout(self, value: float): self._api_requester.timeout = value def create_request(self, **kwargs) -> ResponseCreate: """ Create bulk domain names processing request :key domains: Required. list[str] :return: `ResponseCreate` instance :raises ConnectionError: :raises BulkWhoisApiError: Base class for all errors below :raises ResponseError: response contains an error message :raises ApiAuthError: Server returned 401, 402 or 403 HTTP code :raises BadRequestError: Server returned 400, 417 or 422 HTTP code :raises HttpApiError: HTTP code >= 300 and not equal to above codes :raises ParameterError: invalid parameter value """ kwargs['output_format'] = Client._PARSABLE_FORMAT response = self.create_request_raw(**kwargs) try: parsed = loads(str(response)) if 'requestId' in parsed: return ResponseCreate(parsed) raise UnparsableApiResponseError( "Could not find the correct root element.", None) except JSONDecodeError as error: raise UnparsableApiResponseError( "Could not parse API response", error) def download(self, **kwargs): """ Download processing results CSV and save to file :key request_id: Required. str. Request ID :key search_type: Optional. Supported options: SEARCH_ALL, SEARCH_NO_ERROR. SEARCH_ALL by default :raises ConnectionError: :raises BulkWhoisApiError: Base class for all errors below :raises ResponseError: response contains an error message :raises ApiAuthError: Server returned 401, 402 or 403 HTTP code :raises BadRequestError: Server returned 400, 417 or 422 HTTP code :raises HttpApiError: HTTP code >= 300 and not equal to above codes :raises ParameterError: invalid parameter value """ filename = None kwargs['output_format'] = Client._PARSABLE_FORMAT if 'filename' in kwargs: filename = kwargs['filename'] if type(filename) is not str or not filename: raise ParameterError('Output file name required') try: result_file = open(filename, 'w') except Exception: raise FileError('Cannot open output file') result_file.close() response = self.download_raw(**kwargs) try: result_file = open(filename, 'w') result_file.write(response) except Exception: raise FileError('Cannot write result to file') finally: result_file.close() def get_records(self, **kwargs) -> ResponseRecords: """ Get Whois records :key request_id: Required. str. Request ID :key max_records: Required. int. Max number of records to return. Min: 1 :key start_index: Optional. int. First record to be returned. Min: 1. Use for pagination :return: `ResponseRecords` instance :raises ConnectionError: :raises BulkWhoisApiError: Base class for all errors below :raises ResponseError: response contains an error message :raises ApiAuthError: Server returned 401, 402 or 403 HTTP code :raises BadRequestError: Server returned 400, 417 or 422 HTTP code :raises HttpApiError: HTTP code >= 300 and not equal to above codes :raises ParameterError: invalid parameter value """ kwargs['output_format'] = Client._PARSABLE_FORMAT response = self.get_records_raw(**kwargs) try: parsed = loads(str(response)) if 'whoisRecords' in parsed: return ResponseRecords(parsed) raise UnparsableApiResponseError( 'Cannot find the correct root element', None) except JSONDecodeError as error: raise UnparsableApiResponseError( 'Could not parse API response', error) def get_requests(self, **kwargs) -> ResponseRequests: """ Get a list of your requests :return: `ResponseRequests` instance :raises ConnectionError: :raises BulkWhoisApiError: Base class for all errors below :raises ResponseError: response contains an error message :raises ApiAuthError: Server returned 401, 402 or 403 HTTP code :raises BadRequestError: Server returned 400, 417 or 422 HTTP code :raises HttpApiError: HTTP code >= 300 and not equal to above codes :raises ParameterError: invalid parameter value """ kwargs['output_format'] = Client._PARSABLE_FORMAT response = self.get_requests_raw(**kwargs) try: parsed = loads(str(response)) if 'userRequests' in parsed: return ResponseRequests(parsed) raise UnparsableApiResponseError( 'Cannot find the correct root element', None) except JSONDecodeError as error: raise UnparsableApiResponseError( 'Could not parse API response', error) def create_request_raw(self, **kwargs) -> str: """ Get raw create response :key domains: Required. list[str] :key output_format: Optional. Response output format. Supported options: JSON_FORMAT, XML_FORMAT. JSON_FORMAT by default :return: str :raises ConnectionError: :raises BulkWhoisApiError: Base class for all errors below :raises ResponseError: response contains an error message :raises ApiAuthError: Server returned 401, 402 or 403 HTTP code :raises BadRequestError: Server returned 400, 417 or 422 HTTP code :raises HttpApiError: HTTP code >= 300 and not equal to above codes :raises ParameterError: invalid parameter value """ domains = None if self.api_key == '': raise EmptyApiKeyError('') if 'domains' in kwargs: domains = Client._validate_domains(kwargs['domains']) if not domains: raise ParameterError('Domain names required') if 'response_format' in kwargs: kwargs['output_format'] = kwargs['response_format'] if 'output_format' in kwargs: output_format = Client._validate_output_format( kwargs['output_format']) else: output_format = Client._PARSABLE_FORMAT return self._api_requester.post( self._PATH_CREATE, self._build_payload(self.api_key, output_format, domains) ) def download_raw(self, **kwargs) -> str: """ Get raw download response :key request_id: Required. str. Request ID :key search_type: Optional. Supported options: SEARCH_ALL, SEARCH_NO_ERROR. SEARCH_ALL by default :return: str :raises ConnectionError: :raises BulkWhoisApiError: Base class for all errors below :raises ResponseError: response contains an error message :raises ApiAuthError: Server returned 401, 402 or 403 HTTP code :raises BadRequestError: Server returned 400, 417 or 422 HTTP code :raises HttpApiError: HTTP code >= 300 and not equal to above codes :raises ParameterError: invalid parameter value """ request_id, search_type = [None] * 2 if self.api_key == '': raise EmptyApiKeyError('') if 'request_id' in kwargs: request_id = Client._validate_request_id(kwargs['request_id']) if not request_id: raise ParameterError('Request ID required') if 'search_type' in kwargs: search_type = Client._validate_search_type(kwargs['search_type']) return self._api_requester.post( self._PATH_DOWNLOAD, self._build_payload( api_key=self.api_key, request_id=request_id, search_type=search_type ) ) def get_records_raw(self, **kwargs) -> str: """ Get raw records response :key request_id: Required. str. Request ID :key max_records: Required. int. Max number of records to return. Min: 1 :key start_index: Optional. int. First record to be returned. Min: 1. Use for pagination :key output_format: Optional. Response output format. Supported options: JSON_FORMAT, XML_FORMAT. JSON_FORMAT by default :return: str :raises ConnectionError: :raises BulkWhoisApiError: Base class for all errors below :raises ResponseError: response contains an error message :raises ApiAuthError: Server returned 401, 402 or 403 HTTP code :raises BadRequestError: Server returned 400, 417 or 422 HTTP code :raises HttpApiError: HTTP code >= 300 and not equal to above codes :raises ParameterError: invalid parameter value """ request_id, max_records, start_index = [None] * 3 if self.api_key == '': raise EmptyApiKeyError('') if 'request_id' in kwargs: request_id = Client._validate_request_id(kwargs['request_id']) if not request_id: raise ParameterError('Request ID required') if 'max_records' in kwargs: max_records = Client._validate_max_records(kwargs['max_records']) if not max_records: raise ParameterError('Max record number required') if 'start_index' in kwargs: start_index = Client._validate_start_index(kwargs['start_index']) if 'response_format' in kwargs: kwargs['output_format'] = kwargs['response_format'] if 'output_format' in kwargs: output_format = Client._validate_output_format( kwargs['output_format']) else: output_format = Client._PARSABLE_FORMAT return self._api_requester.post( self._PATH_RECORDS, self._build_payload( self.api_key, output_format, None, request_id, max_records, start_index ) ) def get_requests_raw(self, **kwargs) -> str: """ Get raw list response :key output_format: Optional. Response output format. Supported options: JSON_FORMAT, XML_FORMAT. JSON_FORMAT by default :return: str :raises ConnectionError: :raises BulkWhoisApiError: Base class for all errors below :raises ResponseError: response contains an error message :raises ApiAuthError: Server returned 401, 402 or 403 HTTP code :raises BadRequestError: Server returned 400, 417 or 422 HTTP code :raises HttpApiError: HTTP code >= 300 and not equal to above codes :raises ParameterError: invalid parameter value """ if self.api_key == '': raise EmptyApiKeyError('') if 'response_format' in kwargs: kwargs['output_format'] = kwargs['response_format'] if 'output_format' in kwargs: output_format = Client._validate_output_format( kwargs['output_format']) else: output_format = Client._PARSABLE_FORMAT return self._api_requester.post( self._PATH_REQUESTS, self._build_payload(self.api_key, output_format) ) @staticmethod def _build_payload( api_key, output_format=None, domains=None, request_id=None, max_records=None, start_index=None, search_type=None ) -> dict: tmp = { 'apiKey': api_key, 'outputFormat': output_format, 'domains': domains, 'requestId': request_id, 'maxRecords': max_records, 'startIndex': start_index, 'searchType': search_type } payload = {} for k, v in tmp.items(): if
""" Utitlity functions that will be used by the sequence data generators IGNORE_FOR_SPHINX_DOCS: List of functions: getChromPositions - returns two column dataframe of chromosome positions spanning the entire chromosome at a) regular intervals or b) random locations getPeakPositions - returns two column dataframe of chromosome positions getInputTasks - when input data is fed as a path to a directory, that contains files (single task) or sub directories (multi tasl) that follow a strict naming convention, this function returns a nested python dictionary of tasks, specifying the 'signal' and/or 'control' bigWigs, 'peaks' file, 'task_id' & 'strand roundToMultiple - Return the largest multiple of y < x one_hot_encode - returns a 3-dimension numpy array of one hot encoding of a list of DNA sequences reverse_complement_of_sequences - returns the reverse complement of a list of sequences reverse_complement_of_profiles - returns the reverse complement of the assay signal License: MIT License Copyright (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. IGNORE_FOR_SPHINX_DOCS """ import glob import logging import numpy as np import os import pandas as pd from collections import OrderedDict from mseqgen.exceptionhandler import NoTracebackException def getChromPositions(chroms, chrom_sizes, flank, mode='sequential', num_positions=-1, step=50): """ Chromosome positions spanning the entire chromosome at a) regular intervals or b) random locations Args: chroms (list): The list of required chromosomes chrom_sizes (pandas.Dataframe): dataframe of chromosome sizes with 'chrom' and 'size' columns flank (int): Buffer size before & after the position to ensure we dont fetch values at index < 0 & > chrom size mode (str): mode of returned position 'sequential' (from the beginning) or 'random' num_positions (int): number of chromosome positions to return on each chromosome, use -1 to return positions across the entrire chromosome for all given chromosomes in `chroms`. mode='random' cannot be used with num_positions=-1 step (int): the interval between consecutive chromosome positions in 'sequential' mode Returns: pandas.DataFrame: two column dataframe of chromosome positions (chrom, pos) """ if mode == 'random' and num_positions == -1: raise NoTracebackException( "Incompatible parameter pairing: 'mode' = random, " "'num_positions' = -1") # check if chrom_sizes has a column called 'chrom' if 'chrom' not in chrom_sizes.columns: logging.error("Expected column 'chrom' not found in chrom_sizes") return None chrom_sizes = chrom_sizes.set_index('chrom') # initialize an empty dataframe with 'chrom' and 'pos' columns positions = pd.DataFrame(columns=['chrom', 'pos']) # for each chromosome in the list for i in range(len(chroms)): chrom_size = chrom_sizes.at[chroms[i], 'size'] # keep start & end within bounds start = flank end = chrom_size - flank + 1 if mode == 'random': # randomly sample positions pos_array = np.random.randint(start, end, num_positions) if mode == 'sequential': _end = end if num_positions != -1: # change the last positon based on the number of # required positions _end = start + step * num_positions # if the newly computed 'end' goes beyond the # chromosome end (we could throw an error here) if _end > end: _end = end # positions at regular intervals pos_array = list(range(start, _end, step)) # construct a dataframe for this chromosome chrom_df = pd.DataFrame({'chrom': [chroms[i]] * len(pos_array), 'pos': pos_array}) # concatenate to existing df positions = pd.concat([positions, chrom_df]) return positions def getPeakPositions(tasks, chroms, chrom_sizes, flank, drop_duplicates=False): """ Peak positions for all the tasks filtered based on required chromosomes and other qc filters. Since 'task' here refers one strand of input/output, if the data is stranded the peaks will be duplicated for the plus and minus strand. Args: tasks (dict): A python dictionary containing the task information. Each task in tasks should have the key 'peaks' that has the path to he peaks file chroms (list): The list of required test chromosomes chrom_sizes (pandas.Dataframe): dataframe of chromosome sizes with 'chrom' and 'size' columns flank (int): Buffer size before & after the position to ensure we dont fetch values at index < 0 & > chrom size drop_duplicates (boolean): True if duplicates should be dropped from returned dataframe. Returns: pandas.DataFrame: two column dataframe of peak positions (chrom, pos) """ # necessary for dataframe apply operation below --->>> chrom_size_dict = dict(chrom_sizes.to_records(index=False)) # initialize an empty dataframe allPeaks = pd.DataFrame() for task in tasks: peaks_df = pd.read_csv(tasks[task]['peaks'], sep='\t', header=None, names=['chrom', 'st', 'end', 'name', 'score', 'strand', 'signal', 'p', 'q', 'summit']) # keep only those rows corresponding to the required # chromosomes peaks_df = peaks_df[peaks_df['chrom'].isin(chroms)] # create new column for peak pos peaks_df['pos'] = peaks_df['st'] + peaks_df['summit'] # compute left flank coordinates of the input sequences # (including the allowed jitter) peaks_df['flank_left'] = (peaks_df['pos'] - flank).astype(int) # compute right flank coordinates of the input sequences # (including the allowed jitter) peaks_df['flank_right'] = (peaks_df['pos'] + flank).astype(int) # filter out rows where the left flank coordinate is < 0 peaks_df = peaks_df[peaks_df['flank_left'] >= 0] # --->>> create a new column for chrom size peaks_df["chrom_size"] = peaks_df['chrom'].apply( lambda chrom: chrom_size_dict[chrom]) # filter out rows where the right flank coordinate goes beyond # chromosome size peaks_df = peaks_df[peaks_df['flank_right'] <= peaks_df['chrom_size']] # sort based on chromosome number and right flank coordinate peaks_df = peaks_df.sort_values(['chrom', 'flank_right']).reset_index( drop=True) # append to all peaks data frame allPeaks = allPeaks.append(peaks_df[['chrom', 'pos']]) allPeaks = allPeaks.reset_index(drop=True) # drop the duplicate rows, i.e. the peaks that get duplicated # for the plus and minus strand tasks if drop_duplicates: allPeaks = allPeaks.drop_duplicates(ignore_index=True) return allPeaks def roundToMultiple(x, y): """Return the largest multiple of y < x Args: x (int): the number to round y (int): the multiplier Returns: int: largest multiple of y <= x """ r = (x + int(y / 2)) & ~(y - 1) if r > x: r = r - y return r def round_to_multiple(x, y, smallest=False): """ Return the largest multiple of y <= x or smallest multiple of y >= x Args: x (int): the number to round up to y (int): the multiplier smallest (boolean): set to True to return smallest multiple of y >= x Returns: int: if 'smallest' is False then largest multiple of y <= x, else smallest multiple of y >= x """ # remainder val = x % y # x is a multiple of y if val == 0: return x if smallest: # subtract remainder and the multiplier return (x - val) + y else: # subtract remainder return (x - val) def fix_sequence_length(sequence, length): """ Function to check if length of sequence matches specified length and then return a sequence that's either padded or truncated to match the given length Args: sequence (str): the input sequence length (int): expected length Returns: str: string of length 'length' """ # check
68m & 2.45981E+02 2.775E-20 1.066E+02 3.490E-14 0.00E+00 3.618E-14 2.565E-06 Co 69 & 4.72547E+01 5.410E-21 1.443E+02 7.644E-14 3.12E-16 7.644E-14 8.312E-06 Co 70 & 5.27271E+00 6.125E-22 3.071E+01 2.216E-14 0.00E+00 2.216E-14 2.902E-06 Co 70m & 2.65498E+01 3.084E-21 3.681E+01 2.695E-14 0.00E+00 2.695E-14 3.555E-06 Co 71 & 5.78020E+00 6.810E-22 4.130E+01 2.499E-14 0.00E+00 2.499E-14 2.969E-06 Co 72 & 1.12038E+00 1.339E-22 8.629E+00 6.746E-15 0.00E+00 6.746E-15 9.172E-07 Ni 61 # 2.15649E+01 2.182E-21 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Ni 62 # 3.94185E+03 4.054E-19 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Ni 63 1.21606E+04 1.271E-18 2.655E-06 7.413E-24 0.00E+00 0.000E+00 0.000E+00 Ni 64 # 2.30325E+04 2.445E-18 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Ni 65 3.12959E+04 3.374E-18 2.391E+00 2.412E-16 0.00E+00 2.107E-16 3.564E-08 Ni 66 5.02815E+04 5.505E-18 1.780E-01 1.860E-18 0.00E+00 0.000E+00 0.000E+00 Ni 67 7.64187E+03 8.493E-19 2.522E+02 6.156E-14 0.00E+00 2.031E-15 3.253E-07 Ni 68 & 1.70677E+04 1.925E-18 4.079E+02 4.582E-14 0.00E+00 4.582E-14 6.939E-07 Ni 69 7.46260E+03 8.542E-19 4.537E+02 8.534E-14 0.00E+00 1.916E-13 3.095E-05 Ni 69m & 3.09266E+02 3.540E-20 6.125E+01 1.988E-14 0.00E+00 1.988E-14 1.396E-06 Ni 70 & 7.01159E+03 8.143E-19 8.100E+02 1.550E-13 0.00E+00 1.550E-13 5.572E-06 Ni 71 & 2.19362E+03 2.584E-19 5.939E+02 2.383E-13 0.00E+00 2.383E-13 2.066E-05 Ni 72 & 1.30148E+03 1.555E-19 5.746E+02 1.793E-13 0.00E+00 1.793E-13 1.206E-05 Ni 73 & 2.57153E+02 3.115E-20 2.122E+02 1.034E-13 0.00E+00 1.034E-13 1.057E-05 Ni 74 & 1.22773E+02 1.508E-20 1.251E+02 5.104E-14 0.00E+00 5.104E-14 4.492E-06 Ni 75 & 2.32655E+01 2.896E-21 2.688E+01 1.450E-14 6.95E-17 1.450E-14 1.598E-06 Ni 76 & 4.87190E+00 6.145E-22 7.185E+00 3.594E-15 0.00E+00 3.594E-15 3.747E-07 Cu 65 # 3.56547E+02 3.844E-20 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Cu 66 7.44947E+01 8.155E-21 1.687E-01 2.895E-17 0.00E+00 2.213E-18 3.240E-10 Cu 67 6.88037E+04 7.647E-18 2.140E-01 5.338E-18 0.00E+00 3.957E-18 1.783E-11 Cu 68 1.88329E+04 2.124E-18 4.197E+02 9.963E-14 0.00E+00 6.866E-14 1.104E-05 Cu 68m 8.67520E+02 9.786E-20 2.673E+00 8.735E-17 0.00E+00 4.710E-16 5.191E-08 Cu 69 1.02013E+05 1.168E-17 4.135E+02 5.873E-14 0.00E+00 3.478E-14 4.850E-06 Cu 70 1.12032E+04 1.301E-18 1.745E+02 3.711E-14 0.00E+00 9.764E-14 1.470E-05 Cu 70m & 7.55421E+03 8.772E-19 1.587E+02 2.948E-14 0.00E+00 3.071E-14 1.057E-06 Cu 70n & 8.03087E+03 9.326E-19 8.434E+02 2.868E-13 0.00E+00 2.881E-13 2.125E-05 Cu 71 3.67297E+04 4.326E-18 1.306E+03 3.050E-13 0.00E+00 2.603E-13 2.751E-05 Cu 72 1.47235E+04 1.759E-18 1.546E+03 7.731E-13 0.00E+00 3.539E-13 5.268E-05 Cu 73 1.06880E+04 1.294E-18 1.764E+03 0.000E+00 0.00E+00 8.637E-14 5.738E-06 Cu 74 & 2.58865E+03 3.178E-19 1.126E+03 5.834E-13 0.00E+00 5.834E-13 6.244E-05 Cu 75 & 1.61255E+03 2.007E-19 9.132E+02 3.975E-13 4.50E-15 3.975E-13 3.705E-05 Cu 76 & 2.74493E+02 3.462E-20 2.968E+02 1.729E-13 1.22E-15 1.729E-13 2.005E-05 Cu 76m & 6.58225E+00 8.301E-22 3.592E+00 2.142E-15 0.00E+00 2.142E-15 2.521E-07 Cu 77 & 8.85038E+01 1.131E-20 1.308E+02 7.083E-14 0.00E+00 7.083E-14 7.822E-06 Cu 78 & 1.18635E+01 1.536E-21 2.404E+01 1.617E-14 0.00E+00 1.617E-14 2.041E-06 Cu 79 & 1.48049E+00 1.941E-22 5.458E+00 2.289E-15 8.34E-16 2.289E-15 2.066E-07 Zn 66 # 2.51558E+01 2.754E-21 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Zn 67 # 6.00858E+01 6.678E-21 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Zn 68 # 8.98337E+04 1.013E-17 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Zn 69 6.96994E+04 7.977E-18 1.428E+01 7.386E-16 0.00E+00 1.374E-20 9.049E-13 Zn 69m 4.74668E+02 5.433E-20 6.632E-03 2.378E-20 0.00E+00 4.425E-19 2.628E-11 Zn 70 # 2.93620E+05 3.409E-17 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Zn 71 2.13018E+05 2.509E-17 1.004E+03 1.687E-13 0.00E+00 5.068E-14 4.488E-06 Zn 71m 3.06239E+04 3.607E-18 1.489E+00 1.281E-16 0.00E+00 3.721E-16 2.650E-08 Zn 72 7.14428E+05 8.533E-17 2.958E+00 4.877E-17 0.00E+00 7.228E-17 3.042E-10 Zn 73 1.07914E+05 1.307E-17 3.183E+03 9.406E-13 0.00E+00 5.348E-14 7.581E-06 Zn 73m & 1.72954E+04 2.095E-18 9.222E+02 0.000E+00 0.00E+00 2.888E-14 1.948E-07 Zn 73n & 7.09177E+03 8.588E-19 8.475E+02 1.024E-13 0.00E+00 1.053E-13 1.812E-06 Zn 74 7.61597E+05 9.350E-17 5.522E+03 7.078E-13 0.00E+00 2.654E-13 1.325E-05 Zn 75 9.09853E+04 1.132E-17 6.183E+03 1.922E-12 0.00E+00 1.697E-12 2.554E-04 Zn 76 6.19430E+04 7.810E-18 7.533E+03 1.914E-12 0.00E+00 6.311E-13 5.273E-05 Zn 77 & 1.17079E+04 1.496E-18 3.902E+03 1.515E-12 0.00E+00 1.515E-12 1.275E-04 Zn 77m & 3.08027E+02 3.935E-20 2.033E+02 4.368E-14 0.00E+00 5.626E-14 2.382E-06 Zn 78 & 6.65101E+03 8.608E-19 3.136E+03 1.066E-12 0.00E+00 1.066E-12 7.864E-05 Zn 79 & 1.03352E+03 1.355E-19 7.200E+02 3.458E-13 8.31E-16 3.458E-13 3.494E-05 Zn 80 2.43929E+02 3.238E-20 3.102E+02 1.289E-13 0.00E+00 7.835E-14 8.781E-06 Zn 81 & 7.36875E+00 9.905E-22 1.761E+01 1.057E-14 2.61E-16 1.057E-14 1.249E-06 Ga 69 # 1.52835E+03 1.749E-19 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Ga 70 5.01827E+01 5.827E-21 2.742E-02 2.814E-18 0.00E+00 4.035E-20 4.773E-12 Ga 71 # 1.66366E+05 1.959E-17 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Ga 72 7.16503E+03 8.558E-19 9.784E-02 7.943E-18 0.00E+00 4.240E-17 6.778E-09 Ga 73 9.85038E+05 1.193E-16 3.902E+01 2.793E-15 0.00E+00 2.132E-15 7.028E-08 Ga 74 1.10883E+06 1.361E-16 1.578E+03 2.498E-13 0.00E+00 7.598E-13 1.190E-04 Ga 74m 1.38264E+03 1.697E-19 1.009E+02 2.726E-16 0.00E+00 6.944E-16 2.272E-09 Ga 75 1.35310E+06 1.684E-16 7.203E+03 1.599E-12 0.00E+00 7.743E-14 6.308E-06 Ga 76 6.13727E+05 7.738E-17 1.305E+04 3.765E-12 0.00E+00 5.675E-12 8.703E-04 Ga 77 3.04804E+05 3.894E-17 1.625E+04 5.498E-12 0.00E+00 1.190E-12 1.250E-04 Ga 78 1.02396E+05 1.325E-17 1.394E+04 5.817E-12 0.00E+00 5.585E-12 8.467E-04 Ga 79 6.08186E+04 7.972E-18 1.405E+04 5.021E-12 6.30E-13 4.143E-12 7.654E-04 Ga 80 1.56046E+04 2.071E-18 6.374E+03 3.529E-12 1.12E-15 2.416E-12 3.473E-04 Ga 81 & 6.17731E+03 8.302E-19 3.518E+03 1.382E-12 5.81E-14 1.382E-12 1.176E-04 Ga 82 & 4.72792E+02 6.433E-20 5.471E+02 3.103E-13 2.24E-14 3.103E-13 3.535E-05 Ga 83 & 5.95193E+01 8.198E-21 1.339E+02 6.807E-14 1.62E-14 6.807E-14 7.181E-06 Ga 84 & 1.44962E+00 2.021E-22 1.182E+01 5.568E-15 2.89E-15 5.568E-15 5.540E-07 Ge 70 # 4.20502E+00 4.883E-22 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Ge 72 # 2.34658E+02 2.803E-20 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Ge 73 # 7.01944E+03 8.500E-19 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Ge 73m 2.86483E+01 3.469E-21 3.979E+01 3.410E-16 0.00E+00 6.992E-17 6.716E-10 Ge 74 # 2.22447E+05 2.731E-17 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Ge 75 1.36854E+06 1.703E-16 1.910E+02 1.285E-14 0.00E+00 1.063E-15 1.793E-08 Ge 75m 1.99641E+04 2.484E-18 2.883E+02 3.781E-15 0.00E+00 2.682E-15 1.190E-08 Ge 76 3.98550E+06 5.025E-16 5.540E-23 1.810E-38 0.00E+00 0.000E+00 0.000E+00 Ge 77 2.51544E+06 3.213E-16 4.286E+01 4.410E-15 0.00E+00 7.406E-15 6.463E-07 Ge 77m 1.31119E+06 1.675E-16 1.718E+04 2.659E-12 0.00E+00 2.037E-13 6.807E-06 Ge 78 1.11925E+07 1.448E-15 1.469E+03 5.337E-14 0.00E+00 6.546E-14 9.197E-07 Ge 79 8.17941E+05 1.072E-16 2.987E+04 8.203E-12 0.00E+00 1.243E-12 1.879E-04 Ge 79m 1.23758E+06 1.622E-16 2.200E+04 4.551E-12 0.00E+00 4.215E-12 4.295E-04 Ge 80 2.75501E+06 3.656E-16 7.073E+04 1.076E-11 0.00E+00 3.884E-12 4.578E-04 Ge 81 5.30736E+05 7.132E-17 4.841E+04 1.295E-11 0.00E+00 2.047E-11 2.754E-03 Ge 81m 4.78455E+04 6.430E-18 4.364E+03 1.731E-12 0.00E+00 1.045E-12 1.658E-04 Ge 82 3.09790E+05 4.215E-17 4.719E+04 1.191E-11 0.00E+00 8.157E-12 1.223E-03 Ge 83 & 3.47586E+04 4.787E-18 1.302E+04 6.246E-12 0.00E+00 6.246E-12 6.304E-04 Ge 84 & 7.02105E+03 9.786E-19 5.101E+03 1.981E-12 7.85E-14 1.981E-12 1.667E-04 Ge 85 & 6.11080E+02 8.619E-20 7.844E+02 3.910E-13 2.17E-14 3.910E-13 4.065E-05 Ge 86 & 9.75936E+01 1.393E-20 2.255E+02 1.121E-13 0.00E+00 1.121E-13 1.164E-05 Ge 87 & 2.92570E+00 4.224E-22 1.352E+01 8.477E-15 0.00E+00 8.477E-15 1.029E-06 As 74 4.80072E+01 5.893E-21 2.166E-05 9.312E-22 0.00E+00 2.636E-21 1.705E-13 As 75 # 2.24363E+04 2.791E-18 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 As 76 8.65531E+03 1.091E-18 6.356E-02 1.083E-17 0.00E+00 4.274E-18 3.895E-10 As 77 3.03753E+06 3.880E-16 1.506E+01 5.441E-16 0.00E+00 2.006E-17 5.894E-10 As 78 6.63417E+05 8.584E-17 8.450E+01 1.701E-14 0.00E+00 1.759E-14 2.511E-06 As 79 1.32354E+07 1.735E-15 1.697E+04 2.282E-12 0.00E+00 9.185E-14 7.756E-06 As 80 2.03452E+06 2.700E-16 9.278E+04 3.192E-11 0.00E+00 8.653E-12 1.193E-03 As 81 5.36713E+06 7.212E-16 1.117E+05 2.820E-11 0.00E+00 4.122E-12 4.212E-04 As 82 2.75141E+06 3.743E-16 9.985E+04 5.115E-11 0.00E+00 4.924E-12 7.563E-04 As 82m 5.95044E+05 8.095E-17 3.033E+04 9.899E-12 0.00E+00 1.443E-11 2.142E-03 As 83 2.59814E+06 3.578E-16 1.344E+05 2.950E-11 0.00E+00 4.350E-11 7.049E-03 As 84 4.26866E+05 5.949E-17 5.380E+04 1.724E-11 0.00E+00 4.603E-11 2.321E-03 As 84m & 1.31322E+04 1.832E-18 1.400E+04 7.383E-12 0.00E+00 7.383E-12 8.001E-04 As 85 1.24987E+05 1.763E-17 4.247E+04 2.300E-11 1.03E-12 2.440E-12 3.900E-04 As 86 & 1.56747E+04 2.237E-18 1.150E+04 5.477E-12 7.91E-13 5.477E-12 5.500E-04 As 87 & 3.87257E+03 5.591E-19 4.400E+03 2.284E-12 1.76E-13 2.284E-12 2.446E-04 As 88 & 2.20532E+02 3.221E-20 5.095E+02 3.426E-13 0.00E+00 3.426E-13 4.326E-05 As 89 & 3.42281E+01 5.056E-21 1.186E+02 7.640E-14 0.00E+00 7.640E-14 9.418E-06 Se 76 # 1.42575E+02 1.797E-20 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Se 77 # 3.44707E+03 4.403E-19 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Se 77m 1.05052E+02 1.342E-20 4.194E+00 4.901E-17 0.00E+00 5.968E-17 2.356E-10 Se 78 # 3.50090E+04 4.530E-18 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Se 79 7.64685E+05 1.002E-16 4.455E-08 3.751E-25 0.00E+00 0.000E+00 0.000E+00 Se 79m 1.83898E+06 2.410E-16 5.447E+03 7.145E-14 0.00E+00 1.218E-14 5.728E-08 Se 80 # 2.43628E+07 3.233E-15 0.000E+00 0.000E+00 0.00E+00 0.000E+00 0.000E+00 Se 81 2.68000E+07 3.601E-15 1.684E+04 1.643E-12 0.00E+00 2.305E-14 1.136E-06 Se 81m 4.21500E+06 5.664E-16 8.501E+02 1.163E-14 0.00E+00 2.455E-15 1.264E-08 Se 82 5.76029E+07 7.835E-15 1.046E-20 5.017E-36 0.00E+00 0.000E+00 0.000E+00 Se 83 4.54829E+07 6.263E-15 2.353E+04 2.262E-12 0.00E+00 9.084E-12 1.275E-03 Se 83m 1.18171E+07 1.627E-15 1.168E+05 2.382E-11 0.00E+00 1.819E-11 2.662E-03 Se 84 7.50419E+07 1.046E-14 2.797E+05 2.421E-11 0.00E+00 1.829E-11 1.087E-03 Se 85 1.49170E+07 2.104E-15 3.262E+05 8.466E-11 0.00E+00 1.244E-10 1.910E-02 Se 86 & 6.78269E+06 9.678E-16 3.073E+05 8.368E-11 0.00E+00 8.368E-11 4.810E-03 Se
<filename>ccb/ml.py """Machine learning utility functions""" import multiprocessing as _mp from sklearn import ensemble as _ensemble from sklearn import linear_model as _linear_model from sklearn import metrics as _metrics from sklearn import model_selection as _model_selection from sklearn import svm as _svm from sklearn import tree as _tree # global runtime settings _ncpu = _mp.cpu_count() class tuner(object): def __init__( self, x, y, optimizer=_model_selection.GridSearchCV, param_grid=None, scoring=None, fit_params=None, n_jobs=_ncpu, refit=True, verbose=1, error_score="raise", return_train_score=True, cv=None, n_splits=5, ): """Initializes a model tuning object wtih functions to optimize hyperparameter selection across multiple sklearn model types :param x: the model covariates :param y: the response variable :param optimizer: the parameter search and optimization method. default is a sklearn.model_selection.GridSearchCV instance :param param_grid: dictionary with hyperparameter names as keys and lists of hyperparameter settings to try in grid search :param scoring: the model performance metric to optimize. accepts string values and sklear.metrics.* instances :param fit_params: parameters to pass to the `fit` method of the estimator :param n_jobs: number of cpus to use in parameter estimation :param refit: compute and store a `best_estimator_` based on the best hyperparameter fit :param error_score: the value to return whenan error occurs in fitting. set to 'raise' to raise an exception. :param return_train_score: boolean to compute and save training scores. setting to false may save computation time. :param cv: determines the cross-validation splitting strategy. accepts inputs to sklearn.model_selection.GridSearchCV :param n_splits: number of cross-validation splits :return object: a class instance with model tuning utilities / functions """ # set the variables to the tune class self.x = x self.y = y self.optimizer = optimizer self.param_grid = param_grid self.scoring = scoring self.fit_params = fit_params self.n_jobs = n_jobs self.refit = refit self.verbose = verbose self.error_score = error_score self.return_train_score = return_train_score self.cv = cv self.n_splits = n_splits def run_gs(self, estimator): """Runs a grid search based on the input hyperparameter options. :param estimator: the sklearn model estimator with an estimator.fit() function :return None: updates the tuner object with grid search results """ # create the grid search gs = self.optimizer( estimator, param_grid=self.param_grid, scoring=self.scoring, n_jobs=self.n_jobs, cv=self.cv, refit=self.refit, verbose=self.verbose, error_score=self.error_score, return_train_score=self.return_train_score, ) # begin fitting the grid search gs.fit(self.x, self.y) # update the tuning object with the outputs of the tuning self.cv_results = gs.cv_results_ self.best_estimator = gs.best_estimator_ self.best_score = gs.best_score_ self.best_params = gs.best_params_ self.best_index = gs.best_index_ self.scorer = gs.scorer_ self.n_splits = gs.n_splits_ self.gs = gs def LinearRegression(self, optimizer=None, param_grid=None, scoring=None, fit_params=None, cv=None): """Creates a linear regression model estimator. :param optimizer: the parameter search and optimization method. default is a sklearn.model_selection.GridSearchCV instance :param param_grid: dictionary with hyperparameter names as keys and lists of hyperparameter settings to try in grid search :param scoring: the model performance metric to optimize. accepts string values and sklear.metrics.* instances :param fit_params: parameters to pass to the `fit` method of the estimator :param cv: determines the cross-validation splitting strategy. accepts inputs to sklearn.model_selection.GridSearchCV :return None: updates the `tuner` object with the passed parameters and runs a grid search using the LinearRegression estimator """ # check if the optimizer has changed, otherwise use default if optimizer is not None: self.optimizer = optimizer # check if the parameter grid has been set, otherwise set defaults if param_grid is None: if self.param_grid is None: param_grid = {"normalize": (True, False), "fit_intercept": (True, False)} self.param_grid = param_grid else: self.param_grid = param_grid # set the scoring function if scoring is None: if self.scoring is None: scoring = _metrics.explained_variance_score self.scoring = scoring else: self.scoring = scoring # set the default fit parameters if fit_params is not None: self.fit_params = fit_params # set the cross validation strategy if cv is None: if self.cv is None: cv = _model_selection.StratifiedKFold(n_splits=self.n_splits) self.cv = cv else: self.cv = cv # create the estimator and run the grid search estimator = _linear_model.LinearRegression() self.run_gs(estimator) def LogisticRegression(self, optimizer=None, param_grid=None, scoring=None, fit_params=None, cv=None): """Creates a logistic regression model estimator. :param optimizer: the parameter search and optimization method. default is a sklearn.model_selection.GridSearchCV instance :param param_grid: dictionary with hyperparameter names as keys and lists of hyperparameter settings to try in grid search :param scoring: the model performance metric to optimize. accepts string values and sklear.metrics.* instances :param fit_params: parameters to pass to the `fit` method of the estimator :param cv: determines the cross-validation splitting strategy. accepts inputs to sklearn.model_selection.GridSearchCV :return None: updates the `tuner` object with the passed parameters and runs a grid search using the LogisticRegression estimator """ # check if the optimizer has changed, otherwise use default if optimizer is not None: self.optimizer = optimizer # check if the parameter grid has been set, otherwise set defaults if param_grid is None: if self.param_grid is None: param_grid = {"C": (1e-2, 1e-1, 1e0, 1e1), "tol": (1e-3, 1e-4, 1e-5), "fit_intercept": (True, False)} self.param_grid = param_grid else: self.param_grid = param_grid # set the scoring function if scoring is None: if self.scoring is None: scoring = "roc_auc" self.scoring = scoring else: self.scoring = scoring # set the default fit parameters if fit_params is not None: self.fit_params = fit_params # set the cross validation strategy if cv is None: if self.cv is None: cv = _model_selection.StratifiedKFold(n_splits=self.n_splits) self.cv = cv else: self.cv = cv # create the estimator and run the grid search estimator = _linear_model.LogisticRegression() self.run_gs(estimator) def DecisionTreeClassifier(self, optimizer=None, param_grid=None, scoring=None, fit_params=None, cv=None): """Creates a decision tree model estimator. :param optimizer: the parameter search and optimization method. default is a sklearn.model_selection.GridSearchCV instance :param param_grid: dictionary with hyperparameter names as keys and lists of hyperparameter settings to try in grid search :param scoring: the model performance metric to optimize. accepts string values and sklear.metrics.* instances :param fit_params: parameters to pass to the `fit` method of the estimator :param cv: determines the cross-validation splitting strategy. accepts inputs to sklearn.model_selection.GridSearchCV :return None: updates the `tuner` object with the passed parameters and runs a grid search using the DecisionTreeClassifier estimator """ # check if the optimizer has changed, otherwise use default if optimizer is not None: self.optimizer = optimizer # check if the parameter grid has been set, otherwise set defaults if param_grid is None: if self.param_grid is None: param_grid = { "criterion": ("gini", "entropy"), "splitter": ("best", "random"), "max_features": ("sqrt", "log2", None), "max_depth": (2, 5, 10, None), "min_samples_split": (2, 0.01, 0.1), "min_impurity_split": (1e-7, 1e-6), } self.param_grid = param_grid else: self.param_grid = param_grid # set the scoring function if scoring is None: if self.scoring is None: scoring = "neg_log_loss" self.scoring = scoring else: self.scoring = scoring # set the default fit parameters if fit_params is not None: self.fit_params = fit_params # set the cross validation strategy if cv is None: if self.cv is None: cv = _model_selection.StratifiedKFold(n_splits=self.n_splits) self.cv = cv else: self.cv = cv # create the estimator and run the grid search estimator = _tree.DecisionTreeClassifier() self.run_gs(estimator) def SVC(self, optimizer=None, param_grid=None, scoring=None, fit_params=None, cv=None, class_weight=None): """Creates a support vector machine classifier model estimator. :param optimizer: the parameter search and optimization method. default is a sklearn.model_selection.GridSearchCV instance :param param_grid: dictionary with hyperparameter names as keys and lists of hyperparameter settings to try in grid search :param scoring: the model performance metric to optimize. accepts string values and sklear.metrics.* instances :param fit_params: parameters to pass to the `fit` method of the estimator :param cv: determines the cross-validation splitting strategy. accepts inputs to sklearn.model_selection.GridSearchCV :return None: updates the `tuner` object with the passed parameters and runs a grid search using the SVC estimator """ # check if the optimizer has changed, otherwise use default if optimizer is not None: self.optimizer = optimizer # check if the parameter grid has been set, otherwise set defaults if param_grid is None: if self.param_grid is None: param_grid = { "C": (1e-3, 1e-2, 1e-1, 1e0, 1e1), "kernel": ("rbf", "linear"), "gamma": (1e-3, 1e-4, 1e-5, 1e-6, 1e-7), } self.param_grid = param_grid # set the scoring function if scoring is None: if self.scoring is None: scoring = "neg_log_loss" self.scoring = scoring # set the default fit parameters if fit_params is not None: self.fit_params = fit_params # set the cross
<reponame>rolker/noaadata #!/usr/bin/env python """Tools to generate python code to serialize/deserialize messages between python and ais binary. Trying to be as inline as possible, so no XML on the fly like in ais-py. serialize: python to ais binary deserialize: ais binary to python The generated code uses translators.py, binary.py, and aisstring.py which should be packaged with the resulting files. @license: Apache 2.0 TODO(schwehr):add a link to generated doc string to bring up the html for the pretty version TODO(schwehr):write a separate validation script that distinguishes standard messages and bin messages TODO(schwehr):make sure binary is only used in AIS ITU messages and not within the binary messages! TODO(schwehr):arrays TODO(schwehr):handle entry ranges in lookup tables TODO(schwehr):arraylength of -1 for messages 12 and 14 TODO(schwehr):in the table html/kml form output, if no LUT and value is the unknown case, say so in the converted column! TODO(schwehr):stop using sqlhelp. Can have trouble with corrupted data. @bug: NOT complete @note: This compiler assumes that all locations are in WGS 84 (EPSG 4326) TODO(schwehr):add type checking of command line parameters for crafting AIS messages """ import datetime import os import sys from decimal import Decimal from lxml import etree def suggestType(name,curType,printout=True): '''Try to suggest a type name if one did not work. @param printout: if true, write a suggestion to stdout. >>> suggestType('myFieldName', 'unsigned int') Recommend switching "unsigned int" to "uint" for field "myFieldName" 'uint' >>> suggestType('JohnWarfon', 'yoyodyne') Sorry! No recommendation available for bad type "yoyodyne" for field "JohnWarfon" ''' newType = None if curType.lower()=='unsigned int': newType = 'uint' elif curType.lower()=='unsigned decimal': newType = 'udecimal' if printout: if newType: print 'Recommend switching "'+curType+'" to "'+newType+'" for field "'+name+'"' else: print 'Sorry! No recommendation available for bad type "'+curType+'" for field "'+name+'"' return newType def hasSubTag(et,subtag): ''' @return: true if the tag a sub tag with name subtag ''' if 0<len(et.xpath(subtag)): return True return False def writeBeginning(o): '''Write the doc string header for the message file. @param o: Open output file to write code to. Must be pre-expanded with the expandais.py command. ''' d = datetime.datetime.utcnow() dateStr = str(d.year)+'-'+("%02d" %d.month)+'-'+("%02d"%d.day) # Need to pass in info about the source file, etc. # Minor trickery to get svn to ignore the keywords in the next few lines o.write('''#!/usr/bin/env python \"\"\"Autogenerated python functions to serialize/deserialize binary messages. Generated by: ''' + __file__ + ''' Need to then wrap these functions with the outer AIS packet and then convert the whole binary blob to a NMEA string. Those functions are not currently provided in this file. serialize: python to ais binary deserialize: ais binary to python The generated code uses translators.py, binary.py, and aisstring.py which should be packaged with the resulting files. ''') o.write(''' TODO(schwehr):FIX: put in a description of the message here with fields and types. \"\"\" import doctest import sys from decimal import Decimal import unittest from aisutils.BitVector import BitVector from aisutils import aisstring from aisutils import binary from aisutils import sqlhelp from aisutils import uscg # FIX: check to see if these will be needed TrueBV = BitVector(bitstring="1") "Why always rebuild the True bit? This should speed things up a bunch" FalseBV = BitVector(bitstring="0") "Why always rebuild the False bit? This should speed things up a bunch" ''') return def generatePython(infile,outfile, prefixName=False,verbose=False): ''' @param infile: xml ais binary message definition file @param outfile: where to dump the python code ''' aisMsgsET = etree.parse(infile).getroot() o = file(outfile,'w') os.chmod(outfile,0755) writeBeginning(o) for msgET in aisMsgsET: if msgET.tag != 'message': continue print msgET.tag, msgET.attrib['name'] if len(msgET.xpath('include-struct')) > 0: sys.exit("ERROR: cannot handle xml that still has include-struct tags.\n Please use expandais.py.") buildHelpers(o,msgET,prefixName=prefixName,verbose=verbose) buildEncode(o,msgET,prefixName=prefixName,verbose=verbose) buildDecode(o,msgET,prefixName=prefixName) buildDecodeParts(o,msgET,prefixName=prefixName) # functions that only decode one field buildPrint(o,msgET,prefixName=prefixName) buildLUT(o,msgET,prefixName=prefixName) buildSQL(o,msgET,prefixName=prefixName) buildLaTeX(o,msgET,prefixName=prefixName,verbose=verbose) buildTextDef(o,msgET,prefixName=prefixName) o.write('\n\n######################################################################\n') o.write('# UNIT TESTING\n') o.write('######################################################################\n') for msgET in aisMsgsET: if msgET.tag != 'message': continue print 'Building unit tests for message ...', msgET.attrib['name'] buildUnitTest(o,msgET, prefixName=prefixName) for msgET in aisMsgsET: if msgET.tag != 'message': continue buildMain(o,msgET, prefixName=prefixName) return ###################################################################### # Build Helpers ###################################################################### def buildHelpers(o,msgET, verbose=False, prefixName=False): ''' emit the fieldList and other things??? @param o: open file where resulting code will be written @param msgET: Element Tree starting at a message node TODO(schwehr):for lookuptable/entry values, make it also print the decoded value. TODO(schwehr):use a different name for message and field TODO(schwehr):put in comments with the python and sql data type for each field ''' if verbose: msgname = msgET.attrib['name'] print 'Building helpers ...',msgname if prefixName: o.write(prefixName,'FieldList = (\n') else: o.write('fieldList = (\n') for field in msgET.xpath('field'): name = field.attrib['name'] o.write(' \''+name+'\',\n') o.write(')\n\n') # FIX: add some documentation to the fieldList # FIX: like that it is used as the default csv list if prefixName: o.write(prefixName,'FieldListPostgres = (\n') else: o.write('fieldListPostgres = (\n') finished=[] # postgis names for field in msgET.xpath('field'): name = field.attrib['name'] if 'postgisName' in field.attrib: name = field.attrib['postgisName'] if name in finished: continue # already done, so skip finished.append(name) o.write(' \''+name+'\', # PostGIS data type\n') else: o.write(' \''+name+'\',\n') o.write(')\n\n') del finished if prefixName: o.write(prefixName,'ToPgFields = {\n') else: o.write('toPgFields = {\n') for field in msgET.xpath('field'): if 'postgisName' not in field.attrib: continue name = field.attrib['name'] pgName = field.attrib['postgisName'] o.write(' \''+name+'\':\''+pgName+'\',\n') o.write('}\n') o.write('''\"\"\" Go to the Postgis field names from the straight field name \"\"\" ''') if prefixName: o.write(prefixName,'FromPgFields = {\n') else: o.write('fromPgFields = {\n') finished=[] # postgis names for field in msgET.xpath('field'): if 'postgisName' not in field.attrib: continue name = field.attrib['name'] pgName = field.attrib['postgisName'] if pgName in finished: continue # already done, so skip finished.append(pgName) o.write(' \''+pgName+'\':(') xp = 'field[@postgisName=\''+pgName+'\']' parts = ['\''+part.attrib['name']+'\'' for part in msgET.xpath(xp)] o.write(','.join(parts)+',),\n') o.write('}\n') o.write('''\"\"\" Go from the Postgis field names to the straight field name \"\"\" ''') if prefixName: o.write(prefixName,'PgTypes = {\n') else: o.write('pgTypes = {\n') finished=[] # postgis names for field in msgET.xpath('field'): if 'postgisName' not in field.attrib: continue pgType = field.attrib['postgisType'] pgName = field.attrib['postgisName'] if pgName in finished: continue # already done, so skip finished.append(pgName) o.write(' \''+pgName+'\':\''+pgType+'\',\n') o.write('}\n') o.write('''\"\"\" Lookup table for each postgis field name to get its type. \"\"\" ''') ###################################################################### # SIMPLE PRINT ###################################################################### def getMaxFieldNameLen(msgET): '''Get the maximum string length of any field name''' maxStrLen=0 for field in msgET.xpath('field'): fieldLen = len(field.attrib['name']) if fieldLen>maxStrLen: maxStrLen = fieldLen return maxStrLen def padStrRight(aStr,strlen): '''Pad a string out to the length requested with spaces out to the right''' return aStr + ' '*(strlen-len(aStr)) def haveLocatableMessage(msgET): '''Make sure this message has both long/x and lat/y fields. @rtype: bool ''' #if getLongitudeFieldName(msgET) and getLatitudeFieldName(msgET): return True if 0==len(msgET.xpath('field[contains(@name, "longitude")]')): return False if 0==len(msgET.xpath('field[contains(@name, "latitude")]')): return False return True def getLongitudeFieldName(msgET): ''' Dig up the first field name that include longitude and return it TODO(schwehr):might want to allow a search for a special tag to mark this ''' return msgET.xpath('field[contains(@name, "longitude")]')[0].attrib['name'] def getLatitudeFieldName(msgET): ''' Dig up the first field name that include longitude and return it TODO(schwehr):might want to allow a search for a special tag to mark this ''' return msgET.xpath('field[contains(@name, "latitude")]')[0].attrib['name'] def buildPrint(o,msgET, verbose=False, prefixName=False): ''' Write a simple in order print for the resulting dictionary. @param o: open file where resulting code will be written @param msgET: Element Tree starting at a message node TODO(schwehr):for lookuptable/entry values, make it also print the decoded value. TODO(schwehr):use a different name for message and field ''' assert(msgET.tag=='message') msgName = msgET.attrib['name'] #msgName = msgname = name # FIX: make these all msgName print 'Generating print ...',msgName # FIX: verbose? # +1 for the ':' maxFieldLen = 1 + getMaxFieldNameLen(msgET) ############################## # Html builder ############################## printHtmlName = 'printHtml' if prefixName: printHtmlName = name+'printHtml' #################### ####### HTML format #################### #o.write(' elif \'html\'==format:\n') o.write('\n') o.write('def '+printHtmlName+'(params, out=sys.stdout):\n') o.write(' out.write("<h3>'+msgName+'</h3>\\n")\n') o.write(' out.write("<table border=\\"1\\">\\n")\n') #o.write(' out.write("<tr bgcolor=\\"#9acd32\\">\\n")\n') o.write(' out.write("<tr bgcolor=\\"orange\\">\\n")\n') o.write(' out.write("<th align=\\"left\\">Field Name</th>\\n")\n') o.write(' out.write("<th align=\\"left\\">Type</th>\\n")\n') o.write(' out.write("<th align=\\"left\\">Value</th>\\n")\n') o.write(' out.write("<th align=\\"left\\">Value in Lookup Table</th>\\n")\n') o.write(' out.write("<th align=\\"left\\">Units</th>\\n")\n') o.write(' out.write("</tr>\\n")\n') for field in msgET.xpath('field'): o.write(' out.write("\\n")\n') o.write(' out.write("<tr>\\n")\n') fieldname = field.attrib['name'] fieldtype = field.attrib['type'] o.write(' out.write("<td>'+fieldname+'</td>\\n")\n') o.write(' out.write("<td>'+fieldtype+'</td>\\n")\n') numbits = int(field.attrib['numberofbits']) required = None; if hasSubTag(field,'required'): required = field.xpath('required')[0].text unavailable=None; if hasSubTag(field,'unavailable'): unavailable = field.xpath('unavailable')[0].text arraylen=1 if 'arraylength' in field.attrib: arraylen=int(field.attrib['arraylength']) if 1==arraylen or fieldtype=='aisstr6': o.write(' if \''+fieldname+'\' in params:\n out.write(" <td>"+str(params[\''+fieldname+'\'])+"</td>\\n")\n') if not hasSubTag(field,'lookuptable'): # Just duplicate the value through o.write(' out.write(" <td>"+str(params[\''+fieldname+'\'])+"</td>\\n")\n') else: lutName = fieldname+'DecodeLut' if prefixName: lutName = msgname+fieldname.capitalize()+'DecodeLut' o.write(' if str(params[\''+fieldname+'\']) in '+lutName+':\n') o.write(' out.write("<td>"+'+lutName+'[str(params[\''+fieldname+'\'])]+"</td>")\n') o.write(' else:\n') o.write(' out.write("<td><i>Missing LUT entry</i></td>")\n')
is non-zero.)""" if field: return self._getField(field,native=native,prompt=prompt) # may prompt for value if prompt flag is set #XXX should change _optionalPrompt so we prompt for each element of #XXX the array separately? I think array parameters are #XXX not useful as non-hidden params. if prompt: self._optionalPrompt(mode) if index is not None: sumindex = self._sumindex(index) try: if native: return self.value[sumindex] else: return self.toString(self.value[sumindex]) except IndexError: # should never happen raise SyntaxError("Illegal index [" + repr(sumindex) + "] for array parameter " + self.name) elif native: # return object itself for an array because it is # indexable, can have values assigned, etc. return self else: # return blank-separated string of values for array return str(self) def set(self, value, field=None, index=None, check=1): """Set value of this parameter from a string or other value. Field is optional parameter field (p_prompt, p_minimum, etc.) Index is optional array index (zero-based). Set check=0 to assign the value without checking to see if it is within the min-max range or in the choice list.""" if index is not None: sumindex = self._sumindex(index) try: value = self._coerceOneValue(value) if check: self.value[sumindex] = self.checkOneValue(value) else: self.value[sumindex] = value return except IndexError: # should never happen raise SyntaxError("Illegal index [" + repr(sumindex) + "] for array parameter " + self.name) if field: self._setField(value,field,check=check) else: if check: self.value = self.checkValue(value) else: self.value = self._coerceValue(value) self.setChanged() def checkValue(self,value,strict=0): """Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.) """ v = self._coerceValue(value,strict) for i in range(len(v)): self.checkOneValue(v[i],strict=strict) return v #-------------------------------------------- # special methods #-------------------------------------------- # array parameters can be subscripted # note subscripts start at zero, unlike CL subscripts # that start at one def __getitem__(self, index): return self.get(index=index,native=1) def __setitem__(self, index, value): self.set(value, index=index) def __str__(self): """Return readable description of parameter""" # This differs from non-arrays in that it returns a # print string with just the values. That's because # the object itself is returned as the native value. sv = list(map(str, self.value)) for i in range(len(sv)): if self.value[i] is None: sv[i] = "INDEF" return ' '.join(sv) def __len__(self): return len(self.value) #-------------------------------------------- # private methods #-------------------------------------------- def _sumindex(self, index=None): """Convert tuple index to 1-D index into value""" try: ndim = len(index) except TypeError: # turn index into a 1-tuple index = (index,) ndim = 1 if len(self.shape) != ndim: raise ValueError("Index to %d-dimensional array %s has too %s dimensions" % (len(self.shape), self.name, ["many","few"][len(self.shape) > ndim])) sumindex = 0 for i in range(ndim-1,-1,-1): index1 = index[i] if index1 < 0 or index1 >= self.shape[i]: raise ValueError("Dimension %d index for array %s is out of bounds (value=%d)" % (i+1, self.name, index1)) sumindex = index1 + sumindex*self.shape[i] return sumindex def _getPType(self): """Get underlying datatype for this parameter (strip off 'a' array params)""" return self.type[1:] def _coerceValue(self,value,strict=0): """Coerce parameter to appropriate type Should accept None or null string. Must be an array. """ try: if isinstance(value,str): # allow single blank-separated string as input value = value.split() if len(value) != len(self.value): raise IndexError v = len(self.value)*[0] for i in range(len(v)): v[i] = self._coerceOneValue(value[i],strict) return v except (IndexError, TypeError): raise ValueError("Value must be a " + repr(len(self.value)) + "-element array for " + self.name) def isLegal(self): """Dont call checkValue for arrays""" try: return self.value is not None except ValueError: return 0 # ----------------------------------------------------- # IRAF string parameter mixin class # ----------------------------------------------------- class _StringMixin: """IRAF string parameter mixin class""" #-------------------------------------------- # public methods #-------------------------------------------- def toString(self, value, quoted=0): """Convert a single (non-array) value of the appropriate type for this parameter to a string""" if value is None: return "" elif quoted: return repr(value) else: return value # slightly modified checkOneValue allows minimum match for # choice strings and permits null string as value def checkOneValue(self,v,strict=0): if v is None or v[:1] == ")": return v elif self.choice is not None: try: v = self.choiceDict[v] except minmatch.AmbiguousKeyError: clist = self.choiceDict.getall(v) raise ValueError("Parameter %s: " "ambiguous value `%s', could be %s" % (self.name, str(v), "|".join(clist))) except KeyError: raise ValueError("Parameter %s: " "value `%s' is not in choice list (%s)" % (self.name, str(v), "|".join(self.choice))) elif (self.min is not None and v<self.min): raise ValueError("Parameter %s: " "value `%s' is less than minimum `%s'" % (self.name, str(v), str(self.min))) elif (self.max is not None and v>self.max): raise ValueError("Parameter %s: " "value `%s' is greater than maximum `%s'" % (self.name, str(v), str(self.max))) return v #-------------------------------------------- # private methods #-------------------------------------------- def _checkAttribs(self, strict): """Check initial attributes to make sure they are legal""" if self.min: warning("Minimum value not allowed for string-type parameter " + self.name, strict) self.min = None if self.max: if not self.prompt: warning("Maximum value not allowed for string-type parameter " + self.name + " (probably missing comma)", strict) # try to recover by assuming max string is prompt self.prompt = self.max else: warning("Maximum value not allowed for string-type parameter " + self.name, strict) self.max = None # If not in strict mode, allow file (f) to act just like string (s). # Otherwise choice is also forbidden for file type if strict and self.type == "f" and self.choice: warning("Illegal choice value for type '" + self.type + "' for parameter " + self.name, strict) self.choice = None def _setChoiceDict(self): """Create min-match dictionary for choice list""" # value is full name of choice parameter self.choiceDict = minmatch.MinMatchDict() for c in self.choice: self.choiceDict.add(c, c) def _nullPrompt(self): """Returns value to use when answer to prompt is null string""" # for string, null string is a legal value # keep current default unless it is None if self.value is None: return "" else: return self.value def _coerceOneValue(self,value,strict=0): if value is None: return value elif isinstance(value,str): # strip double quotes and remove escapes before quotes return irafutils.removeEscapes(irafutils.stripQuotes(value)) else: return str(value) # ----------------------------------------------------- # IRAF string parameter class # ----------------------------------------------------- class IrafParS(_StringMixin, IrafPar): """IRAF string parameter class""" pass # ----------------------------------------------------- # IRAF string array parameter class # ----------------------------------------------------- class IrafParAS(_StringMixin,IrafArrayPar): """IRAF string array parameter class""" pass # ----------------------------------------------------- # IRAF boolean parameter mixin class # ----------------------------------------------------- class _BooleanMixin: """IRAF boolean parameter mixin class""" #-------------------------------------------- # public methods #-------------------------------------------- def toString(self, value, quoted=0): if value in [None, INDEF]: return "" elif isinstance(value,str): # presumably an indirection value ')task.name' if quoted: return repr(value) else: return value else: # must be internal yes, no value return str(value) #-------------------------------------------- # private methods #-------------------------------------------- def _checkAttribs(self, strict): """Check initial attributes to make sure they are legal""" if self.min: warning("Minimum value not allowed for boolean-type parameter " + self.name, strict) self.min = None if self.max: if not self.prompt: warning("Maximum value not allowed for boolean-type parameter " + self.name + " (probably missing comma)", strict) # try to recover by assuming max string is prompt self.prompt = self.max else: warning("Maximum value not allowed for boolean-type parameter " + self.name, strict) self.max = None if self.choice: warning("Choice values not allowed for boolean-type parameter " + self.name, strict) self.choice = None # accepts special yes, no objects, integer values 0,1 or # string 'yes','no' and variants # internal value is yes, no, None/INDEF, or indirection string def _coerceOneValue(self,value,strict=0): if value == INDEF: return INDEF elif value is None or value == "": return None elif value in (1, 1.0, yes, "yes", "YES", "y", "Y", True): return yes elif value in (0, 0.0, no, "no", "NO", "n", "N", False): return no elif isinstance(value,str): v2 = irafutils.stripQuotes(value.strip()) if v2 == "" or v2 == "INDEF" or \ ((not strict) and (v2.upper() == "INDEF")): return INDEF elif v2[0:1] == ")": # assume this is indirection -- just save it as a string return v2 raise ValueError("Parameter %s: illegal boolean value %s or type %s" % (self.name, repr(value), str(type(value)))) # ----------------------------------------------------- # IRAF boolean parameter class # ----------------------------------------------------- class IrafParB(_BooleanMixin,IrafPar): """IRAF boolean parameter class""" pass # ----------------------------------------------------- # IRAF boolean array parameter class # ----------------------------------------------------- class IrafParAB(_BooleanMixin,IrafArrayPar): """IRAF boolean array parameter class""" pass # ----------------------------------------------------- # IRAF integer parameter mixin class # ----------------------------------------------------- class _IntMixin: """IRAF
<gh_stars>0 # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for model utils.""" import datetime from google.appengine.api import datastore_errors from google.appengine.ext import ndb from google.appengine.ext.ndb import polymodel from upvote.gae.datastore import utils from upvote.gae.shared.common import basetest class SingletonTest(basetest.UpvoteTestCase): def setUp(self): super(SingletonTest, self).setUp() def testGetAndSet(self): class A(utils.Singleton): a = ndb.StringProperty() self.assertIsNone(A.GetInstance()) inst = A.SetInstance(a='abcd') self.assertEqual('abcd', inst.a) inst = A.GetInstance() self.assertEqual('abcd', inst.a) self.assertEqual('A', A.GetInstance().key.id()) def testOverrideGetId(self): class A(utils.Singleton): a = ndb.StringProperty() @classmethod def _GetId(cls): return '1' inst = A.SetInstance(a='abcd') self.assertEqual('1', inst.key.id()) class CopyEntityTest(basetest.UpvoteTestCase): def setUp(self): super(CopyEntityTest, self).setUp() class A(ndb.Model): a = ndb.StringProperty() self.default_model = A def testUpdateProperties(self): inst = self.default_model(a='abc') inst.put() new = utils.CopyEntity(inst, a='xyz') new.put() self.assertEqual('abc', inst.a) self.assertEqual('xyz', new.a) self.assertNotEqual(new.key, inst.key) def testFailToSet_AutoNowProperty(self): class A(ndb.Model): a = ndb.DateTimeProperty(auto_now=True) inst = A() inst.put() with self.assertRaises(utils.PropertyError): utils.CopyEntity( inst, a=datetime.datetime.utcnow()) def testFailToSet_ComputedProperty(self): class A(ndb.Model): a = ndb.StringProperty() b = ndb.ComputedProperty(lambda self: self.a[0]) inst = A(a='xyz') inst.put() self.assertEqual('x', inst.b) with self.assertRaises(utils.PropertyError): utils.CopyEntity(inst, b='a') def testModelWithComputedProperty(self): class A(ndb.Model): a = ndb.StringProperty() b = ndb.ComputedProperty(lambda self: self.a[0]) inst = A(a='xyz') inst.put() self.assertEqual('x', inst.b) new = utils.CopyEntity(inst, a='abc') new.put() self.assertEqual('a', new.b) def testPolyModel(self): class A(utils.polymodel.PolyModel): a = ndb.StringProperty() class B(A): pass inst = B(a='abc') inst.put() new = utils.CopyEntity(inst, a='xyz') new.put() self.assertEqual('xyz', new.a) self.assertIsInstance(new, B) def testPolyModel_NoClass(self): class A(utils.polymodel.PolyModel): a = ndb.StringProperty() class B(A): pass inst = B(a='abc') a_copy = utils.CopyEntity(inst, a='xyz') a_copy.put() inst.put() self.assertEqual('xyz', a_copy.a) self.assertEqual('abc', inst.a) def testNewId(self): inst = self.default_model(a='abc') inst.put() new = utils.CopyEntity(inst, id='an_id') new.put() self.assertEqual('abc', new.a) self.assertEqual('an_id', new.key.id()) def testNewIdWithParent(self): inst = self.default_model(a='abc') inst.put() parent = ndb.Key('C', 'c', 'B', 'b') expected = ndb.Key('C', 'c', 'B', 'b', 'A', 'an_id') new = utils.CopyEntity( inst, new_parent=parent, id='an_id') new.put() self.assertEqual(expected, new.key) def testIdWithKey(self): inst = self.default_model(a='abc') inst.put() with self.assertRaises(datastore_errors.BadArgumentError): utils.CopyEntity( inst, new_key=ndb.Key('A', 'a_key'), id='an_id') def testParentWithKey(self): inst = self.default_model(a='abc') inst.put() parent = ndb.Key('C', 'c', 'B', 'b') with self.assertRaises(datastore_errors.BadArgumentError): utils.CopyEntity(inst, new_key=ndb.Key('A', 'a_key'), new_parent=parent) def testUnknownProperty(self): inst = self.default_model(a='abc') inst.put() with self.assertRaises(utils.PropertyError): utils.CopyEntity(inst, not_a_property='a') def testDeletedProperty(self): inst = self.default_model(a='abc') inst.put() class A(ndb.Model): # pylint: disable=unused-variable b = ndb.StringProperty() inst = inst.key.get(use_cache=False) copy = utils.CopyEntity(inst) self.assertFalse(hasattr(copy, 'a')) class DeletePropertyTest(basetest.UpvoteTestCase): def setUp(self): super(DeletePropertyTest, self).setUp() def testSameSchema(self): # Initial schema class A(ndb.Model): a = ndb.StringProperty() b = ndb.StringProperty() # Create an entity using the initial schema inst = A(a='abc', b='def') inst.put() self.assertIsNotNone(inst.b) # Delete the property and save the entity utils.DeleteProperty(inst, 'b') inst.put() inst = A.get_by_id(inst.key.id()) # The old data is gone :) self.assertIsNone(inst.b) def testSameSchema_DoesntDeleteProperty(self): # Initial schema class A(ndb.Model): a = ndb.StringProperty() b = ndb.StringProperty() # Create an entity using the initial schema inst = A(a='abc', b='def') inst.put() # Delete the property and save the entity utils.DeleteProperty(inst, 'b') inst.put() # Create a new instance and verify that the 'b' hasn't disappeared new = A(a='abc', b='def') new.put() self.assertTrue(utils.HasProperty(new, 'b')) def testSameSchema_RepeatedProperty(self): # Initial schema class A(ndb.Model): a = ndb.StringProperty() b = ndb.StringProperty(repeated=True) # Create an entity using the initial schema inst = A(a='abc', b=['def']) inst.put() self.assertIsNotNone(inst.b) # Delete the property and save the entity utils.DeleteProperty(inst, 'b') inst.put() inst = A.get_by_id(inst.key.id()) # The old data is...kinda gone :| self.assertEqual([], inst.b) def testChangeSchema(self): # Initial schema class A(ndb.Model): a = ndb.StringProperty() b = ndb.StringProperty() # Create an entity using the initial schema inst = A(a='abc', b='def') inst.put() # Revised schema class A(ndb.Model): # pylint: disable=function-redefined a = ndb.StringProperty() # Retrieve and save the old instance inst = A.get_by_id(inst.key.id()) inst.put() # The old data is still there :( self.assertIsNotNone(inst.b) # Delete the property and save the entity utils.DeleteProperty(inst, 'b') inst.put() inst = A.get_by_id(inst.key.id()) # The old data is gone :) self.assertIsNone(inst.b) def testChangeSchema_RequiredField(self): # Initial schema but this time with a required property class A(ndb.Model): a = ndb.StringProperty() b = ndb.StringProperty(required=True) # Create an entity using the initial schema inst = A(a='abc', b='def') inst.put() # Revised schema without the required property class A(ndb.Model): # pylint: disable=function-redefined a = ndb.StringProperty() # Retrieve and save the old instance inst = A.get_by_id(inst.key.id()) inst.put() # The old data is still there :( self.assertIsNotNone(inst.b) # Delete the property and save the entity utils.DeleteProperty(inst, 'b') inst.put() inst = A.get_by_id(inst.key.id()) # The old data is gone :) self.assertIsNone(inst.b) def testUnknownProperty(self): class A(ndb.Model): a = ndb.StringProperty() inst = A(a='abc') inst.put() utils.DeleteProperty(inst, 'b') inst.put() inst = A.get_by_id(inst.key.id()) self.assertIsNotNone(inst.a) def testChangeSchema_PolyModel(self): # Initial schema class Base(polymodel.PolyModel): a = ndb.StringProperty() b = ndb.StringProperty(required=True) class A(Base): pass # Create an entity using the initial schema inst = A(a='abc', b='def') inst.put() # Revised schema class Base(polymodel.PolyModel): # pylint: disable=function-redefined a = ndb.StringProperty() class A(Base): # pylint: disable=function-redefined pass # Retrieve and save the old instance inst = A.get_by_id(inst.key.id()) inst.put() # The old data is still there :( self.assertIsNotNone(inst.b) # Delete the property and save the entity utils.DeleteProperty(inst, 'b') inst.put() inst = A.get_by_id(inst.key.id()) # The old data is gone :) self.assertIsNone(inst.b) class DeletePropertyValueTest(basetest.UpvoteTestCase): def setUp(self): super(DeletePropertyValueTest, self).setUp() def testDeleteValue(self): # Initial schema class A(ndb.Model): a = ndb.StringProperty() b = ndb.StringProperty() # Create an entity using the initial schema inst = A(a='abc', b='def') inst.put() self.assertIsNotNone(inst.b) # Delete the property and save the entity utils.DeletePropertyValue(inst, 'b') inst.put() inst = A.get_by_id(inst.key.id()) # The old data is gone :) self.assertIsNone(inst.b) def testDatetimeAutoNowAdd(self): # Initial schema class A(ndb.Model): a = ndb.StringProperty() b = ndb.DateTimeProperty(auto_now_add=True) # Create an entity using the initial schema inst = A(a='abc') inst.put() # Delete the property and save the entity utils.DeletePropertyValue(inst, 'b') inst.put() self.assertTrue(utils.HasProperty(inst, 'b')) self.assertIsNotNone(inst.b) def testRepeatedProperty(self): # Initial schema class A(ndb.Model): a = ndb.StringProperty() b = ndb.StringProperty(repeated=True) # Create an entity using the initial schema inst = A(a='abc', b=['def']) inst.put() self.assertIsNotNone(inst.b) # Delete the property and save the entity utils.DeletePropertyValue(inst, 'b') inst.put() inst = A.get_by_id(inst.key.id()) # The old data is gone self.assertEqual([], inst.b) def testRequiredField(self): # Initial schema but this time with a required property class A(ndb.Model): a = ndb.StringProperty() b = ndb.StringProperty(required=True) # Create an entity using the initial schema inst = A(a='abc', b='def') inst.put() # Delete the property and save the entity utils.DeletePropertyValue(inst, 'b') # Property required but no longer has a value. with self.assertRaises(Exception): inst.put() def testUnknownProperty(self): class A(ndb.Model): a = ndb.StringProperty() inst = A(a='abc') inst.put() utils.DeletePropertyValue(inst, 'b') inst.put() inst = A.get_by_id(inst.key.id()) self.assertIsNotNone(inst.a) class GetLocalComputedPropertyValueTest(basetest.UpvoteTestCase): def setUp(self): super(GetLocalComputedPropertyValueTest, self).setUp() class A(ndb.Model): a = ndb.StringProperty() b = ndb.ComputedProperty(lambda self: self.a[0]) self.inst = A(a='xyz') def testNormal(self): self.assertIsNone(utils.GetLocalComputedPropertyValue(self.inst, 'b')) self.inst.put() self.assertEqual('x', utils.GetLocalComputedPropertyValue(self.inst, 'b')) self.inst.a = 'cdg' self.assertEqual('x', utils.GetLocalComputedPropertyValue(self.inst, 'b')) self.inst.put() self.assertEqual('c', utils.GetLocalComputedPropertyValue(self.inst, 'b')) def testUnknownProperty(self): with self.assertRaises(utils.PropertyError): utils.GetLocalComputedPropertyValue(self.inst, 'NotARealProperty') def testNotComputedProperty(self): with self.assertRaises(utils.PropertyError): utils.GetLocalComputedPropertyValue(self.inst, 'a') class FutureFactoryTest(basetest.UpvoteTestCase): def testInTxn(self): def AssertInTxn(): self.assertTrue(ndb.in_transaction()) def RunAssert(): fut = utils.GetNoOpFuture() fut.add_callback(AssertInTxn) fut.add_immediate_callback(AssertInTxn) fut.get_result() ndb.transaction(RunAssert) class GetMultiFutureTest(basetest.UpvoteTestCase): def testNoInput(self): mf = utils.GetMultiFuture([]) self.assertTrue(mf.done()) def testSingleFuture(self): f = ndb.Future() mf = utils.GetMultiFuture([f]) self.assertFalse(f.done()) self.assertFalse(mf.done()) f.set_result(None) self.assertTrue(f.done()) self.assertFalse(mf.done()) # Event loop must run for the MultiFuture to be marked as done. mf.wait() self.assertTrue(mf.done()) def testManyFutures(self): futures = [ndb.Future() for _ in xrange(3)] mf = utils.GetMultiFuture(futures) self.assertFalse(any(f.done() for f in futures)) self.assertFalse(mf.done()) for f in futures: f.set_result(None) self.assertTrue(all(f.done() for f in futures)) self.assertFalse(mf.done()) # Event loop must run for the MultiFuture to be marked as done. mf.wait() self.assertTrue(mf.done()) def testCantModifyResult(self): f = ndb.Future() mf = utils.GetMultiFuture([f]) with self.assertRaises(RuntimeError): mf.add_dependent(ndb.Future()) class GetChainingMultiFutureTest(basetest.UpvoteTestCase): def testNoInput(self): mf = utils.GetChainingMultiFuture([]) self.assertTrue(mf.done()) def testSingleFuture(self): f = ndb.Future() mf = utils.GetChainingMultiFuture([f]) self.assertFalse(f.done()) self.assertFalse(mf.done()) f.set_result([]) self.assertTrue(f.done()) self.assertFalse(mf.done()) # Event loop must run for the MultiFuture to be marked as done. mf.wait() self.assertTrue(mf.done()) self.assertEqual([], mf.get_result()) def testManyFutures(self): futures = [ndb.Future() for _ in xrange(3)] mf = utils.GetChainingMultiFuture(futures) self.assertFalse(any(f.done() for f in futures)) self.assertFalse(mf.done()) for i, f in enumerate(futures): f.set_result([i]) self.assertTrue(all(f.done() for f in futures)) self.assertFalse(mf.done()) # Event loop must run for the MultiFuture to be marked as done. mf.wait() self.assertTrue(mf.done()) self.assertEqual([0, 1, 2],
log-likelihoods in harmonic mean calculation' % nignored) self.output('Log of marginal likelihood (harmonic mean method) = %f' % log_harmonic_mean) return log_harmonic_mean def summary_stats(self, v, cutoff=95): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ Computes the following summary statistics for the supplied vector v: first-order autocorrelation (lag=1), effective sample size, lower credible interval bound, upper credible interval bound, minimum, maximum, sample mean, and sample standard deviation (i.e. divide by n-1). The value of cutoff is the percentage to use for the credible interval. If v is None, returns tuple of header strings. If v is not None, returns tuple of summary statistics. """ if v is None: h = ('autocorr', 'ess', 'lower %d%%' % int(cutoff), 'upper %d%%' % int(cutoff), 'min', 'max', 'mean', 'stddev') return h if len(v) < 2: raise VarianceUndefinedError() s = [] # compute autocorr and ess try: r,ess = self.autocorr_ess(v) except VarianceZeroError: raise VarianceZeroError() else: s.extend((r,ess)) # compute lower and upper v.sort() n = float(len(v)) p = float(cutoff)/100.0 lower_at = int(math.ceil(n*(1 - p))) upper_at = int(math.ceil(n*p)) lower = v[lower_at] upper = v[upper_at] s.extend((lower, upper)) # compute min and max s.extend((v[0], v[-1])) # compute mean and stddev mean = sum(v)/n ss = sum([x**2 for x in v]) var = (ss - n*mean**2)/(n - 1.0) sd = math.sqrt(var) s.extend((mean, sd)) return tuple(s) def std_summary(self, headers, lines, skip): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ Produces a table of summary statistics for each parameter using the data in a param file. This is the companion to marginal_likelihood for the standard mcmc case. The supplied list headers holds the column headers from the param file. The parameter names are taken from this. The supplied lines is a list of lines from the param file. The supplied skip indicates the number of initial lines to ignore (usually will be 1 because the starting values of all parameters is always output and should always be skipped). See documentation for the summary_stats function for a list of summary statistics computed. """ # Create params dictionary such that, for example, params['lnL'] is a list of # all log-likelihood values (in the order in which they were sampled) params = {} for h in headers: params[h] = [] row_start = 2 + skip # first line ID, second line headers for i,line in enumerate(lines[row_start:]): parts = line.split() if len(parts) != len(headers): raise InvalidNumberOfColumnsError(len(parts), len(headers), i + row_start + 1) for h,x in zip(headers,parts): params[h].append(float(x)) # Output summary statistics for each parameter (and the log-likelihood) self.output('\nSummary statistics:\n') stats_headers = ('param','n') + self.summary_stats(None) sz = len(stats_headers) gss = '%20s' + '%15s'*(sz-1) + '\n' self.output(gss % stats_headers) for h in headers[1:]: # skip 'Gen' header v = params[h] try: stats = (h,len(v)) + self.summary_stats(v) gss = '%20s' + '%15d' + '%15.5f'*(sz - 2) self.output(gss % stats) except (VarianceZeroError,VarianceUndefinedError): gss = '%20s' + '%15s'*(sz-1) sub = tuple([h] + ['---']*(sz-1)) self.output(gss % sub) marglike = None self.output() marglike = self.harmonic_mean(params['lnL']) return marglike def calcLogHM(self, vect_of_log_values): logn = math.log(float(len(vect_of_log_values))) logLmin = min(vect_of_log_values) sum_log_diffs = 0.0 for logx in vect_of_log_values: sum_log_diffs += math.exp(logLmin - logx) loghm = logn + logLmin - math.log(sum_log_diffs) return loghm def _cpoOpenRFile(self): if self._cpoRFile is None: sp = self.optsout.cpoplot self._cpoRFilename = sp._getFilename() self._cpoRFile = sp.open(self.stdout) return self._cpoRFile def _cpoOpenInfoFile(self): if self._cpoInfoFile is None: sp = self.optsout.cpoinfo self._cpoInfoFilename = sp._getFilename() self._cpoInfoFile = sp.open(self.stdout) return self._cpoInfoFile def cpo_summary(self, lines, skip): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ Produces an R file containing commands for producing a plot of CPO (Conditional Predictive Ordinates). This plot has site position as the x-coordinate and site CPO as the y-coordinate. The title of the plot contains the summary measure (sum of CPO over all sites). """ self.output('\nCPO analysis') # Each line in lines comprises nsites log-site-likelihood values (one sample from the chain) nsites = len(lines[0].split()) # Create nsites lists, each of which holds all log-site-likelihood values sampled from one site loglikes = [[] for i in range(nsites)] for line in lines[skip:]: parts = line.split() assert len(parts) == nsites for i,logx in enumerate(parts): loglikes[i].append(float(logx)) # Create the default partition if none has been defined partition.validate(nsites) # Compute the log-CPO measure for each site, and the sum over all sites # Sites that have been excluded will have lognm = 0.0 and thus will not # contribute to total_cpo cpovect = [0.0]*nsites # This vector has sites grouped by partition subset! cpomap = {} # key is site index, value is log(cpo) total_cpo = 0.0 k = 0 subset_names = [] # list of subset names subset_sitelists = [] # list of subset sitelists for subset_index,(subset_name,subset_sitelist,subset_model) in enumerate(partition.subset): subset_names.append(subset_name) subset_sitelists.append(subset_sitelist) print 'CPO: processing subset = %s...' % subset_name for i in subset_sitelist: loghm = self.calcLogHM(loglikes[i-1]) total_cpo += loghm cpovect[k] = loghm cpomap[i] = loghm k += 1 self.output('LPML (Log PseudoMarginal Likelihood) = %.5f' % total_cpo) # Identify the worst sites in terms of CPO, placing these in cpo_worst # The list cpo_worst lists sites by partition subset, not in original order cpo_worst = [] for i in range(nsites): if cpovect[i] < 0.0: cpo_worst.append((i,cpovect[i])) cpo_worst.sort(cmp=lambda x,y: cmp(x[1], y[1])) nincluded = len(cpo_worst) last_of_worst = int(math.ceil(self.opts.cpo_cutoff*nincluded)) cpo_worst[last_of_worst:] = [] # Identify the worst sites again, placing these in the list cpo_worst_orig # The list cpo_worst_orig lists sites in their original order, not by partition subset # Sites with cpo higher than best_of_the_worst will have value None best_of_the_worst = cpo_worst[-1][1] cpo_worst_orig = [None]*nsites for i in cpomap.keys(): if cpomap[i] <= best_of_the_worst: cpo_worst_orig[i-1] = cpomap[i] # Create a mask showing which sites are in the worst category # This mask string can be aligned to the original data matrix making it easy to identify the worst sites mask = ['-']*nsites for i,v in enumerate(cpo_worst_orig): if v is not None: mask[i] = '*' maskstr = ''.join(mask) # Create R and info files. The R file will produce a plot (using R) that plots log CPO values as impulses # and sorted by partition subset (with sites in the worst CPO category colored red). The info file is # tab-delimited and designed to contain the same information in way that could be easily read and processed # for other programs/uses self._cpoRFilename = None self._cpoRFile = None self._cpoInfoFilename = None self._cpoInfoFile = None nsubsets = len(subset_names) if bool(self.optsout.cpoplot): try: # Create CPO info file self._cpoOpenInfoFile() # Write mask self._cpoInfoFile.write('Mask showing worst (lowest %.1f%% CPO values) sites as *\n' % (100.0*self.opts.cpo_cutoff,)) self._cpoInfoFile.write(' (order of sites is that of the original data matrix)\n') self._cpoInfoFile.write('BEGIN_MASK\n') self._cpoInfoFile.write(' %s\n' % maskstr) self._cpoInfoFile.write('END_MASK\n') subset_logCPOs = [] for i in range(nsubsets): subset_logCPOs.append([]) tally = [0]*nsubsets # Write table of log(CPO) values self._cpoInfoFile.write('\nBEGIN_LOG_CPO_TABLE\n') self._cpoInfoFile.write('%12s\t%12s\t%12s\t%12s\n' % ('site', 'log(CPO)', 'subset', 'worst')) for site_index in range(nsites): site_number = site_index+1 inworst = 0 if cpo_worst_orig[site_index] is not None: inworst = 1 which_subset = None for subset_index in range(nsubsets): if site_number in subset_sitelists[subset_index]: which_subset = subset_names[subset_index] subset_logCPOs[subset_index].append(cpomap[site_number]) tally[subset_index] += inworst break self.phycassert(which_subset is not None, "Failed to determine the partition subset to which site number %d belongs" % (site_number)) self._cpoInfoFile.write('%12d\t%12.5f\t%12s\t%12d\n' % (site_number,cpomap[site_number], which_subset, inworst)) self._cpoInfoFile.write('END_LOG_CPO_TABLE\n') # Write subset summary self._cpoInfoFile.write('\nBEGIN_SUBSET_SUMMARY\n') self._cpoInfoFile.write('%12s\t%12s\t%12s\t%12s\t%12s\n' % ('subset', 'nsites', 'nworst', 'mean log(CPO)', 'log(mean CPO)')) for i in range(nsubsets): n = len(subset_logCPOs[i]) mean_log = sum(subset_logCPOs[i])/n max_logCPO = max(subset_logCPOs[i]) sum_diffs = sum([math.exp(logCPO - max_logCPO) for logCPO in subset_logCPOs[i]]) log_mean = max_logCPO + math.log(sum_diffs) - math.log(n) self._cpoInfoFile.write('%12s\t%12d\t%12d\t%12.5f\t%12.5f\n' % (subset_names[i], n, tally[i], mean_log, log_mean)) self._cpoInfoFile.write('END_SUBSET_SUMMARY\n') self._cpoInfoFile.close() #numWorst = len(cpo_worst) #meanLogCPOWorst = 0.0 #for i in range(numWorst): # meanLogCPOWorst += cpo_worst[i][1] #meanLogCPOWorst /= numWorst #print 'Number of worst sites:',numWorst #print 'Mean of log(CPO) of worst sites:',meanLogCPOWorst # Create CPO R plot file self._cpoOpenRFile() self._cpoRFile.write('# Plot log(CPO) for each site (sites grouped by partition subset)\n') self._cpoRFile.write('x = c(%s)\n' % ','.join(['%d' % x for x in range(nsites)])) self._cpoRFile.write('y = c(%s)\n' % ','.join(['%g' % y for y in cpovect])) self._cpoRFile.write('colvec = rep("black",%d)\n' % nsites) self._cpoRFile.write('z = c(%s)\n' % ','.join(['%d' % (zz[0]+1) for zz in cpo_worst])) self._cpoRFile.write('colvec[z] = "red"\n') self._cpoRFile.write("plot(x, y, type='h', col=colvec, main='Overall CPO = %.5f', xlab='Site', ylab =
<filename>run/run_interventions.py #! import jax.numpy as np from jax import jit, random, vmap from jax.ops import index_add, index_update, index import matplotlib.pyplot as plt import functools import itertools from scipy import optimize from scipy.special import gamma from tqdm import tqdm import numpy as np2 import pandas as pd import pickle import os from models import model config_data = pd.read_csv('configlin.csv', sep=',', header=None, index_col=0) figures_path = config_data.loc['figures_dir'][1] results_path = config_data.loc['results_dir'][1] ages_data_path = config_data.loc['bogota_age_data_dir'][1] houses_data_path = config_data.loc['bogota_houses_data_dir'][1] #from networks import networks from networks import create_networks import argparse parser = argparse.ArgumentParser(description='Simulating interventions') parser.add_argument('--population', default=1000, type=int, help='Speficy the number of individials') parser.add_argument('--intervention', default=0.6, type=float, help='Intervention efficiancy') parser.add_argument('--work_occupation', default=0.6, type=float, help='Percentage of occupation at workplaces over intervention') parser.add_argument('--school_occupation', default=0.35, type=float, help='Percentage of occupation at classrooms over intervention') parser.add_argument('--school_openings', default=20, type=int, help='Day of the simulation where schools are open') parser.add_argument('--school_alternancy', default=False, type=bool, help='Percentage of occupation at classrooms over intervention') parser.add_argument('--Tmax', default=180, type=int, help='Length of simulation (days)') parser.add_argument('--delta_t', default=0.08, type=float, help='Time steps') parser.add_argument('--number_trials', default=10, type=int, help='Number of iterations per step') parser.add_argument('--schools_mean', default=9.4, type=float, help='Schools degree distribution (mean)') parser.add_argument('--schools_std', default=1.8, type=float, help='Schools degree distribution (standard deviation)') parser.add_argument('--schools_size', default=35, type=float, help='Number of students per classroom') parser.add_argument('--schools_r', default=1, type=float, help='Correlation in schools layer') parser.add_argument('--work_mean', default=14.4/3, type=float, help='Work degree distribution (mean)') parser.add_argument('--work_std', default=6.2/3, type=float, help='Work degree distribution (standard deviation)') parser.add_argument('--work_size', default=10, type=float, help='Approximation of a work place size') parser.add_argument('--work_r', default=1, type=float, help='Correlation in work layer') parser.add_argument('--community_mean', default=4.3/2, type=float, help='Community degree distribution (mean)') parser.add_argument('--community_std', default=1.9/2, type=float, help='Community degree distribution (standard deviation)') parser.add_argument('--community_n', default=1, type=float, help='Number of community') parser.add_argument('--community_r', default=0, type=float, help='Correlation in community layer') parser.add_argument('--R0', default=3, type=float, help='Fixed basic reproduction number') parser.add_argument('--MILDINF_DURATION', default=6, type=int, help='Duration of mild infection, days') args = parser.parse_args() number_nodes = args.population pop = number_nodes ## Parameters # Model parameter values # Means IncubPeriod=5 #Incubation period, days DurMildInf=6 #Duration of mild infections, days DurSevereInf=6 #Duration of hospitalization (severe infection), days DurCritInf=8 #Time from ICU admission to death/recovery (critical infection), days # Standard deviations std_IncubPeriod=4 #Incubation period, days std_DurMildInf=2 #Duration of mild infections, days std_DurSevereInf=4.5 #Duration of hospitalization (severe infection), days std_DurCritInf=6 #Time from ICU admission to death/recovery (critical infection), days FracSevere=0.15 #Fraction of infections that are severe FracCritical=0.05 #Fraction of infections that are critical CFR=0.02 #Case fatality rate (fraction of infections resulting in death) FracMild=1-FracSevere-FracCritical #Fraction of infections that are mild # Get gamma distribution parameters mean_vec = np.array( [1., IncubPeriod, DurMildInf, DurSevereInf, DurCritInf, 1., 1.]) std_vec=np.array( [1., std_IncubPeriod, std_DurMildInf, std_DurSevereInf, std_DurCritInf, 1., 1.]) shape_vec=(mean_vec/std_vec)**2# This will contain shape values for each state scale_vec=(std_vec**2)/mean_vec # This will contain scale values for each state # Define transition probabilities # Define probability of recovering (as opposed to progressing or dying) from each state recovery_probabilities = np.array([0., 0., FracMild, FracSevere / (FracSevere + FracCritical), 1. - CFR / FracCritical, 0., 0.]) # Define relative infectivity of each state infection_probabilities = np.array([0., 0., 1.0, 0., 0., 0., 0.]) def discrete_gamma(key, alpha, beta, shape=()): shape_ = shape if shape_ == (): try: shape_ = alpha.shape except: shape_ = () return _discrete_gamma(key, alpha, beta, shape_) @functools.partial(jit, static_argnums=(3,)) def _discrete_gamma(key, alpha, beta, shape=()): samples = np.round(random.gamma(key, alpha, shape=shape) / beta) return samples.astype(np.int32) @jit def state_length_sampler(key, new_state): """Duration in transitional state. Must be at least 1 time unit.""" alphas = shape_vec[new_state] betas = delta_t/scale_vec[new_state] key, subkey = random.split(key) lengths = 1 + discrete_gamma(subkey, alphas, betas) # Time must be at least 1. return key, lengths * model.is_transitional(new_state) # Makes sure non-transitional states are returning 0. ### Get age distribution ages_data_BOG = pd.read_csv(ages_data_path, encoding= 'unicode_escape', delimiter=';') total_pop_BOG = int(ages_data_BOG['Total.3'][17].replace('.','')) # Ages 0-4 very_young_ = [int(ages_data_BOG['Total.3'][0].replace('.',''))] very_young = sum(very_young_)/total_pop_BOG # Ages 5-19 school_ = [int(ages_data_BOG['Total.3'][i].replace('.','')) for i in range(1,3+1)] school = sum(school_)/total_pop_BOG # Ages 19-24 university_ = int(ages_data_BOG['Total.3'][4].replace('.','')) university = int(ages_data_BOG['Total.3'][4].replace('.',''))/total_pop_BOG # Ages 24-64 work_ = [int(ages_data_BOG['Total.3'][i].replace('.','')) for i in range(5,12+1)] work = sum(work_)/total_pop_BOG # Ages 65+ elderly_ = [int(ages_data_BOG['Total.3'][i].replace('.','')) for i in range(13,16+1)] elderly = sum(elderly_)/total_pop_BOG # Community ages community_ = very_young_ + school_ + [university_] + work_ + elderly_ community = sum(community_)/total_pop_BOG ### Get household size distribution from 2018 census data census_data_BOG = pd.read_csv(houses_data_path) one_house = np2.sum(census_data_BOG['HA_TOT_PER'] == 1.0) two_house = np2.sum(census_data_BOG['HA_TOT_PER'] == 2.0) three_house = np2.sum(census_data_BOG['HA_TOT_PER'] == 3.0) four_house = np2.sum(census_data_BOG['HA_TOT_PER'] == 4.0) five_house = np2.sum(census_data_BOG['HA_TOT_PER'] == 5.0) six_house = np2.sum(census_data_BOG['HA_TOT_PER'] == 6.0) seven_house = np2.sum(census_data_BOG['HA_TOT_PER'] == 7.0) total_house = one_house + two_house + three_house + four_house + five_house + six_house + seven_house house_size_dist = np2.array([one_house,two_house,three_house,four_house,five_house,six_house,seven_house])/total_house # House-hold sizes household_sizes = [] household_sizes.extend(np2.random.choice(np.arange(1,8,1),p=house_size_dist,size=int(pop/3))) # This division is just to make the code faster pop_house = sum(household_sizes) while pop_house <= pop: size = np2.random.choice(np.arange(1,8,1),p=house_size_dist,size=1) household_sizes.extend(size) pop_house += size[0] household_sizes[-1] -= pop_house-pop # Mean of household degree dist mean_household = sum((np2.asarray(household_sizes)-1)*np2.asarray(household_sizes))/pop # Keeping track of the household indx for each individual house_indices = np2.repeat(np2.arange(0,len(household_sizes),1), household_sizes) # Keeping track of the household size for each individual track_house_size = np2.repeat(household_sizes, household_sizes) # Keep track of the 5 yr age groups for each individual labelled from 0-16 age_tracker_all = np2.zeros(pop) ####### Community # Degree dist. mean and std div obtained by Prem et al data, scaled by 1/2.5 in order to ensure that community+friends+school = community data in Prem et al mean, std = args.community_mean, args.community_std p = 1-(std**2/mean) n_binom = mean/p community_degree = np2.random.binomial(n_binom, p, size = pop) # No correlation between contacts n_community = args.community_n r_community = args.community_r # Split the age group of old population according to the population seen in the data prob = [] for i in range(0,len(community_)): prob.append(community_[i]/sum(community_)) age_group_community = np2.random.choice(np2.arange(0,len(community_),1),size=pop,p=prob,replace=True) community_indx = np2.arange(0,pop,1) for i in range(pop): age_tracker_all[community_indx[i]] = age_group_community[i] ############################### ##### Degree distribution ##### # Frac of population that is school going, working, preschool or elderly dist_of_pop = [school,work,very_young+university+elderly] # Classifying each person classify_pop = np2.random.choice(['schools','work','other'], size=pop, p=dist_of_pop) # Number of individuals in each group state, counts = np2.unique(classify_pop, return_counts=True) dict_of_counts = dict(zip(state,counts)) school_going = dict_of_counts['schools'] working = dict_of_counts['work'] other = dict_of_counts['other'] # Indices of individuals in each group school_indx = np2.where(classify_pop=='schools')[0] work_indx = np2.where(classify_pop=='work')[0] other_indx = np2.where(classify_pop=='other')[0] age_tracker = np2.zeros(pop) ####### schools mean, std = args.schools_mean, args.schools_std p = 1-(std**2/mean) n_binom = mean/p schools_degree = np2.random.binomial(n_binom, p, size = school_going) n_school = school_going/args.schools_size r_school = args.schools_r school_clroom = np2.random.choice(np.arange(0,n_school+1,1),size=school_going) # Assign ages to the school going population acc. to their proportion from the census data prob = [] for i in range(0,len(school_)): prob.append(school_[i]/sum(school_)) age_group_school = np2.random.choice([1,2,3],size=school_going,p=prob,replace=True) for i in range(school_going): age_tracker[school_indx[i]] = age_group_school[i] ####### Work # Degree dist., the mean and std div have been taken from the Potter et al data. The factor of 1/3 is used to correspond to daily values and is chosen to match with the work contact survey data mean, std = args.work_mean, args.work_std p = 1-(std**2/mean) n_binom = mean/p work_degree = np2.random.binomial(n_binom, p, size = working) # Assuming that on average the size of a work place is ~ 10 people and the correlation is # chosen such that the clustering coeff is high as the network in Potter et al had a pretty high value work_place_size = args.work_size n_work = working/work_place_size r_work = args.work_r # Assign each working individual a 'work place' job_place = np2.random.choice(np.arange(0,n_work+1,1),size=working) # Split the age group of working population according to the population seen in the data p = [] for i in range(0,len(work_)): p.append(work_[i]/sum(work_)) age_group_work = np2.random.choice(np.arange(0,len(work_),1),size=working,p=p,replace=True) for i in range(working): age_tracker[work_indx[i]] = age_group_work[i] print('Creating graphs...') ## Households matrix_household = create_networks.create_fully_connected(household_sizes,np2.arange(0,pop,1),args.R0,args.MILDINF_DURATION,args.delta_t) # Get row, col, data information from the sparse matrices # Converting into DeviceArrays to run faster with jax. Not sure why the lists have to be first converted to usual numpy arrays though matrix_household_row = np.asarray(np2.asarray(matrix_household[0])) matrix_household_col = np.asarray(np2.asarray(matrix_household[1])) matrix_household_data = np.asarray(np2.asarray(matrix_household[2])) ## School matrix_school = create_networks.create_external_corr(pop,school_going,schools_degree,n_school,r_school,school_indx,school_clroom,args.R0,args.MILDINF_DURATION,args.delta_t) matrix_school_row = np.asarray(np2.asarray(matrix_school[0])) matrix_school_col = np.asarray(np2.asarray(matrix_school[1])) matrix_school_data = np.asarray(np2.asarray(matrix_school[2])) ## Work matrix_work = create_networks.create_external_corr(pop,working,work_degree,n_work,r_work,work_indx,job_place,args.R0,args.MILDINF_DURATION,args.delta_t) matrix_work_row = np.asarray(np2.asarray(matrix_work[0])) matrix_work_col = np.asarray(np2.asarray(matrix_work[1])) matrix_work_data = np.asarray(np2.asarray(matrix_work[2])) ## Community matrix_community = create_networks.create_external_corr(pop,pop,community_degree,n_community,r_community,np2.arange(0,pop,1),age_group_community,args.R0,args.MILDINF_DURATION,args.delta_t) matrix_community_row = np.asarray(np2.asarray(matrix_community[0])) matrix_community_col = np.asarray(np2.asarray(matrix_community[1])) matrix_community_data = np.asarray(np2.asarray(matrix_community[2])) # Save graphs matrix multilayer_matrix = [matrix_household,matrix_school,matrix_work,matrix_community] # Time paramas Tmax = args.Tmax days_intervals = [1] * Tmax delta_t = args.delta_t step_intervals = [int(x/delta_t) for x in days_intervals] total_steps = sum(step_intervals) # Create dynamic import networks.network_dynamics as nd print('Creating dynamics...') if args.school_alternancy: time_intervals, ws = nd.create_day_intervention_altern_schools_dynamics(multilayer_matrix,Tmax=Tmax,total_steps=total_steps,schools_day_open=args.school_openings, interv_glob=args.intervention,schl_occupation=args.school_occupation,work_occupation=args.work_occupation) else: time_intervals, ws = nd.create_day_intervention_dynamics(multilayer_matrix,Tmax=Tmax,total_steps=total_steps,schools_day_open=args.school_openings, interv_glob=args.intervention,schl_occupation=args.school_occupation,work_occupation=args.work_occupation) # Bogota data cum_cases = 632532 cum_rec = 593329 mild_house = 17595 hosp_beds = 5369 ICU_beds = 1351 deaths = 13125 BOG_E = int( pop * (cum_cases-cum_rec-mild_house-deaths)/total_pop_BOG) BOG_R = int( pop * 0.3 ) # Assuming that 30% of population is already recovered BOG_I1 = int( pop * mild_house/total_pop_BOG ) BOG_I2 = int( pop * hosp_beds/total_pop_BOG ) BOG_I3 = int( pop * ICU_beds/total_pop_BOG ) BOG_D = int( pop * deaths/total_pop_BOG ) ####################### RUN print('Simulating...') soln=np.zeros((args.number_trials,total_steps,7)) soln_cum=np.zeros((args.number_trials,total_steps,7)) for key in tqdm(range(args.number_trials), total=args.number_trials): #Initial condition init_ind_E = random.uniform(random.PRNGKey(key), shape=(BOG_E,), maxval=pop).astype(np.int32) init_ind_I1 = random.uniform(random.PRNGKey(key), shape=(BOG_I1,), maxval=pop).astype(np.int32) init_ind_I2 = random.uniform(random.PRNGKey(key), shape=(BOG_I2,), maxval=pop).astype(np.int32) init_ind_I3 = random.uniform(random.PRNGKey(key), shape=(BOG_I3,), maxval=pop).astype(np.int32) init_ind_D = random.uniform(random.PRNGKey(key), shape=(BOG_D,), maxval=pop).astype(np.int32) init_ind_R = random.uniform(random.PRNGKey(key), shape=(BOG_R,), maxval=pop).astype(np.int32) init_state = np.zeros(pop, dtype=np.int32) init_state = index_update(init_state,init_ind_E,np.ones(BOG_E, dtype=np.int32)*1) # E init_state = index_update(init_state,init_ind_I1,np.ones(BOG_I1, dtype=np.int32)*2) # I1 init_state = index_update(init_state,init_ind_I2,np.ones(BOG_I2, dtype=np.int32)*3) # I2 init_state = index_update(init_state,init_ind_I3,np.ones(BOG_I3, dtype=np.int32)*4) # I3 init_state = index_update(init_state,init_ind_D,np.ones(BOG_D, dtype=np.int32)*5) # D init_state = index_update(init_state,init_ind_R,np.ones(BOG_R, dtype=np.int32)*6) # R _, init_state_timer = state_length_sampler(random.PRNGKey(key), init_state) #Run simulation _, state, _, _, total_history = model.simulate_intervals( ws, time_intervals, state_length_sampler, infection_probabilities, recovery_probabilities, init_state, init_state_timer, key = random.PRNGKey(key), epoch_len=1) history = np.array(total_history)[:, 0, :] # This unpacks current state
have to give up raise Exception('Not enough neighboring targets were ' 'found. under_fitting_metric failed') # Too few found, increase search radius dynamic_search_radius *= 1.5 else: continue_searching = False return metric def _correct_initialization(self, cbv_type='SingleScale', cbv_indices='ALL', ext_dm=None): """ Performs all the preparatory work needed before applying a 'correct' method. This helper function is used so that multiple correct methods can be used without the need to repeat preparatory code. The main thing this method does is set up the design matrix, given the requested CBVs and external design matrix. Parameters ---------- cbv_type : str list List of CBV types to use Can be None if only ext_dm is used cbv_indices : list of lists List of CBV vectors to use in each passed cbv_type. {'ALL' => Use all} Can be None if only ext_dm is used ext_dm : `.DesignMatrix` or `.DesignMatrixCollection` Optionally pass an extra design matrix to additionally be used in the fit """ assert not ((cbv_type is None) ^ (cbv_indices is None)), \ 'Both cbv_type and cbv_indices must be None, or neither' if (cbv_type is None and cbv_indices is None): use_cbvs = False else: use_cbvs = True # If any DesignMatrix was passed then store it self.extra_design_matrix = ext_dm # Check that extra design matrix is aligned with lc flux if ext_dm is not None: assert isinstance(ext_dm, DesignMatrix), \ 'ext_dm must be a DesignMatrix' if (ext_dm.df.shape[0] != len(self.lc.flux)): raise ValueError( 'ext_dm must contain the same number of cadences as lc.flux') # Create a CBV design matrix for each CBV set requested self.cbv_design_matrix = [] if use_cbvs: assert (not isinstance(cbv_type, str) and not isinstance(cbv_indices[0], int)), \ 'cbv_type and cbv_indices must be lists of strings' if (self.lc.mission in ['Kepler', 'K2']): assert len(cbv_type) == 1 , \ 'cbv_type must be only Single-Scale for Kepler and K2 missions' assert cbv_type == ['SingleScale'], \ 'cbv_type must be Single-Scale for Kepler and K2 missions' if (isinstance(cbv_type, list) and len(cbv_type) != 1): assert (self.lc.mission == 'TESS'), \ 'Multiple CBV types are only allowed for TESS' assert (len(cbv_type) == len(cbv_indices)), \ 'cbv_type and cbv_indices must be the same list length' # Loop through all the stored CBVs and find the ones matching the # requested cbv_type list for idx in np.arange(len(cbv_type)): for cbvs in self.cbvs: # Temporarily copy the cbv_indices requested cbv_idx_loop = cbv_indices[idx] # If requesting 'ALL' CBVs then set to max default number # Remember, cbv indices is 1-based! if (isinstance(cbv_idx_loop, str) and (cbv_idx_loop == 'ALL')): cbv_idx_loop = cbvs.cbv_indices # Trim to nCBVs in cbvs cbv_idx_loop = np.array([idx for idx in cbv_idx_loop if bool(np.in1d(idx, cbvs.cbv_indices))]) if cbv_type[idx].find('MultiScale') >= 0: # Find the correct band if this is a multi-scale CBV set band = int(cbv_type[idx][-1]) if (cbvs.cbv_type in cbv_type[idx] and cbvs.band == band): self.cbv_design_matrix.append(cbvs.to_designmatrix( cbv_indices=cbv_idx_loop, name=cbv_type[idx])) else: if (cbvs.cbv_type in cbv_type[idx]): self.cbv_design_matrix.append(cbvs.to_designmatrix( cbv_indices=cbv_idx_loop, name=cbv_type[idx])) #*** # Create the design matrix collection with CBVs, plus extra passed basis vectors # Create the full design matrix collection from all the sub-design # matrices (I.e 'flatten' the design matrix collection) if self.extra_design_matrix is not None and \ self.cbv_design_matrix != []: # Combine cbv_design_matrix and extra_design_matrix dm_to_flatten = [[cbv_dm for cbv_dm in self.cbv_design_matrix], [self.extra_design_matrix]] flattened_dm_list = [item for sublist in dm_to_flatten for item in sublist] elif self.cbv_design_matrix != []: # Just use cbv_design_matrix dm_to_flatten = [[cbv_dm for cbv_dm in self.cbv_design_matrix]] flattened_dm_list = [item for sublist in dm_to_flatten for item in sublist] else: # Just use extra_design_matrix flattened_dm_list = [self.extra_design_matrix] # Add in a constant to the design matrix collection # Note: correct_elasticnet ASSUMES the the last vector in the # design_matrix_collection is the constant flattened_dm_list.append(DesignMatrix(np.ones(flattened_dm_list[0].shape[0]), columns=['Constant'], name='Constant')) self.design_matrix_collection = DesignMatrixCollection(flattened_dm_list) self.design_matrix_collection.validate() def _set_prior_width(self, sigma): """ Sets the Gaussian prior in the design_matrix_collection widths to sigma Parameters ---------- sigma : scalar float all widths are set to the same value If sigma = None then uniform sigma is set """ if (isinstance(sigma, list)): raise Exception("Seperate widths is not yet implemented") for dm in self.design_matrix_collection: nCBVs = len(dm.prior_sigma) if sigma is None: dm.prior_sigma = np.ones(nCBVs) * np.inf else: dm.prior_sigma = np.ones(nCBVs) * sigma def _goodness_metric_obj_fun(self, alpha): """ The objective function to minimize with scipy.optimize.minimize_scalar First sets the alpha regularization penalty then runs RegressionCorrector.correct and then computes the over- and under-fitting goodness metrics to return a scalar penalty term to minimize. Uses the paramaters in self.optimization_params. Parameters (in self.optimization_params) ---------- alpha : float regularization penalty term value to set cadence_mask : np.ndarray of bools (optional) Mask, where True indicates a cadence that should be used. target_over_score : float Target Over-fitting metric score If <=0 then ignore over-fitting metric target_under_score : float Target under-fitting metric score If <=0 then ignore under-fitting metric Returns ------- penalty : float Penalty term for minimizer, based on goodness metrics """ # Add in a width to the Gaussian priors # alpha = flux_sigma^2 / sigma^2 sigma = np.median(self.lc.flux_err.value) / np.sqrt(np.abs(alpha)) self._set_prior_width(sigma) # Use RegressionCorrector.correct for the actual fitting self.correct_regressioncorrector(self.design_matrix_collection, cadence_mask=self.optimization_params['cadence_mask']) # Do not compute and ignore if target score < 0 if (self.optimization_params['target_over_score'] > 0): overMetric = self.over_fitting_metric( n_samples=self.optimization_params['over_metric_nSamples']) else: overMetric = 1.0 # Do not compute and ignore if target score < 0 if (self.optimization_params['target_under_score'] > 0): underMetric = self.under_fitting_metric() else: underMetric = 1.0 # Once we hit the target we want to ease-back on increasing the metric # However, we don't want to ease-back to zero pressure, that will # unconstrain the penalty term and cause the optmizer to run wild. # So, use a "Leaky ReLU" # metric' = threshold + (metric - threshold) * leakFactor leakFactor = 0.01 if (self.optimization_params['target_over_score'] > 0 and overMetric >= self.optimization_params['target_over_score']): overMetric = (self.optimization_params['target_over_score'] + leakFactor * (overMetric - self.optimization_params['target_over_score'])) if (self.optimization_params['target_under_score'] > 0 and underMetric >= self.optimization_params['target_under_score']): underMetric = (self.optimization_params['target_under_score'] + leakFactor * (underMetric - self.optimization_params['target_under_score'])) penalty = -(overMetric + underMetric) return penalty def diagnose(self): """ Returns diagnostic plots to assess the most recent correction. If a correction has not yet been fitted, a ``ValueError`` will be raised. Returns ------- `~matplotlib.axes.Axes` The matplotlib axes object. """ axs = self._diagnostic_plot() plt.title('Alpha = {0:2.3e}'.format(self.alpha)) return axs def goodness_metric_scan_plot(self, cbv_type=['SingleScale'], cbv_indices=[np.arange(1,9)], alpha_range_log10=[-4, 4], ext_dm=None, cadence_mask=None): """ Returns a diagnostic plot of the over and under goodness metrics as a function of the L2-Norm regularization term, alpha. alpha is scanned by default to the range 10^-4 : 10^4 in logspace cbvCorrector.correct_gaussian_prior is used to make the correction for each alpha. Then the over and under goodness metric are computed. If a correction has already been performed (via one of the correct_* methods) then the used alpha value is also plotted for reference. Parameters ---------- cbv_type : str list List of CBV types to use in correction {'ALL' => Use all} cbv_indices : list of lists List of CBV vectors to use in each of cbv_type passed. {'ALL' => Use all} NOTE: 1-Based indexing! alpha_range_log10 : [list of two] The start and end exponent for the logspace scan. Default = [-4, 4] ext_dm : `.DesignMatrix` or `.DesignMatrixCollection` Optionally pass an extra design matrix to also be used in the fit cadence_mask : np.ndarray of bools (optional) Mask, where True indicates a cadence that should be used. Returns ------- `~matplotlib.axes.Axes` The matplotlib axes object. """ alphaArray = np.logspace(alpha_range_log10[0], alpha_range_log10[1], num=100) # We need to make a copy of self so that the scan's final fit parameters # do not over-write any stored fit parameters cbvCorrectorCopy = self.copy() # Compute both metrics vs. alpha overMetric = [] underMetric = [] for thisAlpha in alphaArray: cbvCorrectorCopy.correct_gaussian_prior(cbv_type=cbv_type, cbv_indices=cbv_indices, alpha=thisAlpha, ext_dm=ext_dm, cadence_mask=cadence_mask) overMetric.append(cbvCorrectorCopy.over_fitting_metric(n_samples=1)) underMetric.append(cbvCorrectorCopy.under_fitting_metric()) # plot both fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.semilogx(alphaArray, underMetric, 'b.', label='UnderFit') ax.semilogx(alphaArray, overMetric, 'r.', label='OverFit') if (isinstance(self.alpha, float)): ax.semilogx([self.alpha, self.alpha], [0, 1.0], 'k-', label='corrected_lc Alpha = {0:2.3e}'.format(self.alpha)) plt.title('Goodness Metrics
<gh_stars>0 # -*- coding: utf-8 -*- ## ## RS Downloader ## by AliAbdul ## ## from __future__ import print_function from __future__ import absolute_import from base64 import encodestring from Components.ActionMap import ActionMap from Components.config import config, ConfigClock, ConfigInteger, ConfigSelection, ConfigSubsection, ConfigText, ConfigYesNo, getConfigListEntry from Components.ConfigList import ConfigListScreen from Components.Console import Console as eConsole from Components.FileList import FileList from Components.Label import Label from Components.Language import language from Components.MenuList import MenuList from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest from Components.ScrollLabel import ScrollLabel from .container.decrypt import decrypt from enigma import eListboxPythonMultiContent, eTimer, gFont, RT_HALIGN_CENTER, RT_HALIGN_RIGHT from os import listdir, remove, system from Plugins.Plugin import PluginDescriptor from Screens.ChoiceBox import ChoiceBox from Screens.Console import Console as ConsoleScreen from Screens.MessageBox import MessageBox from Screens.Screen import Screen from Screens.VirtualKeyBoard import VirtualKeyBoard from time import localtime, sleep, strftime, time from Tools.Directories import fileExists, resolveFilename, SCOPE_SKIN_IMAGE, SCOPE_LANGUAGE, SCOPE_PLUGINS from Tools.Downloader import HTTPProgressDownloader from Tools.LoadPixmap import LoadPixmap from twisted.internet import reactor from twisted.python import failure from twisted.web.client import getPage from xml.etree.cElementTree import parse import os, gettext, re, socket, sys from six.moves.urllib.parse import urlparse, urlunparse from six.moves.urllib.request import Request, urlopen import six ############################################################################## config.plugins.RSDownloader = ConfigSubsection() config.plugins.RSDownloader.onoff = ConfigYesNo(default=True) config.plugins.RSDownloader.username = ConfigText(default="", fixed_size=False) config.plugins.RSDownloader.password = ConfigText(default="", fixed_size=False) config.plugins.RSDownloader.lists_directory = ConfigText(default="/media/hdd/rs/lists/", fixed_size=False) config.plugins.RSDownloader.downloads_directory = ConfigText(default="/media/hdd/rs/downloads", fixed_size=False) config.plugins.RSDownloader.ignore_time = ConfigYesNo(default=False) config.plugins.RSDownloader.start_time = ConfigClock(default=time()) config.plugins.RSDownloader.end_time = ConfigClock(default=time()) config.plugins.RSDownloader.download_monday = ConfigYesNo(default=True) config.plugins.RSDownloader.download_tuesday = ConfigYesNo(default=True) config.plugins.RSDownloader.download_wednesday = ConfigYesNo(default=True) config.plugins.RSDownloader.download_thursday = ConfigYesNo(default=True) config.plugins.RSDownloader.download_friday = ConfigYesNo(default=True) config.plugins.RSDownloader.download_saturday = ConfigYesNo(default=True) config.plugins.RSDownloader.download_sunday = ConfigYesNo(default=True) config.plugins.RSDownloader.count_downloads = ConfigInteger(default=3, limits=(1, 10)) config.plugins.RSDownloader.count_maximal_downloads = ConfigInteger(default=40, limits=(1, 1000)) config.plugins.RSDownloader.write_log = ConfigYesNo(default=True) config.plugins.RSDownloader.reconnect_type = ConfigSelection(choices={"script": _("Script"), "fritz": _("fritz.Box"), "no": _("No reconnect")}, default="fritz") config.plugins.RSDownloader.reconnect_script = ConfigText(default="", fixed_size=False) config.plugins.RSDownloader.autorestart_failed = ConfigYesNo(default=False) config.plugins.RSDownloader.mark_small_as_failed = ConfigYesNo(default=True) config.plugins.RSDownloader.unrar_password = ConfigText(default="", fixed_size=False) config.plugins.RSDownloader.reconnect_start_time = ConfigClock(default=time()) config.plugins.RSDownloader.reconnect_end_time = ConfigClock(default=time()) config.plugins.Netload = ConfigSubsection() config.plugins.Netload.username = ConfigText(default="", fixed_size=False) config.plugins.Netload.password = ConfigText(default="", fixed_size=False) config.plugins.Uploaded = ConfigSubsection() config.plugins.Uploaded.username = ConfigText(default="", fixed_size=False) config.plugins.Uploaded.password = ConfigText(default="", fixed_size=False) ############################################################################## PluginLanguageDomain = "RSDownloader" PluginLanguagePath = "Extensions/RSDownloader/locale/" def localeInit(): gettext.bindtextdomain(PluginLanguageDomain, resolveFilename(SCOPE_PLUGINS, PluginLanguagePath)) def _(txt): if gettext.dgettext(PluginLanguageDomain, txt): return gettext.dgettext(PluginLanguageDomain, txt) else: print("[" + PluginLanguageDomain + "] fallback to default translation for " + txt) return gettext.gettext(txt) language.addCallback(localeInit()) ############################################################################## def writeLog(message): if config.plugins.RSDownloader.write_log.value: try: f = open("/tmp/rapidshare.log", "a") f.write(strftime("%c", localtime(time())) + " - " + message + "\n") f.close() except: pass ############################################################################## def _parse(url): url = url.strip() parsed = urlparse(url) scheme = parsed[0] path = urlunparse(('', '') + parsed[2:]) host, port = parsed[1], 80 if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') else: password = "" else: username = "" password = "" if ':' in host: host, port = host.split(':') port = int(port) if path == "": path = "/" return scheme, host, port, path, username, password class ProgressDownload: def __init__(self, url, outputfile, contextFactory=None, *args, **kwargs): scheme, host, port, path, username, password = _parse(url) if username and password: url = scheme + '://' + host + ':' + str(port) + path basicAuth = encodestring("%s:%s"%(username, password)) authHeader = "Basic " + basicAuth.strip() AuthHeaders = {"Authorization": authHeader} if "headers" in kwargs: kwargs["headers"].update(AuthHeaders) else: kwargs["headers"] = AuthHeaders self.factory = HTTPProgressDownloader(url, outputfile, *args, **kwargs) self.connection = reactor.connectTCP(host, port, self.factory) def start(self): return self.factory.deferred def stop(self): self.connection.disconnect() def addProgress(self, progress_callback): self.factory.progress_callback = progress_callback ############################################################################## def get(url): try: data = urlopen(url) return data.read() except: return "" def post(url, data): try: return urlopen(url, data).read() except: return "" def matchGet(rex, string): match = re.search(rex, string) if match: if len(match.groups()) == 0: return string[match.span()[0]:match.span()[1]] if len(match.groups()) == 1: return match.groups()[0] else: return False ############################################################################## def reconnect(host='fritz.box', port=49000): writeLog("Reconnecting fritz.Box...") http_body = '\r\n'.join(( '<?xml version="1.0" encoding="utf-8"?>', '<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">', ' <s:Body>', ' <u:ForceTermination xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1"/>', ' </s:Body>', '</s:Envelope>')) http_data = '\r\n'.join(( 'POST /upnp/control/WANIPConn1 HTTP/1.1', 'Host: %s:%d'%(host, port), 'SoapAction: urn:schemas-upnp-org:service:WANIPConnection:1#ForceTermination', 'Content-Type: text/xml; charset="utf-8"', 'Content-Length: %d'%len(http_body), '', http_body)) try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.send(http_data) s.close() except: writeLog("Error while reconnecting fritz.Box: " + str(sys.exc_info())) ############################################################################## def reconnect_script(): script = config.plugins.RSDownloader.reconnect_script.value if script != "" and fileExists(script): writeLog("Reconnecting with script %s..."%script) system(script) else: writeLog("Error: Reconnect script %s not found!"%script) ############################################################################## std_headers = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'Accept-Language': 'en-us,en;q=0.5', } class RSDownload: def __init__(self, url): writeLog("Adding: %s"%url) self.url = url self.download = None self.downloading = False self.progress = 0 self.size = 0 self.status = _("Waiting") self.name = self.url.split("/")[-1] self.finishCallbacks = [] def mayReconnect(self): start = config.plugins.RSDownloader.reconnect_start_time.value end = config.plugins.RSDownloader.reconnect_end_time.value t = localtime() hour_now = t[3] minute_now = t[4] hour_start = start[0] minute_start = start[1] hour_end = end[0] minute_end = end[1] if start == end: # Same start and end-time return True elif hour_end < hour_start: # Different days!!! if hour_now > hour_start or hour_now < hour_end: return True elif hour_now == hour_start and minute_now > minute_start: return True elif hour_now == hour_end and minute_now < minute_end: return True else: return False elif hour_now > hour_start and hour_now < hour_end: # Same day... return True elif hour_now == hour_start and minute_now > minute_start: # Same day, same start-hour... return True elif hour_now == hour_end and minute_now < minute_end: # Same day, same end-hour... return True else: return False def start(self): writeLog("Downloading: %s"%self.url) self.downloading = True self.progress = 0 self.size = 0 username = config.plugins.RSDownloader.username.value password = config.plugins.RSDownloader.password.value nl_username = config.plugins.Netload.username.value nl_password = config.plugins.Netload.password.value ul_username = config.plugins.Uploaded.username.value ul_password = config.plugins.Uploaded.password.value if self.url.__contains__("rapidshare.com") and username == "" and password == "": writeLog("Free RS-Download: %s"%self.url) self.status = _("Checking") if self.mayReconnect(): if config.plugins.RSDownloader.reconnect_type.value == "fritz": reconnect() sleep(3) if config.plugins.RSDownloader.reconnect_type.value == "script": reconnect_script() sleep(3) data = get(self.url) url = matchGet('<form[^>]+action="([^"]+)', data) if not url: writeLog("Failed: %s"%self.url) self.httpFailed(True, "Failed to get download page url: %s"%self.url) else: data = post(url, "dl.start=Free") seconds = matchGet('var c=([0-9]+)', data) if not seconds: self.httpFailed(True, "Failed to get download page url: %s"%self.url) else: writeLog("Free RS-Download... must wait %s seconds: %s"%(seconds, self.url)) self.status = "%s %s"%(_("Waiting"), seconds) url = matchGet('"dlf" action="([^"]+)', data) if not url: self.httpFailed(True, "Failed to get download page url: %s"%self.url) else: self.freeDownloadUrl = url self.freeDownloadTimer = eTimer() self.freeDownloadTimer.callback.append(self.freeDownloadStart) self.freeDownloadTimer.start((int(seconds) + 2) * 1000, 1) elif (self.url.__contains__("uploaded.to") or self.url.__contains__("ul.to")) and ul_username == "" and ul_password == "": writeLog("Free Uploaded.to-Download: %s"%self.url) self.status = _("Checking") if self.mayReconnect(): if config.plugins.RSDownloader.reconnect_type.value == "fritz": reconnect() sleep(3) if config.plugins.RSDownloader.reconnect_type.value == "script": reconnect_script() sleep(3) data = get(self.url) tmp = re.search(r"Or wait (\d+) minutes", data) if tmp: minutes = tmp.group(1) writeLog("Free Uploaded.to-Download... must wait %s minutes: %s"%(minutes, self.url)) self.status = "%s %s"%(_("Waiting"), minutes) self.freeDownloadTimer = eTimer() self.freeDownloadTimer.callback.append(self.start) self.freeDownloadTimer.start((int(minutes) + 1) * 60000, 1) else: try: url = re.search(r".*<form name=\"download_form\" method=\"post\" action=\"(.*)\">", data).group(1) except: url = None if url: self.name = re.search(r"<td><b>\s+(.+)\s", data).group(1) + re.search(r"</td><td>(\..+)</td></tr>", data).group(1) self.status = _("Downloading") self.download = ProgressDownload(url, ("%s/%s"%(config.plugins.RSDownloader.downloads_directory.value, self.name)).replace("//", "/")) self.download.addProgress(self.httpProgress) self.download.start().addCallback(self.httpFinished).addErrback(self.httpFailed) else: self.httpFailed(True, "File is offline: %s"%self.url) elif self.url.__contains__("youtube.com"): writeLog("Getting youtube video link: %s"%self.url) self.status = _("Checking") downloadLink = self.getYoutubeDownloadLink() if downloadLink: self.status = _("Downloading") writeLog("Downloading video: %s"%downloadLink) req = Request(downloadLink) url_handle = urlopen(req) headers = url_handle.info() if headers.getheader("content-type") == "video/mp4": ext = "mp4" else: ext = "flv" self.download = ProgressDownload(downloadLink, ("%s/%s.%s"%(config.plugins.RSDownloader.downloads_directory.value, self.name, ext)).replace("//", "/")) self.download.addProgress(self.httpProgress) self.download.start().addCallback(self.httpFinished).addErrback(self.httpFailed) else: self.httpFailed(True, "Failed to get video url: %s"%self.url) else: if self.url.__contains__("rapidshare.com") and username != "" and password != "": url = self.url.replace("http://", "http://" + username + ":" + password + "@") elif (self.url.__contains__("uploaded.to") or self.url.__contains__("ul.to")) and ul_username != "" and ul_password != "": url = self.url.replace("http://", "http://" + ul_username + ":" + ul_password + "@") elif self.url.__contains__("netload.in") and nl_username != "" and nl_password != "": url = self.url.replace("http://", "http://" + nl_username + ":" + nl_password + "@") else: url = self.url self.status = _("Downloading") self.download = ProgressDownload(url, ("%s/%s"%(config.plugins.RSDownloader.downloads_directory.value, self.name)).replace("//", "/").replace(".html", "")) self.download.addProgress(self.httpProgress) self.download.start().addCallback(self.httpFinished).addErrback(self.httpFailed) def freeDownloadStart(self): self.status = _("Downloading") self.download = ProgressDownload(self.freeDownloadUrl, ("%s/%s"%(config.plugins.RSDownloader.downloads_directory.value, self.name)).replace("//", "/").replace(".html", "")) self.download.addProgress(self.httpProgress) self.download.start().addCallback(self.httpFinished).addErrback(self.httpFailed) def stop(self): self.progress = 0 self.downloading = False self.status = _("Waiting") if self.download: writeLog("Stopping download: %s"%self.url) self.download.stop() def httpProgress(self, recvbytes, totalbytes): if self.size == 0: self.size = int((totalbytes / 1024) / 1024) self.progress = int(100.0 * float(recvbytes) / float(totalbytes)) def httpFinished(self, string=None): if string is not None: writeLog("Failed: %s"%self.url) writeLog("Error: %s"%string) self.status = _("Checking") self.checkTimer = eTimer() self.checkTimer.callback.append(self.doCheckTimer) self.checkTimer.start(10000, 1) def doCheckTimer(self): if (self.size == 0) or (self.progress < 100) or ((config.plugins.RSDownloader.mark_small_as_failed.value == True) and (self.size < 1)): self.status = _("Failed") if config.plugins.RSDownloader.autorestart_failed.value: self.restartFailedTimer = eTimer() self.restartFailedTimer.callback.append(self.restartFailedCheck) self.restartFailedTimer.start(10000*60, 1) elif self.progress == 100: self.status = _("Finished") writeLog("Finished: %s"%self.url) self.downloading = False self.execFinishCallbacks() def restartFailedCheck(self): if self.status == _("Failed"): # check if user didn't restart already self.download = None self.status = _("Waiting") def execFinishCallbacks(self): for x in self.finishCallbacks: x() def httpFailed(self, failure=None, error=""): if failure: if error == "": error = failure.getErrorMessage() if error != "" and not error.startswith("[Errno 2]"): writeLog("Failed: %s"%self.url) writeLog("Error: %s"%error) self.status = _("Checking") self.checkTimer = eTimer() self.checkTimer.callback.append(self.doCheckTimer) self.checkTimer.start(10000, 1) def getTubeId(self): url = self.url if url.__contains__("&feature="): idx = url.index("&feature=") url = url[:idx] split = url.split("=") ret = split.pop() if ret == 'youtube_gdata': tmpval = split.pop() if tmpval.endswith("&feature"): tmp = tmpval.split("&") ret = tmp.pop(0) return ret def getYoutubeDownloadLink(self): html = get(self.url) if html != "": reonecat = re.compile(r'<title>(.+?)</title>', re.DOTALL) titles = reonecat.findall(html) if titles: self.name = titles[0] if self.name.__contains__("\t- "): idx = self.name.index("\t- ") self.name = (self.name[idx+3:]).replace("&amp;", "&").replace("\t", "").replace("\n", "") mrl = None isHDAvailable = False video_id = str(self.getTubeId()) watch_url = "http://www.youtube.com/watch?v="+video_id watchrequest = Request(watch_url, None, std_headers) try: watchvideopage = urlopen(watchrequest).read() except: watchvideopage = "" if "isHDAvailable = true" in watchvideopage: isHDAvailable = True info_url = 'http://www.youtube.com/get_video_info?&video_id=%s&el=detailpage&ps=default&eurl=&gl=US&hl=en'%video_id inforequest = Request(info_url, None, std_headers) try: infopage = urlopen(inforequest).read() except: infopage = "" mobj = re.search(r'(?m)&token=([^&]+)(?:&|$)', infopage) if mobj: token = unquote(mobj.group(1)) myurl = 'http://www.youtube.com/get_video?video_id=%s&t=%s&eurl=&el=detailpage&ps=default&gl=US&hl=en'%(video_id, token) if isHDAvailable is True: mrl = '%s&fmt=%s'%(myurl, '22') else: mrl = '%s&fmt=%s'%(myurl, '18') return mrl ############################################################################## class RS: def __init__(self): self.downloads = [] self.checkTimer = eTimer() self.checkTimer.callback.append(self.startDownloading) self.checkTimer.start(5000*60, False) def mayDownload(self): if config.plugins.RSDownloader.onoff.value == False: writeLog("RS Downloader is turned off...") return False elif config.plugins.RSDownloader.ignore_time.value: return True else: start = config.plugins.RSDownloader.start_time.value end = config.plugins.RSDownloader.end_time.value t = localtime() weekday = t[6] if weekday == 0 and config.plugins.RSDownloader.download_monday.value == False: return False elif weekday == 1 and config.plugins.RSDownloader.download_tuesday.value == False: return False elif weekday == 2 and config.plugins.RSDownloader.download_wednesday.value == False: return False elif weekday == 3 and config.plugins.RSDownloader.download_thursday.value == False: return False elif weekday == 4 and config.plugins.RSDownloader.download_friday.value == False: return False elif weekday == 5 and config.plugins.RSDownloader.download_saturday.value == False: return False elif weekday == 6 and config.plugins.RSDownloader.download_sunday.value == False: return False else: hour_now = t[3] minute_now = t[4] hour_start = start[0] minute_start = start[1] hour_end = end[0] minute_end = end[1] if start == end: # Same start and end-time return True elif hour_end < hour_start: # Different days!!! if hour_now > hour_start or hour_now < hour_end: return True elif hour_now == hour_start and minute_now > minute_start: return True elif hour_now == hour_end and minute_now < minute_end: return True else: return False elif hour_now > hour_start and hour_now < hour_end: # Same day... return True elif hour_now == hour_start and minute_now > minute_start: # Same day, same start-hour... return True elif hour_now == hour_end and minute_now < minute_end: # Same day, same end-hour... return True else: return False def allDownloadsFinished(self): allDone = True for download in self.downloads: if (download.status != _("Failed")) and (download.status !=
# Copyright (c) 2017 The Johns Hopkins University/Applied Physics Laboratory # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import testtools from kmip.core import utils from kmip.core.messages import payloads class TestGetUsageAllocationRequestPayload(testtools.TestCase): """ Test suite for the GetUsageAllocation request payload. """ def setUp(self): super(TestGetUsageAllocationRequestPayload, self).setUp() # Encoding obtained from the KMIP 1.1 testing document, Section 5.1. # # This encoding matches the following set of values: # Request Payload # Unique Identifier - 2c23217e-f53c-4bdf-ad0a-58a31fd3d4b6 # Usage Limits Count - 500 self.full_encoding = utils.BytearrayStream( b'\x42\x00\x79\x01\x00\x00\x00\x40' b'\x42\x00\x94\x07\x00\x00\x00\x24' b'\x32\x63\x32\x33\x32\x31\x37\x65\x2D\x66\x35\x33\x63\x2D\x34\x62' b'\x64\x66\x2D\x61\x64\x30\x61\x2D\x35\x38\x61\x33\x31\x66\x64\x33' b'\x64\x34\x62\x36\x00\x00\x00\x00' b'\x42\x00\x96\x03\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x01\xF4' ) # This encoding matches the following set of values: # Request Payload # Usage Limits Count - 500 self.partial_encoding = utils.BytearrayStream( b'\x42\x00\x79\x01\x00\x00\x00\x10' b'\x42\x00\x96\x03\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x01\xF4' ) self.empty_encoding = utils.BytearrayStream( b'\x42\x00\x79\x01\x00\x00\x00\x00' ) def tearDown(self): super(TestGetUsageAllocationRequestPayload, self).tearDown() def test_init(self): """ Test that a GetUsageAllocation request payload can be constructed with no arguments. """ payload = payloads.GetUsageAllocationRequestPayload() self.assertEqual(None, payload.unique_identifier) self.assertEqual(None, payload.usage_limits_count) def test_init_with_args(self): """ Test that a GetUsageAllocation request payload can be constructed with valid values. """ payload = payloads.GetUsageAllocationRequestPayload( unique_identifier='00000000-1111-2222-3333-444444444444', usage_limits_count=10 ) self.assertEqual( '00000000-1111-2222-3333-444444444444', payload.unique_identifier ) self.assertEqual(10, payload.usage_limits_count) def test_invalid_unique_identifier(self): """ Test that a TypeError is raised when an invalid value is used to set the unique identifier of a GetUsageAllocation request payload. """ kwargs = {'unique_identifier': 0} self.assertRaisesRegex( TypeError, "Unique identifier must be a string.", payloads.GetUsageAllocationRequestPayload, **kwargs ) payload = payloads.GetUsageAllocationRequestPayload() args = (payload, 'unique_identifier', 0) self.assertRaisesRegex( TypeError, "Unique identifier must be a string.", setattr, *args ) def test_invalid_usage_limits_count(self): """ Test that a TypeError is raised when an invalid value is used to set the usage limits count of a GetUsageAllocation request payload. """ kwargs = {'usage_limits_count': 'invalid'} self.assertRaisesRegex( TypeError, "Usage limits count must be an integer.", payloads.GetUsageAllocationRequestPayload, **kwargs ) payload = payloads.GetUsageAllocationRequestPayload() args = (payload, 'usage_limits_count', 'invalid') self.assertRaisesRegex( TypeError, "Usage limits count must be an integer.", setattr, *args ) def test_read(self): """ Test that a GetUsageAllocation request payload can be read from a data stream. """ payload = payloads.GetUsageAllocationRequestPayload() self.assertEqual(None, payload.unique_identifier) self.assertEqual(None, payload.usage_limits_count) payload.read(self.full_encoding) self.assertEqual( '2c23217e-f53c-4bdf-ad0a-58a31fd3d4b6', payload.unique_identifier ) self.assertEqual(500, payload.usage_limits_count) def test_read_partial(self): """ Test that a GetUsageAllocation request payload can be read from a partial data stream. """ payload = payloads.GetUsageAllocationRequestPayload() self.assertEqual(None, payload.unique_identifier) self.assertEqual(None, payload.usage_limits_count) payload.read(self.partial_encoding) self.assertEqual(None, payload.unique_identifier) self.assertEqual(500, payload.usage_limits_count) def test_read_empty(self): """ Test that a GetUsageAllocation request payload can be read from an empty data stream. """ payload = payloads.GetUsageAllocationRequestPayload() self.assertEqual(None, payload.unique_identifier) self.assertEqual(None, payload.usage_limits_count) payload.read(self.empty_encoding) self.assertEqual(None, payload.unique_identifier) self.assertEqual(None, payload.usage_limits_count) def test_write(self): """ Test that a GetUsageAllocation request payload can be written to a data stream. """ payload = payloads.GetUsageAllocationRequestPayload( unique_identifier='2c23217e-f53c-4bdf-ad0a-58a31fd3d4b6', usage_limits_count=500 ) stream = utils.BytearrayStream() payload.write(stream) self.assertEqual(len(self.full_encoding), len(stream)) self.assertEqual(str(self.full_encoding), str(stream)) def test_write_partial(self): """ Test that a partial GetUsageAllocation request payload can be written to a data stream. """ payload = payloads.GetUsageAllocationRequestPayload( usage_limits_count=500 ) stream = utils.BytearrayStream() payload.write(stream) self.assertEqual(len(self.partial_encoding), len(stream)) self.assertEqual(str(self.partial_encoding), str(stream)) def test_write_empty(self): """ Test that an empty GetUsageAllocation request payload can be written to a data stream. """ payload = payloads.GetUsageAllocationRequestPayload() stream = utils.BytearrayStream() payload.write(stream) self.assertEqual(len(self.empty_encoding), len(stream)) self.assertEqual(str(self.empty_encoding), str(stream)) def test_equal_on_equal(self): """ Test that the equality operator returns True when comparing two GetUsageAllocation request payloads with the same data. """ a = payloads.GetUsageAllocationRequestPayload() b = payloads.GetUsageAllocationRequestPayload() self.assertTrue(a == b) self.assertTrue(b == a) a = payloads.GetUsageAllocationRequestPayload( unique_identifier='49a1ca88-6bea-4fb2-b450-7e58802c3038', usage_limits_count=200 ) b = payloads.GetUsageAllocationRequestPayload( unique_identifier='49a1ca88-6bea-4fb2-b450-7e58802c3038', usage_limits_count=200 ) self.assertTrue(a == b) self.assertTrue(b == a) def test_equal_on_not_equal_unique_identifier(self): """ Test that the equality operator returns False when comparing two GetUsageAllocation request payloads with different unique identifiers. """ a = payloads.GetUsageAllocationRequestPayload( unique_identifier='a' ) b = payloads.GetUsageAllocationRequestPayload( unique_identifier='b' ) self.assertFalse(a == b) self.assertFalse(b == a) def test_equal_on_not_equal_usage_limits_count(self): """ Test that the equality operator returns False when comparing two GetUsageAllocation request payloads with different usage limits counts. """ a = payloads.GetUsageAllocationRequestPayload( usage_limits_count=0 ) b = payloads.GetUsageAllocationRequestPayload( usage_limits_count=1 ) self.assertFalse(a == b) self.assertFalse(b == a) def test_equal_on_type_mismatch(self): """ Test that the equality operator returns False when comparing two GetUsageAllocation request payloads with different types. """ a = payloads.GetUsageAllocationRequestPayload() b = 'invalid' self.assertFalse(a == b) self.assertFalse(b == a) def test_not_equal_on_equal(self): """ Test that the inequality operator returns False when comparing two GetUsageAllocation request payloads with the same data. """ a = payloads.GetUsageAllocationRequestPayload() b = payloads.GetUsageAllocationRequestPayload() self.assertFalse(a != b) self.assertFalse(b != a) a = payloads.GetUsageAllocationRequestPayload( unique_identifier='49a1ca88-6bea-4fb2-b450-7e58802c3038', usage_limits_count=200 ) b = payloads.GetUsageAllocationRequestPayload( unique_identifier='49a1ca88-6bea-4fb2-b450-7e58802c3038', usage_limits_count=200 ) self.assertFalse(a != b) self.assertFalse(b != a) def test_not_equal_on_not_equal_unique_identifier(self): """ Test that the inequality operator returns True when comparing two GetUsageAllocation request payloads with different unique identifiers. """ a = payloads.GetUsageAllocationRequestPayload( unique_identifier='a' ) b = payloads.GetUsageAllocationRequestPayload( unique_identifier='b' ) self.assertTrue(a != b) self.assertTrue(b != a) def test_not_equal_on_not_equal_usage_limits_count(self): """ Test that the inequality operator returns True when comparing two GetUsageAllocation request payloads with different usage limits counts. """ a = payloads.GetUsageAllocationRequestPayload( usage_limits_count=0 ) b = payloads.GetUsageAllocationRequestPayload( usage_limits_count=1 ) self.assertTrue(a != b) self.assertTrue(b != a) def test_not_equal_on_type_mismatch(self): """ Test that the inequality operator returns True when comparing two GetUsageAllocation request payloads with different types. """ a = payloads.GetUsageAllocationRequestPayload() b = 'invalid' self.assertTrue(a != b) self.assertTrue(b != a) def test_repr(self): """ Test that repr can be applied to a GetUsageAllocation request payload. """ payload = payloads.GetUsageAllocationRequestPayload( unique_identifier='49a1ca88-6bea-4fb2-b450-7e58802c3038', usage_limits_count=1000 ) expected = ( "GetUsageAllocationRequestPayload(" "unique_identifier='49a1ca88-6bea-4fb2-b450-7e58802c3038', " "usage_limits_count=1000)" ) observed = repr(payload) self.assertEqual(expected, observed) def test_str(self): """ Test that str can be applied to a GetUsageAllocation request payload. """ payload = payloads.GetUsageAllocationRequestPayload( unique_identifier='49a1ca88-6bea-4fb2-b450-7e58802c3038', usage_limits_count=1000 ) expected = str({ 'unique_identifier': '49a1ca88-6bea-4fb2-b450-7e58802c3038', 'usage_limits_count': 1000 }) observed = str(payload) self.assertEqual(expected, observed) class TestGetUsageAllocationResponsePayload(testtools.TestCase): """ Test suite for the GetUsageAllocation response payload. """ def setUp(self): super(TestGetUsageAllocationResponsePayload, self).setUp() # Encoding obtained from the KMIP 1.1 testing document, Section 5.1. # # This encoding matches the following set of values: # Response Payload # Unique Identifier - 2c23217e-f53c-4bdf-ad0a-58a31fd3d4b6 self.full_encoding = utils.BytearrayStream( b'\x42\x00\x7C\x01\x00\x00\x00\x30' b'\x42\x00\x94\x07\x00\x00\x00\x24' b'\x32\x63\x32\x33\x32\x31\x37\x65\x2D\x66\x35\x33\x63\x2D\x34\x62' b'\x64\x66\x2D\x61\x64\x30\x61\x2D\x35\x38\x61\x33\x31\x66\x64\x33' b'\x64\x34\x62\x36\x00\x00\x00\x00' ) self.empty_encoding = utils.BytearrayStream( b'\x42\x00\x7C\x01\x00\x00\x00\x00' ) def tearDown(self): super(TestGetUsageAllocationResponsePayload, self).tearDown() def test_init(self): """ Test that a GetUsageAllocation response payload can be constructed with no arguments. """ payload = payloads.GetUsageAllocationResponsePayload() self.assertEqual(None, payload.unique_identifier) def test_init_with_args(self): """ Test that a GetUsageAllocation response payload can be constructed with valid values. """ payload = payloads.GetUsageAllocationResponsePayload( unique_identifier='00000000-1111-2222-3333-444444444444' ) self.assertEqual( '00000000-1111-2222-3333-444444444444', payload.unique_identifier ) def test_invalid_unique_identifier(self): """ Test that a TypeError is raised when an invalid value is used to set the unique identifier of a GetUsageAllocation response payload. """ kwargs = {'unique_identifier': 0} self.assertRaisesRegex( TypeError, "Unique identifier must be a string.", payloads.GetUsageAllocationResponsePayload, **kwargs ) payload = payloads.GetUsageAllocationResponsePayload() args = (payload, 'unique_identifier', 0) self.assertRaisesRegex( TypeError, "Unique identifier must be a string.", setattr, *args ) def test_read(self): """ Test that a GetUsageAllocation response payload can be read from a data stream. """ payload = payloads.GetUsageAllocationResponsePayload() self.assertEqual(None, payload.unique_identifier) payload.read(self.full_encoding) self.assertEqual( '2c23217e-f53c-4bdf-ad0a-58a31fd3d4b6', payload.unique_identifier ) def test_read_empty(self): """ Test that a GetUsageAllocation response payload can be read from an empty data stream. """ payload = payloads.GetUsageAllocationResponsePayload() self.assertEqual(None, payload.unique_identifier) payload.read(self.empty_encoding) self.assertEqual(None, payload.unique_identifier) def test_write(self): """ Test that a GetUsageAllocation response payload can be written to a data stream. """ payload = payloads.GetUsageAllocationResponsePayload( unique_identifier='2c23217e-f53c-4bdf-ad0a-58a31fd3d4b6' ) stream = utils.BytearrayStream() payload.write(stream) self.assertEqual(len(self.full_encoding), len(stream)) self.assertEqual(str(self.full_encoding), str(stream)) def test_write_empty(self): """ Test that an empty GetUsageAllocation response payload can be written to a data stream. """ payload = payloads.GetUsageAllocationResponsePayload() stream = utils.BytearrayStream() payload.write(stream) self.assertEqual(len(self.empty_encoding), len(stream)) self.assertEqual(str(self.empty_encoding), str(stream)) def test_equal_on_equal(self): """ Test that the equality operator returns True when comparing two GetUsageAllocation response payloads with the same data. """ a = payloads.GetUsageAllocationResponsePayload() b = payloads.GetUsageAllocationResponsePayload() self.assertTrue(a == b) self.assertTrue(b == a) a = payloads.GetUsageAllocationResponsePayload( unique_identifier='49a1ca88-6bea-4fb2-b450-7e58802c3038' ) b = payloads.GetUsageAllocationResponsePayload( unique_identifier='49a1ca88-6bea-4fb2-b450-7e58802c3038' ) self.assertTrue(a == b) self.assertTrue(b == a) def test_equal_on_not_equal_unique_identifier(self): """ Test that the equality operator returns False when comparing two GetUsageAllocation response payloads with different unique identifiers. """ a
import operator as op import statistics as st from abc import ABC, abstractmethod import numpy as np from ortools.graph import pywrapgraph as ortg from tqdm import tqdm import mapnames.string def vertex_diff(u, v, string_metric, **kwargs): return string_metric(u.label, v.label, **kwargs) class Vertex: def __init__(self, label, idx=None): self.label = label self.idx = idx self.prefs = None self.ratings = None self.__ratings = None def set_ratings(self, others, h_fn, sort=False, also_prefs=False): """ Sets the rating list of this vertex according to the results of h_fn. As setting the ratings might be computationally expensive, this method stores the result in an internal attribute that is exposed through the public self.ratings one. It is safe to modify self.ratings as it is recoverable through this internal backup with self.restore_ratings(). :param others: set of other vertices to compute rating list against :param h_fn: must be a function accepting two vertices and returning an integer that describes how closely related these two vertices are. The function will be called with self and another vertex in others. The integers will be used to sort the list, if asked. They need not be the final vertex position. :param sort: if the rating list should be sorted at the end :param also_prefs: if the preference list should be set at the end (will also sort the ratings before actually setting prefs). """ self.__ratings = [(other, h_fn(self, other)) for other in others] if sort or also_prefs: self.__ratings.sort(key=op.itemgetter(1)) if also_prefs: self.restore_prefs() self.restore_ratings() def restore_ratings(self): """ Set self.ratings based on an internal backup of it. For more information, see self.set_ratings(). """ self.ratings = self.__ratings.copy() def restore_prefs(self): """ Set self.prefs based on self.ratings. Will make self.prefs store only the reference to the vertices, making it a "real" preference list. Mainly for stable marriage or algorithms that alter the preference lists during their execution. """ self.prefs = [other for (other, _) in self.__ratings] def __str__(self): return self.label def __repr__(self): return self.__str__() ################################################################################ # ABSTRACT BASE CLASSES ################################################################################ class BipartiteMatcher(ABC): def __init__(self): self.left = None self.right = None self.n = None @abstractmethod def match(self): """ Run the matching implemented """ pass @abstractmethod def set_prefs(self, h_fn): """ Set the necessary preference lists according to h_fn. See Vertex.set_ratings() for more details regarding h_fn. """ pass @abstractmethod def accuracy(self, correct_mapping, opt_dict_out=None): """ Computes the achieved accuracy according to correct_mapping. The accuracy must be between 0.0 and 1.0. Other optional return values may be returned through opt_dict_out, e.g. the list of mismatches (of which the elements may vary per implementation). :param correct_mapping: a dict holding the correct mapping :param opt_dict_out: optional dictionary for additional output values """ pass class CompleteBipartiteMatcher(BipartiteMatcher, ABC): def set_prefs(self, h_fn): """ Sets the preference list for all vertices in the left set against all in the right, and all in the right set against all in the left. Shows a progress-bar for each of the two runs. :param h_fn: see Vertex.set_ratings() """ for l in tqdm(self.left): l.set_ratings(self.right, h_fn, also_prefs=True) for r in tqdm(self.right): r.set_ratings(self.left, h_fn, also_prefs=True) def restore_prefs(self): for l in self.left: l.restore_prefs() for r in self.right: r.restore_prefs() class IncompleteBipartiteMatcher(BipartiteMatcher, ABC): def __init__(self): super().__init__() # filter_on_left is used to filter left-side candidates, # thus should be queried with a right vertex (and vice-versa) self.filter_on_left = None self.filter_on_right = None # preference statistics computed on self.set_prefs # if a filter was provided self.prefs_min = None self.prefs_max = None self.prefs_mean = None self.prefs_std = None self.prefs_qtiles = None def set_prefs(self, h_fn, sort=False, also_prefs=False): """ Sets the preference list for all vertices in the left set against some in the right, and all in the right set against some in the left, where 'some' depends on the provided filter. If no filter was provided, 'some' will be 'all'. Shows a progress-bar for each of the two runs. For a description of the parameters, see Vertex.set_ratings(). """ prefs_len = [] for these, those, filter_on_them in \ zip([self.left, self.right], [self.right, self.left], [self.filter_on_right, self.filter_on_left]): for this in tqdm(these): if filter_on_them is not None: filtrd_idxs = filter_on_them(this.label) them = those[filtrd_idxs] prefs_len.append(len(them)) else: them = those this.set_ratings(them, h_fn, sort, also_prefs) if self.filter_on_left is not None or self.filter_on_right is not None: self.prefs_min = min(prefs_len) self.prefs_max = max(prefs_len) self.prefs_mean = st.mean(prefs_len) self.prefs_std = st.pstdev(prefs_len, self.prefs_mean) self.prefs_qtiles = np.percentile(prefs_len, [25, 50, 75]) class IncompleteStableMarriage(IncompleteBipartiteMatcher, ABC): def __init__(self, left, right, filter_class=mapnames.string.SuffixArray): """ :param left: left set of elements :param right: right set of elements :param filter_class: a callable class to build filters for left and right sets (so the constructor will be called with them). Upon called with a string, must return a list of indexes of candidates to compare to that string. """ super().__init__() self.n = len(left) # holds the result of self.match() self.assignment = None if filter_class is not None: self.filter_on_left = filter_class(left) self.filter_on_right = filter_class(right) self.left = np.array([Vertex(left[l], l) for l in range(len(left))]) self.right = np.array([Vertex(right[r], r) for r in range(len(right))]) def accuracy(self, correct_mapping, opt_dict_out=None): """ Computes the achieved accuracy and the list of mismatches. The accuracy takes into account unmatched elements as wrong matchings. :param correct_mapping: a dict holding the correct mapping :param opt_dict_out: if not None, a list of mismatched and a list of unmatched Vertex elements from self.left :return: the accuracy """ errors = [] for l, r in self.assignment.items(): is_equal = r.label == correct_mapping[l.label] if not is_equal: errors.append(l) unmatched = self.get_unmatched() if opt_dict_out is not None: opt_dict_out['errors'] = errors opt_dict_out['unmatched'] = unmatched return (self.n - len(errors) - len(unmatched)) / self.n def get_unmatched(self): return [l for l in self.left if l not in self.assignment] ################################################################################ # IMPLEMENTATIONS ################################################################################ class StableMarriage(CompleteBipartiteMatcher): def __init__(self, left, right): """ :param left: left set of elements :param right: right set of elements """ super().__init__() self.n = len(left) # holds the result of self.match() self.assignment = None self.left = np.array([Vertex(l) for l in left]) self.right = np.array([Vertex(r) for r in right]) def match(self): """ Run Irving's weakly-stable marriage algorithm. It is Irving's extension to Gale-Shapley's. Must be called after a call to self.set_ratings(also_prefs=True) and will ruin the preference lists (they can be restored with self.restore_prefs()). Stores its result in self.assignment. """ husband = {} self.assignment = {} # preference lists will get screwed... free_men = set(self.left) while len(free_men) > 0: m = free_men.pop() w = m.prefs[0] # if some man h is engaged to w, # set him free h = husband.get(w) if h is not None: del self.assignment[h] free_men.add(h) # m engages w self.assignment[m] = w husband[w] = m # for each successor m' of m in w's preferences, # remove w from the preferences of m' so that no man # less desirable than m will propose w succ_index = w.prefs.index(m) + 1 for i in range(succ_index, len(w.prefs)): successor = w.prefs[i] successor.prefs.remove(w) # and delete all m' from w's preferences so we won't # attempt to remove w from their list more than once del w.prefs[succ_index:] def accuracy(self, correct_mapping, opt_dict_out=None): """ Computes the achieved accuracy and the list of mismatches. :param correct_mapping: a dict holding the correct mapping :param opt_dict_out: if not None, a list of mismatched Vertex elements from self.left :return: the accuracy """ errors = [] for l, r in self.assignment.items(): is_equal = r.label == correct_mapping[l.label] if not is_equal: errors.append(l) if opt_dict_out is not None: opt_dict_out['errors'] = errors return (self.n - len(errors)) / self.n class SimpleMarriageAttempt(IncompleteStableMarriage): def match(self): """ Run a (somewhat bad) adaptation to Irving's weakly-stable marriage algorithm with support for incomplete preference lists. Must be called after a call to self.set_ratings() and will ruin the preference lists (they can be restored with self.restore_prefs()). Stores its result in self.assignment. """ husbands = {} self.assignment = {} free_men = list(self.left) while free_men: man = free_men.pop(0) # man preferences might get emptied later on if not man.prefs: continue # pop to prevent infinite loop woman = man.prefs.pop(0) # if some man husband is engaged to woman, # check if man is better than him and, if so, # change the marriage husband = husbands.get(woman) if husband is not None:
<reponame>zhaokai-l/bag # SPDX-License-Identifier: BSD-3-Clause AND Apache-2.0 # Copyright 2018 Regents of the University of California # 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. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # 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 HOLDER 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. # Copyright 2019 Blue Cheetah Analog Design Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module defines layout template classes. """ from __future__ import annotations from typing import ( TYPE_CHECKING, Union, Dict, Any, List, TypeVar, Type, Optional, Tuple, Iterable, Mapping, Sequence, Set, cast ) from bag.typing import PointType import abc from itertools import product from pybag.enum import ( PathStyle, BlockageType, BoundaryType, DesignOutput, Orient2D, SupplyWrapMode, Orientation, Direction, MinLenMode, RoundMode, PinMode, Direction2D ) from pybag.core import ( BBox, BBoxArray, PyLayCellView, Transform, PyLayInstRef, PyPath, PyBlockage, PyBoundary, PyRect, PyVia, PyPolygon, PyPolygon90, PyPolygon45, ViaParam, COORD_MIN, COORD_MAX, RTree, BBoxCollection, TrackColoring, make_tr_colors ) from ..util.immutable import ImmutableSortedDict, Param from ..util.cache import DesignMaster, MasterDB, format_cell_name from ..util.interval import IntervalSet from ..util.math import HalfInt from ..design.module import Module from .core import PyLayInstance from .tech import TechInfo from .routing.base import Port, TrackID, WireArray from .routing.grid import RoutingGrid from .data import MOMCapInfo, TemplateEdgeInfo GeoType = Union[PyRect, PyPolygon90, PyPolygon45, PyPolygon] TemplateType = TypeVar('TemplateType', bound='TemplateBase') DiffWarrType = Tuple[Optional[WireArray], Optional[WireArray]] if TYPE_CHECKING: from ..core import BagProject from ..typing import TrackType, SizeType class TemplateDB(MasterDB): """A database of all templates. This class is a subclass of MasterDB that defines some extra properties/function aliases to make creating layouts easier. Parameters ---------- routing_grid : RoutingGrid the default RoutingGrid object. lib_name : str the cadence library to put all generated templates in. prj : Optional[BagProject] the BagProject instance. name_prefix : str generated layout name prefix. name_suffix : str generated layout name suffix. """ def __init__(self, routing_grid: RoutingGrid, lib_name: str, prj: Optional[BagProject] = None, name_prefix: str = '', name_suffix: str = '') -> None: MasterDB.__init__(self, lib_name, prj=prj, name_prefix=name_prefix, name_suffix=name_suffix) self._grid = routing_grid self._tr_colors = make_tr_colors(self._grid.tech_info) @property def grid(self) -> RoutingGrid: """RoutingGrid: The global RoutingGrid instance.""" return self._grid @property def tech_info(self) -> TechInfo: return self._grid.tech_info @property def tr_colors(self) -> TrackColoring: return self._tr_colors def new_template(self, temp_cls: Type[TemplateType], params: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> TemplateType: """Alias for new_master() for backwards compatibility. """ return self.new_master(temp_cls, params=params, **kwargs) def instantiate_layout(self, template: TemplateBase, top_cell_name: str = '', output: DesignOutput = DesignOutput.LAYOUT, **kwargs: Any) -> None: """Alias for instantiate_master(), with default output type of LAYOUT. """ self.instantiate_master(output, template, top_cell_name, **kwargs) def batch_layout(self, info_list: Sequence[Tuple[TemplateBase, str]], output: DesignOutput = DesignOutput.LAYOUT, **kwargs: Any) -> None: """Alias for batch_output(), with default output type of LAYOUT. """ self.batch_output(output, info_list, **kwargs) def get_cap_via_extensions(info: MOMCapInfo, grid: RoutingGrid, bot_layer: int, top_layer: int) -> Dict[int, int]: via_ext_dict: Dict[int, int] = {lay: 0 for lay in range(bot_layer, top_layer + 1)} # get via extensions on each layer for lay0 in range(bot_layer, top_layer): lay1 = lay0 + 1 # port-to-port via extension bot_tr_w = info.get_port_tr_w(lay0) top_tr_w = info.get_port_tr_w(lay1) ext_pp = grid.get_via_extensions(Direction.LOWER, lay0, bot_tr_w, top_tr_w) w0, sp0, _, _ = info.get_cap_specs(lay0) w1, sp1, _, _ = info.get_cap_specs(lay1) # cap-to-cap via extension ext_cc = grid.get_via_extensions_dim(Direction.LOWER, lay0, w0, w1) # cap-to-port via extension ext_cp = grid.get_via_extensions_dim_tr(Direction.LOWER, lay0, w0, top_tr_w) # port-to-cap via extension ext_pc = grid.get_via_extensions_dim_tr(Direction.UPPER, lay1, w1, bot_tr_w) via_ext_dict[lay0] = max(via_ext_dict[lay0], ext_pp[0], ext_cc[0], ext_cp[0], ext_pc[0]) via_ext_dict[lay1] = max(via_ext_dict[lay1], ext_pp[1], ext_cc[1], ext_cp[1], ext_pc[1]) return via_ext_dict class TemplateBase(DesignMaster): """The base template class. Parameters ---------- temp_db : TemplateDB the template database. params : Param the parameter values. **kwargs : Any dictionary of the following optional parameters: grid : RoutingGrid the routing grid to use for this template. """ def __init__(self, temp_db: TemplateDB, params: Param, **kwargs: Any) -> None: # add hidden parameters DesignMaster.__init__(self, temp_db, params, **kwargs) # private attributes self._size: Optional[SizeType] = None self._ports: Dict[str, Port] = {} self._port_params: Dict[str, Dict[str, Any]] = {} self._array_box: Optional[BBox] = None self._fill_box: Optional[BBox] = None self._sch_params: Optional[Param] = None self._cell_boundary_added: bool = False self._instances: Dict[str, PyLayInstance] = {} self._use_color: bool = False # public attributes self.prim_top_layer: Optional[int] = None self.prim_bound_box: Optional[BBox] = None # get private attributes from parameters tmp_grid: RoutingGrid = self.params['grid'] if tmp_grid is None: self._grid: RoutingGrid = temp_db.grid else: self._grid: RoutingGrid = tmp_grid tmp_colors: TrackColoring = self.params['tr_colors'] if tmp_colors is None: self._tr_colors: TrackColoring = temp_db.tr_colors else: self._tr_colors: TrackColoring = tmp_colors self._show_pins: bool = self.params['show_pins'] self._edge_info: Optional[TemplateEdgeInfo] = None # create Cython wrapper object self._layout: PyLayCellView = PyLayCellView(self._grid, self._tr_colors, self.cell_name) @classmethod def get_hidden_params(cls) -> Dict[str, Any]: ans = DesignMaster.get_hidden_params() ans['grid'] = None ans['tr_colors'] = None ans['show_pins'] = True return ans @classmethod def get_schematic_class(cls) -> Optional[Type[Module]]: return None @abc.abstractmethod def draw_layout(self) -> None: """Draw the layout of this template. Override this method to create the layout. WARNING: you should never call this method yourself. """ pass def get_schematic_class_inst(self) -> Optional[Type[Module]]: return self.get_schematic_class() def get_master_basename(self) -> str: """Returns the base name to use for this instance. Returns ------- basename : str the base name for this instance. """ return self.get_layout_basename() def get_layout_basename(self) -> str: """Returns the base name for this template. Returns ------- base_name : str the base name of this template. """ return self.__class__.__name__ def get_content(self, output_type: DesignOutput, rename_dict: Dict[str, str], name_prefix: str, name_suffix: str, shell: bool, exact_cell_names: Set[str], supply_wrap_mode: SupplyWrapMode) -> Tuple[str, Any]: if not self.finalized: raise ValueError('This template is not finalized yet') cell_name = format_cell_name(self.cell_name, rename_dict, name_prefix, name_suffix, exact_cell_names, supply_wrap_mode) return cell_name, self._layout def finalize(self) -> None: """Finalize this master instance. """ # create layout self.draw_layout() # finalize this template grid = self.grid grid.tech_info.finalize_template(self) # construct port objects for net_name, port_params in self._port_params.items(): pin_dict = port_params['pins'] label = port_params['label'] hide = port_params['hide'] if port_params['show']: label = port_params['label'] for lay, geo_list in pin_dict.items(): if isinstance(lay, int): for warr in geo_list: self._layout.add_pin_arr(net_name, label, warr.track_id, warr.lower, warr.upper) else: for box in geo_list: self._layout.add_pin(lay, net_name, label, box) self._ports[net_name] = Port(net_name, pin_dict, label, hide) # call super finalize routine DesignMaster.finalize(self) @property def show_pins(self) -> bool: """bool: True to show pins.""" return self._show_pins @property def sch_params(self) -> Optional[Param]: """Optional[Dict[str, Any]]: The schematic parameters dictionary.""" return self._sch_params @sch_params.setter def sch_params(self, new_params: Dict[str, Any]) -> None: self._sch_params = ImmutableSortedDict(new_params) @property def template_db(self) -> TemplateDB: """TemplateDB: The template database object""" # noinspection PyTypeChecker return self.master_db @property def is_empty(self) -> bool: """bool: True if this template is empty.""" return self._layout.is_empty @property def grid(self) -> RoutingGrid: """RoutingGrid: The RoutingGrid object""" return self._grid @grid.setter def grid(self, new_grid: RoutingGrid) -> None: self._layout.set_grid(new_grid) self._grid = new_grid @property def tr_colors(self) -> TrackColoring: return self._tr_colors @property def array_box(self) -> Optional[BBox]: """Optional[BBox]: The array/abutment bounding box of this template.""" return self._array_box @array_box.setter def
<filename>hmc/transitions.py """Markov chain transition operators.""" import logging import numpy as np from hmc.utils import LogRepFloat from hmc.errors import ( IntegratorError, NonReversibleStepError, ConvergenceError) logger = logging.getLogger(__name__) class IndependentMomentumTransition(object): """Independent momentum transition. Independently resamples the momentum component of the state from its conditional distribution given the remaining state. """ def __init__(self, system): """ Args: system: Hamiltonian system to be simulated. """ self.system = system def sample(self, state, rng): state.mom = self.system.sample_momentum(state, rng) return state, None class CorrelatedMomentumTransition(object): """Correlated (partial) momentum transition. Rather than independently sampling a new momentum, instead a pertubative Crank-Nicolson type update which produces a new momentum value with a specified correlation with the previous value is used. It is assumed that the conditional distribution of the momenta is zero-mean Gaussian such that the Crank-Nicolson update leaves the momenta conditional distribution exactly invariant. This approach is sometimes known as partial momentum refreshing or updating, and was originally proposed in [1]. If the resampling coefficient is equal to zero then the momentum is not randomised at all and succesive applications of the coupled integration transitions will continue along the same simulated Hamiltonian trajectory. When an integration transition is accepted this means the subsequent simulated trajectory will continue evolving in the same direction and so not randomising the momentum will reduce random-walk behaviour. However on a rejection the integration direction is reversed and so without randomisation the trajectory will exactly backtrack along the previous tractory states. A resampling coefficient of one corresponds to the standard case of independent resampling of the momenta while intermediate values between zero and one correspond to varying levels of correlation between the pre and post update momentums. References: 1. <NAME>., 1991. A generalized guided Monte Carlo algorithm. Phys. Lett. B, 268(CERN-TH-6172-91), pp.247-252. """ def __init__(self, system, mom_resample_coeff=1.): self.system = system self.mom_resample_coeff = mom_resample_coeff def sample(self, state, rng): if self.mom_resample_coeff == 1: state.mom = self.system.sample_momentum(state, rng) elif self.mom_resample_coeff != 0: mom_ind = self.system.sample_momentum(state, rng) state.mom *= (1. - self.mom_resample_coeff**2)**0.5 state.mom += self.mom_resample_coeff * mom_ind return state, None class BaseIntegrationTransition(object): def __init__(self, system, integrator): """ Args: system: Hamiltonian system to be simulated. integrator: Symplectic integrator appropriate to the specified Hamiltonian system. """ self.system = system self.integrator = integrator self.statistic_types = { 'hamiltonian': (np.float64, np.nan), 'n_step': (np.int64, -1), 'accept_prob': (np.float64, np.nan), 'non_reversible_step': (np.bool, False), 'convergence_error': (np.bool, False) } class BaseMetropolisIntegrationTransition(BaseIntegrationTransition): """Base for HMC methods using a Metropolis accept step to sample new state. In each transition a trajectory is generated by integrating the Hamiltonian dynamics from the current state in the current integration time direction for a number of integrator steps. The state at the end of the trajectory with the integration direction negated (this ensuring the proposed move is an involution) is used as the proposal in a Metropolis acceptance step. The integration direction is then deterministically negated again irrespective of the accept decision, with the effect being that on acceptance the integration direction will be equal to its initial value and on rejection the integration direction will be the negation of its initial value. """ def _sample_n_step(self, state, n_step, rng): h_init = self.system.h(state) state_p = state try: for s in range(n_step): state_p = self.integrator.step(state_p) except IntegratorError as e: logger.info( f'Terminating trajectory due to integrator error:\n{e!s}') return state, { 'hamiltonian': h_init, 'accept_prob': 0, 'n_step': s, 'non_reversible_step': isinstance(e, NonReversibleStepError), 'convergence_error': isinstance(e, ConvergenceError)} state_p.dir *= -1 h_final = self.system.h(state_p) h_final = np.inf if np.isnan(h_final) else h_final accept_prob = min(1, np.exp(h_init - h_final)) if rng.uniform() < accept_prob: state = state_p state.dir *= -1 stats = {'hamiltonian': self.system.h(state), 'accept_prob': accept_prob, 'n_step': n_step, 'non_reversible_step': False, 'convergence_error': False} return state, stats class MetropolisStaticIntegrationTransition( BaseMetropolisIntegrationTransition): """Static integration transition with Metropolis sampling of new state. In this variant the trajectory is generated by integrating the state through time a fixed number of integrator steps. This is original proposed Hybrid Monte Carlo (often now instead termed Hamiltonian Monte Carlo) algorithm [1,2]. References: 1. <NAME>., <NAME>., <NAME>. and <NAME>., 1987. Hybrid Monte Carlo. Physics letters B, 195(2), pp.216-222. 2. <NAME>., 2011. MCMC using Hamiltonian dynamics. Handbook of Markov Chain Monte Carlo, 2(11), p.2. """ def __init__(self, system, integrator, n_step): super().__init__(system, integrator) self.n_step = n_step def sample(self, state, rng): return self._sample_n_step(state, self.n_step, rng) class MetropolisRandomIntegrationTransition( BaseMetropolisIntegrationTransition): """Random integration transition with Metropolis sampling of new state. In each transition a trajectory is generated by integrating the state in the current integration direction in time a random integer number of integrator steps sampled from the uniform distribution on an integer interval. The randomisation of the number of integration steps avoids the potential of the chain mixing poorly due to using an integration time close to the period of (near) periodic systems [1,2]. References: 1. <NAME>., 2011. MCMC using Hamiltonian dynamics. Handbook of Markov Chain Monte Carlo, 2(11), p.2. 2. <NAME>., 1989. An improved hybrid Monte Carlo method. Physics Letters B, 226(3-4), pp.369-371. """ def __init__(self, system, integrator, n_step_range): super().__init__(system, integrator) n_step_lower, n_step_upper = n_step_range assert n_step_lower > 0 and n_step_lower < n_step_upper self.n_step_range = n_step_range def sample(self, state, rng): n_step = rng.random_integers(*self.n_step_range) return self._sample_n_step(state, n_step, rng) def euclidean_no_u_turn_criterion(system, state_1, state_2, sum_mom): """No-U-turn termination criterion for Euclidean manifolds [1]. Terminates trajectories when the velocities at the terminal states of the trajectory both have negative dot products with the vector from the position of the first terminal state to the position of the second terminal state, corresponding to further evolution of the trajectory reducing the distance between the terminal state positions. Args: system (HamiltonianSystem): Hamiltonian system being integrated. state_1 (HamiltonianState): First terminal state of trajectory. state_2 (HamiltonianState): Second terminal state of trajectory. sum_mom (array): Sum of momentums of trajectory states. Returns: True if termination criterion is satisfied. References: 1. <NAME>. and <NAME>., 2014. The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(1), pp.1593-1623. """ return ( np.sum(system.dh_dmom(state_1) * (state_2.pos - state_1.pos)) < 0 or np.sum(system.dh_dmom(state_2) * (state_2.pos - state_1.pos)) < 0) def riemannian_no_u_turn_criterion(system, state_1, state_2, sum_mom): """Generalised no-U-turn termination criterion on Riemannian manifolds [2]. Terminates trajectories when the velocities at the terminal states of the trajectory both have negative dot products with the sum of the the momentums across the trajectory from the first to second terminal state of the first terminal state to the position of the second terminal state. This generalises the no-U-turn criterion of [1] to Riemannian manifolds where due to the intrinsic curvature of the space the geodesic between two points is general no longer a straight line. Args: system (HamiltonianSystem): Hamiltonian system being integrated. state_1 (HamiltonianState): First terminal state of trajectory. state_2 (HamiltonianState): Second terminal state of trajectory. sum_mom (array): Sum of momentums of trajectory states. Returns: True if termination criterion is satisfied. References: 1. <NAME>. and <NAME>., 2014. The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(1), pp.1593-1623. 2. <NAME>., 2013. Generalizing the no-U-turn sampler to Riemannian manifolds. arXiv preprint arXiv:1304.1920. """ return ( np.sum(system.dh_dmom(state_1) * sum_mom) < 0 or np.sum(system.dh_dmom(state_2) * sum_mom) < 0) class MultinomialDynamicIntegrationTransition(BaseIntegrationTransition): """Dynamic integration transition with multinomial sampling of new state. In each transition a binary tree of states is recursively computed by integrating randomly forward and backward in time by a number of steps equal to the previous tree size [1,2] until a termination criteria on the tree leaves is met. The next chain state is chosen from the candidate states using a progressive multinomial sampling scheme [2] based on the relative probability densities of the different candidate states, with the resampling biased towards states further from the current state. References: 1. <NAME>. and <NAME>., 2014. The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(1), pp.1593-1623. 2. <NAME>., 2017. A conceptual introduction to Hamiltonian Monte Carlo. arXiv preprint arXiv:1701.02434. """ def __init__(self, system, integrator, max_tree_depth=10, max_delta_h=1000, termination_criterion=riemannian_no_u_turn_criterion): super().__init__(system, integrator) self.max_tree_depth = max_tree_depth self.max_delta_h = max_delta_h self._termination_criterion = termination_criterion self.statistic_types['tree_depth'] = (np.int64, -1) self.statistic_types['diverging']
<reponame>datajoely/kedro # Copyright 2021 QuantumBlack Visual Analytics Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND # NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS # BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo # (either separately or in combination, "QuantumBlack Trademarks") are # trademarks of QuantumBlack. The License does not grant you any right or # license to the QuantumBlack Trademarks. You may not use the QuantumBlack # Trademarks or any confusingly similar mark as a trademark for your product, # or use the QuantumBlack Trademarks in any other manner that might cause # confusion in the marketplace, including but not limited to in advertising, # on websites, or on software. # # See the License for the specific language governing permissions and # limitations under the License. import re from functools import wraps from itertools import chain from typing import Callable import pytest import kedro from kedro.io import DataCatalog from kedro.pipeline import Pipeline, node from kedro.pipeline.pipeline import ( CircularDependencyError, ConfirmNotUniqueError, OutputNotUniqueError, _strip_transcoding, _transcode_split, ) from kedro.runner import SequentialRunner class TestTranscodeHelpers: def test_split_no_transcode_part(self): assert _transcode_split("abc") == ("abc", "") def test_split_with_transcode(self): assert _transcode_split("abc@def") == ("abc", "def") def test_split_too_many_parts(self): with pytest.raises(ValueError): _transcode_split("abc@def@ghi") def test_get_transcode_compatible_name(self): assert _strip_transcoding("abc@def") == "abc" # Different dummy func based on the number of arguments def constant_output(): return "output" # pragma: no cover def identity(input1: str): return input1 # pragma: no cover def biconcat(input1: str, input2: str): return input1 + input2 # pragma: no cover def triconcat(input1: str, input2: str, input3: str): return input1 + input2 + input3 # pragma: no cover @pytest.fixture def branchless_pipeline(): return { "nodes": [ node(identity, "E", None), node(identity, "D", "E"), node(identity, "C", "D"), node(identity, "A", "B"), node(identity, "B", "C"), node(constant_output, None, "A"), ], "expected": [ {node(constant_output, None, "A")}, {node(identity, "A", "B")}, {node(identity, "B", "C")}, {node(identity, "C", "D")}, {node(identity, "D", "E")}, {node(identity, "E", None)}, ], "free_inputs": [], "outputs": [], } @pytest.fixture def pipeline_list_with_lists(): return { "nodes": [ node(triconcat, ["H", "I", "M"], "N", name="node1"), node(identity, "H", "I", name="node2"), node(identity, "F", ["G", "M"], name="node3"), node(identity, "E", ["F", "H"], name="node4"), node(identity, "D", None, name="node5"), node(identity, "C", "D", name="node6"), node(identity, "B", ["C", "E"], name="node7"), node(identity, "A", ["B", "L"], name="node8"), node(constant_output, None, "A", name="node9"), ], "expected": [ {node(constant_output, None, "A", name="node9")}, {node(identity, "A", ["B", "L"], name="node8")}, {node(identity, "B", ["C", "E"], name="node7")}, { node(identity, "C", "D", name="node6"), node(identity, "E", ["F", "H"], name="node4"), }, { node(identity, "D", None, name="node5"), node(identity, "H", "I", name="node2"), node(identity, "F", ["G", "M"], name="node3"), }, {node(triconcat, ["H", "I", "M"], "N", name="node1")}, ], "free_inputs": [], "outputs": ["L", "G", "N"], } @pytest.fixture def pipeline_with_dicts(): return { "nodes": [ node(triconcat, ["H", "I", "M"], "N", name="node1"), node(identity, "H", "I", name="node2"), node(identity, "F", dict(M="M", N="G"), name="node3"), node(identity, "E", dict(O="F", P="H"), name="node4"), # NOQA node(identity, dict(input1="D"), None, name="node5"), node(identity, "C", "D", name="node6"), node(identity, "B", dict(P="C", Q="E"), name="node7"), node(identity, "A", dict(R="B", S="L"), name="node8"), node(constant_output, None, "A", name="node9"), ], "expected": [ {node(constant_output, None, "A", name="node9")}, {node(identity, "A", dict(R="B", S="L"), name="node8")}, {node(identity, "B", dict(P="C", Q="E"), name="node7")}, { node(identity, "C", "D", name="node6"), node(identity, "E", dict(O="F", P="H"), name="node4"), # NOQA }, { node(identity, dict(input1="D"), None, name="node5"), node(identity, "H", "I", name="node2"), node(identity, "F", dict(M="M", N="G"), name="node3"), }, {node(triconcat, ["H", "I", "M"], "N", name="node1")}, ], "free_inputs": [], "outputs": ["L", "G", "N"], } @pytest.fixture def free_input_needed_pipeline(): return { "nodes": [ node(identity, "A", "B", name="node1"), # 'A' needs to be free node(identity, "B", "C", name="node2"), node(identity, "C", "D", name="node3"), ], "expected": [ {node(identity, "A", "B", name="node1")}, {node(identity, "B", "C", name="node2")}, {node(identity, "C", "D", name="node3")}, ], "free_inputs": ["A"], "outputs": ["D"], } @pytest.fixture def disjoint_pipeline(): # Two separate pipelines: A->B->C and D->E->F return { "nodes": [ node(identity, "A", "B", name="node1"), node(identity, "B", "C", name="node2"), node(identity, "E", "F", name="node3"), # disjoint part D->E->F node(identity, "D", "E", name="node4"), ], "expected": [ { node(identity, "A", "B", name="node1"), node(identity, "D", "E", name="node4"), }, { node(identity, "B", "C", name="node2"), node(identity, "E", "F", name="node3"), }, ], "free_inputs": ["A", "D"], "outputs": ["C", "F"], } @pytest.fixture def pipeline_input_duplicated(): return { "nodes": [ node(biconcat, ["A", "A"], "B", name="node1"), # input duplicate node(identity, "B", "C", name="node2"), node(identity, "C", "D", name="node3"), ], "expected": [ {node(biconcat, ["A", "A"], "B", name="node1")}, {node(identity, "B", "C", name="node2")}, {node(identity, "C", "D", name="node3")}, ], "free_inputs": ["A"], "outputs": ["D"], } @pytest.fixture def str_node_inputs_list(): return { "nodes": [ node(biconcat, ["input1", "input2"], ["input3"], name="node1"), node(identity, "input3", "input4", name="node2"), ], "expected": [ {node(biconcat, ["input1", "input2"], ["input3"], name="node1")}, {node(identity, "input3", "input4", name="node2")}, ], "free_inputs": ["input1", "input2"], "outputs": ["input4"], } @pytest.fixture( params=[ "branchless_pipeline", "pipeline_list_with_lists", "pipeline_with_dicts", "free_input_needed_pipeline", "disjoint_pipeline", "pipeline_input_duplicated", "str_node_inputs_list", ] ) def input_data(request): return request.getfixturevalue(request.param) class TestValidPipeline: def test_nodes(self, str_node_inputs_list): nodes = str_node_inputs_list["nodes"] pipeline = Pipeline(nodes) assert set(pipeline.nodes) == set(nodes) def test_grouped_nodes(self, input_data): """Check if grouped_nodes func groups the nodes correctly""" nodes_input = input_data["nodes"] expected = input_data["expected"] pipeline = Pipeline(nodes_input) grouped = pipeline.grouped_nodes # Flatten a list of grouped nodes assert pipeline.nodes == list(chain.from_iterable(grouped)) # Check each grouped node matches with expected group assert all(g == e for g, e in zip(grouped, expected)) @pytest.mark.parametrize( "target_node_names", [["node2", "node3", "node4", "node8"], ["node1"]] ) def test_only_nodes(self, target_node_names, pipeline_list_with_lists): full = Pipeline(pipeline_list_with_lists["nodes"]) partial = full.only_nodes(*target_node_names) target_list = list(target_node_names) names = map(lambda node_: node_.name, partial.nodes) assert sorted(names) == sorted(target_list) @pytest.mark.parametrize( "target_namespace,expected_namespaces", [ ("katie", ["katie", "katie.lisa", "katie.lisa.john"]), ("lisa", ["lisa", "lisa.john"]), ("john", ["john"]), ("katie.lisa", ["katie.lisa", "katie.lisa.john"]), ("katie.lisa.john", ["katie.lisa.john"]), ], ) def test_only_nodes_with_namespace(self, target_namespace, expected_namespaces): pipeline = Pipeline( [ node(identity, "A", "B", namespace="katie"), node(identity, "B", "C", namespace="lisa"), node(identity, "C", "D", namespace="john"), node(identity, "D", "E", namespace="katie.lisa"), node(identity, "E", "F", namespace="lisa.john"), node(identity, "F", "G", namespace="katie.lisa.john"), ] ) resulting_pipeline = pipeline.only_nodes_with_namespace(target_namespace) for actual_node, expected_namespace in zip( sorted(resulting_pipeline.nodes), expected_namespaces ): assert actual_node.namespace == expected_namespace def test_free_input(self, input_data): nodes = input_data["nodes"] inputs = input_data["free_inputs"] pipeline = Pipeline(nodes) assert pipeline.inputs() == set(inputs) def test_outputs(self, input_data): nodes = input_data["nodes"] outputs = input_data["outputs"] pipeline = Pipeline(nodes) assert pipeline.outputs() == set(outputs) def test_combine_add(self): pipeline1 = Pipeline([node(biconcat, ["input", "input1"], "output1", name="a")]) pipeline2 = Pipeline([node(biconcat, ["input", "input2"], "output2", name="b")]) new_pipeline = pipeline1 + pipeline2 assert new_pipeline.inputs() == {"input", "input1", "input2"} assert new_pipeline.outputs() == {"output1", "output2"} assert {n.name for n in new_pipeline.nodes} == {"a", "b"} def test_combine_sum(self): pipeline1 = Pipeline([node(biconcat, ["input", "input1"], "output1", name="a")]) pipeline2 = Pipeline([node(biconcat, ["input", "input2"], "output2", name="b")]) new_pipeline = sum([pipeline1, pipeline2]) assert new_pipeline.inputs() == {"input", "input1", "input2"} assert new_pipeline.outputs() == {"output1", "output2"} assert {n.name for n in new_pipeline.nodes} == {"a", "b"} def test_remove(self): """Create a pipeline of 3 nodes and remove one of them""" pipeline1 = Pipeline( [ node(biconcat, ["input", "input1"], "output1", name="a"), node(biconcat, ["input", "input2"], "output2", name="b"), node(biconcat, ["input", "input3"], "output3", name="c"), ] ) pipeline2 = Pipeline([node(biconcat, ["input", "input2"], "output2", name="b")]) new_pipeline = pipeline1 - pipeline2 assert new_pipeline.inputs() == {"input", "input1", "input3"} assert new_pipeline.outputs() == {"output1", "output3"} assert {n.name for n in new_pipeline.nodes} == {"a", "c"} def test_remove_with_partial_intersection(self): """Create a pipeline of 3 nodes and remove one of them using a pipeline that contains a partial match. """ pipeline1 = Pipeline( [ node(biconcat, ["input", "input1"], "output1", name="a"), node(biconcat, ["input", "input2"], "output2", name="b"), node(biconcat, ["input", "input3"], "output3", name="c"), ] ) pipeline2 = Pipeline( [ node(biconcat, ["input", "input2"], "output2", name="b"), node(biconcat, ["input", "input4"], "output4", name="d"), ] ) new_pipeline = pipeline1 - pipeline2 assert new_pipeline.inputs() == {"input", "input1", "input3"} assert new_pipeline.outputs() == {"output1", "output3"} assert {n.name for n in new_pipeline.nodes} == {"a", "c"} def test_remove_empty_from_pipeline(self): """Remove an empty pipeline""" pipeline1 = Pipeline([node(biconcat, ["input", "input1"], "output1", name="a")]) pipeline2 = Pipeline([]) new_pipeline = pipeline1 - pipeline2 assert new_pipeline.inputs() == pipeline1.inputs() assert new_pipeline.outputs() == pipeline1.outputs() assert {n.name for n in new_pipeline.nodes} == {"a"} def test_remove_from_empty_pipeline(self): """Remove node from an empty pipeline""" pipeline1 = Pipeline([node(biconcat, ["input", "input1"], "output1", name="a")]) pipeline2 = Pipeline([]) new_pipeline = pipeline2 - pipeline1 assert new_pipeline.inputs() == pipeline2.inputs() assert new_pipeline.outputs() == pipeline2.outputs() assert not new_pipeline.nodes def test_remove_all_nodes(self): """Remove an entire pipeline""" pipeline1
<reponame>dingcycle/depc import pytest from depc.controllers.dependencies import DependenciesController class NodeMock: def __init__(self, node_data_dict): self._id = node_data_dict.get("id", 0) self._labels = node_data_dict.get("labels", {}) self._properties = node_data_dict.get("properties", {}) def __eq__(self, other): try: return type(self) == type(other) and self.id == other.id except AttributeError: return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.id) def __len__(self): return len(self._properties) def __getitem__(self, name): return self._properties.get(name) def __contains__(self, name): return name in self._properties def __iter__(self): return iter(self._properties) def __repr__(self): return "<Node id=%r labels=%r properties=%r>" % (self._id, self._labels, self._properties) @property def id(self): """ The identity of this entity in its container :class:`.Graph`. """ return self._id @property def labels(self): return frozenset(self._labels) def _update(self, properties, **kwproperties): properties = dict(properties or {}, **kwproperties) self._properties.update((k, v) for k, v in properties.items() if v is not None) def get(self, name, default=None): """ Get a property value by name, optionally with a default. """ return self._properties.get(name, default) def keys(self): """ Return an iterable of all property names. """ return self._properties.keys() def values(self): """ Return an iterable of all property values. """ return self._properties.values() def items(self): """ Return an iterable of all property name-value pairs. """ return self._properties.items() class RelationshipMock: def __init__(self, relationship_data_dict, start_node, end_node): self._id = relationship_data_dict.get("id", 0) self._start_node = start_node self._end_node = end_node self._type = relationship_data_dict.get("type", "") self._properties = relationship_data_dict.get("properties", {}) def __eq__(self, other): try: return type(self) == type(other) and self.id == other.id except AttributeError: return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.id) def __len__(self): return len(self._properties) def __getitem__(self, name): return self._properties.get(name) def __contains__(self, name): return name in self._properties def __iter__(self): return iter(self._properties) def __repr__(self): return "<Relationship id=%r nodes=(%r, %r) type=%r properties=%r>" % ( self._id, self._start_node, self._end_node, self.type, self._properties) @property def id(self): """ The identity of this entity in its container :class:`.Graph`. """ return self._id @property def nodes(self): return self._start_node, self._end_node @property def start_node(self): return self._start_node @property def end_node(self): return self._end_node @property def type(self): return type(self).__name__ def _update(self, properties, **kwproperties): properties = dict(properties or {}, **kwproperties) self._properties.update((k, v) for k, v in properties.items() if v is not None) def get(self, name, default=None): """ Get a property value by name, optionally with a default. """ return self._properties.get(name, default) def keys(self): """ Return an iterable of all property names. """ return self._properties.keys() def values(self): """ Return an iterable of all property values. """ return self._properties.values() def items(self): """ Return an iterable of all property name-value pairs. """ return self._properties.items() offer01_data_dict = { "labels": {'acme_Offer'}, "properties": {'from': 1566338400, 'name': 'offer01'} } offer01_node = NodeMock(offer01_data_dict) website01_data_dict = { "labels": {'acme_Website'}, "properties": {'from': 1566424800, 'name': 'website01'} } website01_node = NodeMock(website01_data_dict) website02_data_dict = { "labels": {'acme_Website'}, "properties": {'from': 1566079200, 'name': 'website02'} } website02_node = NodeMock(website02_data_dict) website03_data_dict = { "labels": {'acme_Website'}, "properties": {'from': 1566079200, 'name': 'website03'} } website03_node = NodeMock(website03_data_dict) server02_data_dict = { "labels": {'acme_Server'}, "properties": {'from': 1566079200, 'name': 'server02'} } server02_node = NodeMock(server02_data_dict) rel_web1_ser2_data_dict = { "type": "DEPENDS_ON", "properties": {'periods': [1566165600, 1566252000, 1566338400]} } rel_web1_ser2_relationship = RelationshipMock(rel_web1_ser2_data_dict, website01_node, server02_node) rel_web2_ser2_data_dict = { "type": "DEPENDS_ON", "properties": {'periods': [1566165600, 1566252000]} } rel_web2_ser2_relationship = RelationshipMock(rel_web2_ser2_data_dict, website02_node, server02_node) rel_web3_ser2_data_dict = { "type": "DEPENDS_ON", "properties": {'periods': [1566338400]} } rel_web3_ser2_relationship = RelationshipMock(rel_web3_ser2_data_dict, website03_node, server02_node) rel_off1_web1_data_dict = { "type": "DEPENDS_ON", "properties": {'periods': [1566338400]} } rel_off1_web1_relationship = RelationshipMock(rel_off1_web1_data_dict, offer01_node, website01_node) rel_off1_web2_data_dict = { "type": "DEPENDS_ON", "properties": {'periods': [1566165600, 1566252000]} } rel_off1_web2_relationship = RelationshipMock(rel_off1_web2_data_dict, offer01_node, website02_node) rel_off1_web3_data_dict = { "type": "DEPENDS_ON", "properties": {'periods': [1566165600, 1566252000, 1566338400]} } rel_off1_web3_relationship = RelationshipMock(rel_off1_web3_data_dict, offer01_node, website03_node) impacted_node_multiple_paths_elements = [ { "nodes": [offer01_node, website03_node, server02_node], "relationships": [rel_off1_web3_relationship, rel_web3_ser2_relationship] }, { "nodes": [offer01_node, website01_node, server02_node], "relationships": [rel_off1_web1_relationship, rel_web1_ser2_relationship] }, { "nodes": [offer01_node, website02_node, server02_node], "relationships": [rel_off1_web2_relationship, rel_web2_ser2_data_dict] } ] impacted_node_data = { "impacted_node": offer01_node, "all_path_elements": impacted_node_multiple_paths_elements } impacted_websites_by_server02 = [ { "impacted_node": website01_node, "all_path_elements": [ { "nodes": [website01_node, server02_node], "relationships": [rel_web1_ser2_relationship] } ] }, { "impacted_node": website02_node, "all_path_elements": [ { "nodes": [website02_node, server02_node], "relationships": [rel_web2_ser2_relationship] } ] }, { "impacted_node": website03_node, "all_path_elements": [ { "nodes": [website03_node, server02_node], "relationships": [rel_web3_ser2_relationship] } ] } ] def test_build_dependencies_query_without_config(app, create_team, create_rule, create_config): team_id = str(create_team('My team')['id']) with app.app_context(): query = DependenciesController()._build_dependencies_query( team_id=team_id, topic='acme', label='Server', node='server.ovh.net', filter_on_config=False ) assert query == ("MATCH(n:acme_Server{name: 'server.ovh.net'}) " "OPTIONAL MATCH (n)-[r]->(m) " "RETURN n,r,m ORDER BY m.name LIMIT 10") def test_build_dependencies_query_rule(app, create_team, create_rule, create_config): team_id = str(create_team('My team')['id']) create_rule('Servers', team_id) create_config(team_id, { 'Server': {'qos': 'rule.Servers'} }) with app.app_context(): query = DependenciesController()._build_dependencies_query( team_id=team_id, topic='acme', label='Server', node='server.ovh.net', filter_on_config=True ) assert query == ("MATCH(n:acme_Server{name: 'server.ovh.net'}) " "OPTIONAL MATCH (n)-[r]->(m) " "RETURN n,r,m ORDER BY m.name LIMIT 10") def test_build_dependencies_query_with_impacted_nodes(app, create_team, create_rule, create_config): team_id = str(create_team('My team')['id']) create_rule('Servers', team_id) create_config(team_id, { 'Server': {'qos': 'rule.Servers'} }) with app.app_context(): query = DependenciesController()._build_dependencies_query( team_id=team_id, topic='acme', label='Server', node='server.ovh.net', filter_on_config=True, impacted=True ) assert query == ("MATCH(n:acme_Server{name: 'server.ovh.net'}) " "OPTIONAL MATCH (n)<-[r]-(m) " "RETURN n,r,m ORDER BY m.name LIMIT 10") @pytest.mark.parametrize("method", [("operation"), ("aggregation")]) def test_build_dependencies_query_one_dep(method, app, create_team, create_rule, create_config): team_id = str(create_team('My team')['id']) create_rule('Servers', team_id) create_config(team_id, { 'Server': {'qos': 'rule.Servers'}, 'Cluster': {'qos': '{0}.AND[Server]'.format(method)} }) with app.app_context(): query = DependenciesController()._build_dependencies_query( team_id=team_id, topic='acme', label='Cluster', node='cluster.ovh.net', filter_on_config=True ) assert query == ("MATCH(n:acme_Cluster{name: 'cluster.ovh.net'}) " "OPTIONAL MATCH (n)-[r]->(m) " "WHERE 'acme_Server' IN LABELS(m) " "RETURN n,r,m ORDER BY m.name LIMIT 10") @pytest.mark.parametrize("method", [("operation"), ("aggregation")]) def test_build_dependencies_query_multiple_deps(method, app, create_team, create_rule, create_config): team_id = str(create_team('My team')['id']) create_rule('Servers', team_id) create_config(team_id, { 'ServerA': {'qos': 'rule.Servers'}, 'ServerB': {'qos': 'rule.Servers'}, 'Cluster': {'qos': '{0}.AND[ServerA, ServerB]'.format(method)} }) with app.app_context(): query = DependenciesController()._build_dependencies_query( team_id=team_id, topic='acme', label='Cluster', node='cluster.ovh.net', filter_on_config=True ) assert query == ("MATCH(n:acme_Cluster{name: 'cluster.ovh.net'}) " "OPTIONAL MATCH (n)-[r]->(m) " "WHERE 'acme_ServerA' IN LABELS(m) " "OR 'acme_ServerB' IN LABELS(m) " "RETURN n,r,m ORDER BY m.name LIMIT 10") def test_build_query_count_nodes(app): with app.app_context(): query = DependenciesController()._build_query_count_nodes( topic='acme', labels=['Foo'] ) assert query == ( "MATCH (n:acme_Foo) WITH 'Foo' AS Label, count(n) AS Count " "RETURN Label, Count " ) with app.app_context(): query = DependenciesController()._build_query_count_nodes( topic='acme', labels=['Foo', 'Bar', 'Baz'] ) assert query == ( "MATCH (n:acme_Foo) WITH 'Foo' AS Label, count(n) AS Count " "RETURN Label, Count " "UNION MATCH (n:acme_Bar) WITH 'Bar' AS Label, count(n) AS Count " "RETURN Label, Count " "UNION MATCH (n:acme_Baz) WITH 'Baz' AS Label, count(n) AS Count " "RETURN Label, Count " ) def test_build_query_nodes(app): with app.app_context(): query = DependenciesController()._build_query_nodes( topic='acme', label='Foo' ) assert query == "MATCH (n:acme_Foo) WITH n RETURN n.name" with app.app_context(): query = DependenciesController()._build_query_nodes( topic='acme', label='Foo', random=True ) assert query == ( "MATCH (n:acme_Foo) WITH n" ", rand() as r ORDER BY r " "RETURN n.name" ) with app.app_context(): query = DependenciesController()._build_query_nodes( topic='acme', label='Foo', random=True, name="bar" ) assert query == ( "MATCH (n:acme_Foo) WITH n" ", rand() as r ORDER BY r " "WHERE n.name CONTAINS 'bar' " "RETURN n.name" ) with app.app_context(): query = DependenciesController()._build_query_nodes( topic='acme', label='Foo', random=True, name="bar", limit=1234 ) assert query == ( "MATCH (n:acme_Foo) WITH n" ", rand() as r ORDER BY r " "WHERE n.name CONTAINS 'bar' " "RETURN n.name " "LIMIT 1234" ) def test_build_impacted_nodes_queries(app): with app.app_context(): query = DependenciesController()._build_impacted_nodes_queries( topic="acme", label="Server", node="server02", impacted_label="Website", skip=0, limit=25, count=False ) assert query == "MATCH p = (n:acme_Website)-[*]->(:acme_Server{name: 'server02'}) " \ "WITH *, relationships(p) AS r_list WITH *, nodes(p) AS n_sub_list RETURN DISTINCT n " \ "AS impacted_node, collect({ relationships: r_list, nodes: n_sub_list }) " \ "AS all_path_elements ORDER BY n.name SKIP 0 LIMIT 25" with app.app_context(): query = DependenciesController()._build_impacted_nodes_queries( topic="acme", label="Server", node="server02", impacted_label="Website", count=True ) assert query == "MATCH (n:acme_Website)-[*]->(:acme_Server{name: 'server02'}) " \ "RETURN count(DISTINCT n) AS count" def test_are_path_elements_all_active(app): path_elements_mock_ko_invalid_node = { "nodes": [website01_node, server02_node], "relationships": [rel_web1_ser2_relationship] } path_elements_mock_ko_invalid_rel = { "nodes": [website02_node, server02_node], "relationships": [rel_web2_ser2_relationship] } path_elements_mock_ok = { "nodes": [website03_node, server02_node], "relationships": [rel_web3_ser2_relationship] } with app.app_context(): bool_result = DependenciesController._are_path_elements_all_active( path_elements_mock_ko_invalid_node, 1566338400 ) assert bool_result is False with app.app_context(): bool_result = DependenciesController._are_path_elements_all_active( path_elements_mock_ko_invalid_rel, 1566338400 ) assert bool_result is False with app.app_context(): bool_result = DependenciesController._are_path_elements_all_active( path_elements_mock_ok, 1566338400 ) assert bool_result is True def test_is_impacted_node_active(app): with app.app_context(): bool_result = DependenciesController._is_impacted_node_active(impacted_node_data, 1566424800) assert bool_result is True with app.app_context(): bool_result = DependenciesController._is_impacted_node_active(impacted_node_data, 1566252000) assert bool_result is False def test_compute_impacted_nodes_from_data(app): with app.app_context(): computed_impacted_nodes = DependenciesController._compute_impacted_nodes_from_data( impacted_websites_by_server02, 1566424800, True ) assert computed_impacted_nodes == [ {'active': True, 'name': 'website01', 'to': None, 'from': 1566424800}, {'active': False, 'name': 'website02', 'to': None, 'from': 1566079200}, {'active': True, 'name': 'website03', 'to': None, 'from': 1566079200} ] with app.app_context(): computed_impacted_nodes = DependenciesController._compute_impacted_nodes_from_data( impacted_websites_by_server02, 1566338400, True ) assert computed_impacted_nodes == [ {'active': False, 'name': 'website01', 'to': None, 'from': 1566424800}, {'active': False, 'name': 'website02', 'to': None, 'from': 1566079200}, {'active': True, 'name': 'website03', 'to': None,
>>> array[where] = np.arange(len(where[0])) + 1 >>> array array([[0, 0, 0, 0, 0], [1, 2, 0, 0, 0], [0, 0, 3, 4, 0], [0, 0, 0, 0, 5], [0, 0, 0, 0, 0]]...) .. versionadded:: 4.6 """ length = max(abs(x1 - x2), abs(y1 - y2)) + 1 array = np.ndarray((2, length), dtype=np.intc) x = ffi.cast("int*", array[0].ctypes.data) y = ffi.cast("int*", array[1].ctypes.data) lib.LineWhere(x1, y1, x2, y2, x, y) if not inclusive: array = array[:, 1:] return tuple(array) # type: ignore @deprecate("Call tcod.map.Map(width, height) instead.") def map_new(w: int, h: int) -> tcod.map.Map: """Return a :any:`tcod.map.Map` with a width and height. .. deprecated:: 4.5 Use the :any:`tcod.map` module for working with field-of-view, or :any:`tcod.path` for working with path-finding. """ return tcod.map.Map(w, h) @deprecate("Use Python's standard copy module instead.") def map_copy(source: tcod.map.Map, dest: tcod.map.Map) -> None: """Copy map data from `source` to `dest`. .. deprecated:: 4.5 Use Python's copy module, or see :any:`tcod.map.Map` and assign between array attributes manually. """ if source.width != dest.width or source.height != dest.height: dest.__init__( # type: ignore source.width, source.height, source._order ) dest._Map__buffer[:] = source._Map__buffer[:] # type: ignore @deprecate("Set properties using the m.transparent and m.walkable arrays.") def map_set_properties( m: tcod.map.Map, x: int, y: int, isTrans: bool, isWalk: bool ) -> None: """Set the properties of a single cell. .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.transparent` and :any:`tcod.map.Map.walkable` arrays to set these properties. """ lib.TCOD_map_set_properties(m.map_c, x, y, isTrans, isWalk) @deprecate("Clear maps using NumPy broadcast rules instead.") def map_clear( m: tcod.map.Map, transparent: bool = False, walkable: bool = False ) -> None: """Change all map cells to a specific value. .. deprecated:: 4.5 Use :any:`tcod.map.Map.transparent` and :any:`tcod.map.Map.walkable` arrays to set these properties. """ m.transparent[:] = transparent m.walkable[:] = walkable @deprecate("Call the map.compute_fov method instead.") def map_compute_fov( m: tcod.map.Map, x: int, y: int, radius: int = 0, light_walls: bool = True, algo: int = FOV_RESTRICTIVE, ) -> None: """Compute the field-of-view for a map instance. .. deprecated:: 4.5 Use :any:`tcod.map.Map.compute_fov` instead. """ m.compute_fov(x, y, radius, light_walls, algo) @deprecate("Use map.fov to check for this property.") def map_is_in_fov(m: tcod.map.Map, x: int, y: int) -> bool: """Return True if the cell at x,y is lit by the last field-of-view algorithm. .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.fov` to check this property. """ return bool(lib.TCOD_map_is_in_fov(m.map_c, x, y)) @deprecate("Use map.transparent to check for this property.") def map_is_transparent(m: tcod.map.Map, x: int, y: int) -> bool: """ .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.transparent` to check this property. """ return bool(lib.TCOD_map_is_transparent(m.map_c, x, y)) @deprecate("Use map.walkable to check for this property.") def map_is_walkable(m: tcod.map.Map, x: int, y: int) -> bool: """ .. note:: This function is slow. .. deprecated:: 4.5 Use :any:`tcod.map.Map.walkable` to check this property. """ return bool(lib.TCOD_map_is_walkable(m.map_c, x, y)) @deprecate("libtcod objects are deleted automatically.") def map_delete(m: tcod.map.Map) -> None: """Does nothing. libtcod objects are managed by Python's garbage collector. This function exists for backwards compatibility with libtcodpy. """ @deprecate("Check the map.width attribute instead.") def map_get_width(map: tcod.map.Map) -> int: """Return the width of a map. .. deprecated:: 4.5 Check the :any:`tcod.map.Map.width` attribute instead. """ return map.width @deprecate("Check the map.height attribute instead.") def map_get_height(map: tcod.map.Map) -> int: """Return the height of a map. .. deprecated:: 4.5 Check the :any:`tcod.map.Map.height` attribute instead. """ return map.height @pending_deprecate() def mouse_show_cursor(visible: bool) -> None: """Change the visibility of the mouse cursor.""" lib.TCOD_mouse_show_cursor(visible) @pending_deprecate() def mouse_is_cursor_visible() -> bool: """Return True if the mouse cursor is visible.""" return bool(lib.TCOD_mouse_is_cursor_visible()) @pending_deprecate() def mouse_move(x: int, y: int) -> None: lib.TCOD_mouse_move(x, y) @deprecate("Use tcod.event.get_mouse_state() instead.") def mouse_get_status() -> Mouse: return Mouse(lib.TCOD_mouse_get_status()) @pending_deprecate() def namegen_parse( filename: str, random: Optional[tcod.random.Random] = None ) -> None: lib.TCOD_namegen_parse(_bytes(filename), random or ffi.NULL) @pending_deprecate() def namegen_generate(name: str) -> str: return _unpack_char_p(lib.TCOD_namegen_generate(_bytes(name), False)) @pending_deprecate() def namegen_generate_custom(name: str, rule: str) -> str: return _unpack_char_p( lib.TCOD_namegen_generate_custom(_bytes(name), _bytes(rule), False) ) @pending_deprecate() def namegen_get_sets() -> List[str]: sets = lib.TCOD_namegen_get_sets() try: lst = [] while not lib.TCOD_list_is_empty(sets): lst.append( _unpack_char_p(ffi.cast("char *", lib.TCOD_list_pop(sets))) ) finally: lib.TCOD_list_delete(sets) return lst @pending_deprecate() def namegen_destroy() -> None: lib.TCOD_namegen_destroy() @pending_deprecate() def noise_new( dim: int, h: float = NOISE_DEFAULT_HURST, l: float = NOISE_DEFAULT_LACUNARITY, # noqa: E741 random: Optional[tcod.random.Random] = None, ) -> tcod.noise.Noise: """Return a new Noise instance. Args: dim (int): Number of dimensions. From 1 to 4. h (float): The hurst exponent. Should be in the 0.0-1.0 range. l (float): The noise lacunarity. random (Optional[Random]): A Random instance, or None. Returns: Noise: The new Noise instance. """ return tcod.noise.Noise(dim, hurst=h, lacunarity=l, seed=random) @pending_deprecate() def noise_set_type(n: tcod.noise.Noise, typ: int) -> None: """Set a Noise objects default noise algorithm. Args: typ (int): Any NOISE_* constant. """ n.algorithm = typ @pending_deprecate() def noise_get( n: tcod.noise.Noise, f: Sequence[float], typ: int = NOISE_DEFAULT ) -> float: """Return the noise value sampled from the ``f`` coordinate. ``f`` should be a tuple or list with a length matching :any:`Noise.dimensions`. If ``f`` is shoerter than :any:`Noise.dimensions` the missing coordinates will be filled with zeros. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. Returns: float: The sampled noise value. """ return float(lib.TCOD_noise_get_ex(n.noise_c, ffi.new("float[4]", f), typ)) @pending_deprecate() def noise_get_fbm( n: tcod.noise.Noise, f: Sequence[float], oc: float, typ: int = NOISE_DEFAULT, ) -> float: """Return the fractal Brownian motion sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. octaves (float): The level of level. Should be more than 1. Returns: float: The sampled noise value. """ return float( lib.TCOD_noise_get_fbm_ex(n.noise_c, ffi.new("float[4]", f), oc, typ) ) @pending_deprecate() def noise_get_turbulence( n: tcod.noise.Noise, f: Sequence[float], oc: float, typ: int = NOISE_DEFAULT, ) -> float: """Return the turbulence noise sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. octaves (float): The level of level. Should be more than 1. Returns: float: The sampled noise value. """ return float( lib.TCOD_noise_get_turbulence_ex( n.noise_c, ffi.new("float[4]", f), oc, typ ) ) @deprecate("libtcod objects are deleted automatically.") def noise_delete(n: tcod.noise.Noise) -> None: # type (Any) -> None """Does nothing. libtcod objects are managed by Python's garbage collector. This function exists for backwards compatibility with libtcodpy. """ def _unpack_union(type_: int, union: Any) -> Any: """ unpack items from parser new_property (value_converter) """ if type_ == lib.TCOD_TYPE_BOOL: return bool(union.b) elif type_ == lib.TCOD_TYPE_CHAR: return union.c.decode("latin-1") elif type_ == lib.TCOD_TYPE_INT: return union.i elif type_ == lib.TCOD_TYPE_FLOAT: return union.f elif ( type_ == lib.TCOD_TYPE_STRING or lib.TCOD_TYPE_VALUELIST15 >= type_ >= lib.TCOD_TYPE_VALUELIST00 ): return _unpack_char_p(union.s) elif type_ == lib.TCOD_TYPE_COLOR: return Color._new_from_cdata(union.col) elif type_ == lib.TCOD_TYPE_DICE: return Dice(union.dice) elif type_ & lib.TCOD_TYPE_LIST: return _convert_TCODList(union.list, type_ & 0xFF) else: raise RuntimeError("Unknown libtcod type: %i" % type_) def _convert_TCODList(clist: Any, type_: int) -> Any: return [ _unpack_union(type_, lib.TDL_list_get_union(clist, i)) for i in range(lib.TCOD_list_size(clist)) ] @deprecate("Parser functions have been deprecated.") def parser_new() -> Any: return ffi.gc(lib.TCOD_parser_new(), lib.TCOD_parser_delete) @deprecate("Parser functions have been deprecated.") def parser_new_struct(parser: Any, name: str) -> Any: return lib.TCOD_parser_new_struct(parser, name) # prevent multiple threads from messing with def_extern callbacks _parser_callback_lock = threading.Lock() # temporary global pointer to a listener instance _parser_listener = None # type: Any @ffi.def_extern() # type: ignore def _pycall_parser_new_struct(struct: Any, name: str) -> Any: return _parser_listener.new_struct(struct, _unpack_char_p(name)) @ffi.def_extern() # type: ignore def _pycall_parser_new_flag(name: str) -> Any: return _parser_listener.new_flag(_unpack_char_p(name)) @ffi.def_extern() # type: ignore def _pycall_parser_new_property(propname: Any, type: Any, value: Any) -> Any: return _parser_listener.new_property( _unpack_char_p(propname), type, _unpack_union(type, value) ) @ffi.def_extern() # type: ignore def _pycall_parser_end_struct(struct: Any, name: Any) -> Any: return _parser_listener.end_struct(struct, _unpack_char_p(name)) @ffi.def_extern() # type: ignore def _pycall_parser_error(msg: Any) -> None: _parser_listener.error(_unpack_char_p(msg)) @deprecate("Parser functions have been deprecated.") def parser_run(parser: Any, filename: str, listener: Any = None) -> None: global _parser_listener if not listener: lib.TCOD_parser_run(parser, _bytes(filename), ffi.NULL) return propagate_manager = _PropagateException() clistener = ffi.new( "TCOD_parser_listener_t *", { "new_struct": lib._pycall_parser_new_struct, "new_flag": lib._pycall_parser_new_flag, "new_property": lib._pycall_parser_new_property, "end_struct": lib._pycall_parser_end_struct, "error": lib._pycall_parser_error, }, ) with _parser_callback_lock: _parser_listener = listener with propagate_manager: lib.TCOD_parser_run(parser, _bytes(filename), clistener) @deprecate("libtcod objects are deleted automatically.") def parser_delete(parser: Any) -> None: # type (Any) -> None """Does nothing. libtcod objects are managed by Python's garbage collector. This function exists for backwards compatibility with libtcodpy. """ @deprecate("Parser functions have been deprecated.") def parser_get_bool_property(parser: Any, name: str) -> bool: return bool(lib.TCOD_parser_get_bool_property(parser, _bytes(name))) @deprecate("Parser functions have been deprecated.") def parser_get_int_property(parser: Any, name: str) -> int: return int(lib.TCOD_parser_get_int_property(parser, _bytes(name))) @deprecate("Parser functions have been deprecated.") def parser_get_char_property(parser: Any, name: str) -> str: return chr(lib.TCOD_parser_get_char_property(parser,
with a range that will make sense for automatic thresholding if sign == "neg": range_data = np.abs(scalar_data[np.where(scalar_data < 0)]) elif sign == "pos": range_data = scalar_data[np.where(scalar_data > 0)] else: range_data = np.abs(scalar_data) # Get the min and max from among various places if min is None: try: min = config.getfloat("overlay", "min_thresh") except ValueError: min_str = config.get("overlay", "min_thresh") if min_str == "robust_min": min = stats.scoreatpercentile(range_data, 2) elif min_str == "actual_min": min = range_data.min() else: min = 2.0 warn("The 'min_thresh' value in your config value must be " "a float, 'robust_min', or 'actual_min', but it is " "%s. I'm setting the overlay min to the config " "default of 2" % min) if max is None: try: max = config.getfloat("overlay", "max_thresh") except ValueError: max_str = config.get("overlay", "max_thresh") if max_str == "robust_max": max = stats.scoreatpercentile(scalar_data, 98) elif max_str == "actual_max": max = range_data.max() else: max = stats.scoreatpercentile(range_data, 98) warn("The 'max_thresh' value in your config value must be " "a float, 'robust_min', or 'actual_min', but it is " "%s. I'm setting the overlay min to the config " "default of robust_max" % max) return min, max ########################################################################### # ADDING DATA PLOTS def add_overlay(self, source, min=None, max=None, sign="abs", name=None, hemi=None): """Add an overlay to the overlay dict from a file or array. Parameters ---------- source : str or numpy array path to the overlay file or numpy array with data min : float threshold for overlay display max : float saturation point for overlay display sign : {'abs' | 'pos' | 'neg'} whether positive, negative, or both values should be displayed name : str name for the overlay in the internal dictionary hemi : str | None If None, it is assumed to belong to the hemipshere being shown. If two hemispheres are being shown, an error will be thrown. """ hemi = self._check_hemi(hemi) # load data here scalar_data, name = self._read_scalar_data(source, hemi, name=name) min, max = self._get_display_range(scalar_data, min, max, sign) if not sign in ["abs", "pos", "neg"]: raise ValueError("Overlay sign must be 'abs', 'pos', or 'neg'") old = OverlayData(scalar_data, self.geo[hemi], min, max, sign) ol = [] views = self._toggle_render(False) for brain in self._brain_list: if brain['hemi'] == hemi: ol.append(brain['brain'].add_overlay(old)) if name in self.overlays_dict: name = "%s%d" % (name, len(self.overlays_dict) + 1) self.overlays_dict[name] = ol self._toggle_render(True, views) def add_data(self, array, min=None, max=None, thresh=None, colormap="blue-red", alpha=1, vertices=None, smoothing_steps=20, time=None, time_label="time index=%d", colorbar=True, hemi=None): """Display data from a numpy array on the surface. This provides a similar interface to add_overlay, but it displays it with a single colormap. It offers more flexibility over the colormap, and provides a way to display four dimensional data (i.e. a timecourse). Note that min sets the low end of the colormap, and is separate from thresh (this is a different convention from add_overlay) Note: If the data is defined for a subset of vertices (specified by the "vertices" parameter), a smoothing method is used to interpolate the data onto the high resolution surface. If the data is defined for subsampled version of the surface, smoothing_steps can be set to None, in which case only as many smoothing steps are applied until the whole surface is filled with non-zeros. Parameters ---------- array : numpy array data array (nvtx vector) min : float min value in colormap (uses real min if None) max : float max value in colormap (uses real max if None) thresh : None or float if not None, values below thresh will not be visible colormap : str | array [256x4] name of Mayavi colormap to use, or a custom look up table (a 256x4 array, with the columns representing RGBA (red, green, blue, alpha) coded with integers going from 0 to 255). alpha : float in [0, 1] alpha level to control opacity vertices : numpy array vertices for which the data is defined (needed if len(data) < nvtx) smoothing_steps : int or None number of smoothing steps (smooting is used if len(data) < nvtx) Default : 20 time : numpy array time points in the data array (if data is 2D) time_label : str | None format of the time label (or None for no label) colorbar : bool whether to add a colorbar to the figure hemi : str | None If None, it is assumed to belong to the hemipshere being shown. If two hemispheres are being shown, an error will be thrown. """ hemi = self._check_hemi(hemi) if min is None: min = array.min() if max is None: max = array.max() # Create smoothing matrix if necessary if len(array) < self.geo[hemi].x.shape[0]: if vertices is None: raise ValueError("len(data) < nvtx: need vertices") adj_mat = utils.mesh_edges(self.geo[hemi].faces) smooth_mat = utils.smoothing_matrix(vertices, adj_mat, smoothing_steps) else: smooth_mat = None # Calculate initial data to plot if array.ndim == 1: array_plot = array elif array.ndim == 2: array_plot = array[:, 0] else: raise ValueError("data has to be 1D or 2D") if smooth_mat is not None: array_plot = smooth_mat * array_plot # Copy and byteswap to deal with Mayavi bug mlab_plot = _prepare_data(array_plot) # process colormap argument if isinstance(colormap, basestring): lut = None else: lut = np.asarray(colormap) if lut.shape != (256, 4): err = ("colormap argument must be mayavi colormap (string) or" " look up table (array of shape (256, 4))") raise ValueError(err) colormap = "blue-red" data = dict(array=array, smoothing_steps=smoothing_steps, fmin=min, fmid=(min + max) / 2, fmax=max, transparent=False, time=0, time_idx=0, vertices=vertices, smooth_mat=smooth_mat) # Create time array and add label if 2D if array.ndim == 2: if time is None: time = np.arange(array.shape[1]) self._times = time self.n_times = array.shape[1] if not self.n_times == len(time): raise ValueError('time is not the same length as ' 'array.shape[1]') data["time_label"] = time_label data["time"] = time data["time_idx"] = 0 y_txt = 0.05 + 0.05 * bool(colorbar) else: self._times = None self.n_times = None surfs = [] bars = [] views = self._toggle_render(False) for bi, brain in enumerate(self._brain_list): if brain['hemi'] == hemi: out = brain['brain'].add_data(array, mlab_plot, vertices, smooth_mat, min, max, thresh, lut, colormap, alpha, time, time_label, colorbar) s, ct, bar = out surfs.append(s) bars.append(bar) row, col = np.unravel_index(bi, self.brain_matrix.shape) if array.ndim == 2 and time_label is not None: self.add_text(0.05, y_txt, time_label % time[0], name="time_label", row=row, col=col) self._toggle_render(True, views) data['surfaces'] = surfs data['colorbars'] = bars data['orig_ctable'] = ct self.data_dict[hemi] = data def add_annotation(self, annot, borders=True, alpha=1, hemi=None, remove_existing=True): """Add an annotation file. Parameters ---------- annot : str Either path to annotation file or annotation name borders : bool Show only borders of regions alpha : float in [0, 1] Alpha level to control opacity hemi : str | None If None, it is assumed to belong to the hemipshere being shown. If two hemispheres are being shown, data must exist for both hemispheres. remove_existing : bool If True (default), remove old annotations. """ hemis = self._check_hemis(hemi) # Figure out where the data is coming from if os.path.isfile(annot): filepath = annot path = os.path.split(filepath)[0] file_hemi, annot = os.path.basename(filepath).split('.')[:2] if len(hemis) > 1: if annot[:2] == 'lh.': filepaths = [filepath, pjoin(path, 'rh' + annot[2:])] elif annot[:2] == 'rh.': filepaths = [pjoin(path, 'lh' + annot[2:], filepath)] else: raise RuntimeError('To add both hemispheres ' 'simultaneously, filename must ' 'begin with "lh." or "rh."') else: filepaths = [filepath] else: filepaths = [] for hemi in hemis: filepath = pjoin(self.subjects_dir, self.subject_id, 'label', ".".join([hemi, annot, 'annot'])) if not os.path.exists(filepath): raise ValueError('Annotation file %s does not exist' % filepath) filepaths += [filepath] views = self._toggle_render(False) if remove_existing is True: # Get rid of any old annots for a in self.annot_list: a['surface'].remove() self.annot_list = [] al = self.annot_list for hemi, filepath in zip(hemis, filepaths): # Read in the data labels, cmap, _ = nib.freesurfer.read_annot(filepath, orig_ids=True) # Maybe zero-out the non-border vertices if borders: n_vertices = labels.size edges = utils.mesh_edges(self.geo[hemi].faces) border_edges = labels[edges.row] != labels[edges.col] show = np.zeros(n_vertices, dtype=np.int) show[np.unique(edges.row[border_edges])] = 1 labels *= show # Handle null labels properly # (tksurfer doesn't
ax.set_title(f'Nodes: {n}, Edges per node: {e}, ') ax.legend() ax.grid() plt.show(block=False) # Save figure out_dir = str(self.path2var / 'figs') tag = '_'.join(fname_parts[0:5]) fname = f'{tag}_{ab}.png' if not os.path.exists(out_dir): os.makedirs(out_dir) out_path = os.path.join(out_dir, fname) plt.savefig(out_path) return def _analyze_scalability(self, path2models, path2nodenames, corpus, epn=10, ref_col='corpusid'): """ Analyzes the influence of the topic model and the similarity graph parameters on the quality of the graph. The similarity graph is validated using a reference graph. Parameters ---------- path2models : str Path specifying the class of models to validate. path2nodenames : str Path to the file containing the node names corpus : str Name of the corpus epn : float or int, optional (default=10) Target number of edges per node in the sparse graph. col_ref : str, optional (default='corpusid') Name of the column in the metadata files containing the node names """ # ################ # Corpus selection # ################ # Paths to the models to analyze. The name of each model is also the # name of the folder that contains it. models = [f for f in os.listdir(path2models) if f.split('_')[0] == corpus and 'interval' in f] # Selected models for the analysis: sel_n_topics = ['25', '40'] sel_alpha = ['1.0', '5.0'] sel_interval = ['0', '10'] sel_run = ['0'] # r_nodes = [0.1, 0.2, 0.4, 0.6, 0.8, 1.0] r_nodes = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] # Filter models selected_models = [] for model in models: # Extract model parameters metadata_i = model.split('_') # Reject model if parameters do not belong to the selected set: if ((metadata_i[2] in sel_n_topics) and (metadata_i[4] in sel_alpha) and (metadata_i[6] in sel_interval) and (metadata_i[8] in sel_run)): selected_models.append(model) logging.info(f"Selected models: {selected_models}") # ####################### # Model-by-model analysis # ####################### # Initialize output variables model_name, n_topics, alpha, interval, run = [], [], [], [], [] n_nodes, n_edges, comp_time, rmax = [], [], [], [] for i, model in enumerate(selected_models): logging.info( f"-- Model {i} ({model}) out of {len(selected_models)}") # Select topic model path = os.path.join(path2models, model) # ##################### # Document-topic matrix # Load doc-topic matrix for the whole corpus data, df_nodes, params = self.readCoordsFromFile( fpath=path, sparse=True, path2nodenames=path2nodenames, ref_col=ref_col) T = data['thetas'] # Doc-topic matrix nodes_model = df_nodes[ref_col].astype(str).tolist() n_nodes_all = len(nodes_model) # nodes = df_nodes[ref_col].tolist() # List of node ids # Extract model parameters metadata_i = model.split('_') n_topics_i = metadata_i[2] alpha_i = metadata_i[4] interval_i = metadata_i[6] run_i = metadata_i[8] # Take metadata information about the model from the model name # alpha_i = params['alpha'] # interval_i = params['optimize-interval'] # ########### # Subsampling # Create graph self.SG.makeSuperNode(label=model, nodes=nodes_model, T=T) for r in r_nodes: t0 = time.time() n_gnodes = int(r * n_nodes_all) n_edges_t = int(epn * n_gnodes) self.SG.sub_snode(model, n_gnodes, ylabel='subgraph', sampleT=True, save_T=False) self.SG.computeSimGraph('subgraph', n_edges=n_edges_t, n_gnodes=n_gnodes, verbose=False) dt = time.time() - t0 # ######################## # Store relevant variables # Store model parameters model_name.append(model) n_topics.append(n_topics_i) alpha.append(alpha_i) interval.append(interval_i) run.append(run_i) # Store graph parameters n_nodes.append(n_gnodes) md = self.SG.snodes['subgraph'].metadata n_edges.append(md['edges']['n_edges']) # Store output variables rmax.append(md['edges']['R']) comp_time.append(dt) # Remove snode, because it is no longer required self.SG.drop_snode('subgraph') self.SG.drop_snode(model) # ############ # Save results # Sort result variables by number of topics # We need to save the original ordering of the number of topics to # sort the cd metrics afterwards. (n_nodes, n_edges, model_name, n_topics, alpha, interval, run, rmax, comp_time) = tuple(zip(*sorted( zip(n_nodes, n_edges, model_name, n_topics, alpha, interval, run, rmax, comp_time)))) # Create summary table df = pd.DataFrame({'Model': model_name, 'Topics': n_topics, 'alpha': alpha, 'i': interval, 'run': run, 'Radius': rmax, 'Time': comp_time, 'Nodes': n_nodes, 'Edges': n_edges}) print("Summary of results:") print(df) # Save summary table preffix = f'{corpus}_{epn}' fname = f'{preffix}.xls' if not os.path.exists(self.path2sca): os.makedirs(self.path2sca) out_path = self.path2sca / fname df.to_excel(out_path) return def analyze_scalability(self): """ Analyzes the scalability of the graph generatio nprocess Parameters ---------- corpus : str {'S2', 'Crunch'} Corpus (Pu: Semantic Scholar, or Co: Crunchbase data) """ logging.info("-- Scalability of similarity graph computations") corpus_data = self.model path2nodenames = corpus_data['path2nodenames'] path2models = corpus_data['path2models'] ref_col = corpus_data['ref_col'] # Parameters print(f"Number of edges per node: {self.epn}") # Validate modesl, one by one... self._analyze_scalability( path2models, path2nodenames, self.corpus_name, epn=self.epn, ref_col=ref_col) exit() return def show_scalability_results(self): """ Shows the results of the scalability analysis done in self.analyze_scalability() """ # ####################### # Configurable parameters # ####################### cols2legend = ['Topics', 'alpha', 'i', 'run'] cols2y = ['Radius', 'Time', 'Edges'] cols2x = ['Nodes'] # Variables to be taken from the file names, and the part of the fname # containing the variable fname2fig = {'corpus': 0, 'epn': 1} # NOT USED. # fname2legend = {} # fname2y = {} # fname2x = {} # Dictionary of abreviations (for the file names). Abbreviatios are # used to reduce the size of legends and other figure text elements abbreviation = {x: x for x in cols2y} abbreviation.update({'Radius': 'Rad', 'Time': 't', 'Edges': 'ne'}) # ############### # Read data files # ############### # Read the file names in the folder containing the xls reports data_dir = self.path2sca data_files = sorted(os.listdir(data_dir)) data2legend = {x: [] for x in cols2legend} data2axis = {x: [] for x in cols2x + cols2y} metadata = {x: [] for x in fname2fig} params, df_dict = {}, {} # fname_struct = ['corpus', 'sim', 'rescale', 'n_nodes', 'n_edges', # 'ig', 'tm_class'] for f in data_files: if f.endswith('.xls'): fname = os.path.splitext(f)[0] fname_parts = fname.split('_') # Read parameters from the file name metadata = {x: metadata[x] + [fname_parts[loc]] for x, loc in fname2fig.items()} params[fname] = {x: fname_parts[loc] for x, loc in fname2fig.items()} # Read report from file fpath = os.path.join(data_dir, f) df_dict[fname] = pd.read_excel(fpath) for x in data2legend: data2legend[x] += df_dict[fname][x].tolist() for x in data2axis: data2axis[x] += df_dict[fname][x].tolist() # ############ # Plot results # ############ # Get the unique values of all variables that will not be in x- or y- # axes for var in cols2legend: data2legend[var] = sorted(list(set(data2legend[var]))) for var in metadata: metadata[var] = sorted(list(set(metadata[var]))) # The following nested loop is aimed to make multiple plots from xls # files inside the same directory. It is actually not needed if all # xls files in the given folder have the same parameter values. for md in itertools.product(*list(metadata.values())): # ################################ # Plot figures for parameter set x # List of all files matching the parameter assignment in x fnames = [f for f in df_dict if list(params[f].values()) == list(md)] if len(fnames) == 0: continue logging.info(f"-- -- Plotting figures from files {fnames}") for var, ab in abbreviation.items(): # ############################# # Plot figures for variable var for col2x in cols2x: # ################################### # Plot variable var vs variable col2x fig, ax = plt.subplots() for fname in fnames: df_f = df_dict[fname] for p in itertools.product( *list(data2legend.values())): df = copy.copy(df_f) for n, param in enumerate(p): df = df[df[cols2legend[n]] == param] x = df[col2x] y = df[var] base_line, = ax.plot(x, y, '.') df_av = df.groupby(col2x).mean() x = df_av.index y = df_av[var] label = ', '.join( f'{name}={value}' for name, value in zip(cols2legend, p)) ax.plot(x, y, '.-', label=label, color=base_line.get_color()) ax.set_xlabel(col2x) ax.set_ylabel(var) title = ', '.join( f'{name}: {value}' for name, value in zip(fname2fig, md)) ax.set_title(title) ax.legend() ax.grid() plt.show(block=False) # Save figure out_dir = os.path.join(self.path2sca, 'figs') tag = '_'.join(fname_parts) fname = f'{tag}_{ab}.png' if not os.path.exists(out_dir): os.makedirs(out_dir) out_path = os.path.join(out_dir, fname) plt.savefig(out_path) return def _compute_all_subtrain_simgraphs(self, path2models, corpus, n_gnodes=20_000, epn=10, reset=False): """ Computes all similarity graphs from the available topic models for a given corpus, and save them in a supergraph structure, to be used later in validation processes. Parameters ---------- path2models : str Path specifying the class of models to validate. corpus : str Name of the corpus n_gnodes : int, optional (default 20_000) Number of nodes of the subsampled graphs epn : float or int, optional (default 10) Target number of edges per node in the sparse graph. reset : boolean, optional (default=False) If True, the simgraph is computed no matter if a previous version exists. """ # ################ # Corpus selection # Paths to the models to analyze. The name of each model is also
<reponame>arnobpl/Rapid-Roll-Lite # Rapid Roll Lite 1.0 # By <NAME> # https://arnobpl.github.io # <EMAIL> # The following values are game settings Screen_Width = 1280 Screen_Height = 720 Screen_Center = 1 Screen_Left = 10 Screen_Top = 10 Full_Screen = 0 Focus_Locked = 1 Game_Speed = 30 building_width_screen = 0.25 safe_bar_width0 = 160 safe_bar_width1 = 200 safe_bar_width2 = 280 danger_bar_width0 = 160 danger_bar_width1 = 200 danger_bar_width2 = 280 window_difference_x = 200 window_difference_y = 200 first_window_x = 40 window_floor_distance = 57 karnisa_length = 100 window_karnisa_distance = 5 game_speed_factor = 1.0001 bar_create_frequency = 100 bar_move_step = 3 bar_type_condition = 80 safe_bar_size_condition0 = 30 safe_bar_size_condition1 = 70 danger_bar_size_condition0 = 30 danger_bar_size_condition1 = 70 max_danger_bar_once = 2 safe_bar_animation_condition = 8 danger_bar_animation_condition = 2 cloud_enabled = 1 cloud_create_frequency0 = 7 cloud_create_frequency1 = 15 cloud_move_step0 = 1 cloud_move_step1 = 2 cloud_scale = 0.7 initial_ball_position = 0.75 ball_move_step_x_keyboard_enabled = 1 ball_move_step_x_keyboard = 15 ball_move_step_x_keyboard_acceleration = 4 ball_move_step_x_mouse_enabled = 1 ball_move_step_y = 10 ball_move_step_y_acceleration = 1 ball_crashed_delay = 30 initial_life_items_gain = 2 max_life_items_gain = 5 initial_life_item_create_condition = 15 life_item_create_condition_factor = 0.999 life_item_crashed_delay = 10 data_directory_name = "Data" icon_data_file_name = "rapid_roll_icon.png" sprite_data_file_name = "rapid_roll_sprites.png" # The above values are game settings def f_range(start, stop, step): if step == 0 or (start > stop and step > 0) or (start < stop and step < 0): return [] if start > stop: start, stop = stop, start step *= -1 f_list = [] while start < stop: f_list.append(start) start += step return f_list def lerp(value, start, stop, step): value += step if value < start: return start, -step if value > stop: return stop, -step return value, step ERROR = 0 try: print("\nPress ESC to exit the game...") from time import sleep sleep(1) loading_str = "Loading, Please Wait..." print("\n\n" + loading_str + "\n\n") import os import sys data_directory_full_path = os.path.join(sys.path[0], data_directory_name) import pygame from random import randrange from math import ceil, floor from pygame.locals import * pygame.init() if Full_Screen: # Screen_Width = pygame.display.Info().current_w # Screen_Height = pygame.display.Info().current_h screen = pygame.display.set_mode((Screen_Width, Screen_Height), FULLSCREEN | HWSURFACE | DOUBLEBUF | NOFRAME) else: if Screen_Center: os.environ["SDL_VIDEO_CENTERED"] = "1" else: os.environ["SDL_VIDEO_WINDOW_POS"] = "\"" + str(Screen_Left) + "," + str(Screen_Top) + "\"" screen = pygame.display.set_mode((Screen_Width, Screen_Height), HWSURFACE | DOUBLEBUF | NOFRAME) ERROR = 1 font = pygame.font.Font(None, 40) screen.blit(font.render(loading_str, True, (255, 255, 255)), ( (Screen_Width >> 1) - (font.size(loading_str)[0] >> 1), (Screen_Height >> 1) - (font.size(loading_str)[1] >> 1))) pygame.display.update() ERROR = 2 pygame.display.set_icon(pygame.image.load(os.path.join(data_directory_full_path, icon_data_file_name))) ERROR = 3 image_data = pygame.image.load(os.path.join(data_directory_full_path, sprite_data_file_name)).convert_alpha() # Initial loading successful ERROR = 0 except Exception as exception: try: pygame.quit() except: pass print('\n' * 150 + "Fatal Error!") print(exception) if ERROR == 0: print("Pygame module is missing or invalid.\nPlease install Pygame using the command: \"pip install pygame\"") elif ERROR == 1: print("Font component of Pygame module is missing or invalid.") elif ERROR == 2: print("\"" + icon_data_file_name + "\" file is missing or invalid.") elif ERROR == 3: print("\"" + sprite_data_file_name + "\" file is missing or invalid.") print("\n Support: <EMAIL>\n\n https://arnobpl.github.io\n\n\nPress ENTER to exit..." + '\n' * 8) input() if ERROR == 0: # Background background_colour = 153, 217, 234 background = pygame.Surface((round(Screen_Width * (1 - building_width_screen)), Screen_Height)) R_step = 20 R_start = background_colour[0] - R_step R_stop = background_colour[0] + R_step G_step = 20 G_start = background_colour[1] - G_step G_stop = background_colour[1] + G_step B_step = 20 B_start = background_colour[2] - B_step B_stop = background_colour[2] + B_step R = randrange(R_start, R_stop) G = randrange(G_start, G_stop) B = randrange(B_start, B_stop) background.fill((R, G, B)) background_left = round(Screen_Width * building_width_screen / 2) # Ball ball = [] ball.append(image_data.subsurface((0, 0, 40, 40))) ball.append(image_data.subsurface((40, 0, 40, 40))) ball.append(image_data.subsurface((80, 0, 40, 40))) ball.append(image_data.subsurface((120, 0, 40, 40))) ball.append(pygame.transform.flip(ball[2], True, False)) ball.append(pygame.transform.flip(ball[1], True, False)) ball.append(image_data.subsurface((160, 0, 40, 40))) # Life Item life_item = [] life_item.append(image_data.subsurface((160, 40, 40, 40))) life_item.append(pygame.transform.flip(life_item[0], True, False)) life_item.append(image_data.subsurface((160, 80, 40, 40))) life_item.append(pygame.transform.flip(life_item[2], True, False)) # Safe Bar Main safe_bar = [] safe_bar.append(image_data.subsurface((120, 40, 10, 20))) safe_bar.append(image_data.subsurface((130, 40, 10, 20))) safe_bar.append(pygame.transform.flip(safe_bar[1], True, False)) # Safe Bar 0 safe_bar0 = [] safe_bar0.append(pygame.Surface((safe_bar_width0, 20), SRCALPHA, 32).convert_alpha()) for i in range(10, safe_bar_width0 - 10, 10): safe_bar0[0].blit(safe_bar[0], (i, 0)) safe_bar0[0].blit(safe_bar[1], (0, 0)) safe_bar0[0].blit(safe_bar[2], (safe_bar_width0 - 10, 0)) safe_bar0.append(pygame.transform.flip(safe_bar0[0], True, False)) # Safe Bar 1 safe_bar1 = [] safe_bar1.append(pygame.Surface((safe_bar_width1, 20), SRCALPHA, 32).convert_alpha()) for i in range(10, safe_bar_width1 - 10, 10): safe_bar1[0].blit(safe_bar[0], (i, 0)) safe_bar1[0].blit(safe_bar[1], (0, 0)) safe_bar1[0].blit(safe_bar[2], (safe_bar_width1 - 10, 0)) safe_bar1.append(pygame.transform.flip(safe_bar1[0], True, False)) # Safe Bar 2 safe_bar2 = [] safe_bar2.append(pygame.Surface((safe_bar_width2, 20), SRCALPHA, 32).convert_alpha()) for i in range(10, safe_bar_width2 - 10, 10): safe_bar2[0].blit(safe_bar[0], (i, 0)) safe_bar2[0].blit(safe_bar[1], (0, 0)) safe_bar2[0].blit(safe_bar[2], (safe_bar_width2 - 10, 0)) safe_bar2.append(pygame.transform.flip(safe_bar2[0], True, False)) # Danger Bar Main danger_bar = [] danger_bar.append(image_data.subsurface((140, 40, 10, 20))) danger_bar.append(image_data.subsurface((150, 40, 10, 20))) danger_bar.append(pygame.transform.flip(danger_bar[1], True, False)) # Danger Bar 0 danger_bar0 = [] danger_bar0.append(pygame.Surface((danger_bar_width0, 20), SRCALPHA, 32).convert_alpha()) for i in range(10, danger_bar_width0 - 10, 10): danger_bar0[0].blit(danger_bar[0], (i, 0)) danger_bar0[0].blit(danger_bar[1], (0, 0)) danger_bar0[0].blit(danger_bar[2], (danger_bar_width0 - 10, 0)) danger_bar0.append(pygame.transform.flip(danger_bar0[0], True, False)) # Danger Bar 1 danger_bar1 = [] danger_bar1.append(pygame.Surface((danger_bar_width1, 20), SRCALPHA, 32).convert_alpha()) for i in range(10, danger_bar_width1 - 10, 10): danger_bar1[0].blit(danger_bar[0], (i, 0)) danger_bar1[0].blit(danger_bar[1], (0, 0)) danger_bar1[0].blit(danger_bar[2], (danger_bar_width1 - 10, 0)) danger_bar1.append(pygame.transform.flip(danger_bar1[0], True, False)) # Danger Bar 2 danger_bar2 = [] danger_bar2.append(pygame.Surface((danger_bar_width2, 20), SRCALPHA, 32).convert_alpha()) for i in range(10, danger_bar_width2 - 10, 10): danger_bar2[0].blit(danger_bar[0], (i, 0)) danger_bar2[0].blit(danger_bar[1], (0, 0)) danger_bar2[0].blit(danger_bar[2], (danger_bar_width2 - 10, 0)) danger_bar2.append(pygame.transform.flip(danger_bar2[0], True, False)) # Top Spike Main top_spike = [] top_spike.append(pygame.transform.flip(image_data.subsurface((120, 60, 10, 20)), False, True)) top_spike.append(pygame.transform.flip(image_data.subsurface((130, 60, 10, 20)), False, True)) top_spike.append(pygame.transform.flip(top_spike[1], True, False)) # Top Spike Object top_spike_surface = pygame.Surface((background.get_width(), 20), SRCALPHA, 32).convert_alpha() for i in range(10, background.get_width() - 10, 10): top_spike_surface.blit(top_spike[0], (i, 0)) top_spike_surface.blit(top_spike[1], (0, 0)) top_spike_surface.blit(top_spike[2], (background.get_width() - 10, 0)) # Bottom Spike Main bottom_spike = [] bottom_spike.append(image_data.subsurface((140, 60, 10, 20))) bottom_spike.append(image_data.subsurface((150, 60, 10, 20))) bottom_spike.append(pygame.transform.flip(bottom_spike[1], True, False)) # Bottom Spike Object bottom_spike_surface = pygame.Surface((background.get_width(), 20), SRCALPHA, 32).convert_alpha() for i in range(10, background.get_width() - 10, 10): bottom_spike_surface.blit(bottom_spike[0], (i, 0)) bottom_spike_surface.blit(bottom_spike[1], (0, 0)) bottom_spike_surface.blit(bottom_spike[2], (background.get_width() - 10, 0)) # Cloud cloud = [] cloud.append(image_data.subsurface((0, 40, 120, 80))) cloud.append(pygame.transform.flip(cloud[0], True, False)) cloud.append(pygame.transform.smoothscale(cloud[0], (round(120 * cloud_scale), round(80 * cloud_scale)))) cloud.append(pygame.transform.flip(cloud[2], True, False)) # Display score_display = image_data.subsurface((160, 120, 40, 40)) life_display = image_data.subsurface((160, 160, 40, 40)) # Building Texture 0 building_texture0 = [image_data.subsurface((120, 80, 15, 15)), pygame.transform.rotate(image_data.subsurface((120, 112, 15, 2)), 90)] # Building Texture 1 building_texture1 = [image_data.subsurface((135, 80, 25, 15)), pygame.transform.rotate(image_data.subsurface((135, 112, 15, 2)), 90)] # Building Window 0 building_window0 = [image_data.subsurface((0, 120, 80, 80))] # Building Window 1 building_window1 = [image_data.subsurface((80, 120, 80, 80))] # Building Ornaments 0 building_ornaments0 = [image_data.subsurface((120, 95, 20, 10)), image_data.subsurface((120, 105, 20, 5)), pygame.transform.rotate(image_data.subsurface((120, 110, 10, 2)), 90), pygame.transform.rotate(image_data.subsurface((140, 110, 5, 2)), 90)] # Building Ornaments 1 building_ornaments1 = [image_data.subsurface((140, 95, 20, 10)), image_data.subsurface((140, 105, 20, 5)), pygame.transform.rotate(image_data.subsurface((130, 110, 10, 2)), 90), pygame.transform.rotate(image_data.subsurface((145, 110, 5, 2)), 90)] # Window Karnisa 0 window_karnisa_surface0 = pygame.Surface((karnisa_length, 10), SRCALPHA, 32).convert_alpha() for i in range(0, karnisa_length, 20): window_karnisa_surface0.blit(building_ornaments0[0], (i, 0)) window_karnisa_surface0.blit(building_ornaments0[2], (0, 0)) window_karnisa_surface0.blit(pygame.transform.flip(building_ornaments0[2], True, False), (karnisa_length - 2, 0)) # Window Karnisa 1 window_karnisa_surface1 = pygame.Surface((karnisa_length, 10), SRCALPHA, 32).convert_alpha() for i in range(0, karnisa_length, 20): window_karnisa_surface1.blit(building_ornaments1[0], (i, 0)) window_karnisa_surface1.blit(building_ornaments1[2], (0, 0)) window_karnisa_surface1.blit(pygame.transform.flip(building_ornaments1[2], True, False), (karnisa_length - 2, 0)) building_width = ceil(Screen_Width * building_width_screen / 2) building0 = pygame.Surface((building_width, Screen_Height + 14), SRCALPHA, 32).convert_alpha() for i in range(0, Screen_Height + 15, 15): for j in range(0, building_width + 15, 15): building0.blit(building_texture0[0], (j, i)) for i in range(0, Screen_Height + 15, 15): building0.blit(building_texture0[1], (0, i)) building1 = pygame.Surface((building_width, Screen_Height + 14), SRCALPHA, 32).convert_alpha() for i in range(0, Screen_Height + 15, 15): for j in range(0, building_width + 25, 25): building1.blit(building_texture1[0], (j, i)) for i in range(0, Screen_Height + 15, 15): building1.blit(building_texture1[1], (0, i)) building_window_surface0 = pygame.Surface((building_width, Screen_Height + window_difference_y - 1), SRCALPHA, 32).convert_alpha() for i in range(0, Screen_Height + window_difference_y, window_difference_y): for j in range(first_window_x, building_width + window_difference_x, window_difference_x): building_window_surface0.blit(building_window0[0], (j, i)) for i in range(window_floor_distance + 80, Screen_Height + window_difference_y, window_difference_y): for j in range(0, building_width + window_difference_x, 20): building_window_surface0.blit(building_ornaments0[1], (j, i)) building_window_surface0.blit(building_ornaments0[3], (0, i)) for i in range(window_difference_y - window_karnisa_distance - 10, Screen_Height + window_difference_y, window_difference_y): for j in range(first_window_x - round(karnisa_length / 2) + 40, building_width + window_difference_x, window_difference_x): building_window_surface0.blit(window_karnisa_surface0, (j, i)) building_window_surface1 = pygame.Surface((building_width, Screen_Height + window_difference_y - 1), SRCALPHA, 32).convert_alpha() for i in range(0, Screen_Height + window_difference_y, window_difference_y): for j in range(first_window_x, building_width + window_difference_x, window_difference_x): building_window_surface1.blit(building_window1[0], (j, i)) for i
<reponame>FiyaFly/python-asana # coding=utf-8 class _Projects: def __init__(self, client=None): self.client = client def add_custom_field_setting_for_project(self, project_gid, params=None, **options): """Add a custom field to a project :param str project_gid: (required) Globally unique identifier for the project. :param Object params: Parameters for the request :param **options - opt_pretty {bool}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. :return: Object """ if params is None: params = {} path = "/projects/{project_gid}/addCustomFieldSetting".replace("{project_gid}", project_gid) return self.client.post(path, params, **options) def add_followers_for_project(self, project_gid, params=None, **options): """Add followers to a project :param str project_gid: (required) Globally unique identifier for the project. :param Object params: Parameters for the request :param **options - opt_fields {list[str]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - opt_pretty {bool}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. :return: Object """ if params is None: params = {} path = "/projects/{project_gid}/addFollowers".replace("{project_gid}", project_gid) return self.client.post(path, params, **options) def add_members_for_project(self, project_gid, params=None, **options): """Add users to a project :param str project_gid: (required) Globally unique identifier for the project. :param Object params: Parameters for the request :param **options - opt_fields {list[str]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - opt_pretty {bool}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. :return: Object """ if params is None: params = {} path = "/projects/{project_gid}/addMembers".replace("{project_gid}", project_gid) return self.client.post(path, params, **options) def create_project(self, params=None, **options): """Create a project :param Object params: Parameters for the request :param **options - opt_fields {list[str]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - opt_pretty {bool}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. :return: Object """ if params is None: params = {} path = "/projects" return self.client.post(path, params, **options) def create_project_for_team(self, team_gid, params=None, **options): """Create a project in a team :param str team_gid: (required) Globally unique identifier for the team. :param Object params: Parameters for the request :param **options - opt_fields {list[str]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - opt_pretty {bool}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. :return: Object """ if params is None: params = {} path = "/teams/{team_gid}/projects".replace("{team_gid}", team_gid) return self.client.post(path, params, **options) def create_project_for_workspace(self, workspace_gid, params=None, **options): """Create a project in a workspace :param str workspace_gid: (required) Globally unique identifier for the workspace or organization. :param Object params: Parameters for the request :param **options - opt_fields {list[str]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - opt_pretty {bool}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. :return: Object """ if params is None: params = {} path = "/workspaces/{workspace_gid}/projects".replace("{workspace_gid}", workspace_gid) return self.client.post(path, params, **options) def delete_project(self, project_gid, params=None, **options): """Delete a project :param str project_gid: (required) Globally unique identifier for the project. :param Object params: Parameters for the request :param **options - opt_fields {list[str]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - opt_pretty {bool}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. :return: Object """ if params is None: params = {} path = "/projects/{project_gid}".replace("{project_gid}", project_gid) return self.client.delete(path, params, **options) def duplicate_project(self, project_gid, params=None, **options): """Duplicate a project :param str project_gid: (required) Globally unique identifier for the project. :param Object params: Parameters for the request :param **options - opt_fields {list[str]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - opt_pretty {bool}: Provides “pretty” output. Provides the
# coding: utf-8 """ Snøskredvarsel API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v5.0.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from varsom_avalanche_client.api_client import ApiClient class AvalancheWarningByCoordinatesApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def avalanche_warning_by_coordinates_detail(self, x, y, langkey, startdate, enddate, **kwargs): # noqa: E501 """avalanche_warning_by_coordinates_detail # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.avalanche_warning_by_coordinates_detail(x, y, langkey, startdate, enddate, async_req=True) >>> result = thread.get() :param async_req bool :param float x: (required) :param float y: (required) :param int langkey: (required) :param datetime startdate: (required) :param datetime enddate: (required) :return: list[AvalancheWarningDetail] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.avalanche_warning_by_coordinates_detail_with_http_info(x, y, langkey, startdate, enddate, **kwargs) # noqa: E501 else: (data) = self.avalanche_warning_by_coordinates_detail_with_http_info(x, y, langkey, startdate, enddate, **kwargs) # noqa: E501 return data def avalanche_warning_by_coordinates_detail_with_http_info(self, x, y, langkey, startdate, enddate, **kwargs): # noqa: E501 """avalanche_warning_by_coordinates_detail # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.avalanche_warning_by_coordinates_detail_with_http_info(x, y, langkey, startdate, enddate, async_req=True) >>> result = thread.get() :param async_req bool :param float x: (required) :param float y: (required) :param int langkey: (required) :param datetime startdate: (required) :param datetime enddate: (required) :return: list[AvalancheWarningDetail] If the method is called asynchronously, returns the request thread. """ all_params = ['x', 'y', 'langkey', 'startdate', 'enddate'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method avalanche_warning_by_coordinates_detail" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'x' is set if ('x' not in params or params['x'] is None): raise ValueError("Missing the required parameter `x` when calling `avalanche_warning_by_coordinates_detail`") # noqa: E501 # verify the required parameter 'y' is set if ('y' not in params or params['y'] is None): raise ValueError("Missing the required parameter `y` when calling `avalanche_warning_by_coordinates_detail`") # noqa: E501 # verify the required parameter 'langkey' is set if ('langkey' not in params or params['langkey'] is None): raise ValueError("Missing the required parameter `langkey` when calling `avalanche_warning_by_coordinates_detail`") # noqa: E501 # verify the required parameter 'startdate' is set if ('startdate' not in params or params['startdate'] is None): raise ValueError("Missing the required parameter `startdate` when calling `avalanche_warning_by_coordinates_detail`") # noqa: E501 # verify the required parameter 'enddate' is set if ('enddate' not in params or params['enddate'] is None): raise ValueError("Missing the required parameter `enddate` when calling `avalanche_warning_by_coordinates_detail`") # noqa: E501 collection_formats = {} path_params = {} if 'x' in params: path_params['x'] = params['x'] # noqa: E501 if 'y' in params: path_params['y'] = params['y'] # noqa: E501 if 'langkey' in params: path_params['langkey'] = params['langkey'] # noqa: E501 if 'startdate' in params: path_params['startdate'] = params['startdate'] # noqa: E501 if 'enddate' in params: path_params['enddate'] = params['enddate'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'text/json', 'application/xml', 'text/xml']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/AvalancheWarningByCoordinates/Detail/{x}/{y}/{langkey}/{startdate}/{enddate}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[AvalancheWarningDetail]', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def avalanche_warning_by_coordinates_obs(self, x, y, langkey, startdate, enddate, **kwargs): # noqa: E501 """avalanche_warning_by_coordinates_obs # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.avalanche_warning_by_coordinates_obs(x, y, langkey, startdate, enddate, async_req=True) >>> result = thread.get() :param async_req bool :param float x: (required) :param float y: (required) :param int langkey: (required) :param datetime startdate: (required) :param datetime enddate: (required) :return: list[ObsWarning] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.avalanche_warning_by_coordinates_obs_with_http_info(x, y, langkey, startdate, enddate, **kwargs) # noqa: E501 else: (data) = self.avalanche_warning_by_coordinates_obs_with_http_info(x, y, langkey, startdate, enddate, **kwargs) # noqa: E501 return data def avalanche_warning_by_coordinates_obs_with_http_info(self, x, y, langkey, startdate, enddate, **kwargs): # noqa: E501 """avalanche_warning_by_coordinates_obs # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.avalanche_warning_by_coordinates_obs_with_http_info(x, y, langkey, startdate, enddate, async_req=True) >>> result = thread.get() :param async_req bool :param float x: (required) :param float y: (required) :param int langkey: (required) :param datetime startdate: (required) :param datetime enddate: (required) :return: list[ObsWarning] If the method is called asynchronously, returns the request thread. """ all_params = ['x', 'y', 'langkey', 'startdate', 'enddate'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method avalanche_warning_by_coordinates_obs" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'x' is set if ('x' not in params or params['x'] is None): raise ValueError("Missing the required parameter `x` when calling `avalanche_warning_by_coordinates_obs`") # noqa: E501 # verify the required parameter 'y' is set if ('y' not in params or params['y'] is None): raise ValueError("Missing the required parameter `y` when calling `avalanche_warning_by_coordinates_obs`") # noqa: E501 # verify the required parameter 'langkey' is set if ('langkey' not in params or params['langkey'] is None): raise ValueError("Missing the required parameter `langkey` when calling `avalanche_warning_by_coordinates_obs`") # noqa: E501 # verify the required parameter 'startdate' is set if ('startdate' not in params or params['startdate'] is None): raise ValueError("Missing the required parameter `startdate` when calling `avalanche_warning_by_coordinates_obs`") # noqa: E501 # verify the required parameter 'enddate' is set if ('enddate' not in params or params['enddate'] is None): raise ValueError("Missing the required parameter `enddate` when calling `avalanche_warning_by_coordinates_obs`") # noqa: E501 collection_formats = {} path_params = {} if 'x' in params: path_params['x'] = params['x'] # noqa: E501 if 'y' in params: path_params['y'] = params['y'] # noqa: E501 if 'langkey' in params: path_params['langkey'] = params['langkey'] # noqa: E501 if 'startdate' in params: path_params['startdate'] = params['startdate'] # noqa: E501 if 'enddate' in params: path_params['enddate'] = params['enddate'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'text/json', 'application/xml', 'text/xml']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/AvalancheWarningByCoordinates/Obs/{x}/{y}/{langkey}/{startdate}/{enddate}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[ObsWarning]', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def avalanche_warning_by_coordinates_simple(self, x, y, langkey, startdate, enddate, **kwargs): # noqa: E501 """avalanche_warning_by_coordinates_simple # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.avalanche_warning_by_coordinates_simple(x, y, langkey, startdate, enddate, async_req=True) >>> result = thread.get() :param async_req bool :param float x: (required) :param float y: (required) :param int langkey: (required) :param datetime startdate: (required) :param datetime enddate: (required) :return: list[AvalancheWarningSimple] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.avalanche_warning_by_coordinates_simple_with_http_info(x, y, langkey, startdate, enddate, **kwargs) # noqa: E501 else: (data) = self.avalanche_warning_by_coordinates_simple_with_http_info(x, y, langkey, startdate, enddate, **kwargs) # noqa: E501 return data def avalanche_warning_by_coordinates_simple_with_http_info(self, x, y, langkey, startdate, enddate, **kwargs): # noqa: E501 """avalanche_warning_by_coordinates_simple # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.avalanche_warning_by_coordinates_simple_with_http_info(x, y, langkey, startdate, enddate, async_req=True) >>> result = thread.get() :param async_req bool :param float x: (required) :param float y: (required) :param int langkey: (required) :param datetime startdate: (required) :param datetime enddate: (required) :return: list[AvalancheWarningSimple] If the method is called asynchronously, returns the request thread. """ all_params = ['x', 'y', 'langkey', 'startdate', 'enddate'] # noqa: E501
'86177371':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u90d1\u5dde\u5e02')}, '861804644':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u8386\u7530\u5e02')}, '861804645':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')}, '861804646':{'en': 'Zhangzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6f33\u5dde\u5e02')}, '861804647':{'en': 'Longyan, Fujian', 'zh': u('\u798f\u5efa\u7701\u9f99\u5ca9\u5e02')}, '861804640':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')}, '861804641':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')}, '861804642':{'en': 'Xiamen, Fujian', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')}, '861804643':{'en': 'Ningde, Fujian', 'zh': u('\u798f\u5efa\u7701\u5b81\u5fb7\u5e02')}, '861813353':{'en': 'Qinhuangdao, Hebei', 'zh': u('\u6cb3\u5317\u7701\u79e6\u7687\u5c9b\u5e02')}, '861804648':{'en': 'Sanming, Fujian', 'zh': u('\u798f\u5efa\u7701\u4e09\u660e\u5e02')}, '861804649':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u5357\u5e73\u5e02')}, '861800734':{'en': 'Hengyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u8861\u9633\u5e02')}, '861800735':{'en': 'Chenzhou, Hunan', 'zh': u('\u6e56\u5357\u7701\u90f4\u5dde\u5e02')}, '861800736':{'en': 'Changde, Hunan', 'zh': u('\u6e56\u5357\u7701\u5e38\u5fb7\u5e02')}, '861800737':{'en': 'Yiyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u76ca\u9633\u5e02')}, '861800730':{'en': 'Yueyang, Hunan', 'zh': u('\u6e56\u5357\u7701\u5cb3\u9633\u5e02')}, '861800731':{'en': 'Changsha, Hunan', 'zh': u('\u6e56\u5357\u7701\u957f\u6c99\u5e02')}, '861800732':{'en': 'Xiangtan, Hunan', 'zh': u('\u6e56\u5357\u7701\u6e58\u6f6d\u5e02')}, '861800733':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u682a\u6d32\u5e02')}, '861813774':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u6d1b\u9633\u5e02')}, '861813775':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u6d1b\u9633\u5e02')}, '861813776':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u6d1b\u9633\u5e02')}, '861813777':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u90d1\u5dde\u5e02')}, '861800738':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u5a04\u5e95\u5e02')}, '861800739':{'en': '<NAME>', 'zh': u('\u6e56\u5357\u7701\u90b5\u9633\u5e02')}, '861813772':{'en': 'Luoyang, Henan', 'zh': u('\u6cb3\u5357\u7701\u6d1b\u9633\u5e02')}, '861813773':{'en': 'Luoyang, Henan', 'zh': u('\u6cb3\u5357\u7701\u6d1b\u9633\u5e02')}, '861802992':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')}, '861802993':{'en': 'Zhuhai, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u73e0\u6d77\u5e02')}, '861802990':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')}, '861802991':{'en': 'Zhongshan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e2d\u5c71\u5e02')}, '861802996':{'en': 'Jieyang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u63ed\u9633\u5e02')}, '861802997':{'en': 'Huizhou, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')}, '861802994':{'en': 'Jieyang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u63ed\u9633\u5e02')}, '861802995':{'en': 'Jieyang, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u63ed\u9633\u5e02')}, '861802998':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')}, '861802999':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u60e0\u5dde\u5e02')}, '861810962':{'en': 'Bengbu, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u868c\u57e0\u5e02')}, '861812005':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u82cf\u5dde\u5e02')}, '861812004':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u82cf\u5dde\u5e02')}, '861811479':{'en': '<NAME>iangsu', 'zh': u('\u6c5f\u82cf\u7701\u5f90\u5dde\u5e02')}, '861812007':{'en': 'Suzhou, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u82cf\u5dde\u5e02')}, '86180884':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')}, '861811923':{'en': '<NAME>', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')}, '861812006':{'en': 'Suzhou, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u82cf\u5dde\u5e02')}, '861812001':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u65e0\u9521\u5e02')}, '86180886':{'en': '<NAME>', 'zh': u('\u5409\u6797\u7701\u957f\u6625\u5e02')}, '861810963':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u829c\u6e56\u5e02')}, '861812000':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u65e0\u9521\u5e02')}, '861771964':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u6986\u6797\u5e02')}, '861771965':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u6986\u6797\u5e02')}, '861771966':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')}, '861771967':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')}, '861771960':{'en': 'Baoji, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5b9d\u9e21\u5e02')}, '861771961':{'en': 'Baoji, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5b9d\u9e21\u5e02')}, '861771962':{'en': 'Baoji, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5b9d\u9e21\u5e02')}, '861771963':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u6986\u6797\u5e02')}, '861809647':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u961c\u9633\u5e02')}, '861812002':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u5f90\u5dde\u5e02')}, '861771968':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')}, '861771969':{'en': '<NAME>', 'zh': u('\u9655\u897f\u7701\u5b89\u5eb7\u5e02')}, '861811922':{'en': '<NAME>', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')}, '861809646':{'en': '<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u5bbf\u5dde\u5e02')}, '861811476':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u82cf\u5dde\u5e02')}, '861811921':{'en': '<NAME>', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')}, '861809649':{'en': 'Huangshan, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u9ec4\u5c71\u5e02')}, '861809648':{'en': 'Fuyang, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u961c\u9633\u5e02')}, '86177092':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')}, '861808837':{'en': 'Lincang, Yunnan', 'zh': u('\u4e91\u5357\u7701\u4e34\u6ca7\u5e02')}, '861808836':{'en': 'Lincang, Yunnan', 'zh': u('\u4e91\u5357\u7701\u4e34\u6ca7\u5e02')}, '861808835':{'en': 'Lincang, Yunnan', 'zh': u('\u4e91\u5357\u7701\u4e34\u6ca7\u5e02')}, '861808834':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')}, '861808833':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u4e34\u6ca7\u5e02')}, '861808832':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')}, '861808831':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')}, '861808830':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')}, '861775069':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u6f33\u5dde\u5e02')}, '861811920':{'en': '<NAME>', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')}, '861808839':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u4e34\u6ca7\u5e02')}, '861775068':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u4e09\u660e\u5e02')}, '861801467':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u76d0\u57ce\u5e02')}, '861801466':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u76d0\u57ce\u5e02')}, '861801465':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u76d0\u57ce\u5e02')}, '861801464':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861801463':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861801462':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861801461':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861801460':{'en': 'Lianyungang, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861801469':{'en': 'Yancheng, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u76d0\u57ce\u5e02')}, '861801468':{'en': 'Yancheng, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u76d0\u57ce\u5e02')}, '861803645':{'en': 'Nantong, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u5357\u901a\u5e02')}, '861775065':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')}, '861803647':{'en': 'Changzhou, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u5e38\u5dde\u5e02')}, '861803646':{'en': 'Changzhou, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u5e38\u5dde\u5e02')}, '861803641':{'en': 'Suqian, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u5bbf\u8fc1\u5e02')}, '861803640':{'en': 'Suqian, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u5bbf\u8fc1\u5e02')}, '861803643':{'en': 'Nantong, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u5357\u901a\u5e02')}, '861775064':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')}, '861811927':{'en': 'Shihezi, Xinjiang', 'zh': u('\u65b0\u7586\u77f3\u6cb3\u5b50\u5e02')}, '861803649':{'en': 'Changzhou, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u5e38\u5dde\u5e02')}, '861775067':{'en': 'Sanming, Fujian', 'zh': u('\u798f\u5efa\u7701\u4e09\u660e\u5e02')}, '861775066':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')}, '861775061':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')}, '861775060':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')}, '861810882':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u6606\u660e\u5e02')}, '861775063':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')}, '861811926':{'en': '<NAME>', 'zh': u('\u65b0\u7586\u77f3\u6cb3\u5b50\u5e02')}, '861775062':{'en': '<NAME>', 'zh': u('\u798f\u5efa\u7701\u53a6\u95e8\u5e02')}, '86180405':{'en': '<NAME>', 'zh': u('\u6e56\u5317\u7701\u6b66\u6c49\u5e02')}, '861811219':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u6cf0\u5dde\u5e02')}, '86180400':{'en': '<NAME>', 'zh': u('\u8fbd\u5b81\u7701\u6c88\u9633\u5e02')}, '861811215':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861811214':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u626c\u5dde\u5e02')}, '861811217':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861811216':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861811211':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u9547\u6c5f\u5e02')}, '861811210':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u9547\u6c5f\u5e02')}, '861811213':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u626c\u5dde\u5e02')}, '861811212':{'en': 'Yangzhou, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u626c\u5dde\u5e02')}, '861811925':{'en': 'Shihezi, Xinjiang', 'zh': u('\u65b0\u7586\u77f3\u6cb3\u5b50\u5e02')}, '861810479':{'en': 'Xilin, Inner Mongolia', 'zh': u('\u5185\u8499\u53e4\u9521\u6797\u90ed\u52d2\u76df')}, '861808492':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5fb7\u9633\u5e02')}, '861811924':{'en': 'Shihezi, Xinjiang', 'zh': u('\u65b0\u7586\u77f3\u6cb3\u5b50\u5e02')}, '8617764':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')}, '861803919':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u7126\u4f5c\u5e02')}, '861803918':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u7126\u4f5c\u5e02')}, '861803915':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5546\u4e18\u5e02')}, '861803914':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5546\u4e18\u5e02')}, '861803917':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u7126\u4f5c\u5e02')}, '861803916':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u5546\u4e18\u5e02')}, '861803911':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u90d1\u5dde\u5e02')}, '861803910':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u90d1\u5dde\u5e02')}, '861803913':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u7126\u4f5c\u5e02')}, '861803912':{'en': '<NAME>', 'zh': u('\u6cb3\u5357\u7701\u7126\u4f5c\u5e02')}, '861800938':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5929\u6c34\u5e02')}, '861800939':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u9647\u5357\u5e02')}, '861800936':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5f20\u6396\u5e02')}, '861800937':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u9152\u6cc9\u5e02')}, '861800934':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5e86\u9633\u5e02')}, '861800935':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u6b66\u5a01\u5e02')}, '861800932':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5b9a\u897f\u5e02')}, '861800933':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u5e73\u51c9\u5e02')}, '861800930':{'en': '<NAME>', 'zh': u('\u7518\u8083\u7701\u4e34\u590f\u56de\u65cf\u81ea\u6cbb\u5dde')}, '861800931':{'en': 'Lanzhou, Gansu', 'zh': u('\u7518\u8083\u7701\u5170\u5dde\u5e02')}, '861809878':{'en': 'LiuAn, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u516d\u5b89\u5e02')}, '861809879':{'en': 'Huaibei, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u6dee\u5317\u5e02')}, '861809874':{'en': 'LiuAn, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u516d\u5b89\u5e02')}, '861809875':{'en': 'Li<NAME>', 'zh': u('\u5b89\u5fbd\u7701\u516d\u5b89\u5e02')}, '861809876':{'en': 'LiuAn, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u516d\u5b89\u5e02')}, '861809877':{'en': 'LiuAn, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u516d\u5b89\u5e02')}, '861809870':{'en': 'Suzhou, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5bbf\u5dde\u5e02')}, '861809871':{'en': 'Suzhou, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5bbf\u5dde\u5e02')}, '861809872':{'en': 'Suzhou, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5bbf\u5dde\u5e02')}, '861809873':{'en': 'Suzhou, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5bbf\u5dde\u5e02')}, '861778178':{'en': 'Suining, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')}, '861778179':{'en': 'YaAn, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u96c5\u5b89\u5e02')}, '861778170':{'en': 'Zigong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u81ea\u8d21\u5e02')}, '861778171':{'en': 'Suining, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')}, '861778172':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u9042\u5b81\u5e02')}, '861778173':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5e7f\u5b89\u5e02')}, '861778174':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5e7f\u5b89\u5e02')}, '861778175':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5e7f\u5b89\u5e02')}, '861778176':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u7518\u5b5c\u85cf\u65cf\u81ea\u6cbb\u5dde')}, '861778177':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u6500\u679d\u82b1\u5e02')}, '861770369':{'en': 'Shuangyashan, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u53cc\u9e2d\u5c71\u5e02')}, '861770368':{'en': 'Hegang, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u9e64\u5c97\u5e02')}, '861810038':{'en': '<NAME>', 'zh': u('\u5c71\u4e1c\u7701\u6d4e\u5357\u5e02')}, '861810039':{'en': '<NAME>', 'zh': u('\u5c71\u4e1c\u7701\u6d4e\u5357\u5e02')}, '861770365':{'en': '<NAME>', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u5927\u5e86\u5e02')}, '861770364':{'en': '<NAME>', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u54c8\u5c14\u6ee8\u5e02')}, '861770367':{'en': '<NAME>', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u9e21\u897f\u5e02')}, '861770366':{'en': '<NAME>', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u54c8\u5c14\u6ee8\u5e02')}, '861770361':{'en': '<NAME>jiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u54c8\u5c14\u6ee8\u5e02')}, '861770360':{'en': 'Harbin, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u54c8\u5c14\u6ee8\u5e02')}, '861770363':{'en': 'Qitaihe, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u4e03\u53f0\u6cb3\u5e02')}, '861770362':{'en': 'Qiqihar, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u9f50\u9f50\u54c8\u5c14\u5e02')}, '861813213':{'en': 'Zhangjiakou, Hebei', 'zh': u('\u6cb3\u5317\u7701\u5f20\u5bb6\u53e3\u5e02')}, '861813212':{'en': 'Baoding, Hebei', 'zh': u('\u6cb3\u5317\u7701\u4fdd\u5b9a\u5e02')}, '861813211':{'en': 'Shijiazhuang, Hebei', 'zh': u('\u6cb3\u5317\u7701\u77f3\u5bb6\u5e84\u5e02')}, '861813210':{'en': 'Handan, Hebei', 'zh': u('\u6cb3\u5317\u7701\u90af\u90f8\u5e02')}, '861813217':{'en': 'Qinhuangdao, Hebei', 'zh': u('\u6cb3\u5317\u7701\u79e6\u7687\u5c9b\u5e02')}, '861813216':{'en': 'Shijiazhuang, Hebei', 'zh': u('\u6cb3\u5317\u7701\u77f3\u5bb6\u5e84\u5e02')}, '861813215':{'en': 'Tangshan, Hebei', 'zh': u('\u6cb3\u5317\u7701\u5510\u5c71\u5e02')}, '861813214':{'en': 'Handan, Hebei', 'zh': u('\u6cb3\u5317\u7701\u90af\u90f8\u5e02')}, '861811928':{'en': 'Shihezi, Xinjiang', 'zh': u('\u65b0\u7586\u77f3\u6cb3\u5b50\u5e02')}, '861813218':{'en': 'Shijiazhuang, Hebei', 'zh': u('\u6cb3\u5317\u7701\u77f3\u5bb6\u5e84\u5e02')}, '861811690':{'en': 'Ili, Xinjiang', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')}, '861811693':{'en': 'Ili, Xinjiang', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')}, '861769235':{'en': 'Baoding, Hebei', 'zh': u('\u6cb3\u5317\u7701\u4fdd\u5b9a\u5e02')}, '861769234':{'en': 'Baoding, Hebei', 'zh': u('\u6cb3\u5317\u7701\u4fdd\u5b9a\u5e02')}, '861769237':{'en': 'Baoding, Hebei', 'zh': u('\u6cb3\u5317\u7701\u4fdd\u5b9a\u5e02')}, '861769236':{'en': 'Baoding, Hebei', 'zh': u('\u6cb3\u5317\u7701\u4fdd\u5b9a\u5e02')}, '861769231':{'en': 'Zhangjiakou, Hebei', 'zh': u('\u6cb3\u5317\u7701\u5f20\u5bb6\u53e3\u5e02')}, '861769230':{'en': 'Zhangjiakou, Hebei', 'zh': u('\u6cb3\u5317\u7701\u5f20\u5bb6\u53e3\u5e02')}, '861769233':{'en': 'Baoding, Hebei', 'zh': u('\u6cb3\u5317\u7701\u4fdd\u5b9a\u5e02')}, '861769232':{'en': 'Zhangjiakou, Hebei', 'zh': u('\u6cb3\u5317\u7701\u5f20\u5bb6\u53e3\u5e02')}, '861811695':{'en': 'Turpan, Xinjiang', 'zh': u('\u65b0\u7586\u5410\u9c81\u756a\u5730\u533a')}, '861769239':{'en': 'Shijiazhuang, Hebei', 'zh': u('\u6cb3\u5317\u7701\u77f3\u5bb6\u5e84\u5e02')}, '861769238':{'en': 'Baoding, Hebei', 'zh': u('\u6cb3\u5317\u7701\u4fdd\u5b9a\u5e02')}, '861811694':{'en': 'Bayingolin, Xinjiang', 'zh': u('\u65b0\u7586\u5df4\u97f3\u90ed\u695e\u8499\u53e4\u81ea\u6cbb\u5dde')}, '861811697':{'en': 'Ili, Xinjiang', 'zh': u('\u65b0\u7586\u4f0a\u7281\u54c8\u8428\u514b\u81ea\u6cbb\u5dde')}, '861810889':{'en': '<NAME>', 'zh': u('\u4e91\u5357\u7701\u5fb7\u5b8f\u50a3\u65cf\u666f\u9887\u65cf\u81ea\u6cbb\u5dde')}, '861811221':{'en': 'Xuzhou, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u5f90\u5dde\u5e02')}, '861770589':{'en': 'Jinhua, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u91d1\u534e\u5e02')}, '861770588':{'en': 'Jiaxing, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5609\u5174\u5e02')}, '861770581':{'en': 'Hangzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u676d\u5dde\u5e02')}, '861770580':{'en': 'Zhoushan, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u821f\u5c71\u5e02')}, '861770583':{'en': 'Jiaxing, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5609\u5174\u5e02')}, '861770582':{'en': 'Huzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u6e56\u5dde\u5e02')}, '861770585':{'en': 'Shaoxing, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u7ecd\u5174\u5e02')}, '861770584':{'en': 'Ningbo, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u5b81\u6ce2\u5e02')}, '861770587':{'en': 'Wenzhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u6e29\u5dde\u5e02')}, '861770586':{'en': 'Taizhou, Zhejiang', 'zh': u('\u6d59\u6c5f\u7701\u53f0\u5dde\u5e02')}, '861803348':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')}, '861803349':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')}, '861812160':{'en': 'Lianyungang, Jiangsu', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861812161':{'en': 'Li<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u8fde\u4e91\u6e2f\u5e02')}, '861812166':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u6dee\u5b89\u5e02')}, '861812167':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u6dee\u5b89\u5e02')}, '861812164':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u6dee\u5b89\u5e02')}, '861812165':{'en': '<NAME>', 'zh': u('\u6c5f\u82cf\u7701\u6dee\u5b89\u5e02')}, '861803340':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')}, '861803341':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')}, '861803342':{'en': '<NAME>', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')}, '861803343':{'en': 'Shenzhen, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')}, '861803344':{'en': 'Shenzhen, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u6df1\u5733\u5e02')}, '861803345':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')}, '861803346':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')}, '861803347':{'en': 'Dongguan, Guangdong', 'zh': u('\u5e7f\u4e1c\u7701\u4e1c\u839e\u5e02')}, '861770978':{'en': 'Xining, Qinghai', 'zh': u('\u9752\u6d77\u7701\u897f\u5b81\u5e02')}, '861770979':{'en': 'Haixi, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u897f\u8499\u53e4\u65cf\u85cf\u65cf\u81ea\u6cbb\u5dde')}, '861812304':{'en': 'Zigong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u81ea\u8d21\u5e02')}, '861812305':{'en': 'Zigong, Sichuan', 'zh': u('\u56db\u5ddd\u7701\u81ea\u8d21\u5e02')}, '861812302':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u6210\u90fd\u5e02')}, '861812303':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u6210\u90fd\u5e02')}, '861812300':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u6210\u90fd\u5e02')}, '861812301':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u6210\u90fd\u5e02')}, '861770970':{'en': 'Haibei, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u5317\u85cf\u65cf\u81ea\u6cbb\u5dde')}, '861770971':{'en': 'Xining, Qinghai', 'zh': u('\u9752\u6d77\u7701\u897f\u5b81\u5e02')}, '861770972':{'en': 'Haidong, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u4e1c\u5730\u533a')}, '861770973':{'en': 'Huangnan, Qinghai', 'zh': u('\u9752\u6d77\u7701\u9ec4\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde')}, '861770974':{'en': 'Hainan, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u5357\u85cf\u65cf\u81ea\u6cbb\u5dde')}, '861770975':{'en': 'Golog, Qinghai', 'zh': u('\u9752\u6d77\u7701\u679c\u6d1b\u85cf\u65cf\u81ea\u6cbb\u5dde')}, '861770976':{'en': 'Yushu, Qinghai', 'zh': u('\u9752\u6d77\u7701\u7389\u6811\u85cf\u65cf\u81ea\u6cbb\u5dde')}, '861770977':{'en': 'Haixi, Qinghai', 'zh': u('\u9752\u6d77\u7701\u6d77\u897f\u8499\u53e4\u65cf\u85cf\u65cf\u81ea\u6cbb\u5dde')}, '86181336':{'en': 'Hefei, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5408\u80a5\u5e02')}, '86181337':{'en': 'Suzhou, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5bbf\u5dde\u5e02')}, '86181331':{'en': 'Fuyang, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u961c\u9633\u5e02')}, '86181332':{'en': 'Suzhou, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u5bbf\u5dde\u5e02')}, '86181333':{'en': 'Fuyang, Anhui', 'zh': u('\u5b89\u5fbd\u7701\u961c\u9633\u5e02')}, '86181339':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')}, '861804589':{'en': 'Shuangyashan, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u53cc\u9e2d\u5c71\u5e02')}, '861804588':{'en': 'Yichun, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u4f0a\u6625\u5e02')}, '861804583':{'en': 'Daqing, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u5927\u5e86\u5e02')}, '861804582':{'en': 'Shuangyashan, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u53cc\u9e2d\u5c71\u5e02')}, '861804581':{'en': 'Hegang, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u9e64\u5c97\u5e02')}, '861804580':{'en': 'Yichun, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u4f0a\u6625\u5e02')}, '861804587':{'en': 'Hegang, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u9e64\u5c97\u5e02')}, '861804586':{'en': 'Shuangyashan, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u53cc\u9e2d\u5c71\u5e02')}, '861804585':{'en': 'Hegang, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u9e64\u5c97\u5e02')}, '861804584':{'en': 'Daqing, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u5927\u5e86\u5e02')}, '861800699':{'en': 'Quanzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6cc9\u5dde\u5e02')}, '861800698':{'en': 'Sanming, Fujian', 'zh': u('\u798f\u5efa\u7701\u4e09\u660e\u5e02')}, '861800693':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')}, '861800692':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')}, '861800691':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')}, '861800690':{'en': 'Fuzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u798f\u5dde\u5e02')}, '861800697':{'en': 'Longyan, Fujian', 'zh': u('\u798f\u5efa\u7701\u9f99\u5ca9\u5e02')}, '861800696':{'en': 'Zhangzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6f33\u5dde\u5e02')}, '861800695':{'en': 'Zhangzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6f33\u5dde\u5e02')}, '861800694':{'en': 'Zhangzhou, Fujian', 'zh': u('\u798f\u5efa\u7701\u6f33\u5dde\u5e02')}, '861808138':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5b9c\u5bbe\u5e02')}, '861808139':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5b9c\u5bbe\u5e02')}, '861808136':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5b9c\u5bbe\u5e02')}, '861808137':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u5b9c\u5bbe\u5e02')}, '861808134':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u4e50\u5c71\u5e02')}, '861808135':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u4e50\u5c71\u5e02')}, '861808132':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u4e50\u5c71\u5e02')}, '861808133':{'en': '<NAME>', 'zh': u('\u56db\u5ddd\u7701\u4e50\u5c71\u5e02')}, '861808130':{'en': '<NAME>',
) W = ( df.pop(self.weights_col) if (self.weights_col is not None) else pd.Series(np.ones((self._n_examples,)), index=df.index, name="weights") ) _clusters = df.pop(self.cluster_col).values if self.cluster_col else None X = df.astype(float) T = T.astype(float) # we check nans here because converting to bools maps NaNs to True.. check_nans_or_infs(E) E = E.astype(bool) self._check_values(X, T, E, W) return X, T, E, W, original_index, _clusters def _check_values(self, X, T, E, W): check_for_numeric_dtypes_or_raise(X) check_nans_or_infs(T) check_nans_or_infs(X) check_low_var(X) check_complete_separation(X, E, T, self.event_col) # check to make sure their weights are okay if self.weights_col: if (W.astype(int) != W).any() and not self.robust: warnings.warn( """It appears your weights are not integers, possibly propensity or sampling scores then? It's important to know that the naive variance estimates of the coefficients are biased. Instead a) set `robust=True` in the call to `fit`, or b) use Monte Carlo to estimate the variances. See paper "Variance estimation when using inverse probability of treatment weighting (IPTW) with survival analysis" """, StatisticalWarning, ) if (W <= 0).any(): raise ValueError("values in weight column %s must be positive." % self.weights_col) def _fit_model( self, X, T, E, weights=None, initial_point=None, step_size=None, precision=1e-07, show_progress=True, max_steps=50, ): # pylint: disable=too-many-statements,too-many-branches """ Newton Rhaphson algorithm for fitting CPH model. Note ---- The data is assumed to be sorted on T! Parameters ---------- X: (n,d) Pandas DataFrame of observations. T: (n) Pandas Series representing observed durations. E: (n) Pandas Series representing death events. weights: (n) an iterable representing weights per observation. initial_point: (d,) numpy array of initial starting point for NR algorithm. Default 0. step_size: float, optional > 0.001 to determine a starting step size in NR algorithm. precision: float, optional the convergence halts if the norm of delta between successive positions is less than epsilon. show_progress: boolean, optional since the fitter is iterative, show convergence diagnostics. max_steps: int, optional the maximum number of iterations of the Newton-Rhaphson algorithm. Returns ------- beta: (1,d) numpy array. """ self.path = [] assert precision <= 1.0, "precision must be less than or equal to 1." _, d = X.shape # make sure betas are correct size. if initial_point is not None: assert initial_point.shape == (d,) beta = initial_point else: beta = np.zeros((d,)) step_sizer = StepSizer(step_size) step_size = step_sizer.next() # Method of choice is just efron right now if self.tie_method == "Efron": decision = BatchVsSingle.decide(self._batch_mode, T.nunique(), X.shape[0], X.shape[1]) get_gradients = getattr(self, "_get_efron_values_%s" % decision) self._batch_mode = decision == "batch" else: raise NotImplementedError("Only Efron is available.") i = 0 converging = True ll, previous_ll = 0, 0 start = time.time() while converging: self.path.append(beta.copy()) i += 1 if self.strata is None: h, g, ll = get_gradients(X.values, T.values, E.values, weights.values, beta) else: g = np.zeros_like(beta) h = np.zeros((beta.shape[0], beta.shape[0])) ll = 0 for _h, _g, _ll in self._partition_by_strata_and_apply(X, T, E, weights, get_gradients, beta): g += _g h += _h ll += _ll if i == 1 and np.all(beta == 0): # this is a neat optimization, the null partial likelihood # is the same as the full partial but evaluated at zero. # if the user supplied a non-trivial initial point, we need to delay this. self._ll_null_ = ll if self.penalizer > 0: # add the gradient and hessian of the l2 term g -= self.penalizer * beta h.flat[:: d + 1] -= self.penalizer # reusing a piece to make g * inv(h) * g.T faster later try: inv_h_dot_g_T = spsolve(-h, g, assume_a="pos", check_finite=False) except ValueError as e: if "infs or NaNs" in str(e): raise ConvergenceError( """Hessian or gradient contains nan or inf value(s). Convergence halted. Please see the following tips in the lifelines documentation: https://lifelines.readthedocs.io/en/latest/Examples.html#problems-with-convergence-in-the-cox-proportional-hazard-model """, e, ) else: # something else? raise e except LinAlgError as e: raise ConvergenceError( """Convergence halted due to matrix inversion problems. Suspicion is high collinearity. Please see the following tips in the lifelines documentation: https://lifelines.readthedocs.io/en/latest/Examples.html#problems-with-convergence-in-the-cox-proportional-hazard-model """, e, ) delta = inv_h_dot_g_T if np.any(np.isnan(delta)): raise ConvergenceError( """delta contains nan value(s). Convergence halted. Please see the following tips in the lifelines documentation: https://lifelines.readthedocs.io/en/latest/Examples.html#problems-with-convergence-in-the-cox-proportional-hazard-model """ ) # Save these as pending result hessian, gradient = h, g norm_delta = norm(delta) # reusing an above piece to make g * inv(h) * g.T faster. newton_decrement = g.dot(inv_h_dot_g_T) / 2 if show_progress: print( "\rIteration %d: norm_delta = %.5f, step_size = %.4f, ll = %.5f, newton_decrement = %.5f, seconds_since_start = %.1f" % (i, norm_delta, step_size, ll, newton_decrement, time.time() - start), end="", ) # convergence criteria if norm_delta < precision: converging, completed = False, True elif previous_ll != 0 and abs(ll - previous_ll) / (-previous_ll) < 1e-09: # this is what R uses by default converging, completed = False, True elif newton_decrement < precision: converging, completed = False, True elif i >= max_steps: # 50 iterations steps with N-R is a lot. # Expected convergence is ~10 steps converging, completed = False, False elif step_size <= 0.00001: converging, completed = False, False elif abs(ll) < 0.0001 and norm_delta > 1.0: warnings.warn( "The log-likelihood is getting suspiciously close to 0 and the delta is still large. There may be complete separation in the dataset. This may result in incorrect inference of coefficients. \ See https://stats.stackexchange.com/q/11109/11867 for more.\n", ConvergenceWarning, ) converging, completed = False, False beta += step_size * delta previous_ll = ll step_size = step_sizer.update(norm_delta).next() self._hessian_ = hessian self._score_ = gradient self.log_likelihood_ = ll if show_progress and completed: print("Convergence completed after %d iterations." % (i)) elif show_progress and not completed: print("Convergence failed. See any warning messages.") # report to the user problems that we detect. if completed and norm_delta > 0.1: warnings.warn( "Newton-Rhaphson convergence completed but norm(delta) is still high, %.3f. This may imply non-unique solutions to the maximum likelihood. Perhaps there is collinearity or complete separation in the dataset?\n" % norm_delta, ConvergenceWarning, ) elif not completed: warnings.warn( "Newton-Rhaphson failed to converge sufficiently in %d steps.\n" % max_steps, ConvergenceWarning ) return beta def _get_efron_values_single(self, X, T, E, weights, beta): """ Calculates the first and second order vector differentials, with respect to beta. Note that X, T, E are assumed to be sorted on T! A good explanation for Efron. Consider three of five subjects who fail at the time. As it is not known a priori that who is the first to fail, so one-third of (φ1 + φ2 + φ3) is adjusted from sum_j^{5} φj after one fails. Similarly two-third of (φ1 + φ2 + φ3) is adjusted after first two individuals fail, etc. From https://cran.r-project.org/web/packages/survival/survival.pdf: "Setting all weights to 2 for instance will give the same coefficient estimate but halve the variance. When the Efron approximation for ties (default) is employed replication of the data will not give exactly the same coefficients as the weights option, and in this case the weighted fit is arguably the correct one." Parameters ---------- X: array (n,d) numpy array of observations. T: array (n) numpy array representing observed durations. E: array (n) numpy array representing death events. weights: array (n) an array representing weights per observation. beta: array (1, d) numpy array of coefficients. Returns ------- hessian: (d, d) numpy array, gradient: (1, d) numpy array log_likelihood: float """ n, d = X.shape hessian = np.zeros((d, d)) gradient = np.zeros((d,)) log_lik = 0 # Init risk and tie sums to zero x_death_sum = np.zeros((d,)) risk_phi, tie_phi = 0, 0 risk_phi_x, tie_phi_x = np.zeros((d,)), np.zeros((d,)) risk_phi_x_x, tie_phi_x_x = np.zeros((d, d)), np.zeros((d, d)) # Init number of ties and weights weight_count = 0.0 tied_death_counts = 0 scores = weights * np.exp(np.dot(X, beta)) phi_x_is = scores[:, None] * X phi_x_x_i = np.empty((d, d)) # Iterate backwards to utilize recursive relationship for i in range(n - 1, -1, -1): # Doing it like this to preserve shape ti = T[i] ei = E[i] xi = X[i] w = weights[i] # Calculate phi values phi_i = scores[i] phi_x_i = phi_x_is[i] # https://stackoverflow.com/a/51481295/1895939 phi_x_x_i = np.multiply.outer(xi, phi_x_i) # Calculate sums of Risk set risk_phi = risk_phi + phi_i risk_phi_x = risk_phi_x + phi_x_i risk_phi_x_x =
tpath = relativize(tid, wrapped_base.rstrip('/')+'/') if logger: logger.debug('Retrieved zen_type: ' + repr((tid, tpath))) return (tid, tpath) def section(self, title): ''' Helper to extract content from a specific section within the page ''' #FIXME: rethink this "caching" business #logger.debug("section_titled: " + repr(title)) return first_item(self.doc.xml_select(u'//*[@title = "%s"]'%title)) def definition_list(self, list_path, contextnode=None, patterns=None): ''' Helper to construct a dictionary from an indicated definition list on the page ''' #FIXME: rethink this "caching" business #Use defaultdict instead, for performance #patterns = patterns or {None: lambda x: U(x) if x else None} patterns = patterns or {None: lambda x: x} contextnode = contextnode or self.doc.s1 top = contextnode.xml_select(list_path) if not top: return None #Go over the glossentries, and map from term to def, applying the matching #Unit transform function from the patterns dict result = dict((U(l), patterns.get(U(l), patterns[None])(first_item(l.xml_select(u'following-sibling::item')))) for l in top[0].label) #logger.debug("definition_list: " + repr(result)) return result def definition_section(self, title, patterns=None): ''' Helper to extract the first definition list from a named section ''' return self.definition_list(u'.//gloss', contextnode=self.section(title), patterns=patterns) def get_proxy(self, environ, method, accept=None): return self.resource_type.run_rulesheet(environ, method, accept) def absolute_wrap(self, link): link = '/' + link.lstrip('/') #if logger: logger.debug('absolute_wrap: ' + repr((self.original_base, self.wrapped_base, link, self.slave_uri))) wrapped_link, orig_link = wiki_uri(self.original_base, self.wrapped_base, link, self.slave_uri) #if logger: logger.debug('absolute_wrap: ' + repr((link, wrapped_link, orig_link))) return wrapped_link UNSPECIFIED = object() TYPE_PATTERN = u'//*[@title="zen:metadata" or @title="akara:metadata"]/gloss/label[.="zen:type" or .="akara:type"]/following-sibling::item[1]//jump/@url' RULESHEET_LINK_PATTERN = u'//*[@title="zen:metadata" or @title="akara:metadata"]/gloss/label[.="zen:rulesheet" or .="akara:rulesheet"]/following-sibling::item[1]//jump/@url' RULESHEET_ATT_PATTERN = u'//*[@title="zen:metadata" or @title="akara:metadata"]/gloss/label[.="zen:rulesheet" or .="akara:rulesheet"]/following-sibling::item[1]//attachment/@href' class resource_type(resource): def get_rulesheet(self): if self.rulesheet is None: #req = urllib2.Request(self.akara_type(), headers={'Accept': XML_IMT}) #isrc = inputsource(req, resolver=self.resolver) rulesheet_link = U(self.doc.xml_select(RULESHEET_LINK_PATTERN)) if rulesheet_link and not is_absolute(rulesheet_link): wrapped, orig = wiki_uri(self.original_base, self.wrapped_base, rulesheet_link, self.slave_uri) self.rulesheet = wrapped elif rulesheet_link: self.rulesheet = rulesheet_link else: rulesheet_att = U(self.doc.xml_select(RULESHEET_ATT_PATTERN)) if rulesheet_att: self.rulesheet = self.slave_uri + u';attachment=' + rulesheet_att else: if logger: logger.debug("rulesheet unspecified: " + repr((self.doc.xml_encode(),))) self.rulesheet = UNSPECIFIED if self.space: self.space.logger.debug('resource_type.get_rulesheet slave_uri, rulesheet: ' + repr((self.slave_uri, self.rulesheet))) return self.rulesheet def run_rulesheet(self, environ, method='GET', accept='application/json'): #FIXME: Deprecate auth = extract_auth(environ) return rulesheet(self.get_rulesheet(), self.space, auth).run(environ, method, accept) class rulesheet(object): def __init__(self, source, space, auth): ''' ''' #rs = inputsource(source, resolver=resolver) #self.token = rs.stream.readline().strip().lstrip('#') h = httplib2.Http('/tmp/.cache') if auth: user, passwd = auth h.add_credentials(user, passwd) resp, body = h.request(source) stream = cStringIO.StringIO(body) self.token = stream.readline().strip().lstrip('#') #XXX In theory this is a microscopic security hole. If someone could find a way #to open up an expliot by changing whitespace *in the middle of the line* #(wiki_normalize does not touch WS at the beginning of a line) #In practice, we accept this small risk self.body = wiki_normalize(stream.read()) self.space = space return def run(self, environ, method='GET', accept='application/json'): #e.g. you can sign a rulesheet as follows: #python -c "import sys, hashlib; print hashlib.sha1('MYzensecret' + sys.stdin.read()).hexdigest()" < rsheet.py #Make sure the rulesheet has not already been signed (i.e. does not have a hash on the first line) rheet_sig = hashlib.sha1(self.space.zensecret + self.body).hexdigest() if self.token != rheet_sig: if logger: logger.debug("Computed signature: " + repr(rheet_sig)) raise RuntimeError('Security token verification failed') #chunks = [] #U1 is just a smarter variant of the "Unicode, dammit!" def U1(text): return U(text, noneok=True) #def write(text): # chunks.append(text) handlers = {} #Decorator that allows the user to define request handler functions in rule sheets def handles(method, match=None, ttl=3600): ''' method - HTTP method for this handler to use, e.g. 'GET' or 'PUT' Might be a non-standard, internal method for special cases (e.g. 'collect') match - condition to determine when this handler is to be invoked for a given method if a Unicode object, this should be an IMT to compare to the Accept info for the request if a callable, should have signature match(accept), return ing True or False ttl - time-to-live for (GET) requests, for setting cache-control headers ''' def deco(func): func.ttl = ttl # Set appropriate default media type when no match is specified in @handles if match is None : func.imt = 'application/json' else : func.imt = match handlers.setdefault(method, []).append((match, func)) return func return deco #env = {'write': write, 'resource': self, 'service': service, 'U': U1} #resource_getter = partial(node.lookup, resolver=self.rtype.resolver) resource_getter = self.space.resource_factory env = {'service': service_proxy, 'U': U1, 'handles': handles, 'R': resource_getter, 'use': use, 'environ': environ, 'logger': logger, 'H': self.space.h} #Execute the rule sheet exec self.body in env default = None matching_handler = None for (match, func) in handlers.get(method, []): if logger: logger.debug('(match, func), method : ' + repr((match, func)) + "," + method ) if isinstance(match, basestring): if match == accept: matching_handler = func elif (match is None): default = func else: if match(accept): matching_handler = func if logger: logger.debug('(matching_handler, default): ' + repr((matching_handler, default))) return matching_handler or default import amara from amara import tree, bindery from amara.bindery import html from amara.lib.util import first_item from amara.lib import inputsource #from amara import inputsource as baseinputsource from amara.lib.irihelpers import resolver as baseresolver #from amara.namespaces import * #from amara.xslt import transform #from amara.writers.struct import * #from amara.bindery.html import parse as htmlparse #from amara.bindery.model import examplotron_model, generate_metadata, metadata_dict from amara.bindery.util import dispatcher, node_handler, property_sequence_getter from zen.services import zservice, service_proxy #Following is updated on each request, to avoid possible reentrancy problems: #H = httplib2.Http('/tmp/.cache') def cleanup_text_blocks(text): return '\n'.join([line.strip() for line in text.splitlines() ]) def linkify(link, wikibase): ''' Try to construct Moin-style link markup from a given link ''' rel = relativize(link, wikibase) if rel: return u'[[%s]]'%rel else: return u'[[%s]]'%link def curation_ingest(slave_uri, mointext, user, H, auth_headers): ''' ''' import diff_match_patch from akara.util.moin import HISTORY_MODEL resp, content = H.request(slave_uri + ';history', "GET", headers=auth_headers) historydoc = bindery.parse(content, model=HISTORY_MODEL) rev = first_item(dropwhile(lambda rev: unicode(rev.editor) != user, (historydoc.history.rev or []))) if not rev or historydoc.history.rev.editor == user: #New record, or the most recent modification is also by the akara user logger.debug('Direct update (no conflict scenario)') return mointext else: #Potential conflict logger.debug('Potential conflict scenario') resp, curr_akara_rev = H.request(slave_uri + '?rev=' + rev.id, "GET", headers=auth_headers) curr_akara_rev = curation_ingest.wiki_normalize(curr_akara_rev) dmp = diff_match_patch.diff_match_patch() patches = dmp.patch_make(curr_akara_rev, mointext) logger.debug('PATCHES: ' + dmp.patch_toText(patches)) diff_match_patch.patch_fixup(patches) #Uche's hack-around for an apparent bug in diff_match_patch logger.debug('PATCHES: ' + dmp.patch_toText(patches)) #XXX Possible race condition. Should probably figure out a way to get all revs atomically resp, present_rev = H.request(slave_uri, "GET", headers=auth_headers) present_rev = curation_ingest.wiki_normalize(present_rev) patched, flags = dmp.patch_apply(patches, present_rev) logger.debug('PATCH RESULTS: ' + repr((flags))) if all(flags): #Patch can be completely automated return patched else: #At least one patch hunk failed logger.debug('CONFLICT: ' + repr(flags)) return None return DIFF_CMD = 'diff -u' PATCH_CMD = 'patch -p0' def curation_ingest_via_subprocess(slave_uri, mointext, prior_ingested, user, H, auth_headers): ''' Support function for freemix services. Inital processing to guess media type of post body. ''' import os import tempfile from subprocess import Popen, PIPE prior_rev, zen_rev, curated_rev = curation_ingest_versions(slave_uri, user, H, auth_headers) if not curated_rev: #If there has never been a curated rev, we don't have to be on guard for conflicts logger.debug('Direct update (no conflict scenario)') return True, mointext else: #Potential conflict logger.debug('Potential conflict scenario') #We need to diff the latest ingest *candidate* (i.e. mointext) version against the prior ingest *candidate* version oldwiki = tempfile.mkstemp(suffix=".txt") newwiki = tempfile.mkstemp(suffix=".txt") os.write(oldwiki[0], prior_ingested) os.write(newwiki[0], mointext) #os.fsync(oldwiki[0]) #is this needed with the close below? os.close(oldwiki[0]) os.close(newwiki[0]) cmdline = ' '.join([DIFF_CMD, oldwiki[1], newwiki[1]]) logger.debug('cmdline1: \n' + cmdline) process = Popen(cmdline, stdout=PIPE, shell=True) patch = process.stdout.read() logger.debug('PATCHES: \n' + patch) #XXX Possible race condition. Should probably figure out a way to get all revs atomically resp, present_rev = H.request(slave_uri, "GET", headers=auth_headers) present_rev = curation_ingest.wiki_normalize(present_rev) currwiki = tempfile.mkstemp(suffix=".txt") os.write(currwiki[0], present_rev) #os.fsync(currwiki[0]) #is this needed with the close below? os.close(currwiki[0]) cmdline = ' '.join([PATCH_CMD, currwiki[1]]) logger.debug('cmdline1: \n' + cmdline) process = Popen(cmdline, stdin=PIPE, stdout=PIPE, shell=True) process.stdin.write(patch) process.stdin.close() cmdoutput = process.stdout.read() #Apparently process.returncode isn't a useful indicator of patch rejection conflict = 'FAILED' in cmdoutput and 'rejects' in cmdoutput logger.debug('PATCH COMMAND OUTPUT: ' + repr((cmdoutput))) patched = open(currwiki[1]).read() patched = curation_ingest.wiki_normalize(patched) logger.debug('PATCH RESULTS: ' + repr((patched))) logger.debug('RETURN CODE: ' + repr((process.returncode))) process.returncode if conflict: #At least one patch hunk failed #logger.debug('CONFLICT: ' + repr(process.returncode)) return False, patch else: #Patch can be completely automated return True, patched return False, none curation_ingest = curation_ingest_via_subprocess #By default, normalize for curator ops using standard Akara wiki normalization curation_ingest.wiki_normalize = wiki_normalize def
an error creating this review ' 'request.\n') sys.stderr.write('\n') sys.stderr.write('There was no matching repository path' 'found on the server.\n') sys.stderr.write('List of configured repositories:\n') for repository in repositories: sys.stderr.write('\t%s\n' % repository['path']) sys.stderr.write('Unknown repository paths found:\n') for foundpath in self.info.path: sys.stderr.write('\t%s\n' % foundpath) sys.stderr.write('Ask the administrator to add one of ' 'these repositories\n') sys.stderr.write('to the Review Board server.\n') sys.stderr.write('For information on adding repositories, ' 'please read\n') sys.stderr.write(ADD_REPOSITORY_DOCS_URL + '\n') die() repository = options.repository_url or self.info.path try: debug("Attempting to create review request on %s for %s" % (repository, changenum)) data = {} if changenum: data['changenum'] = changenum if submit_as: debug("Submitting the review request as %s" % submit_as) data['submit_as'] = submit_as if self.deprecated_api: data['repository_path'] = repository rsp = self.api_post('api/json/reviewrequests/new/', data) else: data['repository'] = repository links = self.root_resource['links'] assert 'review_requests' in links review_request_href = links['review_requests']['href'] rsp = self.api_post(review_request_href, data) except APIError, e: if e.error_code == 204: # Change number in use rsp = e.rsp if options.diff_only: # In this case, fall through and return to tempt_fate. debug("Review request already exists.") else: debug("Review request already exists. Updating it...") self.update_review_request_from_changenum( changenum, rsp['review_request']) elif e.error_code == 206: # Invalid repository sys.stderr.write('\n') sys.stderr.write('There was an error creating this review ' 'request.\n') sys.stderr.write('\n') sys.stderr.write('The repository path "%s" is not in the\n' % self.info.path) sys.stderr.write('list of known repositories on the server.\n') sys.stderr.write('\n') sys.stderr.write('Ask the administrator to add this ' 'repository to the Review Board server.\n') sys.stderr.write('For information on adding repositories, ' 'please read\n') sys.stderr.write(ADD_REPOSITORY_DOCS_URL + '\n') die() else: raise e else: debug("Review request created") return rsp['review_request'] def update_review_request_from_changenum(self, changenum, review_request): if self.deprecated_api: self.api_post( 'api/json/reviewrequests/%s/update_from_changenum/' % review_request['id']) else: self.api_put(review_request['links']['self']['href'], { 'changenum': review_request['changenum'], }) def set_review_request_field(self, review_request, field, value): """ Sets a field in a review request to the specified value. """ rid = review_request['id'] debug("Attempting to set field '%s' to '%s' for review request '%s'" % (field, value, rid)) if self.deprecated_api: self.api_post('api/json/reviewrequests/%s/draft/set/' % rid, { field: value, }) else: self.api_put(review_request['links']['draft']['href'], { field: value, }) def get_review_request(self, rid): """ Returns the review request with the specified ID. """ if self.deprecated_api: url = 'api/json/reviewrequests/%s/' % rid else: url = '%s%s/' % ( self.root_resource['links']['review_requests']['href'], rid) rsp = self.api_get(url) return rsp['review_request'] def get_repositories(self): """ Returns the list of repositories on this server. """ if self.deprecated_api: rsp = self.api_get('api/json/repositories/') repositories = rsp['repositories'] else: rsp = self.api_get( self.root_resource['links']['repositories']['href']) repositories = rsp['repositories'] while 'next' in rsp['links']: rsp = self.api_get(rsp['links']['next']['href']) repositories.extend(rsp['repositories']) return repositories def get_repository_info(self, rid): """ Returns detailed information about a specific repository. """ if self.deprecated_api: url = 'api/json/repositories/%s/info/' % rid else: rsp = self.api_get( '%s%s/' % (self.root_resource['links']['repositories']['href'], rid)) url = rsp['repository']['links']['info']['href'] rsp = self.api_get(url) return rsp['info'] def save_draft(self, review_request): """ Saves a draft of a review request. """ if self.deprecated_api: self.api_post('api/json/reviewrequests/%s/draft/save/' % \ review_request['id']) else: self.api_put(review_request['links']['draft']['href'], { 'public': 1, }) debug("Review request draft saved") def upload_diff(self, review_request, diff_content, parent_diff_content): """ Uploads a diff to a Review Board server. """ debug("Uploading diff, size: %d" % len(diff_content)) if parent_diff_content: debug("Uploading parent diff, size: %d" % len(parent_diff_content)) fields = {} files = {} if self.info.base_path: fields['basedir'] = self.info.base_path files['path'] = { 'filename': 'diff', 'content': diff_content } if parent_diff_content: files['parent_diff_path'] = { 'filename': 'parent_diff', 'content': parent_diff_content } if self.deprecated_api: self.api_post('api/json/reviewrequests/%s/diff/new/' % review_request['id'], fields, files) else: self.api_post(review_request['links']['diffs']['href'], fields, files) def reopen(self, review_request): """ Reopen discarded review request. """ debug("Reopening") if self.deprecated_api: self.api_post('api/json/reviewrequests/%s/reopen/' % review_request['id']) else: self.api_put(review_request['links']['self']['href'], { 'status': 'pending', }) def publish(self, review_request): """ Publishes a review request. """ debug("Publishing") if self.deprecated_api: self.api_post('api/json/reviewrequests/%s/publish/' % review_request['id']) else: self.api_put(review_request['links']['draft']['href'], { 'public': 1, }) def _get_server_info(self): if not self._server_info: self._server_info = self._info.find_server_repository_info(self) return self._server_info info = property(_get_server_info) def process_json(self, data): """ Loads in a JSON file and returns the data if successful. On failure, APIError is raised. """ rsp = json_loads(data) if rsp['stat'] == 'fail': # With the new API, we should get something other than HTTP # 200 for errors, in which case we wouldn't get this far. assert self.deprecated_api self.process_error(200, data) return rsp def process_error(self, http_status, data): """Processes an error, raising an APIError with the information.""" try: rsp = json_loads(data) assert rsp['stat'] == 'fail' debug("Got API Error %d (HTTP code %d): %s" % (rsp['err']['code'], http_status, rsp['err']['msg'])) debug("Error data: %r" % rsp) raise APIError(http_status, rsp['err']['code'], rsp, rsp['err']['msg']) except ValueError: debug("Got HTTP error: %s: %s" % (http_status, data)) raise APIError(http_status, None, None, data) def http_get(self, path): """ Performs an HTTP GET on the specified path, storing any cookies that were set. """ debug('HTTP GETting %s' % path) url = self._make_url(path) rsp = urllib2.urlopen(url).read() try: self.cookie_jar.save(self.cookie_file) except IOError, e: debug('Failed to write cookie file: %s' % e) return rsp def _make_url(self, path): """Given a path on the server returns a full http:// style url""" if path.startswith('http'): # This is already a full path. return path app = urlparse(self.url)[2] if path[0] == '/': url = urljoin(self.url, app[:-1] + path) else: url = urljoin(self.url, app + path) if not url.startswith('http'): url = 'http://%s' % url return url def api_get(self, path): """ Performs an API call using HTTP GET at the specified path. """ try: return self.process_json(self.http_get(path)) except urllib2.HTTPError, e: self.process_error(e.code, e.read()) def http_post(self, path, fields, files=None): """ Performs an HTTP POST on the specified path, storing any cookies that were set. """ if fields: debug_fields = fields.copy() else: debug_fields = {} if 'password' in debug_fields: debug_fields["password"] = "**************" url = self._make_url(path) debug('HTTP POSTing to %s: %s' % (url, debug_fields)) content_type, body = self._encode_multipart_formdata(fields, files) headers = { 'Content-Type': content_type, 'Content-Length': str(len(body)) } try: r = urllib2.Request(str(url), body, headers) data = urllib2.urlopen(r).read() try: self.cookie_jar.save(self.cookie_file) except IOError, e: debug('Failed to write cookie file: %s' % e) return data except urllib2.HTTPError, e: # Re-raise so callers can interpret it. raise e except urllib2.URLError, e: try: debug(e.read()) except AttributeError: pass die("Unable to access %s. The host path may be invalid\n%s" % \ (url, e)) def http_put(self, path, fields): """ Performs an HTTP PUT on the specified path, storing any cookies that were set. """ url = self._make_url(path) debug('HTTP PUTting to %s: %s' % (url, fields)) content_type, body = self._encode_multipart_formdata(fields, None) headers = { 'Content-Type': content_type, 'Content-Length': str(len(body)) } try: r = HTTPRequest(str(url), body, headers, method='PUT') data = urllib2.urlopen(r).read() try: self.cookie_jar.save(self.cookie_file) except IOError, e: debug('Failed to write cookie file: %s' % e) return data except urllib2.HTTPError, e: # Re-raise so callers can interpret it. raise e except urllib2.URLError, e: try: debug(e.read()) except AttributeError: pass die("Unable to access %s. The host path may be invalid\n%s" % \ (url, e)) def http_delete(self, path): """ Performs an HTTP DELETE on the specified path, storing any cookies that were set. """ url = self._make_url(path) debug('HTTP DELETing %s' % url) try: r = HTTPRequest(url, method='DELETE') data = urllib2.urlopen(r).read() try: self.cookie_jar.save(self.cookie_file) except IOError, e: debug('Failed to write cookie file: %s' % e) return data except urllib2.HTTPError, e: # Re-raise so callers can interpret it. raise e except urllib2.URLError, e: try: debug(e.read()) except AttributeError: pass die("Unable to access %s. The host path may be invalid\n%s" % \ (url, e)) def api_post(self, path, fields=None, files=None): """ Performs an API call using HTTP POST at the specified path. """ try: return self.process_json(self.http_post(path, fields, files)) except urllib2.HTTPError, e: self.process_error(e.code, e.read()) def api_put(self, path, fields=None): """ Performs an API call using HTTP PUT at the specified path. """ try: return self.process_json(self.http_put(path, fields)) except urllib2.HTTPError, e: self.process_error(e.code, e.read()) def api_delete(self, path): """ Performs an API call using HTTP DELETE at the specified path. """ try: return self.process_json(self.http_delete(path)) except urllib2.HTTPError, e: self.process_error(e.code, e.read()) def _encode_multipart_formdata(self, fields, files): """ Encodes data for use in an HTTP POST. """ BOUNDARY = mimetools.choose_boundary() content = "" fields = fields or {} files = files or {} for key in fields: content += "--" + BOUNDARY + "\r\n" content += "Content-Disposition: form-data; name=\"%s\"\r\n" % key content += "\r\n" content += str(fields[key]) + "\r\n" for key in files: filename = files[key]['filename'] value = files[key]['content'] content += "--" + BOUNDARY + "\r\n" content += "Content-Disposition: form-data; name=\"%s\"; " % key content += "filename=\"%s\"\r\n" %
return weakref_proxy(self) CDVolume_swigregister = _Volume.CDVolume_swigregister CDVolume_swigregister(CDVolume) class CRGBAVolume(VPLSwig.Core.Core.CObject, swig_base_RGBAVolume, VPLSwig.Image.Image.CSerializable): """Proxy of C++ vpl::img::CVolume<(vpl::img::tRGBAPixel,vpl::base::CPartedData)> class.""" __swig_setmethods__ = {} for _s in [VPLSwig.Core.Core.CObject, swig_base_RGBAVolume, VPLSwig.Image.Image.CSerializable]: __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {})) __setattr__ = lambda self, name, value: _swig_setattr(self, CRGBAVolume, name, value) __swig_getmethods__ = {} for _s in [VPLSwig.Core.Core.CObject, swig_base_RGBAVolume, VPLSwig.Image.Image.CSerializable]: __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {})) __getattr__ = lambda self, name: _swig_getattr(self, CRGBAVolume, name) __repr__ = _swig_repr CLASS_VOLUME = _Volume.CRGBAVolume_CLASS_VOLUME ITERATOR_DECLARED = _Volume.CRGBAVolume_ITERATOR_DECLARED def __init__(self, *args): """ __init__(self) -> CRGBAVolume __init__(self, XSize, YSize, ZSize, Margin=0) -> CRGBAVolume __init__(self, XSize, YSize, ZSize) -> CRGBAVolume __init__(self, Size, Margin=0) -> CRGBAVolume __init__(self, Size) -> CRGBAVolume __init__(self, Volume, x, y, z, XSize, YSize, ZSize) -> CRGBAVolume __init__(self, Volume, x, y, z, XSize, YSize, ZSize, arg9) -> CRGBAVolume __init__(self, Volume) -> CRGBAVolume __init__(self, Volume, arg3) -> CRGBAVolume __init__(self, Volume) -> CRGBAVolume __init__(self, Volume, arg3) -> CRGBAVolume """ if self.__class__ == CRGBAVolume: _self = None else: _self = self this = _Volume.new_CRGBAVolume(_self, *args) try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _Volume.delete_CRGBAVolume __del__ = lambda self: None def resize(self, *args): """ resize(self, XSize, YSize, ZSize, Margin=0) -> CRGBAVolume resize(self, XSize, YSize, ZSize) -> CRGBAVolume resize(self, Size, Margin=0) -> CRGBAVolume resize(self, Size) -> CRGBAVolume """ return _Volume.CRGBAVolume_resize(self, *args) def copy(self, *args): """ copy(self, Volume, Margin=-1) -> CRGBAVolume copy(self, Volume) -> CRGBAVolume copy(self, Volume, x, y, z, XSize, YSize, ZSize, Margin=-1) -> CRGBAVolume copy(self, Volume, x, y, z, XSize, YSize, ZSize) -> CRGBAVolume copy(self, Volume, Margin=-1) -> CRGBAVolume copy(self, Volume) -> CRGBAVolume """ return _Volume.CRGBAVolume_copy(self, *args) def makeRef(self, *args): """ makeRef(self, Volume) -> CRGBAVolume makeRef(self, Volume, x, y, z, XSize, YSize, ZSize) -> CRGBAVolume makeRef(self, Volume) -> CRGBAVolume """ return _Volume.CRGBAVolume_makeRef(self, *args) def getSize(self, *args): """ getSize(self) -> CSize3_int getSize(self) -> CSize3_int """ return _Volume.CRGBAVolume_getSize(self, *args) def getXSize(self): """getXSize(self) -> vpl::tSize""" return _Volume.CRGBAVolume_getXSize(self) def getYSize(self): """getYSize(self) -> vpl::tSize""" return _Volume.CRGBAVolume_getYSize(self) def getZSize(self): """getZSize(self) -> vpl::tSize""" return _Volume.CRGBAVolume_getZSize(self) def width(self): """width(self) -> vpl::tSize""" return _Volume.CRGBAVolume_width(self) def height(self): """height(self) -> vpl::tSize""" return _Volume.CRGBAVolume_height(self) def depth(self): """depth(self) -> vpl::tSize""" return _Volume.CRGBAVolume_depth(self) def getXOffset(self): """getXOffset(self) -> vpl::tSize""" return _Volume.CRGBAVolume_getXOffset(self) def getYOffset(self): """getYOffset(self) -> vpl::tSize""" return _Volume.CRGBAVolume_getYOffset(self) def getZOffset(self): """getZOffset(self) -> vpl::tSize""" return _Volume.CRGBAVolume_getZOffset(self) def getMargin(self): """getMargin(self) -> vpl::tSize""" return _Volume.CRGBAVolume_getMargin(self) def getIdx(self, x, y, z): """getIdx(self, x, y, z) -> vpl::tSize""" return _Volume.CRGBAVolume_getIdx(self, x, y, z) def __call__(self, *args): """ __call__(self, x, y, z) -> CRGBPixel __call__(self, x, y, z) -> CRGBPixel __call__(self, i) -> CRGBPixel __call__(self, i) -> CRGBPixel """ return _Volume.CRGBAVolume___call__(self, *args) def at(self, *args): """ at(self, x, y, z) -> CRGBPixel at(self, i) -> CRGBPixel """ return _Volume.CRGBAVolume_at(self, *args) def set(self, *args): """ set(self, x, y, z, Value) -> CRGBAVolume set(self, i, Value) -> CRGBAVolume """ return _Volume.CRGBAVolume_set(self, *args) def getPtr(self, *args): """ getPtr(self) -> CRGBPixel getPtr(self) -> CRGBPixel getPtr(self, x, y, z) -> CRGBPixel getPtr(self, x, y, z) -> CRGBPixel """ return _Volume.CRGBAVolume_getPtr(self, *args) def getRowPtr(self, *args): """ getRowPtr(self, y, z) -> CRGBPixel getRowPtr(self, y, z) -> CRGBPixel """ return _Volume.CRGBAVolume_getRowPtr(self, *args) def rect(self, *args): """ rect(self, Position, Size) -> vpl::img::CVolume< vpl::img::CRGBPixel,vpl::base::CPartedData >::tRect rect(self, Position, Size) -> vpl::img::CVolume< vpl::img::CRGBPixel,vpl::base::CPartedData >::tRect const rect(self, XRange, YRange, ZRange) -> vpl::img::CVolume< vpl::img::CRGBPixel,vpl::base::CPartedData >::tRect rect(self, XRange, YRange, ZRange) -> vpl::img::CVolume< vpl::img::CRGBPixel,vpl::base::CPartedData >::tRect const """ return _Volume.CRGBAVolume_rect(self, *args) def row(self, *args): """ row(self, y, z) -> vpl::img::CVolume< vpl::img::CRGBPixel,vpl::base::CPartedData >::tRow row(self, y, z) -> vpl::img::CVolume< vpl::img::CRGBPixel,vpl::base::CPartedData >::tRow const """ return _Volume.CRGBAVolume_row(self, *args) def fill(self, c): """fill(self, c) -> CRGBAVolume""" return _Volume.CRGBAVolume_fill(self, c) def fillEntire(self, c): """fillEntire(self, c) -> CRGBAVolume""" return _Volume.CRGBAVolume_fillEntire(self, c) def fillMargin(self, c): """fillMargin(self, c) -> CRGBAVolume""" return _Volume.CRGBAVolume_fillMargin(self, c) def mirrorMargin(self): """mirrorMargin(self) -> CRGBAVolume""" return _Volume.CRGBAVolume_mirrorMargin(self) def replace(self, Value, NewValue): """replace(self, Value, NewValue) -> CRGBAVolume""" return _Volume.CRGBAVolume_replace(self, Value, NewValue) def abs(self): """abs(self) -> CRGBAVolume""" return _Volume.CRGBAVolume_abs(self) def limit(self, Lower, Upper): """limit(self, Lower, Upper) -> CRGBAVolume""" return _Volume.CRGBAVolume_limit(self, Lower, Upper) def cut(self, Lower, Upper): """cut(self, Lower, Upper) -> CRGBAVolume""" return _Volume.CRGBAVolume_cut(self, Lower, Upper) def subSample(self, Volume, l=2, m=2, n=2): """ subSample(self, Volume, l=2, m=2, n=2) -> CRGBAVolume subSample(self, Volume, l=2, m=2) -> CRGBAVolume subSample(self, Volume, l=2) -> CRGBAVolume subSample(self, Volume) -> CRGBAVolume """ return _Volume.CRGBAVolume_subSample(self, Volume, l, m, n) def interpolate(self, Point): """interpolate(self, Point) -> CRGBPixel""" return _Volume.CRGBAVolume_interpolate(self, Point) def color2Voxel(self, Color): """color2Voxel(self, Color) -> CRGBPixel""" return _Volume.CRGBAVolume_color2Voxel(self, Color) def checkPosition(self, x, y, z): """checkPosition(self, x, y, z) -> bool""" return _Volume.CRGBAVolume_checkPosition(self, x, y, z) def getPlaneXY(self, z, Plane): """getPlaneXY(self, z, Plane) -> bool""" return _Volume.CRGBAVolume_getPlaneXY(self, z, Plane) def getPlaneXZ(self, y, Plane): """getPlaneXZ(self, y, Plane) -> bool""" return _Volume.CRGBAVolume_getPlaneXZ(self, y, Plane) def getPlaneYZ(self, x, Plane): """getPlaneYZ(self, x, Plane) -> bool""" return _Volume.CRGBAVolume_getPlaneYZ(self, x, Plane) def setPlaneXY(self, z, Plane): """setPlaneXY(self, z, Plane) -> bool""" return _Volume.CRGBAVolume_setPlaneXY(self, z, Plane) def setPlaneXZ(self, y, Plane): """setPlaneXZ(self, y, Plane) -> bool""" return _Volume.CRGBAVolume_setPlaneXZ(self, y, Plane) def setPlaneYZ(self, x, Plane): """setPlaneYZ(self, x, Plane) -> bool""" return _Volume.CRGBAVolume_setPlaneYZ(self, x, Plane) def enableDummyMode(self, Enable): """enableDummyMode(self, Enable) -> CRGBAVolume""" return _Volume.CRGBAVolume_enableDummyMode(self, Enable) def isDummy(self): """isDummy(self) -> bool""" return _Volume.CRGBAVolume_isDummy(self) def __disown__(self): self.this.disown() _Volume.disown_CRGBAVolume(self) return weakref_proxy(self) CRGBAVolume_swigregister = _Volume.CRGBAVolume_swigregister CRGBAVolume_swigregister(CRGBAVolume) class CComplexVolume(VPLSwig.Core.Core.CObject, swig_base_ComplexVolume, VPLSwig.Image.Image.CSerializable): """Proxy of C++ vpl::img::CVolume<(vpl::img::tComplexPixel,vpl::base::CPartedData)> class.""" __swig_setmethods__ = {} for _s in [VPLSwig.Core.Core.CObject, swig_base_ComplexVolume, VPLSwig.Image.Image.CSerializable]: __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {})) __setattr__ = lambda self, name, value: _swig_setattr(self, CComplexVolume, name, value) __swig_getmethods__ = {} for _s in [VPLSwig.Core.Core.CObject, swig_base_ComplexVolume, VPLSwig.Image.Image.CSerializable]: __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {})) __getattr__ = lambda self, name: _swig_getattr(self, CComplexVolume, name) __repr__ = _swig_repr CLASS_VOLUME = _Volume.CComplexVolume_CLASS_VOLUME ITERATOR_DECLARED = _Volume.CComplexVolume_ITERATOR_DECLARED def __init__(self, *args): """ __init__(self) -> CComplexVolume __init__(self, XSize, YSize, ZSize, Margin=0) -> CComplexVolume __init__(self, XSize, YSize, ZSize) -> CComplexVolume __init__(self, Size, Margin=0) -> CComplexVolume __init__(self, Size) -> CComplexVolume __init__(self, Volume, x, y, z, XSize, YSize, ZSize) -> CComplexVolume __init__(self, Volume, x, y, z, XSize, YSize, ZSize, arg9) -> CComplexVolume __init__(self, Volume) -> CComplexVolume __init__(self, Volume, arg3) -> CComplexVolume __init__(self, Volume) -> CComplexVolume __init__(self, Volume, arg3) -> CComplexVolume """ if self.__class__ == CComplexVolume: _self = None else: _self = self this = _Volume.new_CComplexVolume(_self, *args) try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _Volume.delete_CComplexVolume __del__ = lambda self: None def resize(self, *args): """ resize(self, XSize, YSize, ZSize, Margin=0) -> CComplexVolume resize(self, XSize, YSize, ZSize) -> CComplexVolume resize(self, Size, Margin=0) -> CComplexVolume resize(self, Size) -> CComplexVolume """ return _Volume.CComplexVolume_resize(self, *args) def copy(self, *args): """ copy(self, Volume, Margin=-1) -> CComplexVolume copy(self, Volume) -> CComplexVolume copy(self, Volume, x, y, z, XSize, YSize, ZSize, Margin=-1) -> CComplexVolume copy(self, Volume, x, y, z, XSize, YSize, ZSize) -> CComplexVolume copy(self, Volume, Margin=-1) -> CComplexVolume copy(self, Volume) -> CComplexVolume """ return _Volume.CComplexVolume_copy(self, *args) def makeRef(self, *args): """ makeRef(self, Volume) -> CComplexVolume makeRef(self, Volume, x, y, z, XSize, YSize, ZSize) -> CComplexVolume makeRef(self, Volume) -> CComplexVolume """ return _Volume.CComplexVolume_makeRef(self, *args) def getSize(self, *args): """ getSize(self) -> CSize3_int getSize(self) -> CSize3_int """ return _Volume.CComplexVolume_getSize(self, *args) def getXSize(self): """getXSize(self) -> vpl::tSize""" return _Volume.CComplexVolume_getXSize(self) def getYSize(self): """getYSize(self) -> vpl::tSize""" return _Volume.CComplexVolume_getYSize(self) def getZSize(self): """getZSize(self) -> vpl::tSize""" return _Volume.CComplexVolume_getZSize(self) def width(self): """width(self) -> vpl::tSize""" return _Volume.CComplexVolume_width(self) def height(self): """height(self) -> vpl::tSize""" return _Volume.CComplexVolume_height(self) def depth(self): """depth(self) -> vpl::tSize""" return _Volume.CComplexVolume_depth(self) def getXOffset(self): """getXOffset(self) -> vpl::tSize""" return _Volume.CComplexVolume_getXOffset(self) def getYOffset(self): """getYOffset(self) -> vpl::tSize""" return _Volume.CComplexVolume_getYOffset(self) def getZOffset(self): """getZOffset(self) -> vpl::tSize""" return _Volume.CComplexVolume_getZOffset(self) def getMargin(self): """getMargin(self) -> vpl::tSize""" return _Volume.CComplexVolume_getMargin(self) def getIdx(self, x, y, z): """getIdx(self, x, y, z) -> vpl::tSize""" return _Volume.CComplexVolume_getIdx(self, x, y, z) def __call__(self, *args): """ __call__(self, x, y, z) -> vpl::math::CComplex< float > __call__(self, x, y, z) -> vpl::math::CComplex< float > const __call__(self, i) -> vpl::math::CComplex< float > __call__(self, i) -> vpl::math::CComplex< float > const & """ return _Volume.CComplexVolume___call__(self, *args) def at(self, *args): """ at(self, x, y, z) -> vpl::math::CComplex< float > const at(self, i) -> vpl::math::CComplex< float > const & """ return _Volume.CComplexVolume_at(self, *args) def set(self, *args): """ set(self, x, y, z, Value) -> CComplexVolume set(self, i, Value) -> CComplexVolume """ return _Volume.CComplexVolume_set(self, *args) def getPtr(self, *args): """ getPtr(self) -> vpl::math::CComplex< float > getPtr(self) -> vpl::math::CComplex< float > const getPtr(self, x, y, z) -> vpl::math::CComplex< float > getPtr(self, x, y, z) -> vpl::math::CComplex< float > const * """ return _Volume.CComplexVolume_getPtr(self, *args) def getRowPtr(self,
<gh_stars>0 from __future__ import absolute_import from matplotlib import pyplot as plt import numpy as np from preprocess import get_data class Model: """ This model class will contain the architecture for your single layer Neural Network for classifying MNIST with batched learning. Please implement the TODOs for the entire model but do not change the method and constructor arguments. Make sure that your Model class works with multiple batch sizes. Additionally, please exclusively use NumPy and Python built-in functions for your implementation. """ def __init__(self): # TODO: Initialize all hyperparametrs self.input_size = 784 # Size of image vectors self.num_classes = 10 # Number of classes/possible labels self.batch_size = 100 self.learning_rate = 0.5 # TODO: Initialize weights and biases self.W = np.zeros((self.input_size, self.num_classes)) self.b = np.zeros((1, self.num_classes)) def call(self, inputs): """ Does the forward pass on an batch of input images. :param inputs: normalized (0.0 to 1.0) batch of images, (batch_size x 784) (2D), where batch can be any number. :return: probabilities for each class per image # (batch_size x 10) """ # TODO: Write the forward pass logic for your model # TODO: Calculate, then return, the probability for each class per image using the Softmax equation logits = np.dot(inputs,self.W) + self.b e_l = np.exp(logits) # calculate the e_l for each logits e_sum = np.sum(e_l,axis = 1).reshape(-1, 1) # sum of e_l per image prob = e_l / e_sum.reshape(-1, 1)# probabilities for each class per image return prob def loss(self, probabilities, labels): """ Calculates the model cross-entropy loss after one forward pass. Loss should be decreasing with every training loop (step). NOTE: This function is not actually used for gradient descent in this assignment, but is a sanity check to make sure model is learning. :param probabilities: matrix that contains the probabilities of each class for each image :param labels: the true batch labels :return: average loss per batch element (float) """ # TODO: Calculate average cross-entropy loss for a batch pc = np.zeros(self.batch_size) # record only the prob of the correct label for i in range(self.batch_size): pc[i] = probabilities[i,labels[i]] # cross-entropy loss for each image loss = -np.log(pc) mean_loss = np.mean(loss) #print(mean_loss) return mean_loss def back_propagation(self, inputs, probabilities, labels): """ Returns the gradients for model's weights and biases after one forward pass and loss calculation. The learning algorithm for updating weights and biases mentioned in class works for one image, but because we are looking at batch_size number of images at each step, you should take the average of the gradients across all images in the batch. :param inputs: batch inputs (a batch of images) :param probabilities: matrix that contains the probabilities of each class for each image :param labels: true labels :return: gradient for weights, and gradient for biases """ # TODO: Calculate the gradients for the weights and the gradients for the bias with respect to average loss # "one-hot encoding" for labels, the true label has a value of 1, others has a value of 0 y = np.zeros((len(labels),self.num_classes)) y = np.zeros((self.batch_size,self.num_classes)) for i in range(self.batch_size): y[i,labels[i]] = 1 # the gradients are the dot products of the inputs and (y_j - p_j) # for batch size > 1, each entry of the dot products would be a # sum of the grad of the parameter for all images in the batch, # so divide by batch size to get the average gradient # result is a (784 x 10) matrix, each is a gradient for a weight gradW = np.dot(inputs.T,(probabilities - y))/ self.batch_size # calculate gradient for bias gradB = np.sum((probabilities - y),axis = 0)/ self.batch_size return gradW, gradB def accuracy(self, probabilities, labels): """ Calculates the model's accuracy by comparing the number of correct predictions with the correct answers. :param probabilities: result of running model.call() on test inputs :param labels: test set labels :return: batch accuracy (float [0,1]) """ # TODO: Calculate the batch accuracy # make the prediction and reshape it into a column pred = np.argmax(probabilities, axis = 1).reshape(-1,1) accuracy = np.sum(pred == labels) / len(labels) return accuracy def gradient_descent(self, gradW, gradB): ''' Given the gradients for weights and biases, does gradient descent on the Model's parameters. :param gradW: gradient for weights :param gradB: gradient for biases :return: None ''' # TODO: Change the weights and biases of the model to descend the gradient self.W -= self.learning_rate * gradW self.b -= self.learning_rate * gradB def train(model, train_inputs, train_labels): ''' Trains the model on all of the inputs and labels. :param model: the initialized model to use for the forward pass and backward pass :param train_inputs: train inputs (all inputs to use for training) :param train_inputs: train labels (all labels to use for training) :return: None ''' # TODO: Iterate over the training inputs and labels, in model.batch_size increments and do forward pass # TODO: For every batch, compute and then descend the gradients for the model's weights # Optional TODO: Call visualize_loss and observe the loss per batch as the model trains t = int(train_inputs.shape[0] / model.batch_size) losses = [] for i in range(t): inputs = train_inputs[model.batch_size * i : model.batch_size * (i + 1), :] labels = train_labels[model.batch_size * i : model.batch_size * (i + 1)] probabilities = model.call(inputs) losses.append(model.loss(probabilities, labels)) gradW, gradB = model.back_propagation(inputs, probabilities, labels) model.gradient_descent(gradW, gradB) visualize_loss(losses) # show the loss per batch as the model trains def test(model, test_inputs, test_labels): """ Tests the model on the test inputs and labels. For this assignment, the inputs should be the entire test set, but in the future we will ask you to batch it instead. :param test_inputs: MNIST test data (all images to be tested) :param test_labels: MNIST test labels (all corresponding labels) :return: accuracy (float [0,1]) """ # TODO: Iterate over the testing inputs and labels # TODO: Return accuracy across testing set prob = model.call(test_inputs) accuracy = model.accuracy(prob, test_labels) return accuracy def visualize_loss(losses): """ NOTE: DO NOT EDIT Uses Matplotlib to visualize loss per batch. Call this in train(). When you observe the plot that's displayed, think about: 1. What does the plot demonstrate or show? 2. How long does your model need to train to reach roughly its best accuracy so far, and how do you know that? Optionally, add your answers to README! :param losses: an array of loss value from each batch of train :return: does not return anything, a plot should pop-up """ x = np.arange(1, len(losses)+1) plt.xlabel('i\'th Batch') plt.ylabel('Loss Value') plt.title('Loss per Batch') plt.plot(x, losses) plt.show() def visualize_results(image_inputs, probabilities, image_labels): """ NOTE: DO NOT EDIT Uses Matplotlib to visualize the results of our model. :param image_inputs: image data from get_data() :param probabilities: the output of model.call() :param image_labels: the labels from get_data() :return: does not return anything, a plot should pop-up """ images = np.reshape(image_inputs, (-1, 28, 28)) predicted_labels = np.argmax(probabilities, axis=1) num_images = images.shape[0] fig, axs = plt.subplots(ncols=num_images) fig.suptitle("PL = Predicted Label\nAL = Actual Label") for ind, ax in enumerate(axs): ax.imshow(images[ind], cmap="Greys") ax.set(title="PL: {}\nAL: {}".format(predicted_labels[ind], image_labels[ind])) plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) ax.tick_params(axis='both', which='both', length=0) plt.show() def main(): ''' Read in MNIST data, initialize your model, and train and test your model for one epoch. The number of training steps should be your the number of batches you run through in a single epoch. You should receive a final accuracy on the testing examples of > 80%. :return: None ''' # TODO: load MNIST train and test examples into train_inputs, train_labels, test_inputs, test_labels train_inputs, train_labels = get_data("../../data/train-images-idx3-ubyte.gz", "../../data/train-labels-idx1-ubyte.gz", 60000) test_inputs, test_labels = get_data("../../data/t10k-images-idx3-ubyte.gz", "../../data//t10k-labels-idx1-ubyte.gz", 10000) # TODO: Create Model model = Model() # TODO: Train model by
import cv2 import numpy as np import matplotlib.pyplot as plt class Lane(): fig = plt.figure() plt.ion() def __init__(self, focal_point=None, roi_height=None, source_pts=None): # initalises common variables in the class # focal_point : location of the focal point of the lane. Can be the # vanishing point of the image # roi_height : height where the lane region of interest is at most # considered # source_pts : bottom start points of the lane roi if focal_point is None: self.focal_point = [0,0] else: self.focal_point = focal_point if roi_height is None: self.roi_height = 0. else: self.roi_height = roi_height if source_pts is None: self.source_pts = [[0, 0], [0, 0]] else: self.source_pts = source_pts self.roi_pts = np.float32([[0, 0], [0, 0], [0, 0], [0, 0]]) self.left_fit = None self.right_fit = None def lane_roi(self, img_shape, roi_height=None, focal_point=None, source_pts=None): # defines a lanes region of interest # img_shape : shape of the input image # roi_height : the pixel height of the higest point of interest # focal_point : location of the focal focal_point. If None, will use the center of the image # source_pts : location of the two bottom corner points # return : coordinates of the region of interest of a lane if focal_point is None: focal_point = self.focal_point if roi_height is None: roi_height = self.roi_height h = img_shape[0] # image height # top of the roi is a factor of the height from the bottom of the roi # to the focal point. # ratio = (1 - fph/h) -> focal point position compared to the height # inv_fp = (1 - fph/h)*h -> inverse focal position # h_top = (ratio * (1 - roi_height)) * inv_fp # h_top is the y position of the height with respect to the focal fph = self.focal_point[1] # height of focal point fp_ratio = (1 - fph / h) h_top = h * fp_ratio**2 * (1 - roi_height) if source_pts is None: # create the source points as the two bottom corners of the image source_pts = self.source_pts m_left = (focal_point[1] - source_pts[0][1]) / (focal_point[0] - source_pts[0][0]) b_left = focal_point[1] - (m_left * focal_point[0]) x_left = (h_top - b_left) // m_left m_right = (focal_point[1] - source_pts[1][1]) / (focal_point[0] - source_pts[1][0]) b_right = focal_point[1] - (m_right * focal_point[0]) x_right = (h_top - b_right) // m_right self.roi_pts = np.float32([source_pts[0], [x_left, h_top], [x_right, h_top], source_pts[1]]) return self.roi_pts def draw_lane_roi(self, img, roi_pts=None, focal_point=None, color=(255, 255, 255)): # draws the region of interest onto the supplied image # img : source image # roi_pts : coordinate points of the region of interest # focal_point : location of the focal focal_point # return : the supplied image with the roi drawn on if focal_point is None: focal_point = self.focal_point if roi_pts is None: roi_pts = self.roi_pts image = img.copy() pts = np.int32(roi_pts) pts = pts.reshape((-1, 1, 2)) cv2.circle(image, (focal_point[0], focal_point[1]), 5, color, 2) cv2.polylines(image, [pts], True, color, 2) return image def warp_image(self, img, roi_pts=None, location_pts=None, padding=(0,0)): # img : image to be transformed into the new perspective # roi_pts : location points from the original image to be transformed. # Points must be in a clock wise order. # location_pts : the final location points in the image where the # old_pts will be located. If None supplied, the new points # will be the four corners off the supplied image in a # clockwise order, starting at point (0,0). # offset : adds padding onto the roi points so the warped image is # larger than the roi. Supplied as (width, height) padding # returns : the warped perspective image with the supplied points if roi_pts is None: roi_pts = self.roi_pts h, w = img.shape[:2] if location_pts is None: location_pts = np.float32([[padding[0], h-padding[1]], # bot-left [padding[0], padding[1]], # top-left [w-padding[0], padding[1]], # top-right [w-padding[0], h-padding[1]]]) # bot-right # calculate the perspective transform matrix between the old and new points M = cv2.getPerspectiveTransform(roi_pts, location_pts) # Warp the image to the new perspective return cv2.warpPerspective(img, M, (w, h)) def mask_roi(self, img, roi_pts=None, outside_mask=True): # create a masked image showing only the area of the roi_pts # img : source image to be masked # roi_pts : region for masking # outside_mask : True if masking area outside roi, False if masking roi # return : masked image if roi_pts is None: roi_pts = self.roi_pts pts = np.int32(roi_pts) pts = [pts.reshape((-1, 1, 2))] # create a blank image to create a threshold """mask = np.ones_like(img) ignore_mask_color = (0, 0, 0) # *channel_count # create a polygon that is white m = cv2.fillPoly(mask, pts, ignore_mask_color)""" mask = np.zeros_like(img) ignore_mask_color = (255, 255, 255) # *channel_count # create a polygon that is white m = cv2.fillPoly(mask, pts, ignore_mask_color) # return the applyed mask if outside_mask == False: m = cv2.bitwise_not(m) return cv2.bitwise_and(img, m) else: return cv2.bitwise_and(img, mask) def combine_images(self, img_one, img_two, img_one_weight=0.8, img_two_weight=1.): # combines two images into one for display purposes # img_one : image one # img_two : image two # img_one_weight : transparency weight of image one # img_two_weight : transparency weight of image two # return : combined image return cv2.addWeighted(img_one, img_one_weight, img_two, img_two_weight, 0) def gauss(self, x, mu, sigma, A): # creates a gaussian distribution from the data # x : input data # mu : mean data point # sigma : variance from the mean # return : Gaussian distribution return A * np.exp(-(x - mu) ** 2 / 2 / sigma ** 2) def bimodal(self, x, mu1, sigma1, A1, mu2, sigma2, A2): return self.gauss(x, mu1, sigma1, A1) + self.gauss(x, mu2, sigma2, A2) def plot_histogram(self, data): # plot a real time histogram of the supplied data # data : data to plot plt.clf() plt.plot(data) plt.pause(0.00001) def histogram(self, data): # calculates the histogram of data # data : data to be transformed into a histogram # returns : a vector of the histogram data return np.sum(data, axis=0) def histogram_peaks(self, data, plot_hist=False): hist = self.histogram(data) if plot_hist == True: self.plot_histogram(hist) midpoint = np.int(hist.shape[0] // 2) leftx_base = np.argmax(hist[:midpoint]) rightx_base = np.argmax(hist[midpoint:]) + midpoint return leftx_base, rightx_base def plot_best_fit(self, img, nonzerox, nonzeroy, left_lane_inds, right_lane_inds, margin=100): # Generate x and y values for plotting ploty = np.linspace(0, img.shape[0] - 1, img.shape[0]) left_fitx = self.left_fit[0] * ploty ** 2 + self.left_fit[1] * ploty + self.left_fit[2] right_fitx = self.right_fit[0] * ploty ** 2 + self.right_fit[1] * ploty + self.right_fit[2] # Create an image to draw on and an image to show the selection window out_img = np.dstack((img, img, img)) * 255 window_img = np.zeros_like(out_img) # Color in left and right line pixels out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0] out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255] # Generate a polygon to illustrate the search window area # And recast the x and y points into usable format for cv2.fillPoly() left_line_window1 = np.array([np.transpose(np.vstack([left_fitx - margin, ploty]))]) left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx + margin, ploty])))]) left_line_pts = np.hstack((left_line_window1, left_line_window2)) right_line_window1 = np.array([np.transpose(np.vstack([right_fitx - margin, ploty]))]) right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx + margin, ploty])))]) right_line_pts = np.hstack((right_line_window1, right_line_window2)) # Draw the lane onto the warped blank image cv2.fillPoly(window_img, np.int_([left_line_pts]), (0, 255, 0)) cv2.fillPoly(window_img, np.int_([right_line_pts]), (0, 255, 0)) result = self.combine_images(out_img, window_img, img_one_weight=1, img_two_weight=0.3) cv2.imshow('result', result) # visulise the output of the function def find_lane_lines(self, img, line_windows=10, plot_line=False, draw_square=False): out_img = img.copy() # Set height of windows window_height = np.int(img.shape[0] / line_windows) # Identify the x and y positions of all nonzero pixels in the image nonzero = img.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated for each window leftx, rightx = self.histogram_peaks(img) leftx_current = leftx rightx_current = rightx # Set the width of the windows +/- margin margin = 100 # Set minimum number of pixels found to recenter window minpix = 50 # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] # Step through
# encoding: utf-8 # (c) 2019 Open Risk (https://www.openriskmanagement.com) # # correlationMatrix is licensed under the Apache 2.0 license a copy of which is included # in the source distribution of correlationMatrix. This is notwithstanding any licenses of # third-party software included in this distribution. You may not use this file except in # compliance with the License. # # Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific language governing permissions and # limitations under the License. """ This module provides the key correlation matrix classes * correlationMatrix_ implements the functionality of single period correlation matrix * TODO correlationMatrixSet_ provides a container for a multiperiod correlation matrix collection * TODO PairwiseCorrelation implements functionality for pairwise data analysis of timeseries * EmpiricalCorrelationMatrix implements the functionality of a continuously observed correlation matrix """ import json import numpy as np import pandas as pd import requests import scipy.stats as sp from scipy.linalg import eigh from scipy.linalg import inv from scipy.linalg import lstsq from sklearn.preprocessing import scale from correlationMatrix.settings import EIGENVALUE_TOLERANCE from correlationMatrix.utils.converters import matrix_print def get_data(data_url): r = requests.get(data_url) return r.json() def make_uniform(dates1, values1, dates2, values2): # make the two timeseries arrays uniform (select common observation dates) # find common dates # return values on common dates common_dates = list(set(dates1).intersection(dates2)) new_values1 = [] new_values2 = [] for date in common_dates: i1 = dates1.index(date) i2 = dates2.index(date) new_values1.append(values1[i1]) new_values2.append(values2[i2]) x = new_values1 y = new_values2 return x, y class PairwiseCorrelation(object): # calculate the linear (Pearson) correlation def pearsonr(self, x, y): rho, p = sp.kendalltau(x, y) return rho, p # calculate the kendall correlation between two timeseries def kendallr(self, x, y): rho, p = sp.kendalltau(x, y) return rho, p # calculate the spearman correlation def spearmanr(self, x, y): rho, p = sp.spearmanr(x, y) return rho, p def calculate(self, model_name, input1_url, input2_url): # Get data from URL # TODO specify valid formats raw_data1 = get_data(input1_url) raw_data2 = get_data(input2_url) # Process response (API dependent) json_string1 = raw_data1['_items'][0]['json_dump'] Data1 = json.loads(json_string1) dates1 = Data1['Dates'] values1 = Data1['Values'] json_string2 = raw_data2['_items'][0]['json_dump'] Data2 = json.loads(json_string2) dates2 = Data2['Dates'] values2 = Data2['Values'] # Make data uniform # TODO expand on missing data / dataquality treatment x, y = make_uniform(dates1, values1, dates2, values2) rho = None p = None if model_name == 'Pearson_Correlation': rho, p = self.pearsonr(x, y) elif model_name == 'Kendall_Correlation': rho, p = self.kendallr(x, y) elif model_name == 'Spearman_Correlation': rho, p = self.spearmanr(x, y) return {'rho': rho, 'p': p} class CorrelationMatrix: # class CorrelationMatrix(np.matrix): """ The _`correlationMatrix` object implements a typical (one period) `correlation matrix <https://www.openriskmanual.org/wiki/correlation_Matrix>`_. The class inherits from numpy ndarray (instead of matrix because the latter will be deprecated It implements additional properties specific to correlation matrices. It forms the building block of the correlationMatrixSet_ which holds a collection of matrices in increasing temporal order (to capture systems with time varying correlation) This class does not implement any estimation method, this task is relegated to classes EmpiricalCorrelationMatrix -> Full empirical estimation FactorCorrelationMatrix -> Factor Model estimation PCAMatrix -> PCA Model estimation """ def __init__(self, values=None, type=None, json_file=None, csv_file=None, **kwargs): """ Create a new correlation matrix. Different options for initialization are: * providing values as a list of list * providing values as a numpy array * indicating matrix type and additional parameters * loading values from a csv file * loading values from a json file The above initializations are mutually exclusive and are tested until a valid option is found. Without a valid option, a default identity matrix is generated :param values: initialization values :param type: matrix dimensionality (default is 2) :param json_file: a json file containing correlation matrix data :param csv_file: a csv file containing correlation matrix data :type values: list of lists or numpy array :type type: string :returns: returns a correlationMatrix object :rtype: object .. note:: The initialization in itself does not validate if the provided values form indeed a correlation matrix :Example: .. code-block:: python A = cm.correlationMatrix(values=[[0.6, 0.2, 0.2], [0.2, 0.6, 0.2], [0.2, 0.2, 0.6]]) """ if values is not None: # Initialize with given values self.matrix = np.asarray(values) self.validated = False elif type is not None: self.matrix = np.identity(2) if type == 'UniformSingleFactor': rho = kwargs.get('rho') n = kwargs.get('n') tmp1 = np.identity(n) tmp2 = rho * (np.tri(n) - tmp1) tmp3 = tmp2.transpose() self.matrix = np.asarray(tmp1 + tmp2 + tmp3) elif type == 'TBD': pass else: pass # validation flag is set to True for modelled Matrices self.validated = True elif json_file is not None: # Initialize from file in json format q = pd.read_json(json_file) self.matrix = np.asarray(q.values) self.validated = False elif csv_file is not None: # Initialize from file in csv format q = pd.read_csv(csv_file, index_col=None) self.matrix = np.asarray(q.values) self.validated = False else: # Default instance (2x2 identity matrix) default = np.identity(2) self.matrix = np.asarray(default) self.validated = False # temporary dimension assignment (must validated for squareness) self.dimension = self.matrix.shape[0] def to_json(self, file): """ Write correlation matrix to file in json format :param file: json filename """ q = pd.DataFrame(self.matrix) q.to_json(file, orient='values') def to_csv(self, file): """ Write correlation matrix to file in csv format :param file: csv filename """ q = pd.DataFrame(self.matrix) q.to_csv(file, index=None) def to_html(self, file=None): html_table = pd.DataFrame(self).to_html() if file is not None: file = open(file, 'w') file.write(html_table) file.close() return html_table def fix_negative_values(self): """ If a matrix entity is below zero, set to zero and correct the diagonal element to enforce """ matrix = self.matrix matrix_size = matrix.shape[0] # For all rows # Search all cols for negative entries for i in range(matrix_size): for j in range(matrix_size): if matrix[i, j] < 0.0: self.matrix[i, j] = 0.0 def validate(self, accuracy=1e-3): """ Validate required properties of an input correlation matrix. The following are checked 1. check squareness 2. check symmetry 3. check that all values are between -1 and 1 and diagonal elements == 1 4. check positive definiteness :param accuracy: accuracy level to use for validation :type accuracy: float :returns: List of tuples with validation messages """ validation_messages = [] matrix = self.matrix # checking squareness of matrix if matrix.shape[0] != matrix.shape[1]: validation_messages.append(("Matrix Dimensions Differ: ", matrix.shape)) else: matrix_size = matrix.shape[0] # checking that values of matrix are within allowed range for i in range(matrix_size): if matrix[i, i] != 1: validation_messages.append(("Diagonal Values different than 1: ", (i, matrix[i, i]))) for j in range(matrix_size): if matrix[i, j] < -1: validation_messages.append(("Values less than -1: ", (i, j, matrix[i, j]))) if matrix[i, j] > 1: validation_messages.append(("Values larger than 1: ", (i, j, matrix[i, j]))) # checking symmetry for i in range(matrix_size): for j in range(matrix_size): if matrix[i, j] != matrix[j, i]: validation_messages.append(("Symmetry violating value: ", (i, j, matrix[i, j]))) # checking positive semi-definitess (non-negative eigenvalues) Eigenvalues, Decomposition = eigh(matrix) if not np.all(Eigenvalues > - EIGENVALUE_TOLERANCE): validation_messages.append(("Matrix is not positive semi-definite")) if len(validation_messages) == 0: self.validated = True self.dimension = matrix.shape[0] return self.validated else: self.validated = False return validation_messages def inverse(self): """ Compute the inverse of a correlation matrix (assuming it is a valid matrix) :Example: G = A.inverse() """ if self.validated: inverse = inv(self.matrix) return inverse else: self.validate() if self.validated: inverse = inv(self.matrix) return inverse else: print("Invalid Correlation Matrix") def distance(self): """ Compute Euclidean distances implied by a correlation matrix (assuming it is a valid matrix) :Example: G = A.distance() """ if self.validated: distance = np.sqrt(2.0 * (1.0 - self.matrix)) return distance else: self.validate() if self.validated: distance = np.sqrt(2.0 * (1.0 - self.matrix)) return distance else: print("Invalid Correlation Matrix") def characterize(self): """ TODO Analyse or classify a correlation matrix according to its eigevalue spectrum properties """ pass def print(self, format_type='Standard', accuracy=2): matrix_print(self.matrix, format_type=format_type, accuracy=accuracy) def decompose(self, method): """ :param method: :return: """ if method == 'cholesky': L = np.linalg.cholesky(self.matrix) return L elif method == 'svd': U, S, VH = np.linalg.svd(self.matrix, full_matrices=True) return U, S, VH def stress(self, scenario, method): """ TODO Create a