Search is not available for this dataset
text stringlengths 75 104k |
|---|
def getValue(self, scalarExpression):
"""
Get a scalar value from the underlying AMPL interpreter, as a double or
a string.
Args:
scalarExpression: An AMPL expression which evaluates to a scalar
value.
Returns:
The value of the expression.
... |
def setData(self, data, setName=None):
"""
Assign the data in the dataframe to the AMPL entities with the names
corresponding to the column names.
Args:
data: The dataframe containing the data to be assigned.
setName: The name of the set to which the indices val... |
def readTable(self, tableName):
"""
Read the table corresponding to the specified name, equivalent to the
AMPL statement:
.. code-block:: ampl
read table tableName;
Args:
tableName: Name of the table to be read.
"""
lock_and_call(
... |
def writeTable(self, tableName):
"""
Write the table corresponding to the specified name, equivalent to the
AMPL statement
.. code-block:: ampl
write table tableName;
Args:
tableName: Name of the table to be written.
"""
lock_and_call(
... |
def display(self, *amplExpressions):
"""
Writes on the current OutputHandler the outcome of the AMPL statement.
.. code-block:: ampl
display e1, e2, .., en;
where e1, ..., en are the strings passed to the procedure.
Args:
amplExpressions: Expressions t... |
def setOutputHandler(self, outputhandler):
"""
Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands.
"""
class OutputHandlerInternal(amplpython.OutputHandler):
def output... |
def setErrorHandler(self, errorhandler):
"""
Sets a new error handler.
Args:
errorhandler: The object handling AMPL errors and warnings.
"""
class ErrorHandlerWrapper(ErrorHandler):
def __init__(self, errorhandler):
self.errorhandler = err... |
def getVariables(self):
"""
Get all the variables declared.
"""
variables = lock_and_call(
lambda: self._impl.getVariables(),
self._lock
)
return EntityMap(variables, Variable) |
def getConstraints(self):
"""
Get all the constraints declared.
"""
constraints = lock_and_call(
lambda: self._impl.getConstraints(),
self._lock
)
return EntityMap(constraints, Constraint) |
def getObjectives(self):
"""
Get all the objectives declared.
"""
objectives = lock_and_call(
lambda: self._impl.getObjectives(),
self._lock
)
return EntityMap(objectives, Objective) |
def getSets(self):
"""
Get all the sets declared.
"""
sets = lock_and_call(
lambda: self._impl.getSets(),
self._lock
)
return EntityMap(sets, Set) |
def getParameters(self):
"""
Get all the parameters declared.
"""
parameters = lock_and_call(
lambda: self._impl.getParameters(),
self._lock
)
return EntityMap(parameters, Parameter) |
def getCurrentObjective(self):
"""
Get the the current objective. Returns `None` if no objective is set.
"""
name = self._impl.getCurrentObjectiveName()
if name == '':
return None
else:
return self.getObjective(name) |
def _var(self):
"""
Get/Set a variable.
"""
class Variables(object):
def __getitem__(_self, name):
return self.getVariable(name)
def __setitem__(_self, name, value):
self.getVariable(name).setValue(value)
def __iter__(... |
def _con(self):
"""
Get/Set a constraint.
"""
class Constraints(object):
def __getitem__(_self, name):
return self.getConstraint(name)
def __setitem__(_self, name, value):
self.getConstraint(name).setDual(value)
def __... |
def _obj(self):
"""
Get an objective.
"""
class Objectives(object):
def __getitem__(_self, name):
return self.getObjective(name)
def __iter__(_self):
return self.getObjectives()
return Objectives() |
def _set(self):
"""
Get/Set a set.
"""
class Sets(object):
def __getitem__(_self, name):
return self.getSet(name)
def __setitem__(_self, name, values):
self.getSet(name).setValues(values)
def __iter__(_self):
... |
def _param(self):
"""
Get/Set a parameter.
"""
class Parameters(object):
def __getitem__(_self, name):
return self.getParameter(name)
def __setitem__(_self, name, value):
if isinstance(value, (float, int, basestring)):
... |
def _option(self):
"""
Get/Set an option.
"""
class Options(object):
def __getitem__(_self, name):
return self.getOption(name)
def __setitem__(_self, name, value):
self.setOption(name, value)
return Options() |
def exportData(self, datfile):
"""
Create a .dat file with the data that has been loaded.
Args:
datfile: Path to the file (Relative to the current working
directory or absolute).
"""
def ampl_set(name, values):
def format_entry(e):
... |
def exportGurobiModel(self, gurobiDriver='gurobi', verbose=False):
"""
Export the model to Gurobi as a gurobipy.Model object.
Args:
gurobiDriver: The name or the path of the Gurobi solver driver.
verbose: Whether should generate verbose output.
Returns:
... |
def importGurobiSolution(self, grbmodel):
"""
Import the solution from a gurobipy.Model object.
Args:
grbmodel: A :class:`gurobipy.Model` object with the model solved.
"""
self.eval(''.join(
'let {} := {};'.format(var.VarName, var.X)
for var i... |
def _startRecording(self, filename):
"""
Start recording the session to a file for debug purposes.
"""
self.setOption('_log_file_name', filename)
self.setOption('_log_input_only', True)
self.setOption('_log', True) |
def _loadSession(self, filename):
"""
Load a recorded session.
"""
try:
self.eval(open(filename).read())
except RuntimeError as e:
print(e) |
def ls_dir(base_dir):
"""List files recursively."""
return [
os.path.join(dirpath.replace(base_dir, '', 1), f)
for (dirpath, dirnames, files) in os.walk(base_dir)
for f in files
] |
def get(self, *index):
"""
Get the instance with the specified index.
Returns:
The corresponding instance.
"""
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, list)):
index = index[0]
if len(index) ... |
def find(self, *index):
"""
Searches the current entity for an instance with the specified index.
Returns:
The wanted instance if found, otherwise it returns `None`.
"""
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, ... |
def getValues(self, suffixes=None):
"""
If a list of suffixes is provided, get the specified suffixes value for
all instances. Otherwise, get all the principal values of this entity.
The specific returned value depends on the type of entity (see list
below). For:
- Varia... |
def setValues(self, data):
"""
Set the values of this entiy to the correponding values of a
DataFrame indexed over the same sets (or a subset).
This function assigns the values in the first data column of
the passed dataframe to the entity the function is called from.
In ... |
def addRow(self, *value):
"""
Add a row to the DataFrame. The size of the tuple must be equal to the
total number of columns in the dataframe.
Args:
value: A single argument with a tuple containing all the values
for the row to be added, or multiple arguments ... |
def addColumn(self, header, values=[]):
"""
Add a new column with the corresponding header and values to the
dataframe.
Args:
header: The name of the new column.
values: A list of size :func:`~amplpy.DataFrame.getNumRows` with
all the values of the n... |
def setColumn(self, header, values):
"""
Set the values of a column.
Args:
header: The header of the column to be set.
values: The values to set.
"""
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
... |
def getRow(self, key):
"""
Get a row by value of the indexing columns. If the index is not
specified, gets the only row of a dataframe with no indexing columns.
Args:
key: Tuple representing the index of the desired row.
Returns:
The row.
"""
... |
def getRowByIndex(self, index):
"""
Get row by numeric index.
Args:
index: Zero-based index of the row to get.
Returns:
The corresponding row.
"""
assert isinstance(index, int)
return Row(self._impl.getRowByIndex(index)) |
def getHeaders(self):
"""
Get the headers of this DataFrame.
Returns:
The headers of this DataFrame.
"""
headers = self._impl.getHeaders()
return tuple(
headers.getIndex(i) for i in range(self._impl.getNumCols())
) |
def setValues(self, values):
"""
Set the values of a DataFrame from a dictionary.
Args:
values: Dictionary with the values to set.
"""
ncols = self.getNumCols()
nindices = self.getNumIndices()
for key, value in values.items():
key = Utils.... |
def toDict(self):
"""
Return a dictionary with the DataFrame data.
"""
d = {}
nindices = self.getNumIndices()
for i in range(self.getNumRows()):
row = list(self.getRowByIndex(i))
if nindices > 1:
key = tuple(row[:nindices])
... |
def toList(self):
"""
Return a list with the DataFrame data.
"""
if self.getNumCols() > 1:
return [
tuple(self.getRowByIndex(i))
for i in range(self.getNumRows())
]
else:
return [
self.getRowByInd... |
def toPandas(self):
"""
Return a pandas DataFrame with the DataFrame data.
"""
assert pd is not None
nindices = self.getNumIndices()
headers = self.getHeaders()
columns = {
header: list(self.getColumn(header))
for header in headers[nindices... |
def fromPandas(cls, df):
"""
Create a :class:`~amplpy.DataFrame` from a pandas DataFrame.
"""
assert pd is not None
if isinstance(df, pd.Series):
df = pd.DataFrame(df)
else:
assert isinstance(df, pd.DataFrame)
keys = [
key if is... |
def fromNumpy(cls, data):
"""
Create a :class:`~amplpy.DataFrame` from a numpy array or matrix.
"""
assert np is not None
if isinstance(data, np.ndarray):
index = []
if len(data.shape) == 1:
columns = [('value', data.tolist())]
... |
def set(self, *args):
"""
Set the value of a single instance of this parameter.
Args:
args: value if the parameter is scalar, index and value
otherwise.
Raises:
RuntimeError: If the entity has been deleted in the underlying
AMPL.
... |
def setValues(self, values):
"""
Assign the values (string or float) to the parameter instances with the
specified indices, equivalent to the AMPL code:
.. code-block:: ampl
let {i in indices} par[i] := values[i];
Args:
values: list, dictionary or :clas... |
def setValues(self, values):
"""
Set the tuples in this set. Valid only for non-indexed sets.
Args:
values: A list of tuples or a :class:`~amplpy.DataFrame`.
In the case of a :class:`~amplpy.DataFrame`, the number of indexing
columns of the must be equal to the arit... |
def error(self, amplexception):
"""
Receives notification of an error.
"""
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Error:\n{:s}'.format(msg))
raise amplexception |
def warning(self, amplexception):
"""
Receives notification of a warning.
"""
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Warning:\n{:s}'.format(msg)) |
def register_magics(store_name='_ampl_cells', ampl_object=None):
"""
Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``.
Args:
store_name: Name of the store where ``%%ampl cells`` will be stored.
ampl_object: Object used to evaluate ``%%ampl_eval`` cells.
"""
from IPyth... |
def fix(self, value=None):
"""
Fix all instances of this variable to a value if provided or to
their current value otherwise.
Args:
value: value to be set.
"""
if value is None:
self._impl.fix()
else:
self._impl.fix(value) |
def toVName(name, stripNum=0, upper=False):
"""
Turn a Python name into an iCalendar style name,
optionally uppercase and with characters stripped off.
"""
if upper:
name = name.upper()
if stripNum != 0:
name = name[:-stripNum]
return name.replace('_', '-') |
def parseParams(string):
"""
Parse parameters
"""
all = params_re.findall(string)
allParameters = []
for tup in all:
paramList = [tup[0]] # tup looks like (name, valuesString)
for pair in param_values_re.findall(tup[1]):
# pair looks like ('', value) or (value, '')
... |
def parseLine(line, lineNumber=None):
"""
Parse line
"""
match = line_re.match(line)
if match is None:
raise ParseError("Failed to parse line: {0!s}".format(line), lineNumber)
# Underscores are replaced with dash to work around Lotus Notes
return (match.group('name').replace('_', '-'... |
def dquoteEscape(param):
"""
Return param, or "param" if ',' or ';' or ':' is in param.
"""
if param.find('"') >= 0:
raise VObjectError("Double quotes aren't allowed in parameter values.")
for char in ',;:':
if param.find(char) >= 0:
return '"' + param + '"'
return pa... |
def readComponents(streamOrString, validate=False, transform=True,
ignoreUnreadable=False, allowQP=False):
"""
Generate one Component at a time from a stream.
"""
if isinstance(streamOrString, basestring):
stream = six.StringIO(streamOrString)
else:
stream = stream... |
def readOne(stream, validate=False, transform=True, ignoreUnreadable=False,
allowQP=False):
"""
Return the first component from stream.
"""
return next(readComponents(stream, validate, transform, ignoreUnreadable,
allowQP)) |
def registerBehavior(behavior, name=None, default=False, id=None):
"""
Register the given behavior.
If default is True (or if this is the first version registered with this
name), the version will be the default if no id is given.
"""
if not name:
name = behavior.name.upper()
if id ... |
def getBehavior(name, id=None):
"""
Return a matching behavior if it exists, or None.
If id is None, return the default for name.
"""
name = name.upper()
if name in __behaviorRegistry:
if id:
for n, behavior in __behaviorRegistry[name]:
if n == id:
... |
def validate(self, *args, **kwds):
"""
Call the behavior's validate method, or return True.
"""
if self.behavior:
return self.behavior.validate(self, *args, **kwds)
return True |
def autoBehavior(self, cascade=False):
"""
Set behavior if name is in self.parentBehavior.knownChildren.
If cascade is True, unset behavior and parentBehavior for all
descendants, then recalculate behavior and parentBehavior.
"""
parentBehavior = self.parentBehavior
... |
def setBehavior(self, behavior, cascade=True):
"""
Set behavior. If cascade is True, autoBehavior all descendants.
"""
self.behavior = behavior
if cascade:
for obj in self.getChildren():
obj.parentBehavior = behavior
obj.autoBehavior(Tr... |
def transformToNative(self):
"""
Transform this object into a custom VBase subclass.
transformToNative should always return a representation of this object.
It may do so by modifying self in place then returning self, or by
creating a new object.
"""
if self.isNa... |
def serialize(self, buf=None, lineLength=75, validate=True, behavior=None):
"""
Serialize to buf if it exists, otherwise return a string.
Use self.behavior.serialize if behavior exists.
"""
if not behavior:
behavior = self.behavior
if behavior:
i... |
def valueRepr(self):
"""
Transform the representation of the value
according to the behavior, if any.
"""
v = self.value
if self.behavior:
v = self.behavior.valueRepr(self)
return v |
def setProfile(self, name):
"""
Assign a PROFILE to this unnamed component.
Used by vCard, not by vCalendar.
"""
if self.name or self.useBegin:
if self.name == name:
return
raise VObjectError("This component already has a PROFILE or "
... |
def getChildValue(self, childName, default=None, childNumber=0):
"""
Return a child's value (the first, by default), or None.
"""
child = self.contents.get(toVName(childName))
if child is None:
return default
else:
return child[childNumber].value |
def add(self, objOrName, group=None):
"""
Add objOrName to contents, set behavior if it can be inferred.
If objOrName is a string, create an empty component or line based on
behavior. If no behavior is found for the object, add a ContentLine.
group is an optional prefix to the ... |
def remove(self, obj):
"""
Remove obj from contents.
"""
named = self.contents.get(obj.name.lower())
if named:
try:
named.remove(obj)
if len(named) == 0:
del self.contents[obj.name.lower()]
except ValueEr... |
def setBehaviorFromVersionLine(self, versionLine):
"""
Set behavior if one matches name, versionLine.value.
"""
v = getBehavior(self.name, versionLine.value)
if v:
self.setBehavior(v) |
def transformChildrenToNative(self):
"""
Recursively replace children with their native representation.
Sort to get dependency order right, like vtimezone before vevent.
"""
for childArray in (self.contents[k] for k in self.sortChildKeys()):
for child in childArray:
... |
def transformChildrenFromNative(self, clearBehavior=True):
"""
Recursively transform native children to vanilla representations.
"""
for childArray in self.contents.values():
for child in childArray:
child = child.transformFromNative()
child.tr... |
def serialize(cls, obj, buf=None, lineLength=None, validate=True):
"""
Serialize iCalendar to HTML using the hCalendar microformat (http://microformats.org/wiki/hcalendar)
"""
outbuf = buf or six.StringIO()
level = 0 # holds current indentation level
tabwidth = 3
... |
def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc):
"""
Change the timezone of the specified component.
Args:
cal (Component): the component to change
new_timezone (tzinfo): the timezone to change to
default (tzinfo): a timezone to assume if the dtstart ... |
def foldOneLine(outbuf, input, lineLength = 75):
"""
Folding line procedure that ensures multi-byte utf-8 sequences are not
broken across lines
TO-DO: This all seems odd. Is it still needed, especially in python3?
"""
if len(input) < lineLength:
# Optimize for unfolded line case
... |
def defaultSerialize(obj, buf, lineLength):
"""
Encode and fold obj and its children, write to buf or return a string.
"""
outbuf = buf or six.StringIO()
if isinstance(obj, Component):
if obj.group is None:
groupString = ''
else:
groupString = obj.group + '.'... |
def toUnicode(s):
"""
Take a string or unicode, turn it into unicode, decoding as utf-8
"""
if isinstance(s, six.binary_type):
s = s.decode('utf-8')
return s |
def numToDigits(num, places):
"""
Helper, for converting numbers to textual digits.
"""
s = str(num)
if len(s) < places:
return ("0" * (places - len(s))) + s
elif len(s) > places:
return s[len(s)-places: ]
else:
return s |
def timedeltaToString(delta):
"""
Convert timedelta to an ical DURATION.
"""
if delta.days == 0:
sign = 1
else:
sign = delta.days / abs(delta.days)
delta = abs(delta)
days = delta.days
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds % 3600) / 60)
se... |
def stringToTextValues(s, listSeparator=',', charList=None, strict=False):
"""
Returns list of strings.
"""
if charList is None:
charList = escapableCharList
def escapableChar (c):
return c in charList
def error(msg):
if strict:
raise ParseError(msg)
... |
def stringToDurations(s, strict=False):
"""
Returns list of timedelta objects.
"""
def makeTimedelta(sign, week, day, hour, minute, sec):
if sign == "-": sign = -1
else: sign = 1
week = int(week)
day = int(day)
hour = int(hour)
minute = int(minute)
... |
def parseDtstart(contentline, allowSignatureMismatch=False):
"""
Convert a contentline's value into a date or date-time.
A variety of clients don't serialize dates with the appropriate VALUE
parameter, so rather than failing on these (technically invalid) lines,
if allowSignatureMismatch is True, t... |
def getTransition(transitionTo, year, tzinfo):
"""
Return the datetime of the transition to/from DST, or None.
"""
def firstTransition(iterDates, test):
"""
Return the last date not matching test, or None if all tests matched.
"""
success = None
for dt in iterDate... |
def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020):
"""
Compare offsets and DST transitions from startYear to endYear.
"""
if tzinfo1 == tzinfo2:
return True
elif tzinfo1 is None or tzinfo2 is None:
return False
def dt_test(dt):
if dt is None:
re... |
def registerTzinfo(obj, tzinfo):
"""
Register tzinfo if it's not already registered, return its tzid.
"""
tzid = obj.pickTzid(tzinfo)
if tzid and not getTzid(tzid, False):
registerTzid(tzid, tzinfo)
return tzid |
def settzinfo(self, tzinfo, start=2000, end=2030):
"""
Create appropriate objects in self to represent tzinfo.
Collapse DST transitions to rrules as much as possible.
Assumptions:
- DST <-> Standard transitions occur on the hour
- never within a month of one another
... |
def pickTzid(tzinfo, allowUTC=False):
"""
Given a tzinfo class, use known APIs to determine TZID, or use tzname.
"""
if tzinfo is None or (not allowUTC and tzinfo_eq(tzinfo, utc)):
# If tzinfo is UTC, we don't need a TZID
return None
# try PyICU's tzid key... |
def decode(cls, line):
"""
Remove backslash escaping from line.value.
"""
if line.encoded:
encoding = getattr(line, 'encoding_param', None)
if encoding and encoding.upper() == cls.base64string:
line.value = codecs.decode(self.value.encode("utf-8"),... |
def transformToNative(obj):
"""
Turn a recurring Component into a RecurringComponent.
"""
if not obj.isNative:
object.__setattr__(obj, '__class__', RecurringComponent)
obj.isNative = True
return obj |
def generateImplicitParameters(obj):
"""
Generate a UID if one does not exist.
This is just a dummy implementation, for now.
"""
if not hasattr(obj, 'uid'):
rand = int(random.random() * 100000)
now = datetime.datetime.now(utc)
now = dateTimeTo... |
def transformToNative(obj):
"""
Turn obj.value into a date or datetime.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
return obj
obj.value=obj.value
obj.value=parseDtstart(obj, allowSignatureMismatch=True)
... |
def transformFromNative(obj):
"""
Replace the date or datetime in obj.value with an ISO 8601 string.
"""
if type(obj.value) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = dateToString(obj.value)
return obj
... |
def transformToNative(obj):
"""
Turn obj.value into a list of dates, datetimes, or
(datetime, timedelta) tuples.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
obj.value = []
return obj
tzinfo = ... |
def transformFromNative(obj):
"""
Replace the date, datetime or period tuples in obj.value with
appropriate strings.
"""
if obj.value and type(obj.value[0]) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = ','.join([d... |
def decode(cls, line):
"""
Remove backslash escaping from line.value, then split on commas.
"""
if line.encoded:
line.value = stringToTextValues(line.value,
listSeparator=cls.listSeparator)
line.encoded=False |
def encode(cls, line):
"""
Backslash escape line.value.
"""
if not line.encoded:
line.value = cls.listSeparator.join(backslashEscape(val)
for val in line.value)
line.encoded=True |
def generateImplicitParameters(cls, obj):
"""
Create PRODID, VERSION, and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist.
"""
for comp in obj.components():
if comp.behavior is not None:
... |
def generateImplicitParameters(obj):
"""
Create default ACTION and TRIGGER if they're not set.
"""
try:
obj.action
except AttributeError:
obj.add('action').value = 'AUDIO'
try:
obj.trigger
except AttributeError:
obj.... |
def transformToNative(obj):
"""
Turn obj.value into a datetime.timedelta.
"""
if obj.isNative:
return obj
obj.isNative = True
obj.value=obj.value
if obj.value == '':
return obj
else:
deltalist=stringToDurations(obj.value... |
def transformFromNative(obj):
"""
Replace the datetime.timedelta in obj.value with an RFC2445 string.
"""
if not obj.isNative:
return obj
obj.isNative = False
obj.value = timedeltaToString(obj.value)
return obj |
def transformToNative(obj):
"""
Turn obj.value into a timedelta or datetime.
"""
if obj.isNative:
return obj
value = getattr(obj, 'value_param', 'DURATION').upper()
if hasattr(obj, 'value_param'):
del obj.value_param
if obj.value == '':
... |
def transformToNative(obj):
"""
Convert comma separated periods into tuples.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
obj.value = []
return obj
tzinfo = getTzid(getattr(obj, 'tzid_param', None))
... |
def transformFromNative(cls, obj):
"""
Convert the list of tuples in obj.value to strings.
"""
if obj.isNative:
obj.isNative = False
transformed = []
for tup in obj.value:
transformed.append(periodToString(tup, cls.forceUTC))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.