Search is not available for this dataset
text
stringlengths
75
104k
def columns_used(self): """ Returns all the columns used in this model for filtering and in the model expression. """ return list(tz.unique(tz.concatv( util.columns_in_filters(self.fit_filters), util.columns_in_filters(self.predict_filters), u...
def fit_from_cfg(cls, df, cfgname, debug=False, outcfgname=None): """ Parameters ---------- df : DataFrame The dataframe which contains the columns to use for the estimation. cfgname : string The name of the yaml config file which describes the hedonic mod...
def predict_from_cfg(cls, df, cfgname): """ Parameters ---------- df : DataFrame The dataframe which contains the columns to use for the estimation. cfgname : string The name of the yaml config file which describes the hedonic model. Returns ...
def add_model(self, model): """ Add a `RegressionModel` instance. Parameters ---------- model : `RegressionModel` Should have a ``.name`` attribute matching one of the groupby segments. """ logger.debug( 'adding model {} to gr...
def add_model_from_params(self, name, fit_filters, predict_filters, model_expression, ytransform=None): """ Add a model by passing arguments through to `RegressionModel`. Parameters ---------- name : any Must match a groupby segment name...
def _iter_groups(self, data): """ Iterate over the groups in `data` after grouping by `segmentation_col`. Skips any groups for which there is no model stored. Yields tuples of (name, df) where name is the group key and df is the group DataFrame. Parameters ...
def fit(self, data, debug=False): """ Fit each of the models in the group. Parameters ---------- data : pandas.DataFrame Must have a column with the same name as `segmentation_col`. debug : bool If set to true (default false) will pass the debug p...
def predict(self, data): """ Predict new data for each group in the segmentation. Parameters ---------- data : pandas.DataFrame Data to use for prediction. Must have a column with the same name as `segmentation_col`. Returns ------- ...
def from_yaml(cls, yaml_str=None, str_or_buffer=None): """ Create a SegmentedRegressionModel instance from a saved YAML configuration. Arguments are mutally exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. ...
def add_segment(self, name, model_expression=None, ytransform='default'): """ Add a new segment with its own model expression and ytransform. Parameters ---------- name : Segment name. Must match a segment in the groupby of the data. model_expression : str or...
def fit(self, data, debug=False): """ Fit each segment. Segments that have not already been explicitly added will be automatically added with default model and ytransform. Parameters ---------- data : pandas.DataFrame Must have a column with the same name as ...
def predict(self, data): """ Predict new data for each group in the segmentation. Parameters ---------- data : pandas.DataFrame Data to use for prediction. Must have a column with the same name as `segmentation_col`. Returns ------- ...
def _process_model_dict(self, d): """ Remove redundant items from a model's configuration dict. Parameters ---------- d : dict Modified in place. Returns ------- dict Modified `d`. """ del d['model_type'] ...
def to_dict(self): """ Returns a dict representation of this instance suitable for conversion to YAML. """ return { 'model_type': 'segmented_regression', 'name': self.name, 'segmentation_col': self.segmentation_col, 'fit_filters': ...
def columns_used(self): """ Returns all the columns used across all models in the group for filtering and in the model expression. """ return list(tz.unique(tz.concatv( util.columns_in_filters(self.fit_filters), util.columns_in_filters(self.predict_filter...
def fit_from_cfg(cls, df, cfgname, debug=False, min_segment_size=None, outcfgname=None): """ Parameters ---------- df : DataFrame The dataframe which contains the columns to use for the estimation. cfgname : string The name of the yaml config file which de...
def find_movers(choosers, rates, rate_column): """ Returns an array of the indexes of the `choosers` that are slated to move. Parameters ---------- choosers : pandas.DataFrame Table of agents from which to find movers. rates : pandas.DataFrame Table of relocation rates. Inde...
def _calculate_adjustment( lcm, choosers, alternatives, alt_segmenter, clip_change_low, clip_change_high, multiplier_func=None): """ Calculate adjustments to prices to compensate for supply and demand effects. Parameters ---------- lcm : LocationChoiceModel Used to calcu...
def supply_and_demand( lcm, choosers, alternatives, alt_segmenter, price_col, base_multiplier=None, clip_change_low=0.75, clip_change_high=1.25, iterations=5, multiplier_func=None): """ Adjust real estate prices to compensate for supply and demand effects. Parameters ---------- ...
def _max_form(f, colname): """ Assumes dataframe with hierarchical columns with first index equal to the use and second index equal to the attribute. e.g. f.columns equal to:: mixedoffice building_cost building_revenue b...
def keep_form_with_max_profit(self, forms=None): """ This converts the dataframe, which shows all profitable forms, to the form with the greatest profit, so that more profitable forms outcompete less profitable forms. Parameters ---------- forms: list of strings ...
def compute_units_to_build(num_agents, num_units, target_vacancy): """ Compute number of units to build to match target vacancy. Parameters ---------- num_agents : int number of agents that need units in the region num_units : int number of units ...
def pick(self, form, target_units, parcel_size, ave_unit_size, current_units, max_parcel_size=200000, min_unit_size=400, drop_after_build=True, residential=True, bldg_sqft_per_job=400.0, profit_to_prob_func=None): """ Choose the buildings from the list that are fea...
def merge(old_df, new_df, return_index=False): """ Merge two dataframes of buildings. The old dataframe is usually the buildings dataset and the new dataframe is a modified (by the user) version of what is returned by the pick method. Parameters ---------- old_d...
def start(views, center=[37.7792, -122.2191], zoom=11, shape_json='data/zones.json', geom_name='ZONE_ID', # from JSON file join_name='zone_id', # from data frames precision=8, port=8765, host='localhost', testing=False): """...
def _analyze_root_causes(self): """ Conduct root cause analysis. The first metric of the list is taken as the root cause right now. """ causes = {} for a in self.anomalies: try: causes[a] = self.correlations[a][0] except IndexError:...
def _load(self, time_series): """ Load time series into a TimeSeries object. :param timeseries: a TimeSeries, a dictionary or a path to a csv file(str). :return TimeSeries: a TimeSeries object. """ if isinstance(time_series, TimeSeries): return time_series ...
def _get_algorithm_and_params(self, algorithm_name, algorithm_params): """ Get the specific algorithm and merge the algorithm params. :param str algorithm: name of the algorithm to use. :param dict algorithm_params: additional params for the specific algorithm. """ algori...
def _sanity_check(self): """ Check if the time series have more than two data points. """ if len(self.time_series_a) < 2 or len(self.time_series_b) < 2: raise exceptions.NotEnoughDataPoints('luminol.Correlator: Too few data points!')
def _correlate(self): """ Run correlation algorithm. """ a = self.algorithm(**self.algorithm_params) self.correlation_result = a.run()
def is_correlated(self, threshold=0): """ Compare with a threshold to determine whether two timeseries correlate to each other. :return: a CorrelationResult object if two time series correlate otherwise false. """ return self.correlation_result if self.correlation_result.coeffici...
def _set_scores(self): """ Compute anomaly scores for the time series This algorithm just takes the diff of threshold with current value as anomaly score """ anom_scores = {} for i, (timestamp, value) in enumerate(self.time_series.items()): baseline_value = s...
def _load(self, metrix): """ Load time series. :param timeseries: a TimeSeries, a dictionary or a path to a csv file(str). :return TimeSeries: a TimeSeries object. """ if isinstance(metrix, TimeSeries): return metrix if isinstance(metrix, dict): return TimeSeries(metrix) retu...
def _analyze(self): """ Analyzes if a matrix has anomalies. If any anomaly is found, determine if the matrix correlates with any other matrixes. To be implemented. """ output = defaultdict(list) output_by_name = defaultdict(list) scores = self.anomaly_detector.get_all_scores() if se...
def _set_scores(self): """ Set anomaly scores using a weighted sum. """ anom_scores_ema = self.exp_avg_detector.run() anom_scores_deri = self.derivative_detector.run() anom_scores = {} for timestamp in anom_scores_ema.timestamps: # Compute a weighted a...
def _compute_derivatives(self): """ Compute derivatives of the time series. """ derivatives = [] for i, (timestamp, value) in enumerate(self.time_series_items): if i > 0: pre_item = self.time_series_items[i - 1] pre_timestamp = pre_item...
def _sanity_check(self): """ Check if there are enough data points. """ windows = self.lag_window_size + self.future_window_size if (not self.lag_window_size or not self.future_window_size or self.time_series_length < windows or windows < DEFAULT_BITMAP_MINIMAL_POINTS_IN_WINDOWS)...
def _generate_SAX_single(self, sections, value): """ Generate SAX representation(Symbolic Aggregate approXimation) for a single data point. Read more about it here: Assumption-Free Anomaly Detection in Time Series(http://alumni.cs.ucr.edu/~ratana/SSDBM05.pdf). :param dict sections: value...
def _generate_SAX(self): """ Generate SAX representation for all values of the time series. """ sections = {} self.value_min = self.time_series.min() self.value_max = self.time_series.max() # Break the whole value range into different sections. section_hei...
def _construct_SAX_chunk_dict(self, sax): """ Form a chunk frequency dictionary from a SAX representation. :param str sax: a SAX representation. :return dict: frequency dictionary for chunks in the SAX representation. """ frequency = defaultdict(int) chunk_size = ...
def _construct_all_SAX_chunk_dict(self): """ Construct the chunk dicts for lagging window and future window at each index. e.g: Suppose we have a SAX sequence as '1234567890', both window sizes are 3, and the chunk size is 2. The first index that has a lagging window is 3. For index eq...
def _compute_anom_score_between_two_windows(self, i): """ Compute distance difference between two windows' chunk frequencies, which is then marked as the anomaly score of the data point on the window boundary in the middle. :param int i: index of the data point between two windows. ...
def _set_scores(self): """ Compute anomaly scores for the time series by sliding both lagging window and future window. """ anom_scores = {} self._generate_SAX() self._construct_all_SAX_chunk_dict() length = self.time_series_length lws = self.lag_window_si...
def _denoise_scores(self, scores): """ Denoise anomaly scores. Low anomaly scores could be noisy. The following two series will have good correlation result with out denoise: [0.08, 4.6, 4.6, 4.6, 1.0, 1.0] [0.0010, 0.0012, 0.0012, 0.0008, 0.0008] while the second series ...
def _detect_correlation(self): """ Detect correlation by computing correlation coefficients for all allowed shift steps, then take the maximum. """ correlations = [] shifted_correlations = [] self.time_series_a.normalize() self.time_series_b.normalize() ...
def _set_scores(self): """ Compute anomaly scores for the time series This algorithm just takes the diff of threshold with current value as anomaly score """ anom_scores = {} for timestamp, value in self.time_series.items(): anom_scores[timestamp] = 0.0 ...
def _compute_anom_score(self, lag_window_points, point): """ Compute anomaly score for a single data point. Anomaly score for a single data point(t,v) equals: abs(v - ema(lagging window)). :param list lag_window_points: values in the lagging window. :param float point: data point...
def _compute_anom_data_using_window(self): """ Compute anomaly scores using a lagging window. """ anom_scores = {} values = self.time_series.values stdev = numpy.std(values) for i, (timestamp, value) in enumerate(self.time_series_items): if i < self.la...
def _compute_anom_data_decay_all(self): """ Compute anomaly scores using a lagging window covering all the data points before. """ anom_scores = {} values = self.time_series.values ema = utils.compute_ema(self.smoothing_factor, values) stdev = numpy.std(values) ...
def _generic_binary_op(self, other, op): """ Perform the method operation specified in the op parameter on the values within the instance's time series values and either another time series or a constant number value. :param other: Time series of values or a constant number to u...
def _get_value_type(self, other): """ Get the object type of the value within the values portion of the time series. :return: `type` of object """ if self.values: return type(self.values[0]) elif isinstance(other, TimeSeries) and other.values: ret...
def align(self, other): """ Align two time series so that len(self) == len(other) and self.timstamps == other.timestamps. :return: :tuple:(`TimeSeries` object(the aligned self), `TimeSeries` object(the aligned other)) """ if isinstance(other, TimeSeries): aligned, ot...
def smooth(self, smoothing_factor): """ return a new time series which is a exponential smoothed version of the original data series. soomth forward once, backward once, and then take the average. :param float smoothing_factor: smoothing factor :return: :class:`TimeSeries` objec...
def add_offset(self, offset): """ Return a new time series with all timestamps incremented by some offset. :param int offset: The number of seconds to offset the time series. :return: `None` """ self.timestamps = [ts + offset for ts in self.timestamps]
def normalize(self): """ Return a new time series with all values normalized to 0 to 1. :return: `None` """ maximum = self.max() if maximum: self.values = [value / maximum for value in self.values]
def crop(self, start_timestamp, end_timestamp): """ Return a new TimeSeries object contains all the timstamps and values within the specified range. :param int start_timestamp: the start timestamp value :param int end_timestamp: the end timestamp value :return: :class:`T...
def average(self, default=None): """ Calculate the average value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the average value or `None`. """ return numpy.asscalar(numpy.average(se...
def median(self, default=None): """ Calculate the median value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the median value or `None`. """ return numpy.asscalar(numpy.median(self.v...
def max(self, default=None): """ Calculate the maximum value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the maximum value or `None`. """ return numpy.asscalar(numpy.max(self.value...
def min(self, default=None): """ Calculate the minimum value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the maximum value or `None`. """ return numpy.asscalar(numpy.min(self.value...
def percentile(self, n, default=None): """ Calculate the Nth Percentile value over the time series. :param int n: Integer value of the percentile to calculate. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the Nt...
def stdev(self, default=None): """ Calculate the standard deviation of the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the standard deviation value or `None`. """ return numpy.asscalar(nump...
def sum(self, default=None): """ Calculate the sum of all the values in the times series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the sum or `None`. """ return numpy.asscalar(numpy.sum(self.values))...
def _get_algorithm(self, algorithm_name): """ Get the specific algorithm. :param str algorithm_name: name of the algorithm to use(file name). :return: algorithm object. """ try: algorithm = anomaly_detector_algorithms[algorithm_name] return algorit...
def _detect(self, score_only): """ Detect anomaly periods. :param bool score_only: if true, only anomaly scores are computed. """ try: algorithm = self.algorithm(**self.algorithm_params) self.anom_scores = algorithm.run() except exceptions.NotEnoug...
def _detect_anomalies(self): """ Detect anomalies using a threshold on anomaly scores. """ anom_scores = self.anom_scores max_anom_score = anom_scores.max() anomalies = [] if max_anom_score: threshold = self.threshold or max_anom_score * self.score_pe...
def compute_ema(smoothing_factor, points): """ Compute exponential moving average of a list of points. :param float smoothing_factor: the smoothing factor. :param list points: the data points. :return list: all ema in a list. """ ema = [] # The initial point has a ema equal to itself. ...
def to_epoch(t_str): """ Covert a timestamp string to an epoch number. :param str t_str: a timestamp string. :return int: epoch number of the timestamp. """ try: t = float(t_str) return t except ValueError: for format in constants.TIMESTAMP_STR_FORMATS: tr...
def handle_response(response): """ Given a requests.Response object, throw the appropriate exception, if applicable. """ # ignore valid responses if response.status_code < 400: return cls = _status_to_exception_type.get(response.status_code, HttpError) kwargs = { 'code': r...
def create(self, **kwargs): """Create a new instance of this resource type. As a general rule, the identifier should have been provided, but in some subclasses the identifier is server-side-generated. Those classes have to overload this method to deal with that scenario. """ ...
def update(self, **kwargs): """ Update a resource by passing in modifications via keyword arguments. """ data = self._generate_input_dict(**kwargs) self.load(self.client.put('/'.join(self.url.split('/')[:-1]) + 's', data=data)) return self
def update(self, **kwargs): """Update a resource by passing in modifications via keyword arguments. """ data = [] for cl in self: for classification_item in cl.list: class_item_dict = dict() for field in classification_item.fields: ...
def create(self, data, **kwargs): """ Create classifitions for specific entity """ self.client.post(self.url, data=data)
def delete(self, guid): """ Delete guid """ return self.client.delete(self.url, params={'guid': guid})
def update(self, **kwargs): """Update a resource by passing in modifications via keyword arguments. """ data = self._generate_input_dict(**kwargs) url = self.parent.url + '/relationship' self.load(self.client.put(url, data=data)) return self
def create(self, **kwargs): """Raise error since guid cannot be duplicated """ raise exceptions.MethodNotImplemented(method=self.create, url=self.url, details='GUID cannot be duplicated, to create a new GUID use the relationship resource')
def normalize_underscore_case(name): """Normalize an underscore-separated descriptor to something more readable. i.e. 'NAGIOS_SERVER' becomes 'Nagios Server', and 'host_components' becomes 'Host Components' """ normalized = name.lower() normalized = re.sub(r'_(\w)', lamb...
def normalize_camel_case(name): """Normalize a camelCase descriptor to something more readable. i.e. 'camelCase' or 'CamelCase' becomes 'Camel Case' """ normalized = re.sub('([a-z])([A-Z])', lambda match: ' '.join([match.group(1), match.group(2)]), name) ...
def version_tuple(version): """Convert a version string or tuple to a tuple. Should be returned in the form: (major, minor, release). """ if isinstance(version, str): return tuple(int(x) for x in version.split('.')) elif isinstance(version, tuple): return version else: r...
def version_str(version): """Convert a version tuple or string to a string. Should be returned in the form: major.minor.release """ if isinstance(version, str): return version elif isinstance(version, tuple): return '.'.join([str(int(x)) for x in version]) else: raise Va...
def generate_http_basic_token(username, password): """ Generates a HTTP basic token from username and password Returns a token string (not a byte) """ token = base64.b64encode('{}:{}'.format(username, password).encode('utf-8')).decode('utf-8') return token
def identifier(self): """These models have server-generated identifiers. If we don't already have it in memory, then assume that it has not yet been generated. """ if self.primary_key not in self._data: return 'Unknown' return str(self._data[self.primary_key]...
def url(self): """The url for this collection.""" if self.parent is None: # TODO: differing API Versions? pieces = [self.client.base_url, 'api', 'atlas', 'v2'] else: pieces = [self.parent.url] pieces.append(self.model_class.path) return '/'.jo...
def inflate(self): """Load the collection from the server, if necessary.""" if not self._is_inflated: self.check_version() for k, v in self._filter.items(): if '[' in v: self._filter[k] = ast.literal_eval(v) self.load(self.client.ge...
def load(self, response): """Parse the GET response for the collection. This operates as a lazy-loader, meaning that the data are only downloaded from the server if there are not already loaded. Collection items are loaded sequentially. In some rare cases, a collection can have...
def create(self, *args, **kwargs): """Add a resource to this collection.""" href = self.url if len(args) == 1: kwargs[self.model_class.primary_key] = args[0] href = '/'.join([href, args[0]]) model = self.model_class(self, href=href...
def update(self, **kwargs): """Update all resources in this collection.""" self.inflate() for model in self._models: model.update(**kwargs) return self
def delete(self, **kwargs): """Delete all resources in this collection.""" self.inflate() for model in self._models: model.delete(**kwargs) return
def wait(self, **kwargs): """Wait until any pending asynchronous requests are finished for this collection.""" if self.request: self.request.wait(**kwargs) self.request = None return self.inflate()
def url(self): """Gets the url for the resource this model represents. It will just use the 'href' passed in to the constructor if that exists. Otherwise, it will generated it based on the collection's url and the model's identifier. """ if self._href is not None: ...
def inflate(self): """Load the resource from the server, if not already loaded.""" if not self._is_inflated: if self._is_inflating: # catch infinite recursion when attempting to inflate # an object that doesn't have enough data to inflate msg...
def load(self, response): """The load method parses the raw JSON response from the server. Most models are not returned in the main response body, but in a key such as 'entity', defined by the 'data_key' attribute on the class. Also, related objects are often returned and can be used to...
def create(self, **kwargs): """Create a new instance of this resource type. As a general rule, the identifier should have been provided, but in some subclasses the identifier is server-side-generated. Those classes have to overload this method to deal with that scenario. """ ...
def delete(self, **kwargs): """Delete a resource by issuing a DELETE http request against it.""" self.method = 'delete' if len(kwargs) > 0: self.load(self.client.delete(self.url, params=kwargs)) else: self.load(self.client.delete(self.url)) self.parent.rem...
def publish(obj, event, event_state, **kwargs): """Publish an event from an object. This is a really basic pub-sub event system to allow for tracking progress on methods externally. It fires the events for the first match it finds in the object hierarchy, going most specific to least. If no match is ...
def subscribe(obj, event, callback, event_state=None): """Subscribe an event from an class. Subclasses of the class/object will also fire events for this class, unless a more specific event exists. """ if inspect.isclass(obj): cls = obj.__name__ else: cls = obj.__class__.__name_...
def clean_name(self, suffix=True, prefix=False, middle=False, multi=False): "return cleared version of the business name" name = self.business_name # Run it through the string_stripper once more name = self.string_stripper(name) loname = name.lower() # return name without suffixed/prefixed/middle type ...
def _find_chordless_cycles(bond_graph, max_cycle_size): """Find all chordless cycles (i.e. rings) in the bond graph Traverses the bond graph to determine all cycles (i.e. rings) each atom is contained within. Algorithm has been adapted from: https://stackoverflow.com/questions/4022662/find-all-chordles...
def _prepare_atoms(topology, compute_cycles=False): """Compute cycles and add white-/blacklists to atoms.""" atom1 = next(topology.atoms()) has_whitelists = hasattr(atom1, 'whitelist') has_cycles = hasattr(atom1, 'cycles') compute_cycles = compute_cycles and not has_cycles if compute_cycles or ...
def _add_nodes(self): """Add all atoms in the SMARTS string as nodes in the graph.""" for n, atom in enumerate(self.ast.select('atom')): self.add_node(n, atom=atom) self._atom_indices[id(atom)] = n