Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _convert_type_to_char(self, type_char):
"""
Converts the given type code to an int
:param type_char: A type code character
"""
typecode = type_char
if type(type_char) is int:
typecode = chr(type_char)
if typecode in self.TYPECODES_LIST:
... |
def create(self, classdesc, unmarshaller=None):
# type: (JavaClass, JavaObjectUnmarshaller) -> JavaObject
"""
Transforms a deserialized Java object into a Python object
:param classdesc: The description of a Java class
:return: The Python form of the object, or the original Java... |
def log_start_finish(msg, logger, level=logging.DEBUG):
"""
A context manager to log messages with "start: " and "finish: "
prefixes before and after a block.
Parameters
----------
msg : str
Will be prefixed with "start: " and "finish: ".
logger : logging.Logger
level : int, opt... |
def log_to_file(filename, level=None, fmt=None, datefmt=None):
"""
Send log output to the given file.
Parameters
----------
filename : str
level : int, optional
An optional logging level that will apply only to this stream
handler.
fmt : str, optional
An optional for... |
def mnl_simulate(data, coeff, numalts, GPU=False, returnprobs=True):
"""
Get the probabilities for each chooser choosing between `numalts`
alternatives.
Parameters
----------
data : 2D array
The data are expected to be in "long" form where each row is for
one alternative. Altern... |
def mnl_estimate(data, chosen, numalts, GPU=False, coeffrange=(-3, 3),
weights=None, lcgrad=False, beta=None):
"""
Calculate coefficients of the MNL model.
Parameters
----------
data : 2D array
The data are expected to be in "long" form where each row is for
one alt... |
def unit_choice(chooser_ids, alternative_ids, probabilities):
"""
Have a set of choosers choose from among alternatives according
to a probability distribution. Choice is binary: each
alternative can only be chosen once.
Parameters
----------
chooser_ids : 1d array_like
Array of IDs... |
def from_yaml(cls, yaml_str=None, str_or_buffer=None):
"""
Create a DiscreteChoiceModel instance from a saved YAML configuration.
Arguments are mutally exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load model.
s... |
def apply_fit_filters(self, choosers, alternatives):
"""
Filter `choosers` and `alternatives` for fitting.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
... |
def apply_predict_filters(self, choosers, alternatives):
"""
Filter `choosers` and `alternatives` for prediction.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
... |
def fit(self, choosers, alternatives, current_choice):
"""
Fit and save model parameters based on given data.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
... |
def report_fit(self):
"""
Print a report of the fit results.
"""
if not self.fitted:
print('Model not yet fit.')
return
print('Null Log-liklihood: {0:.3f}'.format(
self.log_likelihoods['null']))
print('Log-liklihood at convergence: {0... |
def probabilities(self, choosers, alternatives, filter_tables=True):
"""
Returns the probabilities for a set of choosers to choose
from among a set of alternatives.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, ... |
def summed_probabilities(self, choosers, alternatives):
"""
Calculate total probability associated with each alternative.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.Data... |
def predict(self, choosers, alternatives, debug=False):
"""
Choose from among alternatives for a group of agents.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
... |
def to_dict(self):
"""
Return a dict respresentation of an MNLDiscreteChoiceModel
instance.
"""
return {
'model_type': 'discretechoice',
'model_expression': self.model_expression,
'sample_size': self.sample_size,
'name': self.name,... |
def to_yaml(self, str_or_buffer=None):
"""
Save a model respresentation to YAML.
Parameters
----------
str_or_buffer : str or file like, optional
By default a YAML string is returned. If a string is
given here the YAML will be written to that file.
... |
def choosers_columns_used(self):
"""
Columns from the choosers table that are used for filtering.
"""
return list(tz.unique(tz.concatv(
util.columns_in_filters(self.choosers_predict_filters),
util.columns_in_filters(self.choosers_fit_filters)))) |
def alts_columns_used(self):
"""
Columns from the alternatives table that are used for filtering.
"""
return list(tz.unique(tz.concatv(
util.columns_in_filters(self.alts_predict_filters),
util.columns_in_filters(self.alts_fit_filters)))) |
def interaction_columns_used(self):
"""
Columns from the interaction dataset used for filtering and in
the model. These may come originally from either the choosers or
alternatives tables.
"""
return list(tz.unique(tz.concatv(
util.columns_in_filters(self.int... |
def columns_used(self):
"""
Columns from any table used in the model. May come from either
the choosers or alternatives tables.
"""
return list(tz.unique(tz.concatv(
self.choosers_columns_used(),
self.alts_columns_used(),
self.interaction_colu... |
def fit_from_cfg(cls, choosers, chosen_fname, alternatives, cfgname, outcfgname=None):
"""
Parameters
----------
choosers : DataFrame
A dataframe in which rows represent choosers.
chosen_fname : string
A string indicating the column in the choosers datafra... |
def predict_from_cfg(cls, choosers, alternatives, cfgname=None, cfg=None,
alternative_ratio=2.0, debug=False):
"""
Simulate choices for the specified choosers
Parameters
----------
choosers : DataFrame
A dataframe of agents doing the choosing... |
def add_model_from_params(
self, name, model_expression, sample_size,
probability_mode='full_product', choice_mode='individual',
choosers_fit_filters=None, choosers_predict_filters=None,
alts_fit_filters=None, alts_predict_filters=None,
interaction_predict_fil... |
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 apply_fit_filters(self, choosers, alternatives):
"""
Filter `choosers` and `alternatives` for fitting.
This is done by filtering each submodel and concatenating
the results.
Parameters
----------
choosers : pandas.DataFrame
Table describing the ag... |
def fit(self, choosers, alternatives, current_choice):
"""
Fit and save models based on given data after segmenting
the `choosers` table.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
... |
def fitted(self):
"""
Whether all models in the group have been fitted.
"""
return (all(m.fitted for m in self.models.values())
if self.models else False) |
def probabilities(self, choosers, alternatives):
"""
Returns alternative probabilties for each chooser segment as
a dictionary keyed by segment name.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households... |
def summed_probabilities(self, choosers, alternatives):
"""
Returns the sum of probabilities for alternatives across all
chooser segments.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
... |
def predict(self, choosers, alternatives, debug=False):
"""
Choose from among alternatives for a group of agents after
segmenting the `choosers` table.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. househol... |
def alts_columns_used(self):
"""
Columns from the alternatives table that are used for filtering.
"""
return list(tz.unique(tz.concat(
m.alts_columns_used() for m in self.models.values()))) |
def from_yaml(cls, yaml_str=None, str_or_buffer=None):
"""
Create a SegmentedMNLDiscreteChoiceModel instance from a saved YAML
configuration. Arguments are mutally exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load mode... |
def add_segment(self, name, model_expression=None):
"""
Add a new segment with its own model expression.
Parameters
----------
name
Segment name. Must match a segment in the groupby of the data.
model_expression : str or dict, optional
A patsy mod... |
def apply_fit_filters(self, choosers, alternatives):
"""
Filter `choosers` and `alternatives` for fitting.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
... |
def apply_predict_filters(self, choosers, alternatives):
"""
Filter `choosers` and `alternatives` for prediction.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
... |
def fit(self, choosers, alternatives, current_choice):
"""
Fit and save models based on given data after segmenting
the `choosers` table. Segments that have not already been explicitly
added will be automatically added with default model.
Parameters
----------
ch... |
def _filter_choosers_alts(self, choosers, alternatives):
"""
Apply filters to the choosers and alts tables.
"""
return (
util.apply_filter_query(
choosers, self.choosers_predict_filters),
util.apply_filter_query(
alternatives, self... |
def probabilities(self, choosers, alternatives):
"""
Returns alternative probabilties for each chooser segment as
a dictionary keyed by segment name.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households... |
def predict(self, choosers, alternatives, debug=False):
"""
Choose from among alternatives for a group of agents after
segmenting the `choosers` table.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. househol... |
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_discretechoice',
'name': self.name,
'segmentation_col': self.segmentation_col,
'sample_siz... |
def to_yaml(self, str_or_buffer=None):
"""
Save a model respresentation to YAML.
Parameters
----------
str_or_buffer : str or file like, optional
By default a YAML string is returned. If a string is
given here the YAML will be written to that file.
... |
def columns_used(self):
"""
Columns from any table used in the model. May come from either
the choosers or alternatives tables.
"""
return list(tz.unique(tz.concatv(
self.choosers_columns_used(),
self.alts_columns_used(),
self.interaction_colu... |
def fit_from_cfg(cls, choosers, chosen_fname, alternatives, cfgname, outcfgname=None):
"""
Parameters
----------
choosers : DataFrame
A dataframe of rows of agents that have made choices.
chosen_fname : string
A string indicating the column in the choosers... |
def cache_to_df(dir_path):
"""
Convert a directory of binary array data files to a Pandas DataFrame.
Parameters
----------
dir_path : str
"""
table = {}
for attrib in glob.glob(os.path.join(dir_path, '*')):
attrib_name, attrib_ext = os.path.splitext(os.path.basename(attrib))
... |
def convert_dirs(base_dir, hdf_name, complib=None, complevel=0):
"""
Convert nested set of directories to
"""
print('Converting directories in {}'.format(base_dir))
dirs = glob.glob(os.path.join(base_dir, '*'))
dirs = {d for d in dirs if os.path.basename(d) in DIRECTORIES}
if not dirs:
... |
def get_run_number():
"""
Get a run number for this execution of the model system, for
identifying the output hdf5 files).
Returns
-------
The integer number for this run of the model system.
"""
try:
f = open(os.path.join(os.getenv('DATA_HOME', "."), 'RUNNUM'), 'r')
num... |
def compute_range(travel_data, attr, travel_time_attr, dist, agg=np.sum):
"""
Compute a zone-based accessibility query using the urbansim format
travel data dataframe.
Parameters
----------
travel_data : dataframe
The dataframe of urbansim format travel data. Has from_zone_id as
... |
def reindex(series1, series2):
"""
This reindexes the first series by the second series. This is an extremely
common operation that does not appear to be in Pandas at this time.
If anyone knows of an easier way to do this in Pandas, please inform the
UrbanSim developers.
The canonical example... |
def fidx(right, left, left_fk=None):
"""
Re-indexes a series or data frame (right) to align with
another (left) series or data frame via foreign key relationship.
The index of the right must be unique.
This is similar to misc.reindex, but allows for data frame
re-indexes and supports re-indexin... |
def numpymat2df(mat):
"""
Sometimes (though not very often) it is useful to convert a numpy matrix
which has no column names to a Pandas dataframe for use of the Pandas
functions. This method converts a 2D numpy matrix to Pandas dataframe
with default column headers.
Parameters
----------
... |
def df64bitto32bit(tbl):
"""
Convert a Pandas dataframe from 64 bit types to 32 bit types to save
memory or disk space.
Parameters
----------
tbl : The dataframe to convert
Returns
-------
The converted dataframe
"""
newtbl = pd.DataFrame(index=tbl.index)
for colname in... |
def series64bitto32bit(s):
"""
Convert a Pandas series from 64 bit types to 32 bit types to save
memory or disk space.
Parameters
----------
s : The series to convert
Returns
-------
The converted series
"""
if s.dtype == np.float64:
return s.astype('float32')
e... |
def pandasdfsummarytojson(df, ndigits=3):
"""
Convert the result of a
Parameters
----------
df : The result of a Pandas describe operation.
ndigits : int, optional - The number of significant digits to round to.
Returns
-------
A json object which captures the describe. Keys are f... |
def column_map(tables, columns):
"""
Take a list of tables and a list of column names and resolve which
columns come from which table.
Parameters
----------
tables : sequence of _DataFrameWrapper or _TableFuncWrapper
Could also be sequence of modified pandas.DataFrames, the important
... |
def column_list(tables, columns):
"""
Take a list of tables and a list of column names and return the columns
that are present in the tables.
Parameters
----------
tables : sequence of _DataFrameWrapper or _TableFuncWrapper
Could also be sequence of modified pandas.DataFrames, the impor... |
def get_probs(data, prob_column=None):
"""
Checks for presence of a probability column and returns the result
as a numpy array. If the probabilities are weights (i.e. they don't
sum to 1), then this will be recalculated.
Parameters
----------
data: pandas.DataFrame
Table to sample f... |
def accounting_sample_replace(total, data, accounting_column, prob_column=None, max_iterations=50):
"""
Sample rows with accounting with replacement.
Parameters
----------
total : int
The control total the sampled rows will attempt to match.
data: pandas.DataFrame
Table to sampl... |
def accounting_sample_no_replace(total, data, accounting_column, prob_column=None):
"""
Samples rows with accounting without replacement.
Parameters
----------
total : int
The control total the sampled rows will attempt to match.
data: pandas.DataFrame
Table to sample from.
... |
def sample_rows(total, data, replace=True, accounting_column=None,
max_iterations=50, prob_column=None, return_status=False):
"""
Samples and returns rows from a data frame while matching a desired control total. The total may
represent a simple row count or may attempt to match a sum/quanti... |
def _convert_types(self):
"""
convert lists and dictionaries that are useful for users to
np vectors that are usable by machines
"""
self.fars = np.array(self.fars)
self.parking_rates = np.array([self.parking_rates[use] for use in self.uses])
self.res_ratios = {}... |
def _building_cost(self, use_mix, stories):
"""
Generate building cost for a set of buildings
Parameters
----------
use_mix : array
The mix of uses for this form
stories : series
A Pandas Series of stories
Returns
-------
... |
def _generate_lookup(self):
"""
Run the developer model on all possible inputs specified in the
configuration object - not generally called by the user. This part
computes the final cost per sqft of the building to construct and
then turns it into the yearly rent necessary to ma... |
def lookup(self, form, df, only_built=True, pass_through=None):
"""
This function does the developer model lookups for all the actual input data.
Parameters
----------
form : string
One of the forms specified in the configuration file
df: dataframe
... |
def _debug_output(self):
"""
this code creates the debugging plots to understand
the behavior of the hypothetical building model
"""
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
c = self.config
df_d = self.dev_d
... |
def add_rows(data, nrows, starting_index=None, accounting_column=None):
"""
Add rows to data table according to a given nrows.
New rows will have their IDs set to NaN.
Parameters
----------
data : pandas.DataFrame
nrows : int
Number of rows to add.
starting_index : int, optional... |
def remove_rows(data, nrows, accounting_column=None):
"""
Remove a random `nrows` number of rows from a table.
Parameters
----------
data : DataFrame
nrows : float
Number of rows to remove.
accounting_column: string, optional
Name of column with accounting totals/quanties to... |
def add_or_remove_rows(data, nrows, starting_index=None, accounting_column=None):
"""
Add or remove rows to/from a table. Rows are added
for positive `nrows` and removed for negative `nrows`.
Parameters
----------
data : DataFrame
nrows : float
Number of rows to add or remove.
s... |
def _update_linked_table(table, col_name, added, copied, removed):
"""
Copy and update rows in a table that has a column referencing another
table that has had rows added via copying.
Parameters
----------
table : pandas.DataFrame
Table to update with new or removed rows.
col_name :... |
def transition(self, data, year):
"""
Add or remove rows to/from a table according to the prescribed
growth rate for this model.
Parameters
----------
data : pandas.DataFrame
Rows will be removed from or added to this table.
year : None, optional
... |
def transition(self, data, year):
"""
Add or remove rows to/from a table according to the prescribed
growth rate for this model and year.
Parameters
----------
data : pandas.DataFrame
Rows will be removed from or added to this table.
year : None, opti... |
def transition(self, data, year):
"""
Add or remove rows to/from a table according to the prescribed
totals for this model and year.
Parameters
----------
data : pandas.DataFrame
Rows will be removed from or added to this table.
year : None, optional
... |
def transition(self, data, year, linked_tables=None):
"""
Add or remove rows from a table based on population targets.
Parameters
----------
data : pandas.DataFrame
Rows will be removed from or added to this table.
year : int
Year number that will... |
def series_to_yaml_safe(series, ordered=False):
"""
Convert a pandas Series to a dict that will survive YAML serialization
and re-conversion back to a Series.
Parameters
----------
series : pandas.Series
ordered: bool, optional, default False
If True, an OrderedDict is returned.
... |
def frame_to_yaml_safe(frame, ordered=False):
"""
Convert a pandas DataFrame to a dictionary that will survive
YAML serialization and re-conversion back to a DataFrame.
Parameters
----------
frame : pandas.DataFrame
ordered: bool, optional, default False
If True, an OrderedDict is r... |
def ordered_yaml(cfg, order=None):
"""
Convert a dictionary to a YAML string with preferential ordering
for some keys. Converted string is meant to be fairly human readable.
Parameters
----------
cfg : dict
Dictionary to convert to a YAML string.
order: list
If provided, ove... |
def convert_to_yaml(cfg, str_or_buffer):
"""
Convert a dictionary to YAML and return the string or write it out
depending on the type of `str_or_buffer`.
Parameters
----------
cfg : dict or OrderedDict
Dictionary or OrderedDict to convert.
str_or_buffer : None, str, or buffer
... |
def yaml_to_dict(yaml_str=None, str_or_buffer=None, ordered=False):
"""
Load YAML from a string, file, or buffer (an object with a .read method).
Parameters are mutually exclusive.
Parameters
----------
yaml_str : str, optional
A string of YAML.
str_or_buffer : str or file like, opt... |
def add_transaction(self, amount, subaccount=None, metadata=None):
"""
Add a new transaction to the account.
Parameters
----------
amount : float
Negative for withdrawls, positive for deposits.
subaccount : object, optional
Any indicator of a suba... |
def total_transactions_by_subacct(self, subaccount):
"""
Get the sum of all transactions for a given subaccount.
Parameters
----------
subaccount : object
Identifier of subaccount.
Returns
-------
total : float
"""
return sum... |
def to_frame(self):
"""
Return transactions as a pandas DataFrame.
"""
col_names = _column_names_from_metadata(
t.metadata for t in self.transactions)
def trow(t):
return tz.concatv(
(t.amount, t.subaccount),
(t.metadata.g... |
def apply_filter_query(df, filters=None):
"""
Use the DataFrame.query method to filter a table down to the
desired rows.
Parameters
----------
df : pandas.DataFrame
filters : list of str or str, optional
List of filters to apply. Will be joined together with
' and ' and pass... |
def _filterize(name, value):
"""
Turn a `name` and `value` into a string expression compatible
the ``DataFrame.query`` method.
Parameters
----------
name : str
Should be the name of a column in the table to which the
filter will be applied.
A suffix of '_max' will resul... |
def filter_table(table, filter_series, ignore=None):
"""
Filter a table based on a set of restrictions given in
Series of column name / filter parameter pairs. The column
names can have suffixes `_min` and `_max` to indicate
"less than" and "greater than" constraints.
Parameters
----------
... |
def has_constant_expr(expr):
"""
Report whether a model expression has constant specific term.
That is, a term explicitly specying whether the model should or
should not include a constant. (e.g. '+ 1' or '- 1'.)
Parameters
----------
expr : str
Model expression to check.
Retur... |
def str_model_expression(expr, add_constant=True):
"""
We support specifying model expressions as strings, lists, or dicts;
but for use with patsy and statsmodels we need a string.
This function will take any of those as input and return a string.
Parameters
----------
expr : str, iterable,... |
def sorted_groupby(df, groupby):
"""
Perform a groupby on a DataFrame using a specific column
and assuming that that column is sorted.
Parameters
----------
df : pandas.DataFrame
groupby : object
Column name on which to groupby. This column must be sorted.
Returns
-------
... |
def columns_in_filters(filters):
"""
Returns a list of the columns used in a set of query filters.
Parameters
----------
filters : list of str or str
List of the filters as passed passed to ``apply_filter_query``.
Returns
-------
columns : list of str
List of all the st... |
def _tokens_from_patsy(node):
"""
Yields all the individual tokens from within a patsy formula
as parsed by patsy.parse_formula.parse_formula.
Parameters
----------
node : patsy.parse_formula.ParseNode
"""
for n in node.args:
for t in _tokens_from_patsy(n):
yield t
... |
def columns_in_formula(formula):
"""
Returns the names of all the columns used in a patsy formula.
Parameters
----------
formula : str, iterable, or dict
Any formula construction supported by ``str_model_expression``.
Returns
-------
columns : list of str
"""
if formul... |
def fit_model(df, filters, model_expression):
"""
Use statsmodels OLS to construct a model relation.
Parameters
----------
df : pandas.DataFrame
Data to use for fit. Should contain all the columns
referenced in the `model_expression`.
filters : list of str
Any filters to... |
def predict(df, filters, model_fit, ytransform=None):
"""
Apply model to new data to predict new dependent values.
Parameters
----------
df : pandas.DataFrame
filters : list of str
Any filters to apply before doing prediction.
model_fit : statsmodels.regression.linear_model.OLSResul... |
def _model_fit_to_table(fit):
"""
Produce a pandas DataFrame of model fit results from a statsmodels
fit result object.
Parameters
----------
fit : statsmodels.regression.linear_model.RegressionResults
Returns
-------
fit_parameters : pandas.DataFrame
Will have columns 'Coe... |
def predict(self, data):
"""
Predict new values by running data through the fit model.
Parameters
----------
data : pandas.DataFrame
Table with columns corresponding to the RHS of `model_expression`.
Returns
-------
predicted : ndarray
... |
def from_yaml(cls, yaml_str=None, str_or_buffer=None):
"""
Create a RegressionModel instance from a saved YAML configuration.
Arguments are mutually exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load model.
str_... |
def fit(self, data, debug=False):
"""
Fit the model to data and store/return the results.
Parameters
----------
data : pandas.DataFrame
Data to use for fitting the model. Must contain all the
columns referenced by the `model_expression`.
debug : b... |
def report_fit(self):
"""
Print a report of the fit results.
"""
if not self.fitted:
print('Model not yet fit.')
return
print('R-Squared: {0:.3f}'.format(self.model_fit.rsquared))
print('Adj. R-Squared: {0:.3f}'.format(self.model_fit.rsquared_adj... |
def predict(self, data):
"""
Predict a new data set based on an estimated model.
Parameters
----------
data : pandas.DataFrame
Data to use for prediction. Must contain all the columns
referenced by the right-hand side of the `model_expression`.
R... |
def to_dict(self):
"""
Returns a dictionary representation of a RegressionModel instance.
"""
d = {
'model_type': 'regression',
'name': self.name,
'fit_filters': self.fit_filters,
'predict_filters': self.predict_filters,
'model... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.