signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def insert_penalty_model(cur, penalty_model):
|
encoded_data = {}<EOL>linear, quadratic, offset = penalty_model.model.to_ising()<EOL>nodelist = sorted(linear)<EOL>edgelist = sorted(sorted(edge) for edge in penalty_model.graph.edges)<EOL>insert_graph(cur, nodelist, edgelist, encoded_data)<EOL>insert_feasible_configurations(cur, penalty_model.feasible_configurations, encoded_data)<EOL>insert_ising_model(cur, nodelist, edgelist, linear, quadratic, offset, encoded_data)<EOL>encoded_data['<STR_LIT>'] = json.dumps(penalty_model.decision_variables, separators=('<STR_LIT:U+002C>', '<STR_LIT::>'))<EOL>encoded_data['<STR_LIT>'] = penalty_model.classical_gap<EOL>encoded_data['<STR_LIT>'] = penalty_model.ground_energy<EOL>insert ="""<STR_LIT>"""<EOL>cur.execute(insert, encoded_data)<EOL>
|
Insert a penalty model into the database.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
penalty_model (:class:`penaltymodel.PenaltyModel`): A penalty
model to be stored in the database.
Examples:
>>> import networkx as nx
>>> import penaltymodel.core as pm
>>> import dimod
>>> graph = nx.path_graph(3)
>>> decision_variables = (0, 2)
>>> feasible_configurations = {(-1, -1): 0., (+1, +1): 0.}
>>> spec = pm.Specification(graph, decision_variables, feasible_configurations, dimod.SPIN)
>>> linear = {v: 0 for v in graph}
>>> quadratic = {edge: -1 for edge in graph.edges}
>>> model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.SPIN)
>>> widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)
>>> with pmc.cache_connect(':memory:') as cur:
... pmc.insert_penalty_model(cur, widget)
|
f5426:m13
|
def iter_penalty_model_from_specification(cur, specification):
|
encoded_data = {}<EOL>nodelist = sorted(specification.graph)<EOL>edgelist = sorted(sorted(edge) for edge in specification.graph.edges)<EOL>encoded_data['<STR_LIT>'] = len(nodelist)<EOL>encoded_data['<STR_LIT>'] = len(edgelist)<EOL>encoded_data['<STR_LIT>'] = json.dumps(edgelist, separators=('<STR_LIT:U+002C>', '<STR_LIT::>'))<EOL>encoded_data['<STR_LIT>'] = len(next(iter(specification.feasible_configurations)))<EOL>encoded_data['<STR_LIT>'] = len(specification.feasible_configurations)<EOL>encoded = {_serialize_config(config): en for config, en in specification.feasible_configurations.items()}<EOL>configs, energies = zip(*sorted(encoded.items()))<EOL>encoded_data['<STR_LIT>'] = json.dumps(configs, separators=('<STR_LIT:U+002C>', '<STR_LIT::>'))<EOL>encoded_data['<STR_LIT>'] = json.dumps(energies, separators=('<STR_LIT:U+002C>', '<STR_LIT::>'))<EOL>encoded_data['<STR_LIT>'] = json.dumps(specification.decision_variables, separators=('<STR_LIT:U+002C>', '<STR_LIT::>'))<EOL>encoded_data['<STR_LIT>'] = json.dumps(specification.min_classical_gap, separators=('<STR_LIT:U+002C>', '<STR_LIT::>'))<EOL>select ="""<STR_LIT>"""<EOL>for row in cur.execute(select, encoded_data):<EOL><INDENT>linear = _decode_linear_biases(row['<STR_LIT>'], nodelist)<EOL>quadratic = _decode_quadratic_biases(row['<STR_LIT>'], edgelist)<EOL>model = dimod.BinaryQuadraticModel(linear, quadratic, row['<STR_LIT>'], dimod.SPIN) <EOL>yield pm.PenaltyModel.from_specification(specification, model, row['<STR_LIT>'], row['<STR_LIT>'])<EOL><DEDENT>
|
Iterate through all penalty models in the cache matching the
given specification.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
specification (:class:`penaltymodel.Specification`): A specification
for a penalty model.
Yields:
:class:`penaltymodel.PenaltyModel`
|
f5426:m14
|
def cache_file(app_name=APPNAME, app_author=APPAUTHOR, filename=DATABASENAME):
|
user_data_dir = homebase.user_data_dir(app_name=app_name, app_author=app_author, create=True)<EOL>return os.path.join(user_data_dir, filename)<EOL>
|
Returns the filename (including path) for the data cache.
The path will depend on the operating system, certain environmental
variables and whether it is being run inside a virtual environment.
See `homebase <https://github.com/dwavesystems/homebase>`_.
Args:
app_name (str, optional): The application name.
Default is given by :obj:`.APPNAME`.
app_author (str, optional): The application author. Default
is given by :obj:`.APPAUTHOR`.
filename (str, optional): The name of the database file.
Default is given by :obj:`DATABASENAME`.
Returns:
str: The full path to the file that can be used as a cache.
Notes:
Creates the directory if it does not already exist.
If run inside of a virtual environment, the cache will be stored
in `/path/to/virtualenv/data/app_name`
|
f5429:m0
|
@pm.interface.penaltymodel_factory(<NUM_LIT:100>)<EOL>def get_penalty_model(specification, database=None):
|
<EOL>if not _is_index_labelled(specification.graph):<EOL><INDENT>relabel_applied = True<EOL>mapping, inverse_mapping = _graph_canonicalization(specification.graph)<EOL>specification = specification.relabel_variables(mapping, inplace=False)<EOL><DEDENT>else:<EOL><INDENT>relabel_applied = False<EOL><DEDENT>if database is None:<EOL><INDENT>conn = cache_connect()<EOL><DEDENT>else:<EOL><INDENT>conn = cache_connect(database)<EOL><DEDENT>with conn as cur:<EOL><INDENT>try:<EOL><INDENT>widget = next(iter_penalty_model_from_specification(cur, specification))<EOL><DEDENT>except StopIteration:<EOL><INDENT>widget = None<EOL><DEDENT><DEDENT>conn.close()<EOL>if widget is None:<EOL><INDENT>raise pm.MissingPenaltyModel("<STR_LIT>")<EOL><DEDENT>if relabel_applied:<EOL><INDENT>widget.relabel_variables(inverse_mapping, inplace=True)<EOL><DEDENT>return widget<EOL>
|
Factory function for penaltymodel_cache.
Args:
specification (penaltymodel.Specification): The specification
for the desired penalty model.
database (str, optional): The path to the desired sqlite database
file. If None, will use the default.
Returns:
:class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.
Raises:
:class:`penaltymodel.MissingPenaltyModel`: If the penalty model is not in the
cache.
Parameters:
priority (int): 100
|
f5430:m0
|
def cache_penalty_model(penalty_model, database=None):
|
<EOL>if not _is_index_labelled(penalty_model.graph):<EOL><INDENT>mapping, __ = _graph_canonicalization(penalty_model.graph)<EOL>penalty_model = penalty_model.relabel_variables(mapping, inplace=False)<EOL><DEDENT>if database is None:<EOL><INDENT>conn = cache_connect()<EOL><DEDENT>else:<EOL><INDENT>conn = cache_connect(database)<EOL><DEDENT>with conn as cur:<EOL><INDENT>insert_penalty_model(cur, penalty_model)<EOL><DEDENT>conn.close()<EOL>
|
Caching function for penaltymodel_cache.
Args:
penalty_model (:class:`penaltymodel.PenaltyModel`): Penalty model to
be cached.
database (str, optional): The path to the desired sqlite database
file. If None, will use the default.
|
f5430:m1
|
def _is_index_labelled(graph):
|
return all(v in graph for v in range(len(graph)))<EOL>
|
graph is index-labels [0, len(graph) - 1]
|
f5430:m2
|
@classmethod<EOL><INDENT>def from_specification(cls, specification, model, classical_gap, ground_energy):<DEDENT>
|
<EOL>return cls(specification.graph,<EOL>specification.decision_variables,<EOL>specification.feasible_configurations,<EOL>specification.vartype,<EOL>model,<EOL>classical_gap,<EOL>ground_energy,<EOL>ising_linear_ranges=specification.ising_linear_ranges,<EOL>ising_quadratic_ranges=specification.ising_quadratic_ranges)<EOL>
|
Construct a PenaltyModel from a Specification.
Args:
specification (:class:`.Specification`): A specification that was used
to generate the model.
model (:class:`dimod.BinaryQuadraticModel`): A binary quadratic model
that has ground states that match the feasible_configurations.
classical_gap (numeric): The difference in classical energy between the ground
state and the first excited state. Must be positive.
ground_energy (numeric): The minimum energy of all possible configurations.
Returns:
:class:`.PenaltyModel`
|
f5435:c0:m1
|
def relabel_variables(self, mapping, inplace=True):
|
<EOL>if inplace:<EOL><INDENT>Specification.relabel_variables(self, mapping, inplace=True)<EOL>self.model.relabel_variables(mapping, inplace=True)<EOL>return self<EOL><DEDENT>else:<EOL><INDENT>spec = Specification.relabel_variables(self, mapping, inplace=False)<EOL>model = self.model.relabel_variables(mapping, inplace=False)<EOL>return PenaltyModel.from_specification(spec, model, self.classical_gap, self.ground_energy)<EOL><DEDENT>
|
Relabel the variables and nodes according to the given mapping.
Args:
mapping (dict[hashable, hashable]): A dict with the current
variable labels as keys and new labels as values. A
partial mapping is allowed.
inplace (bool, optional, default=True):
If True, the penalty model is updated in-place; otherwise, a new penalty model
is returned.
Returns:
:class:`.PenaltyModel`: A PenaltyModel with the variables relabeled according to
mapping.
Examples:
>>> spec = pm.Specification(nx.path_graph(3), (0, 2), {(-1, -1), (1, 1)}, dimod.SPIN)
>>> model = dimod.BinaryQuadraticModel({0: 0, 1: 0, 2: 0}, {(0, 1): -1, (1, 2): -1}, 0.0, dimod.SPIN)
>>> penalty_model = pm.PenaltyModel.from_specification(spec, model, 2., -2.)
>>> relabeled_penalty_model = penalty_model.relabel_variables({0: 'a'}, inplace=False)
>>> relabeled_penalty_model.decision_variables
('a', 2)
>>> spec = pm.Specification(nx.path_graph(3), (0, 2), {(-1, -1), (1, 1)}, dimod.SPIN)
>>> model = dimod.BinaryQuadraticModel({0: 0, 1: 0, 2: 0}, {(0, 1): -1, (1, 2): -1}, 0.0, dimod.SPIN)
>>> penalty_model = pm.PenaltyModel.from_specification(spec, model, 2., -2.)
>>> __ = penalty_model.relabel_variables({0: 'a'}, inplace=True)
>>> penalty_model.decision_variables
('a', 2)
|
f5435:c0:m4
|
@staticmethod<EOL><INDENT>def _check_ising_linear_ranges(linear_ranges, graph):<DEDENT>
|
if linear_ranges is None:<EOL><INDENT>linear_ranges = {}<EOL><DEDENT>for v in graph:<EOL><INDENT>if v in linear_ranges:<EOL><INDENT>linear_ranges[v] = Specification._check_range(linear_ranges[v])<EOL><DEDENT>else:<EOL><INDENT>linear_ranges[v] = [-<NUM_LIT:2>, <NUM_LIT:2>]<EOL><DEDENT><DEDENT>return linear_ranges<EOL>
|
check correctness/populate defaults for ising_linear_ranges.
|
f5437:c0:m1
|
@staticmethod<EOL><INDENT>def _check_ising_quadratic_ranges(quad_ranges, graph):<DEDENT>
|
if quad_ranges is None:<EOL><INDENT>quad_ranges = {}<EOL><DEDENT>for u in graph:<EOL><INDENT>if u not in quad_ranges:<EOL><INDENT>quad_ranges[u] = {}<EOL><DEDENT><DEDENT>for u, neighbors in iteritems(quad_ranges):<EOL><INDENT>for v, rang in iteritems(neighbors):<EOL><INDENT>rang = Specification._check_range(rang)<EOL>if u in quad_ranges[v]:<EOL><INDENT>if quad_ranges[u][v] != quad_ranges[v][u]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>quad_ranges[v][u] = quad_ranges[u][v] = rang<EOL><DEDENT><DEDENT>for u, v in graph.edges:<EOL><INDENT>if u not in quad_ranges[v]:<EOL><INDENT>quad_ranges[u][v] = quad_ranges[v][u] = [-<NUM_LIT:1>, <NUM_LIT:1>]<EOL><DEDENT><DEDENT>return quad_ranges<EOL>
|
check correctness/populate defaults for ising_quadratic_ranges.
|
f5437:c0:m2
|
@staticmethod<EOL><INDENT>def _check_range(range_):<DEDENT>
|
try:<EOL><INDENT>if not isinstance(range_, list):<EOL><INDENT>range_ = list(range_)<EOL><DEDENT>min_, max_ = range_<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(min_, Number) or not isinstance(max_, Number) or min_ > max_:<EOL><INDENT>raise ValueError(("<STR_LIT>"<EOL>"<STR_LIT>"))<EOL><DEDENT>return range_<EOL>
|
Check that a range is in the format we expect [min, max] and return
|
f5437:c0:m3
|
def __eq__(self, specification):
|
<EOL>return (isinstance(specification, Specification) and<EOL>self.graph.edges == specification.graph.edges and<EOL>self.graph.nodes == specification.graph.nodes and<EOL>self.decision_variables == specification.decision_variables and<EOL>self.feasible_configurations == specification.feasible_configurations)<EOL>
|
Implemented equality checking.
|
f5437:c0:m5
|
def relabel_variables(self, mapping, inplace=True):
|
graph = self.graph<EOL>ising_linear_ranges = self.ising_linear_ranges<EOL>ising_quadratic_ranges = self.ising_quadratic_ranges<EOL>try:<EOL><INDENT>old_labels = set(iterkeys(mapping))<EOL>new_labels = set(itervalues(mapping))<EOL><DEDENT>except TypeError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for v in new_labels:<EOL><INDENT>if v in graph and v not in old_labels:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>"<STR_LIT>").format(v))<EOL><DEDENT><DEDENT>if not inplace:<EOL><INDENT>return Specification(nx.relabel_nodes(graph, mapping, copy=True), <EOL>tuple(mapping.get(v, v) for v in self.decision_variables),<EOL>self.feasible_configurations, <EOL>vartype=self.vartype, <EOL>ising_linear_ranges={mapping.get(v, v): ising_linear_ranges[v] for v in graph},<EOL>ising_quadratic_ranges={mapping.get(v, v): {mapping.get(u, u): r<EOL>for u, r in iteritems(neighbors)}<EOL>for v, neighbors in iteritems(ising_quadratic_ranges)})<EOL><DEDENT>else:<EOL><INDENT>shared = old_labels & new_labels<EOL>if shared:<EOL><INDENT>counter = itertools.count(<NUM_LIT:2> * len(self))<EOL>old_to_intermediate = {}<EOL>intermediate_to_new = {}<EOL>for old, new in iteritems(mapping):<EOL><INDENT>if old == new:<EOL><INDENT>continue<EOL><DEDENT>if old in new_labels or new in old_labels:<EOL><INDENT>lbl = next(counter)<EOL>while lbl in new_labels or lbl in old_labels:<EOL><INDENT>lbl = next(counter)<EOL><DEDENT>old_to_intermediate[old] = lbl<EOL>intermediate_to_new[lbl] = new<EOL><DEDENT>else:<EOL><INDENT>old_to_intermediate[old] = new<EOL><DEDENT><DEDENT>Specification.relabel_variables(self, old_to_intermediate, inplace=True)<EOL>Specification.relabel_variables(self, intermediate_to_new, inplace=True)<EOL>return self<EOL><DEDENT>nx.relabel_nodes(self.graph, mapping, copy=False)<EOL>self.decision_variables = tuple(mapping.get(v, v) for v in self.decision_variables)<EOL>for v in old_labels:<EOL><INDENT>if v in mapping:<EOL><INDENT>ising_linear_ranges[mapping[v]] = ising_linear_ranges[v]<EOL>del ising_linear_ranges[v]<EOL><DEDENT><DEDENT>for neighbors in itervalues(ising_quadratic_ranges):<EOL><INDENT>for v in list(neighbors):<EOL><INDENT>if v in mapping:<EOL><INDENT>neighbors[mapping[v]] = neighbors[v]<EOL>del neighbors[v]<EOL><DEDENT><DEDENT><DEDENT>for v in old_labels:<EOL><INDENT>if v in mapping:<EOL><INDENT>ising_quadratic_ranges[mapping[v]] = ising_quadratic_ranges[v]<EOL>del ising_quadratic_ranges[v]<EOL><DEDENT><DEDENT>return self<EOL><DEDENT>
|
Relabel the variables and nodes according to the given mapping.
Args:
mapping (dict): a dict mapping the current variable/node labels
to new ones.
inplace (bool, optional, default=True):
If True, the specification is updated in-place; otherwise, a new specification
is returned.
Returns:
:class:`.Specification`: A Specification with the variables
relabeled according to mapping. If copy=False returns itself,
if copy=True returns a new Specification.
|
f5437:c0:m7
|
def get_penalty_model(specification):
|
<EOL>for factory in iter_factories():<EOL><INDENT>try:<EOL><INDENT>pm = factory(specification)<EOL><DEDENT>except ImpossiblePenaltyModel as e:<EOL><INDENT>raise e<EOL><DEDENT>except FactoryException:<EOL><INDENT>continue<EOL><DEDENT>for cache in iter_caches():<EOL><INDENT>cache(pm)<EOL><DEDENT>return pm<EOL><DEDENT>return None<EOL>
|
Retrieve a PenaltyModel from one of the available factories.
Args:
specification (:class:`.Specification`): The specification
for the desired PenaltyModel.
Returns:
:class:`.PenaltyModel`/None: A PenaltyModel as returned by
the highest priority factory, or None if no factory could
produce it.
Raises:
:exc:`ImpossiblePenaltyModel`: If the specification
describes a penalty model that cannot be built by any
factory.
|
f5439:m0
|
def penaltymodel_factory(priority):
|
def _entry_point(f):<EOL><INDENT>f.priority = priority<EOL>return f<EOL><DEDENT>return _entry_point<EOL>
|
Decorator to assign a `priority` attribute to the decorated function.
Args:
priority (int): The priority of the factory. Factories are queried
in order of decreasing priority.
Examples:
Decorate penalty model factories like:
>>> @pm.penaltymodel_factory(105)
... def factory_function(spec):
... pass
>>> factory_function.priority
105
|
f5439:m1
|
def iter_factories():
|
<EOL>factories = (entry.load() for entry in iter_entry_points(FACTORY_ENTRYPOINT))<EOL>for factory in sorted(factories, key=lambda f: getattr(f, '<STR_LIT>', -<NUM_LIT:1000>), reverse=True):<EOL><INDENT>yield factory<EOL><DEDENT>
|
Iterate through all factories identified by the factory entrypoint.
Yields:
function: A function that accepts a :class:`.Specification` and
returns a :class:`.PenaltyModel`.
|
f5439:m2
|
def iter_caches():
|
<EOL>return iter(entry.load() for entry in iter_entry_points(CACHE_ENTRYPOINT))<EOL>
|
Iterator over the PenaltyModel caches.
Yields:
function: A function that accepts a :class:`PenaltyModel` and caches
it.
|
f5439:m3
|
def generate_and_check(self, graph, configurations, decision_variables,<EOL>linear_energy_ranges, quadratic_energy_ranges,<EOL>min_classical_gap, known_classical_gap=<NUM_LIT:0>):
|
bqm, gap = maxgap.generate(graph, configurations, decision_variables,<EOL>linear_energy_ranges,<EOL>quadratic_energy_ranges,<EOL>min_classical_gap)<EOL>self.assertGreaterEqual(gap, min_classical_gap)<EOL>self.assertGreaterEqual(gap, known_classical_gap - MAX_GAP_DELTA)<EOL>self.assertEqual(len(bqm.linear), len(graph.nodes))<EOL>for v in bqm.linear:<EOL><INDENT>self.assertIn(v, graph.nodes)<EOL><DEDENT>self.assertEqual(len(bqm.quadratic), len(graph.edges))<EOL>for u, v in bqm.quadratic:<EOL><INDENT>self.assertIn((u, v), graph.edges)<EOL><DEDENT>sampleset = dimod.ExactSolver().sample(bqm)<EOL>if len(sampleset):<EOL><INDENT>self.assertAlmostEqual(sampleset.first.energy, min(configurations.values()))<EOL><DEDENT>if isinstance(configurations, dict) and configurations:<EOL><INDENT>highest_feasible_energy = max(configurations.values())<EOL><DEDENT>else:<EOL><INDENT>highest_feasible_energy = <NUM_LIT:0><EOL><DEDENT>best_gap = float('<STR_LIT>')<EOL>seen = set()<EOL>for sample, energy in sampleset.data(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>config = tuple(sample[v] for v in decision_variables)<EOL>if config in seen:<EOL><INDENT>continue<EOL><DEDENT>if config in configurations:<EOL><INDENT>self.assertAlmostEqual(energy, configurations[config])<EOL>seen.add(config)<EOL><DEDENT>else:<EOL><INDENT>best_gap = min(best_gap, energy - highest_feasible_energy)<EOL><DEDENT><DEDENT>for v, bias in bqm.linear.items():<EOL><INDENT>min_, max_ = linear_energy_ranges[v]<EOL>self.assertGreaterEqual(bias, min_)<EOL>self.assertLessEqual(bias, max_)<EOL><DEDENT>for (u, v), bias in bqm.quadratic.items():<EOL><INDENT>min_, max_ = quadratic_energy_ranges.get((u, v), quadratic_energy_ranges.get((v, u), None))<EOL>self.assertGreaterEqual(bias, min_)<EOL>self.assertLessEqual(bias, max_)<EOL><DEDENT>self.assertAlmostEqual(best_gap, gap)<EOL>
|
Checks that MaxGap's BQM and gap obeys the constraints set by configurations,
linear and quadratic energy ranges, and min classical gap.
Args:
known_classical_gap: a known gap for this graph and configuration
|
f5443:c0:m1
|
def check_table_energies_exact(self, graph, decision_variables, h, J):
|
<EOL>aux_variables = tuple(v for v in graph if v not in decision_variables)<EOL>linear_ranges = {v: (bias, bias) for v, bias in h.items()}<EOL>quadratic_ranges = {edge: (bias, bias) for edge, bias in J.items()}<EOL>table = Table(graph, decision_variables, linear_ranges, quadratic_ranges)<EOL>for config in itertools.product((-<NUM_LIT:1>, <NUM_LIT:1>), repeat=len(decision_variables)):<EOL><INDENT>spins = dict(zip(decision_variables, config))<EOL>energy = float('<STR_LIT>')<EOL>for aux_config in itertools.product((-<NUM_LIT:1>, <NUM_LIT:1>), repeat=len(aux_variables)):<EOL><INDENT>aux_spins = dict(zip(aux_variables, aux_config))<EOL>aux_spins.update(spins)<EOL>aux_energy = ising_energy(h, J, aux_spins)<EOL>if aux_energy < energy:<EOL><INDENT>energy = aux_energy<EOL><DEDENT><DEDENT>assertions = table.assertions<EOL>theta = table.theta <EOL>self.assertSat(And(assertions))<EOL>table_energy = table.energy(spins, break_aux_symmetry=False)<EOL>for offset in [<NUM_LIT:0>, -<NUM_LIT>, -<NUM_LIT>, -<NUM_LIT>, <NUM_LIT>, <NUM_LIT:1>, <NUM_LIT>]:<EOL><INDENT>self.assertSat(And([Equals(table_energy, limitReal(energy + offset)),<EOL>And(assertions),<EOL>Equals(theta.offset, limitReal(offset))]),<EOL>msg='<STR_LIT>')<EOL>self.assertUnsat(And([Not(Equals(table_energy, limitReal(energy + offset))),<EOL>And(assertions),<EOL>Equals(theta.offset, limitReal(offset))]),<EOL>msg='<STR_LIT>')<EOL><DEDENT>table_energy_upperbound = table.energy_upperbound(spins)<EOL>for offset in [-<NUM_LIT>, -<NUM_LIT>, -<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:1>, <NUM_LIT>]:<EOL><INDENT>self.assertSat(And([GE(table_energy_upperbound, limitReal(energy + offset)),<EOL>And(assertions),<EOL>Equals(theta.offset, limitReal(offset))]),<EOL>msg='<STR_LIT>')<EOL><DEDENT><DEDENT>
|
For a given ising problem, check that the table gives the correct
energies when linear and quadratic energies are specified exactly.
|
f5445:c0:m3
|
def generate(graph, feasible_configurations, decision_variables,<EOL>linear_energy_ranges, quadratic_energy_ranges, min_classical_gap,<EOL>smt_solver_name=None):
|
if len(graph) == <NUM_LIT:0>:<EOL><INDENT>return dimod.BinaryQuadraticModel.empty(dimod.SPIN), float('<STR_LIT>')<EOL><DEDENT>table = Table(graph, decision_variables, linear_energy_ranges, quadratic_energy_ranges)<EOL>for config in itertools.product((-<NUM_LIT:1>, <NUM_LIT:1>), repeat=len(decision_variables)):<EOL><INDENT>spins = dict(zip(decision_variables, config))<EOL>if config in feasible_configurations:<EOL><INDENT>table.set_energy(spins, feasible_configurations[config])<EOL><DEDENT>else:<EOL><INDENT>if isinstance(feasible_configurations, dict) and feasible_configurations:<EOL><INDENT>highest_feasible_energy = max(feasible_configurations.values())<EOL><DEDENT>else:<EOL><INDENT>highest_feasible_energy = <NUM_LIT:0><EOL><DEDENT>table.set_energy_upperbound(spins, highest_feasible_energy)<EOL><DEDENT><DEDENT>with Solver(smt_solver_name) as solver:<EOL><INDENT>for assertion in table.assertions:<EOL><INDENT>solver.add_assertion(assertion)<EOL><DEDENT>gap_assertion = table.gap_bound_assertion(min_classical_gap)<EOL>solver.add_assertion(gap_assertion)<EOL>if solver.solve():<EOL><INDENT>model = solver.get_model()<EOL>gmin = min_classical_gap<EOL>gmax = sum(max(abs(r) for r in linear_energy_ranges[v]) for v in graph)<EOL>gmax += sum(max(abs(r) for r in quadratic_energy_ranges[(u, v)])<EOL>for (u, v) in graph.edges)<EOL>gmax *= <NUM_LIT:2><EOL>g = max(<NUM_LIT>, gmin)<EOL>while abs(gmax - gmin) >= MAX_GAP_DELTA:<EOL><INDENT>solver.push()<EOL>gap_assertion = table.gap_bound_assertion(g)<EOL>solver.add_assertion(gap_assertion)<EOL>if solver.solve():<EOL><INDENT>model = solver.get_model()<EOL>gmin = float(model.get_py_value(table.gap))<EOL><DEDENT>else:<EOL><INDENT>solver.pop()<EOL>gmax = g<EOL><DEDENT>g = min(gmin + <NUM_LIT>, (gmax + gmin) / <NUM_LIT:2>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ImpossiblePenaltyModel("<STR_LIT>")<EOL><DEDENT><DEDENT>classical_gap = float(model.get_py_value(table.gap))<EOL>if (len(decision_variables) == len(graph) and<EOL>decision_variables and <EOL>len(feasible_configurations) == <NUM_LIT:2>**len(decision_variables)):<EOL><INDENT>classical_gap = float('<STR_LIT>')<EOL><DEDENT>return table.theta.to_bqm(model), classical_gap<EOL>
|
Generates the Ising model that induces the given feasible configurations. The code is based
on the papers [#do]_ and [#mc]_.
Args:
graph (nx.Graph): The target graph on which the Ising model is to be built.
feasible_configurations (dict): The set of feasible configurations
of the decision variables. The key is a feasible configuration
as a tuple of spins, the values are the associated energy.
decision_variables (list/tuple): Which variables in the graph are
assigned as decision variables.
linear_energy_ranges (dict, optional): A dict of the form
{v: (min, max), ...} where min and max are the range
of values allowed to v.
quadratic_energy_ranges (dict): A dict of the form
{(u, v): (min, max), ...} where min and max are the range
of values allowed to (u, v).
min_classical_gap (float): The minimum energy gap between the highest feasible state and the
lowest infeasible state.
smt_solver_name (str/None): The name of the smt solver. Must
be a solver available to pysmt. If None, uses the pysmt default.
Returns:
tuple: A 4-tuple containing:
dict: The linear biases of the Ising problem.
dict: The quadratic biases of the Ising problem.
:obj:`dimod.BinaryQuadraticModel`
float: The classical energy gap between ground and the first
excited state.
Raises:
ImpossiblePenaltyModel: If the penalty model cannot be built. Normally due
to a non-zero infeasible gap.
.. [#do] Bian et al., "Discrete optimization using quantum annealing on sparse Ising models",
https://www.frontiersin.org/articles/10.3389/fphy.2014.00056/full
.. [#mc] Z. Bian, F. Chudak, R. Israel, B. Lackey, W. G. Macready, and A. Roy
"Mapping constrained optimization problems to quantum annealing with application to fault diagnosis"
https://arxiv.org/pdf/1603.03111.pdf
|
f5447:m0
|
def limitReal(x, max_denominator=<NUM_LIT>):
|
f = Fraction(x).limit_denominator(max_denominator)<EOL>return Real((f.numerator, f.denominator))<EOL>
|
Creates an pysmt Real constant from x.
Args:
x (number): A number to be cast to a pysmt constant.
max_denominator (int, optional): The maximum size of the denominator.
Default 1000000.
Returns:
A Real constant with the given value and the denominator limited.
|
f5449:m0
|
def __init__(self, linear, quadratic, offset, vartype):
|
dimod.BinaryQuadraticModel.__init__(self, linear, quadratic, offset, vartype)<EOL>self.assertions = set()<EOL>
|
Theta is a BQM where the biases are pysmt Symbols.
Theta is normally constructed using :meth:`.Theta.from_graph`.
|
f5449:c0:m0
|
@classmethod<EOL><INDENT>def from_graph(cls, graph, linear_energy_ranges, quadratic_energy_ranges):<DEDENT>
|
get_env().enable_infix_notation = True <EOL>theta = cls.empty(dimod.SPIN)<EOL>theta.add_offset(Symbol('<STR_LIT>', REAL))<EOL>def Linear(v):<EOL><INDENT>"""<STR_LIT>"""<EOL>bias = Symbol('<STR_LIT>'.format(v), REAL)<EOL>min_, max_ = linear_energy_ranges[v]<EOL>theta.assertions.add(LE(bias, limitReal(max_)))<EOL>theta.assertions.add(GE(bias, limitReal(min_)))<EOL>return bias<EOL><DEDENT>def Quadratic(u, v):<EOL><INDENT>"""<STR_LIT>"""<EOL>bias = Symbol('<STR_LIT>'.format(u, v), REAL)<EOL>if (v, u) in quadratic_energy_ranges:<EOL><INDENT>min_, max_ = quadratic_energy_ranges[(v, u)]<EOL><DEDENT>else:<EOL><INDENT>min_, max_ = quadratic_energy_ranges[(u, v)]<EOL><DEDENT>theta.assertions.add(LE(bias, limitReal(max_)))<EOL>theta.assertions.add(GE(bias, limitReal(min_)))<EOL>return bias<EOL><DEDENT>for v in graph.nodes:<EOL><INDENT>theta.add_variable(v, Linear(v))<EOL><DEDENT>for u, v in graph.edges:<EOL><INDENT>theta.add_interaction(u, v, Quadratic(u, v))<EOL><DEDENT>return theta<EOL>
|
Create Theta from a graph and energy ranges.
Args:
graph (:obj:`networkx.Graph`):
Provides the structure for Theta.
linear_energy_ranges (dict):
A dict of the form {v: (min, max), ...} where min and max are the
range of values allowed to v.
quadratic_energy_ranges (dict):
A dict of the form {(u, v): (min, max), ...} where min and max
are the range of values allowed to (u, v).
Returns:
:obj:`.Theta`
|
f5449:c0:m1
|
def to_bqm(self, model):
|
linear = ((v, float(model.get_py_value(bias)))<EOL>for v, bias in self.linear.items())<EOL>quadratic = ((u, v, float(model.get_py_value(bias)))<EOL>for (u, v), bias in self.quadratic.items())<EOL>offset = float(model.get_py_value(self.offset))<EOL>return dimod.BinaryQuadraticModel(linear, quadratic, offset, dimod.SPIN)<EOL>
|
Given a pysmt model, return a bqm.
Adds the values of the biases as determined by the SMT solver to a bqm.
Args:
model: A pysmt model.
Returns:
:obj:`dimod.BinaryQuadraticModel`
|
f5449:c0:m2
|
def SpinTimes(spin, bias):
|
if not isinstance(spin, int):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if spin == -<NUM_LIT:1>:<EOL><INDENT>return Times(Real((-<NUM_LIT:1>, <NUM_LIT:1>)), bias) <EOL><DEDENT>elif spin == <NUM_LIT:1>:<EOL><INDENT>return bias<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>
|
Define our own multiplication for bias times spins. This allows for
cleaner log code as well as value checking.
Args:
spin (int): -1 or 1
bias (:class:`pysmt.shortcuts.Symbol`): The bias
Returns:
spins * bias
|
f5450:m0
|
def _elimination_trees(theta, decision_variables):
|
<EOL>auxiliary_variables = set(n for n in theta.linear if n not in decision_variables)<EOL>adj = {v: {u for u in theta.adj[v] if u in auxiliary_variables}<EOL>for v in theta.adj if v in auxiliary_variables}<EOL>tw, order = dnx.treewidth_branch_and_bound(adj)<EOL>ancestors = {}<EOL>for n in order:<EOL><INDENT>ancestors[n] = set(adj[n])<EOL>neighbors = adj[n]<EOL>for u, v in itertools.combinations(neighbors, <NUM_LIT:2>):<EOL><INDENT>adj[u].add(v)<EOL>adj[v].add(u)<EOL><DEDENT>for v in neighbors:<EOL><INDENT>adj[v].discard(n)<EOL><DEDENT>del adj[n]<EOL><DEDENT>roots = {}<EOL>nodes = {v: {} for v in ancestors}<EOL>for vidx in range(len(order) - <NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>v = order[vidx]<EOL>if ancestors[v]:<EOL><INDENT>for u in order[vidx + <NUM_LIT:1>:]:<EOL><INDENT>if u in ancestors[v]:<EOL><INDENT>nodes[u][v] = nodes[v] <EOL>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>roots[v] = nodes[v] <EOL><DEDENT><DEDENT>return roots, ancestors<EOL>
|
From Theta and the decision variables, determine the elimination order and the induced
trees.
|
f5450:m1
|
def energy_upperbound(self, spins):
|
subtheta = self.theta.copy()<EOL>subtheta.fix_variables(spins)<EOL>trees = self._trees<EOL>if not trees:<EOL><INDENT>assert not subtheta.linear and not subtheta.quadratic<EOL>return subtheta.offset<EOL><DEDENT>energy = Plus(self.message_upperbound(trees, {}, subtheta), subtheta.offset)<EOL>return energy<EOL>
|
A formula for an upper bound on the energy of Theta with spins fixed.
Args:
spins (dict): Spin values for a subset of the variables in Theta.
Returns:
Formula that upper bounds the energy with spins fixed.
|
f5450:c0:m1
|
def energy(self, spins, break_aux_symmetry=True):
|
subtheta = self.theta.copy()<EOL>subtheta.fix_variables(spins)<EOL>av = next(self._auxvar_counter)<EOL>auxvars = {v: Symbol('<STR_LIT>'.format(av, v), BOOL) for v in subtheta.linear}<EOL>if break_aux_symmetry and av == <NUM_LIT:0>:<EOL><INDENT>self.assertions.update(set(auxvars.values()))<EOL><DEDENT>trees = self._trees<EOL>if not trees:<EOL><INDENT>assert not subtheta.linear and not subtheta.quadratic<EOL>return subtheta.offset<EOL><DEDENT>energy = Plus(self.message(trees, {}, subtheta, auxvars), subtheta.offset)<EOL>return energy<EOL>
|
A formula for the exact energy of Theta with spins fixed.
Args:
spins (dict): Spin values for a subset of the variables in Theta.
break_aux_symmetry (bool, optional): Default True. If True, break
the aux variable symmetry by setting all aux variable to 1
for one of the feasible configurations. If the energy ranges
are not symmetric then this can make finding models impossible.
Returns:
Formula for the exact energy of Theta with spins fixed.
|
f5450:c0:m2
|
def message(self, tree, spins, subtheta, auxvars):
|
energy_sources = set()<EOL>for v, children in tree.items():<EOL><INDENT>aux = auxvars[v]<EOL>assert all(u in spins for u in self._ancestors[v])<EOL>def energy_contributions():<EOL><INDENT>yield subtheta.linear[v]<EOL>for u, bias in subtheta.adj[v].items():<EOL><INDENT>if u in spins:<EOL><INDENT>yield SpinTimes(spins[u], bias)<EOL><DEDENT><DEDENT><DEDENT>plus_energy = Plus(energy_contributions())<EOL>minus_energy = SpinTimes(-<NUM_LIT:1>, plus_energy)<EOL>if children:<EOL><INDENT>spins[v] = <NUM_LIT:1><EOL>plus_energy = Plus(plus_energy, self.message(children, spins, subtheta, auxvars))<EOL>spins[v] = -<NUM_LIT:1><EOL>minus_energy = Plus(minus_energy, self.message(children, spins, subtheta, auxvars))<EOL>del spins[v]<EOL><DEDENT>m = FreshSymbol(REAL)<EOL>ancestor_aux = {auxvars[u] if spins[u] > <NUM_LIT:0> else Not(auxvars[u])<EOL>for u in self._ancestors[v]}<EOL>plus_aux = And({aux}.union(ancestor_aux))<EOL>minus_aux = And({Not(aux)}.union(ancestor_aux))<EOL>self.assertions.update({LE(m, plus_energy),<EOL>LE(m, minus_energy),<EOL>Implies(plus_aux, GE(m, plus_energy)),<EOL>Implies(minus_aux, GE(m, minus_energy))<EOL>})<EOL>energy_sources.add(m)<EOL><DEDENT>return Plus(energy_sources)<EOL>
|
Determine the energy of the elimination tree.
Args:
tree (dict): The current elimination tree
spins (dict): The current fixed spins
subtheta (dict): Theta with spins fixed.
auxvars (dict): The auxiliary variables for the given spins.
Returns:
The formula for the energy of the tree.
|
f5450:c0:m3
|
def message_upperbound(self, tree, spins, subtheta):
|
energy_sources = set()<EOL>for v, subtree in tree.items():<EOL><INDENT>assert all(u in spins for u in self._ancestors[v])<EOL>def energy_contributions():<EOL><INDENT>yield subtheta.linear[v]<EOL>for u, bias in subtheta.adj[v].items():<EOL><INDENT>if u in spins:<EOL><INDENT>yield Times(limitReal(spins[u]), bias)<EOL><DEDENT><DEDENT><DEDENT>energy = Plus(energy_contributions())<EOL>if subtree:<EOL><INDENT>spins[v] = <NUM_LIT:1.><EOL>plus = self.message_upperbound(subtree, spins, subtheta)<EOL>spins[v] = -<NUM_LIT:1.><EOL>minus = self.message_upperbound(subtree, spins, subtheta)<EOL>del spins[v]<EOL><DEDENT>else:<EOL><INDENT>plus = minus = limitReal(<NUM_LIT:0.0>)<EOL><DEDENT>m = FreshSymbol(REAL)<EOL>self.assertions.update({LE(m, Plus(energy, plus)),<EOL>LE(m, Plus(Times(energy, limitReal(-<NUM_LIT:1.>)), minus))})<EOL>energy_sources.add(m)<EOL><DEDENT>return Plus(energy_sources)<EOL>
|
Determine an upper bound on the energy of the elimination tree.
Args:
tree (dict): The current elimination tree
spins (dict): The current fixed spins
subtheta (dict): Theta with spins fixed.
Returns:
The formula for the energy of the tree.
|
f5450:c0:m4
|
def set_energy(self, spins, target_energy):
|
spin_energy = self.energy(spins)<EOL>self.assertions.add(Equals(spin_energy, limitReal(target_energy)))<EOL>
|
Set the energy of Theta with spins fixed to target_energy.
Args:
spins (dict): Spin values for a subset of the variables in Theta.
target_energy (float): The desired energy for Theta with spins fixed.
Notes:
Add equality constraint to assertions.
|
f5450:c0:m5
|
def set_energy_upperbound(self, spins, offset=<NUM_LIT:0>):
|
spin_energy = self.energy_upperbound(spins)<EOL>self.assertions.add(GE(spin_energy, self.gap + offset))<EOL>
|
Upper bound the energy of Theta with spins fixed to be greater than (gap + offset).
Args:
spins (dict): Spin values for a subset of the variables in Theta.
offset (float): A value that is added to the upper bound. Default value is 0.
Notes:
Add equality constraint to assertions.
|
f5450:c0:m6
|
def gap_bound_assertion(self, gap_lowerbound):
|
return GE(self.gap, limitReal(gap_lowerbound))<EOL>
|
The formula that lower bounds the gap.
Args:
gap_lowerbound (float): Return the formula that sets a lower
bound on the gap.
|
f5450:c0:m7
|
@pm.penaltymodel_factory(-<NUM_LIT:100>) <EOL>def get_penalty_model(specification):
|
<EOL>feasible_configurations = specification.feasible_configurations<EOL>if specification.vartype is dimod.BINARY:<EOL><INDENT>feasible_configurations = {tuple(<NUM_LIT:2> * v - <NUM_LIT:1> for v in config): en<EOL>for config, en in feasible_configurations.items()}<EOL><DEDENT>ising_quadratic_ranges = specification.ising_quadratic_ranges<EOL>quadratic_ranges = {(u, v): ising_quadratic_ranges[u][v] for u, v in specification.graph.edges}<EOL>bqm, gap = generate(specification.graph,<EOL>feasible_configurations,<EOL>specification.decision_variables,<EOL>specification.ising_linear_ranges,<EOL>quadratic_ranges,<EOL>specification.min_classical_gap,<EOL>None) <EOL>try:<EOL><INDENT>ground = max(feasible_configurations.values())<EOL><DEDENT>except ValueError:<EOL><INDENT>ground = <NUM_LIT:0.0> <EOL><DEDENT>return pm.PenaltyModel.from_specification(specification, bqm, gap, ground)<EOL>
|
Factory function for penaltymodel_maxgap.
Args:
specification (penaltymodel.Specification): The specification
for the desired penalty model.
Returns:
:class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.
Raises:
:class:`penaltymodel.ImpossiblePenaltyModel`: If the penalty cannot be built.
Parameters:
priority (int): -100
|
f5451:m0
|
def get_connector(database_name=None):
|
from django.db import connections, DEFAULT_DB_ALIAS<EOL>database_name = database_name or DEFAULT_DB_ALIAS<EOL>connection = connections[database_name]<EOL>engine = connection.settings_dict['<STR_LIT>']<EOL>connector_settings = settings.CONNECTORS.get(database_name, {})<EOL>connector_path = connector_settings.get('<STR_LIT>', CONNECTOR_MAPPING[engine])<EOL>connector_module_path = '<STR_LIT:.>'.join(connector_path.split('<STR_LIT:.>')[:-<NUM_LIT:1>])<EOL>module = import_module(connector_module_path)<EOL>connector_name = connector_path.split('<STR_LIT:.>')[-<NUM_LIT:1>]<EOL>connector = getattr(module, connector_name)<EOL>return connector(database_name, **connector_settings)<EOL>
|
Get a connector from its database key in setttings.
|
f5480:m0
|
@property<EOL><INDENT>def settings(self):<DEDENT>
|
if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>sett = self.connection.settings_dict.copy()<EOL>sett.update(settings.CONNECTORS.get(self.database_name, {}))<EOL>self._settings = sett<EOL><DEDENT>return self._settings<EOL>
|
Mix of database and connector settings.
|
f5480:c0:m1
|
def _create_dump(self):
|
raise NotImplementedError("<STR_LIT>")<EOL>
|
Override this method to define dump creation.
|
f5480:c0:m4
|
def restore_dump(self, dump):
|
result = self._restore_dump(dump)<EOL>return result<EOL>
|
:param dump: Dump file
:type dump: file
|
f5480:c0:m5
|
def _restore_dump(self, dump):
|
raise NotImplementedError("<STR_LIT>")<EOL>
|
Override this method to define dump creation.
:param dump: Dump file
:type dump: file
|
f5480:c0:m6
|
def run_command(self, command, stdin=None, env=None):
|
cmd = shlex.split(command)<EOL>stdout = SpooledTemporaryFile(max_size=settings.TMP_FILE_MAX_SIZE,<EOL>dir=settings.TMP_DIR)<EOL>stderr = SpooledTemporaryFile(max_size=settings.TMP_FILE_MAX_SIZE,<EOL>dir=settings.TMP_DIR)<EOL>full_env = os.environ.copy() if self.use_parent_env else {}<EOL>full_env.update(self.env)<EOL>full_env.update(env or {})<EOL>try:<EOL><INDENT>if isinstance(stdin, (ContentFile, SFTPStorageFile)):<EOL><INDENT>process = Popen(cmd, stdin=PIPE, stdout=stdout, stderr=stderr, env=full_env)<EOL>process.communicate(input=stdin.read())<EOL><DEDENT>else:<EOL><INDENT>process = Popen(cmd, stdin=stdin, stdout=stdout, stderr=stderr, env=full_env)<EOL><DEDENT>process.wait()<EOL>if process.poll():<EOL><INDENT>stderr.seek(<NUM_LIT:0>)<EOL>raise exceptions.CommandConnectorError(<EOL>"<STR_LIT>".format(command, stderr.read().decode('<STR_LIT:utf-8>')))<EOL><DEDENT>stdout.seek(<NUM_LIT:0>)<EOL>stderr.seek(<NUM_LIT:0>)<EOL>return stdout, stderr<EOL><DEDENT>except OSError as err:<EOL><INDENT>raise exceptions.CommandConnectorError(<EOL>"<STR_LIT>".format(command, str(err)))<EOL><DEDENT>
|
Launch a shell command line.
:param command: Command line to launch
:type command: str
:param stdin: Standard input of command
:type stdin: file
:param env: Environment variable used in command
:type env: dict
:return: Standard output of command
:rtype: file
|
f5480:c1:m0
|
def get_storage(path=None, options=None):
|
path = path or settings.STORAGE<EOL>options = options or settings.STORAGE_OPTIONS<EOL>if not path:<EOL><INDENT>raise ImproperlyConfigured('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return Storage(path, **options)<EOL>
|
Get the specified storage configured with options.
:param path: Path in Python dot style to module containing the storage
class. If empty settings.DBBACKUP_STORAGE will be used.
:type path: ``str``
:param options: Parameters for configure the storage, if empty
settings.DBBACKUP_STORAGE_OPTIONS will be used.
:type options: ``dict``
:return: Storage configured
:rtype: :class:`.Storage`
|
f5485:m0
|
def __init__(self, storage_path=None, **options):
|
self._storage_path = storage_path or settings.STORAGE<EOL>options = options.copy()<EOL>options.update(settings.STORAGE_OPTIONS)<EOL>options = dict([(key.lower(), value) for key, value in options.items()])<EOL>self.storageCls = get_storage_class(self._storage_path)<EOL>self.storage = self.storageCls(**options)<EOL>self.name = self.storageCls.__name__<EOL>
|
Initialize a Django Storage instance with given options.
:param storage_path: Path to a Django Storage class with dot style
If ``None``, ``settings.DBBACKUP_STORAGE`` will
be used.
:type storage_path: str
|
f5485:c2:m1
|
def list_backups(self, encrypted=None, compressed=None, content_type=None,<EOL>database=None, servername=None):
|
if content_type not in ('<STR_LIT>', '<STR_LIT>', None):<EOL><INDENT>msg = "<STR_LIT>" % (<EOL>content_type)<EOL>raise TypeError(msg)<EOL><DEDENT>files = [f for f in self.list_directory() if utils.filename_to_datestring(f)]<EOL>if encrypted is not None:<EOL><INDENT>files = [f for f in files if ('<STR_LIT>' in f) == encrypted]<EOL><DEDENT>if compressed is not None:<EOL><INDENT>files = [f for f in files if ('<STR_LIT>' in f) == compressed]<EOL><DEDENT>if content_type == '<STR_LIT>':<EOL><INDENT>files = [f for f in files if '<STR_LIT>' in f]<EOL><DEDENT>elif content_type == '<STR_LIT>':<EOL><INDENT>files = [f for f in files if '<STR_LIT>' not in f]<EOL><DEDENT>if database:<EOL><INDENT>files = [f for f in files if database in f]<EOL><DEDENT>if servername:<EOL><INDENT>files = [f for f in files if servername in f]<EOL><DEDENT>return files<EOL>
|
List stored files except given filter. If filter is None, it won't be
used. ``content_type`` must be ``'db'`` for database backups or
``'media'`` for media backups.
:param encrypted: Filter by encrypted or not
:type encrypted: ``bool`` or ``None``
:param compressed: Filter by compressed or not
:type compressed: ``bool`` or ``None``
:param content_type: Filter by media or database backup, must be
``'db'`` or ``'media'``
:type content_type: ``str`` or ``None``
:param database: Filter by source database's name
:type: ``str`` or ``None``
:param servername: Filter by source server's name
:type: ``str`` or ``None``
:returns: List of files
:rtype: ``list`` of ``str``
|
f5485:c2:m7
|
def get_older_backup(self, encrypted=None, compressed=None,<EOL>content_type=None, database=None, servername=None):
|
files = self.list_backups(encrypted=encrypted, compressed=compressed,<EOL>content_type=content_type, database=database,<EOL>servername=servername)<EOL>if not files:<EOL><INDENT>raise FileNotFound("<STR_LIT>")<EOL><DEDENT>return min(files, key=utils.filename_to_date)<EOL>
|
Return the older backup's file name.
:param encrypted: Filter by encrypted or not
:type encrypted: ``bool`` or ``None``
:param compressed: Filter by compressed or not
:type compressed: ``bool`` or ``None``
:param content_type: Filter by media or database backup, must be
``'db'`` or ``'media'``
:type content_type: ``str`` or ``None``
:param database: Filter by source database's name
:type: ``str`` or ``None``
:param servername: Filter by source server's name
:type: ``str`` or ``None``
:returns: Older file
:rtype: ``str``
:raises: FileNotFound: If no backup file is found
|
f5485:c2:m9
|
def clean_old_backups(self, encrypted=None, compressed=None,<EOL>content_type=None, database=None, servername=None,<EOL>keep_number=None):
|
if keep_number is None:<EOL><INDENT>keep_number = settings.CLEANUP_KEEP if content_type == '<STR_LIT>'else settings.CLEANUP_KEEP_MEDIA<EOL><DEDENT>keep_filter = settings.CLEANUP_KEEP_FILTER<EOL>files = self.list_backups(encrypted=encrypted, compressed=compressed,<EOL>content_type=content_type, database=database,<EOL>servername=servername)<EOL>files = sorted(files, key=utils.filename_to_date, reverse=True)<EOL>files_to_delete = [fi for i, fi in enumerate(files) if i >= keep_number]<EOL>for filename in files_to_delete:<EOL><INDENT>if keep_filter(filename):<EOL><INDENT>continue<EOL><DEDENT>self.delete_file(filename)<EOL><DEDENT>
|
Delete olders backups and hold the number defined.
:param encrypted: Filter by encrypted or not
:type encrypted: ``bool`` or ``None``
:param compressed: Filter by compressed or not
:type compressed: ``bool`` or ``None``
:param content_type: Filter by media or database backup, must be
``'db'`` or ``'media'``
:type content_type: ``str`` or ``None``
:param database: Filter by source database's name
:type: ``str`` or ``None``
:param servername: Filter by source server's name
:type: ``str`` or ``None``
:param keep_number: Number of files to keep, other will be deleted
:type keep_number: ``int`` or ``None``
|
f5485:c2:m10
|
def read_local_file(self, path):
|
return open(path, '<STR_LIT:rb>')<EOL>
|
Open file in read mode on local filesystem.
|
f5491:c0:m6
|
def write_local_file(self, outputfile, path):
|
self.logger.info("<STR_LIT>", path)<EOL>outputfile.seek(<NUM_LIT:0>)<EOL>with open(path, '<STR_LIT:wb>') as fd:<EOL><INDENT>copyfileobj(outputfile, fd)<EOL><DEDENT>
|
Write file to the desired path.
|
f5491:c0:m7
|
def _cleanup_old_backups(self, database=None, servername=None):
|
self.storage.clean_old_backups(encrypted=self.encrypt,<EOL>compressed=self.compress,<EOL>content_type=self.content_type,<EOL>database=database,<EOL>servername=servername)<EOL>
|
Cleanup old backups, keeping the number of backups specified by
DBBACKUP_CLEANUP_KEEP and any backups that occur on first of the month.
|
f5491:c0:m9
|
def _explore_storage(self):
|
path = '<STR_LIT>'<EOL>dirs = [path]<EOL>while dirs:<EOL><INDENT>path = dirs.pop()<EOL>subdirs, files = self.media_storage.listdir(path)<EOL>for media_filename in files:<EOL><INDENT>yield os.path.join(path, media_filename)<EOL><DEDENT>dirs.extend([os.path.join(path, subdir) for subdir in subdirs])<EOL><DEDENT>
|
Generator of all files contained in media storage.
|
f5493:c0:m1
|
def _create_tar(self, name):
|
fileobj = utils.create_spooled_temporary_file()<EOL>mode = '<STR_LIT>' if self.compress else '<STR_LIT:w>'<EOL>tar_file = tarfile.open(name=name, fileobj=fileobj, mode=mode)<EOL>for media_filename in self._explore_storage():<EOL><INDENT>tarinfo = tarfile.TarInfo(media_filename)<EOL>media_file = self.media_storage.open(media_filename)<EOL>tarinfo.size = len(media_file)<EOL>tar_file.addfile(tarinfo, media_file)<EOL><DEDENT>tar_file.close()<EOL>return fileobj<EOL>
|
Create TAR file.
|
f5493:c0:m2
|
def backup_mediafiles(self):
|
<EOL>extension = "<STR_LIT>" % ('<STR_LIT>' if self.compress else '<STR_LIT>')<EOL>filename = utils.filename_generate(extension,<EOL>servername=self.servername,<EOL>content_type=self.content_type)<EOL>tarball = self._create_tar(filename)<EOL>if self.encrypt:<EOL><INDENT>encrypted_file = utils.encrypt_file(tarball, filename)<EOL>tarball, filename = encrypted_file<EOL><DEDENT>self.logger.debug("<STR_LIT>", utils.handle_size(tarball))<EOL>tarball.seek(<NUM_LIT:0>)<EOL>if self.path is None:<EOL><INDENT>self.write_to_storage(tarball, filename)<EOL><DEDENT>else:<EOL><INDENT>self.write_local_file(tarball, self.path)<EOL><DEDENT>
|
Create backup file and write it to storage.
|
f5493:c0:m3
|
def handle(self, *args, **options):
|
self.verbosity = int(options.get('<STR_LIT>'))<EOL>self.quiet = options.get('<STR_LIT>')<EOL>self._set_logger_level()<EOL>try:<EOL><INDENT>connection.close()<EOL>self.filename = options.get('<STR_LIT>')<EOL>self.path = options.get('<STR_LIT>')<EOL>self.servername = options.get('<STR_LIT>')<EOL>self.decrypt = options.get('<STR_LIT>')<EOL>self.uncompress = options.get('<STR_LIT>')<EOL>self.passphrase = options.get('<STR_LIT>')<EOL>self.interactive = options.get('<STR_LIT>')<EOL>self.database_name, self.database = self._get_database(options)<EOL>self.storage = get_storage()<EOL>self._restore_backup()<EOL><DEDENT>except StorageError as err:<EOL><INDENT>raise CommandError(err)<EOL><DEDENT>
|
Django command handler.
|
f5494:c0:m0
|
def _get_database(self, options):
|
database_name = options.get('<STR_LIT>')<EOL>if not database_name:<EOL><INDENT>if len(settings.DATABASES) > <NUM_LIT:1>:<EOL><INDENT>errmsg = "<STR_LIT>""<STR_LIT>"<EOL>raise CommandError(errmsg)<EOL><DEDENT>database_name = list(settings.DATABASES.keys())[<NUM_LIT:0>]<EOL><DEDENT>if database_name not in settings.DATABASES:<EOL><INDENT>raise CommandError("<STR_LIT>" % database_name)<EOL><DEDENT>return database_name, settings.DATABASES[database_name]<EOL>
|
Get the database to restore.
|
f5494:c0:m1
|
def _restore_backup(self):
|
input_filename, input_file = self._get_backup_file(database=self.database_name,<EOL>servername=self.servername)<EOL>self.logger.info("<STR_LIT>",<EOL>self.database_name, self.servername)<EOL>self.logger.info("<STR_LIT>" % input_filename)<EOL>if self.decrypt:<EOL><INDENT>unencrypted_file, input_filename = utils.unencrypt_file(input_file, input_filename,<EOL>self.passphrase)<EOL>input_file.close()<EOL>input_file = unencrypted_file<EOL><DEDENT>if self.uncompress:<EOL><INDENT>uncompressed_file, input_filename = utils.uncompress_file(input_file, input_filename)<EOL>input_file.close()<EOL>input_file = uncompressed_file<EOL><DEDENT>self.logger.info("<STR_LIT>", utils.handle_size(input_file))<EOL>if self.interactive:<EOL><INDENT>self._ask_confirmation()<EOL><DEDENT>input_file.seek(<NUM_LIT:0>)<EOL>self.connector = get_connector(self.database_name)<EOL>self.connector.restore_dump(input_file)<EOL>
|
Restore the specified database.
|
f5494:c0:m2
|
def _save_new_backup(self, database):
|
self.logger.info("<STR_LIT>", database['<STR_LIT>'])<EOL>filename = self.connector.generate_filename(self.servername)<EOL>outputfile = self.connector.create_dump()<EOL>if self.compress:<EOL><INDENT>compressed_file, filename = utils.compress_file(outputfile, filename)<EOL>outputfile = compressed_file<EOL><DEDENT>if self.encrypt:<EOL><INDENT>encrypted_file, filename = utils.encrypt_file(outputfile, filename)<EOL>outputfile = encrypted_file<EOL><DEDENT>filename = self.filename if self.filename else filename<EOL>self.logger.debug("<STR_LIT>", utils.handle_size(outputfile))<EOL>outputfile.seek(<NUM_LIT:0>)<EOL>if self.path is None:<EOL><INDENT>self.write_to_storage(outputfile, filename)<EOL><DEDENT>else:<EOL><INDENT>self.write_local_file(outputfile, self.path)<EOL><DEDENT>
|
Save a new backup file.
|
f5495:c0:m1
|
def handle(self, *args, **options):
|
self.verbosity = int(options.get('<STR_LIT>'))<EOL>self.quiet = options.get('<STR_LIT>')<EOL>self._set_logger_level()<EOL>self.servername = options.get('<STR_LIT>')<EOL>self.decrypt = options.get('<STR_LIT>')<EOL>self.uncompress = options.get('<STR_LIT>')<EOL>self.filename = options.get('<STR_LIT>')<EOL>self.path = options.get('<STR_LIT>')<EOL>self.replace = options.get('<STR_LIT:replace>')<EOL>self.passphrase = options.get('<STR_LIT>')<EOL>self.interactive = options.get('<STR_LIT>')<EOL>self.storage = get_storage()<EOL>self.media_storage = get_storage_class()()<EOL>self._restore_backup()<EOL>
|
Django command handler.
|
f5496:c0:m0
|
def bytes_to_str(byteVal, decimals=<NUM_LIT:1>):
|
for unit, byte in BYTES:<EOL><INDENT>if (byteVal >= byte):<EOL><INDENT>if decimals == <NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT>' % (int(round(byteVal / byte, <NUM_LIT:0>)), unit)<EOL><DEDENT>return '<STR_LIT>' % (round(byteVal / byte, decimals), unit)<EOL><DEDENT><DEDENT>return '<STR_LIT>' % byteVal<EOL>
|
Convert bytes to a human readable string.
:param byteVal: Value to convert in bytes
:type byteVal: int or float
:param decimal: Number of decimal to display
:type decimal: int
:returns: Number of byte with the best unit of measure
:rtype: str
|
f5497:m0
|
def handle_size(filehandle):
|
filehandle.seek(<NUM_LIT:0>, <NUM_LIT:2>)<EOL>return bytes_to_str(filehandle.tell())<EOL>
|
Get file's size to a human readable string.
:param filehandle: File to handle
:type filehandle: file
:returns: File's size with the best unit of measure
:rtype: str
|
f5497:m1
|
def mail_admins(subject, message, fail_silently=False, connection=None,<EOL>html_message=None):
|
if not settings.ADMINS:<EOL><INDENT>return<EOL><DEDENT>mail = EmailMultiAlternatives('<STR_LIT>' % (settings.EMAIL_SUBJECT_PREFIX, subject),<EOL>message, settings.SERVER_EMAIL, [a[<NUM_LIT:1>] for a in settings.ADMINS],<EOL>connection=connection)<EOL>if html_message:<EOL><INDENT>mail.attach_alternative(html_message, '<STR_LIT>')<EOL><DEDENT>mail.send(fail_silently=fail_silently)<EOL>
|
Sends a message to the admins, as defined by the DBBACKUP_ADMINS setting.
|
f5497:m2
|
def email_uncaught_exception(func):
|
@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>func(*args, **kwargs)<EOL><DEDENT>except:<EOL><INDENT>logger = logging.getLogger('<STR_LIT>')<EOL>exc_type, exc_value, tb = sys.exc_info()<EOL>tb_str = '<STR_LIT>'.join(traceback.format_tb(tb))<EOL>msg = '<STR_LIT>' % (exc_type.__name__, exc_value, tb_str)<EOL>logger.error(msg)<EOL>raise<EOL><DEDENT>finally:<EOL><INDENT>connection.close()<EOL><DEDENT><DEDENT>return wrapper<EOL>
|
Function decorator for send email with uncaught exceptions to admins.
Email is sent to ``settings.DBBACKUP_FAILURE_RECIPIENTS``
(``settings.ADMINS`` if not defined). The message contains a traceback
of error.
|
f5497:m3
|
def create_spooled_temporary_file(filepath=None, fileobj=None):
|
spooled_file = tempfile.SpooledTemporaryFile(<EOL>max_size=settings.TMP_FILE_MAX_SIZE,<EOL>dir=settings.TMP_DIR)<EOL>if filepath:<EOL><INDENT>fileobj = open(filepath, '<STR_LIT>')<EOL><DEDENT>if fileobj is not None:<EOL><INDENT>fileobj.seek(<NUM_LIT:0>)<EOL>copyfileobj(fileobj, spooled_file, settings.TMP_FILE_READ_SIZE)<EOL><DEDENT>return spooled_file<EOL>
|
Create a spooled temporary file. if ``filepath`` or ``fileobj`` is
defined its content will be copied into temporary file.
:param filepath: Path of input file
:type filepath: str
:param fileobj: Input file object
:type fileobj: file
:returns: Spooled temporary file
:rtype: :class:`tempfile.SpooledTemporaryFile`
|
f5497:m4
|
def encrypt_file(inputfile, filename):
|
import gnupg<EOL>tempdir = tempfile.mkdtemp(dir=settings.TMP_DIR)<EOL>try:<EOL><INDENT>filename = '<STR_LIT>' % filename<EOL>filepath = os.path.join(tempdir, filename)<EOL>try:<EOL><INDENT>inputfile.seek(<NUM_LIT:0>)<EOL>always_trust = settings.GPG_ALWAYS_TRUST<EOL>g = gnupg.GPG()<EOL>result = g.encrypt_file(inputfile, output=filepath,<EOL>recipients=settings.GPG_RECIPIENT,<EOL>always_trust=always_trust)<EOL>inputfile.close()<EOL>if not result:<EOL><INDENT>msg = '<STR_LIT>' % result.status<EOL>raise EncryptionError(msg)<EOL><DEDENT>return create_spooled_temporary_file(filepath), filename<EOL><DEDENT>finally:<EOL><INDENT>if os.path.exists(filepath):<EOL><INDENT>os.remove(filepath)<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>os.rmdir(tempdir)<EOL><DEDENT>
|
Encrypt input file using GPG and remove .gpg extension to its name.
:param inputfile: File to encrypt
:type inputfile: ``file`` like object
:param filename: File's name
:type filename: ``str``
:returns: Tuple with file and new file's name
:rtype: :class:`tempfile.SpooledTemporaryFile`, ``str``
|
f5497:m5
|
def unencrypt_file(inputfile, filename, passphrase=None):
|
import gnupg<EOL>def get_passphrase(passphrase=passphrase):<EOL><INDENT>return passphrase or getpass('<STR_LIT>') or None<EOL><DEDENT>temp_dir = tempfile.mkdtemp(dir=settings.TMP_DIR)<EOL>try:<EOL><INDENT>new_basename = os.path.basename(filename).replace('<STR_LIT>', '<STR_LIT>')<EOL>temp_filename = os.path.join(temp_dir, new_basename)<EOL>try:<EOL><INDENT>inputfile.seek(<NUM_LIT:0>)<EOL>g = gnupg.GPG()<EOL>result = g.decrypt_file(file=inputfile, passphrase=get_passphrase(),<EOL>output=temp_filename)<EOL>if not result:<EOL><INDENT>raise DecryptionError('<STR_LIT>' % result.status)<EOL><DEDENT>outputfile = create_spooled_temporary_file(temp_filename)<EOL><DEDENT>finally:<EOL><INDENT>if os.path.exists(temp_filename):<EOL><INDENT>os.remove(temp_filename)<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>os.rmdir(temp_dir)<EOL><DEDENT>return outputfile, new_basename<EOL>
|
Unencrypt input file using GPG and remove .gpg extension to its name.
:param inputfile: File to encrypt
:type inputfile: ``file`` like object
:param filename: File's name
:type filename: ``str``
:param passphrase: Passphrase of GPG key, if equivalent to False, it will
be asked to user. If user answer an empty pass, no
passphrase will be used.
:type passphrase: ``str`` or ``None``
:returns: Tuple with file and new file's name
:rtype: :class:`tempfile.SpooledTemporaryFile`, ``str``
|
f5497:m6
|
def compress_file(inputfile, filename):
|
outputfile = create_spooled_temporary_file()<EOL>new_filename = filename + '<STR_LIT>'<EOL>zipfile = gzip.GzipFile(filename=filename, fileobj=outputfile, mode="<STR_LIT:wb>")<EOL>try:<EOL><INDENT>inputfile.seek(<NUM_LIT:0>)<EOL>copyfileobj(inputfile, zipfile, settings.TMP_FILE_READ_SIZE)<EOL><DEDENT>finally:<EOL><INDENT>zipfile.close()<EOL><DEDENT>return outputfile, new_filename<EOL>
|
Compress input file using gzip and change its name.
:param inputfile: File to compress
:type inputfile: ``file`` like object
:param filename: File's name
:type filename: ``str``
:returns: Tuple with compressed file and new file's name
:rtype: :class:`tempfile.SpooledTemporaryFile`, ``str``
|
f5497:m7
|
def uncompress_file(inputfile, filename):
|
zipfile = gzip.GzipFile(fileobj=inputfile, mode="<STR_LIT:rb>")<EOL>try:<EOL><INDENT>outputfile = create_spooled_temporary_file(fileobj=zipfile)<EOL><DEDENT>finally:<EOL><INDENT>zipfile.close()<EOL><DEDENT>new_basename = os.path.basename(filename).replace('<STR_LIT>', '<STR_LIT>')<EOL>return outputfile, new_basename<EOL>
|
Uncompress this file using gzip and change its name.
:param inputfile: File to compress
:type inputfile: ``file`` like object
:param filename: File's name
:type filename: ``str``
:returns: Tuple with file and new file's name
:rtype: :class:`tempfile.SpooledTemporaryFile`, ``str``
|
f5497:m8
|
def timestamp(value):
|
value = value if timezone.is_naive(value) else timezone.localtime(value)<EOL>return value.strftime(settings.DATE_FORMAT)<EOL>
|
Return the timestamp of a datetime.datetime object.
:param value: a datetime object
:type value: datetime.datetime
:return: the timestamp
:rtype: str
|
f5497:m9
|
def datefmt_to_regex(datefmt):
|
new_string = datefmt<EOL>for pat, reg in PATTERN_MATCHNG:<EOL><INDENT>new_string = new_string.replace(pat, reg)<EOL><DEDENT>return re.compile(r'<STR_LIT>' % new_string)<EOL>
|
Convert a strftime format string to a regex.
:param datefmt: strftime format string
:type datefmt: ``str``
:returns: Equivalent regex
:rtype: ``re.compite``
|
f5497:m11
|
def filename_to_date(filename, datefmt=None):
|
datefmt = datefmt or settings.DATE_FORMAT<EOL>datestring = filename_to_datestring(filename, datefmt)<EOL>if datestring is not None:<EOL><INDENT>return datetime.strptime(datestring, datefmt)<EOL><DEDENT>
|
Return a datetime from a file name.
:param datefmt: strftime format string, ``settings.DATE_FORMAT`` is used
if is ``None``
:type datefmt: ``str`` or ``NoneType``
:returns: Date guessed or nothing if no date found
:rtype: ``datetime.datetime`` or ``NoneType``
|
f5497:m13
|
def filename_generate(extension, database_name='<STR_LIT>', servername=None, content_type='<STR_LIT>', wildcard=None):
|
if content_type == '<STR_LIT>':<EOL><INDENT>if '<STR_LIT:/>' in database_name:<EOL><INDENT>database_name = os.path.basename(database_name)<EOL><DEDENT>if '<STR_LIT:.>' in database_name:<EOL><INDENT>database_name = database_name.split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL><DEDENT>template = settings.FILENAME_TEMPLATE<EOL><DEDENT>elif content_type == '<STR_LIT>':<EOL><INDENT>template = settings.MEDIA_FILENAME_TEMPLATE<EOL><DEDENT>else:<EOL><INDENT>template = settings.FILENAME_TEMPLATE<EOL><DEDENT>params = {<EOL>'<STR_LIT>': servername or settings.HOSTNAME,<EOL>'<STR_LIT>': wildcard or datetime.now().strftime(settings.DATE_FORMAT),<EOL>'<STR_LIT>': database_name,<EOL>'<STR_LIT>': extension,<EOL>'<STR_LIT>': content_type<EOL>}<EOL>if callable(template):<EOL><INDENT>filename = template(**params)<EOL><DEDENT>else:<EOL><INDENT>filename = template.format(**params)<EOL>filename = REG_FILENAME_CLEAN.sub('<STR_LIT:->', filename)<EOL>filename = filename[<NUM_LIT:1>:] if filename.startswith('<STR_LIT:->') else filename<EOL><DEDENT>return filename<EOL>
|
Create a new backup filename.
:param extension: Extension of backup file
:type extension: ``str``
:param database_name: If it is database backup specify its name
:type database_name: ``str``
:param servername: Specify server name or by default ``settings.DBBACKUP_HOSTNAME``
:type servername: ``str``
:param content_type: Content type to backup, ``'media'`` or ``'db'``
:type content_type: ``str``
:param wildcard: Replace datetime with this wilecard regex
:type content_type: ``str``
:returns: Computed file name
:rtype: ``str`
|
f5497:m14
|
def _to_base36(number):
|
if number < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>chars = "<STR_LIT>"<EOL>while number != <NUM_LIT:0>:<EOL><INDENT>number, i = divmod(number, <NUM_LIT>) <EOL>chars = _alphabet[i] + chars<EOL><DEDENT>return chars or "<STR_LIT:0>"<EOL>
|
Convert a positive integer to a base36 string.
Taken from Stack Overflow and modified.
|
f5507:m0
|
def _pad(string, size):
|
strlen = len(string)<EOL>if strlen == size:<EOL><INDENT>return string<EOL><DEDENT>if strlen < size:<EOL><INDENT>return _padding[<NUM_LIT:0>:size-strlen] + string<EOL><DEDENT>return string[-size:]<EOL>
|
'Pad' a string with leading zeroes to fit the given size, truncating
if necessary.
|
f5507:m1
|
def _random_block():
|
<EOL>random_number = random.randint(<NUM_LIT:0>, DISCRETE_VALUES)<EOL>random_string = _to_base36(random_number)<EOL>return _pad(random_string, BLOCK_SIZE)<EOL>
|
Generate a random string of `BLOCK_SIZE` length.
|
f5507:m2
|
def get_process_fingerprint():
|
pid = os.getpid()<EOL>hostname = socket.gethostname()<EOL>padded_pid = _pad(_to_base36(pid), <NUM_LIT:2>)<EOL>hostname_hash = sum([ord(x) for x in hostname]) + len(hostname) + <NUM_LIT><EOL>padded_hostname = _pad(_to_base36(hostname_hash), <NUM_LIT:2>)<EOL>return padded_pid + padded_hostname<EOL>
|
Extract a unique fingerprint for the current process, using a
combination of the process PID and the system's hostname.
|
f5507:m3
|
@property<EOL><INDENT>def counter(self):<DEDENT>
|
self._counter += <NUM_LIT:1><EOL>if self._counter >= DISCRETE_VALUES:<EOL><INDENT>self._counter = <NUM_LIT:0><EOL><DEDENT>return self._counter<EOL>
|
Rolling counter that ensures same-machine and same-time
cuids don't collide.
|
f5507:c0:m1
|
def cuid(self):
|
<EOL>identifier = "<STR_LIT:c>"<EOL>millis = int(time.time() * <NUM_LIT:1000>)<EOL>identifier += _to_base36(millis)<EOL>count = _pad(_to_base36(self.counter), BLOCK_SIZE)<EOL>identifier += count<EOL>identifier += self.fingerprint<EOL>identifier += _random_block()<EOL>identifier += _random_block()<EOL>return identifier<EOL>
|
Generate a full-length cuid as a string.
|
f5507:c0:m2
|
def slug(self):
|
identifier = "<STR_LIT>"<EOL>millis = int(time.time() * <NUM_LIT:1000>)<EOL>millis_string = _to_base36(millis)<EOL>identifier += millis_string[-<NUM_LIT:2>:]<EOL>count = _pad(_to_base36(self.counter), <NUM_LIT:1>)<EOL>identifier += count<EOL>identifier += self.fingerprint[<NUM_LIT:0>]<EOL>identifier += self.fingerprint[-<NUM_LIT:1>]<EOL>random_data = _random_block()<EOL>identifier += random_data[-<NUM_LIT:2>:]<EOL>return identifier<EOL>
|
Generate a short (7-character) cuid as a bytestring.
While this is a convenient shorthand, this is much less likely
to be unique and should not be relied on. Prefer full-size
cuids where possible.
|
f5507:c0:m3
|
def unicode2Date(value, format=None):
|
<EOL>if value == None:<EOL><INDENT>return None<EOL><DEDENT>if format != None:<EOL><INDENT>try:<EOL><INDENT>if format.endswith("<STR_LIT>") and "<STR_LIT:.>" not in value:<EOL><INDENT>value += "<STR_LIT>"<EOL><DEDENT>return _unix2Date(datetime2unix(datetime.strptime(value, format)))<EOL><DEDENT>except Exception as e:<EOL><INDENT>from mo_logs import Log<EOL>Log.error("<STR_LIT>", value=value, format=format, cause=e)<EOL><DEDENT><DEDENT>value = value.strip()<EOL>if value.lower() == "<STR_LIT>":<EOL><INDENT>return _unix2Date(datetime2unix(_utcnow()))<EOL><DEDENT>elif value.lower() == "<STR_LIT>":<EOL><INDENT>return _unix2Date(math.floor(datetime2unix(_utcnow()) / <NUM_LIT>) * <NUM_LIT>)<EOL><DEDENT>elif value.lower() in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>return _unix2Date(math.floor(datetime2unix(_utcnow()) / <NUM_LIT>) * <NUM_LIT> + <NUM_LIT>)<EOL><DEDENT>if any(value.lower().find(n) >= <NUM_LIT:0> for n in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"] + list(MILLI_VALUES.keys())):<EOL><INDENT>return parse_time_expression(value)<EOL><DEDENT>try: <EOL><INDENT>local_value = parse_date(value) <EOL>return _unix2Date(datetime2unix((local_value - local_value.utcoffset()).replace(tzinfo=None)))<EOL><DEDENT>except Exception as e:<EOL><INDENT>e = Except.wrap(e) <EOL>pass<EOL><DEDENT>formats = [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>]<EOL>for f in formats:<EOL><INDENT>try:<EOL><INDENT>return _unix2Date(datetime2unix(datetime.strptime(value, f)))<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>deformats = [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>]<EOL>value = deformat(value)<EOL>for f in deformats:<EOL><INDENT>try:<EOL><INDENT>return unicode2Date(value, format=f)<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>from mo_logs import Log<EOL>Log.error("<STR_LIT>", value=value)<EOL><DEDENT>
|
CONVERT UNICODE STRING TO UNIX TIMESTAMP VALUE
|
f5512:m4
|
def deformat(value):
|
output = []<EOL>for c in value:<EOL><INDENT>if c in delchars:<EOL><INDENT>continue<EOL><DEDENT>output.append(c)<EOL><DEDENT>return "<STR_LIT>".join(output)<EOL>
|
REMOVE NON-ALPHANUMERIC CHARACTERS
|
f5512:m9
|
def _mod(value, mod=<NUM_LIT:1>):
|
if value == None:<EOL><INDENT>return None<EOL><DEDENT>elif mod <= <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>elif value < <NUM_LIT:0>:<EOL><INDENT>return (value % mod + mod) % mod<EOL><DEDENT>else:<EOL><INDENT>return value % mod<EOL><DEDENT>
|
RETURN NON-NEGATIVE MODULO
RETURN None WHEN GIVEN INVALID ARGUMENTS
|
f5512:m10
|
@property<EOL><INDENT>def hour(self):<DEDENT>
|
return int(int(self.unix)/<NUM_LIT>/<NUM_LIT> % <NUM_LIT>)<EOL>
|
:return: HOUR (int) IN THE GMT DAY
|
f5512:c0:m9
|
@property<EOL><INDENT>def dow(self):<DEDENT>
|
return int(self.unix / <NUM_LIT> / <NUM_LIT> / <NUM_LIT> / <NUM_LIT:7> + <NUM_LIT:5>) % <NUM_LIT:7><EOL>
|
:return: DAY-OF-WEEK MONDAY=0, SUNDAY=6
|
f5512:c0:m10
|
@staticmethod<EOL><INDENT>def eod():<DEDENT>
|
return _unix2Date(Date.today().unix + <NUM_LIT>)<EOL>
|
RETURN END-OF-TODAY (WHICH IS SAME AS BEGINNING OF TOMORROW)
|
f5512:c0:m14
|
def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
|
first = datetime.datetime(year, month, <NUM_LIT:1>, hour, minute)<EOL>weekdayone = first.replace(day=((dayofweek-first.isoweekday())%<NUM_LIT:7>+<NUM_LIT:1>))<EOL>for n in range(whichweek):<EOL><INDENT>dt = weekdayone+(whichweek-n)*ONEWEEK<EOL>if dt.month == month:<EOL><INDENT>return dt<EOL><DEDENT><DEDENT>
|
dayofweek == 0 means Sunday, whichweek 5 means last instance
|
f5514:m1
|
def valuestodict(key):
|
dict = {}<EOL>size = winreg.QueryInfoKey(key)[<NUM_LIT:1>]<EOL>for i in range(size):<EOL><INDENT>data = winreg.EnumValue(key, i)<EOL>dict[data[<NUM_LIT:0>]] = data[<NUM_LIT:1>]<EOL><DEDENT>return dict<EOL>
|
Convert a registry key's values to a dictionary.
|
f5514:m2
|
def list():
|
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)<EOL>tzkey = winreg.OpenKey(handle, TZKEYNAME)<EOL>result = [winreg.EnumKey(tzkey, i)<EOL>for i in range(winreg.QueryInfoKey(tzkey)[<NUM_LIT:0>])]<EOL>tzkey.Close()<EOL>handle.Close()<EOL>return result<EOL>
|
Return a list of all time zones known to the system.
|
f5514:c0:m3
|
def _parsems(value):
|
if "<STR_LIT:.>" not in value:<EOL><INDENT>return int(value), <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>i, f = value.split("<STR_LIT:.>")<EOL>return int(i), int(f.ljust(<NUM_LIT:6>, "<STR_LIT:0>")[:<NUM_LIT:6>])<EOL><DEDENT>
|
Parse a I[.F] seconds value into (seconds, microseconds).
|
f5515:m2
|
def tzname_in_python2(myfunc):
|
def inner_func(*args, **kwargs):<EOL><INDENT>if PY3:<EOL><INDENT>return myfunc(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>return myfunc(*args, **kwargs).encode()<EOL><DEDENT><DEDENT>return inner_func<EOL>
|
Change unicode output into bytestrings in Python 2
tzname() API changed in Python 3. It used to return bytes, but was changed
to unicode strings
|
f5518:m0
|
def easter(year, method=EASTER_WESTERN):
|
if not (<NUM_LIT:1> <= method <= <NUM_LIT:3>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>y = year<EOL>g = y % <NUM_LIT><EOL>e = <NUM_LIT:0><EOL>if method < <NUM_LIT:3>:<EOL><INDENT>i = (<NUM_LIT>*g+<NUM_LIT:15>)%<NUM_LIT:30><EOL>j = (y+y//<NUM_LIT:4>+i)%<NUM_LIT:7><EOL>if method == <NUM_LIT:2>:<EOL><INDENT>e = <NUM_LIT:10><EOL>if y > <NUM_LIT>:<EOL><INDENT>e = e+y//<NUM_LIT:100>-<NUM_LIT:16>-(y//<NUM_LIT:100>-<NUM_LIT:16>)//<NUM_LIT:4><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>c = y//<NUM_LIT:100><EOL>h = (c-c//<NUM_LIT:4>-(<NUM_LIT:8>*c+<NUM_LIT>)//<NUM_LIT>+<NUM_LIT>*g+<NUM_LIT:15>)%<NUM_LIT:30><EOL>i = h-(h//<NUM_LIT>)*(<NUM_LIT:1>-(h//<NUM_LIT>)*(<NUM_LIT>//(h+<NUM_LIT:1>))*((<NUM_LIT>-g)//<NUM_LIT:11>))<EOL>j = (y+y//<NUM_LIT:4>+i+<NUM_LIT:2>-c+c//<NUM_LIT:4>)%<NUM_LIT:7><EOL><DEDENT>p = i-j+e<EOL>d = <NUM_LIT:1>+(p+<NUM_LIT>+(p+<NUM_LIT:6>)//<NUM_LIT>)%<NUM_LIT><EOL>m = <NUM_LIT:3>+(p+<NUM_LIT>)//<NUM_LIT:30><EOL>return datetime.date(int(y), int(m), int(d))<EOL>
|
This method was ported from the work done by GM Arts,
on top of the algorithm by Claus Tondering, which was
based in part on the algorithm of Ouding (1940), as
quoted in "Explanatory Supplement to the Astronomical
Almanac", P. Kenneth Seidelmann, editor.
This algorithm implements three different easter
calculation methods:
1 - Original calculation in Julian calendar, valid in
dates after 326 AD
2 - Original method, with date converted to Gregorian
calendar, valid in years 1583 to 4099
3 - Revised method, in Gregorian calendar, valid in
years 1583 to 4099 as well
These methods are represented by the constants:
EASTER_JULIAN = 1
EASTER_ORTHODOX = 2
EASTER_WESTERN = 3
The default method is method 3.
More about the algorithm may be found at:
http://users.chariot.net.au/~gmarts/eastalg.htm
and
http://www.tondering.dk/claus/calendar.html
|
f5520:m0
|
def _string2Duration(text):
|
if text == "<STR_LIT>" or text == "<STR_LIT>":<EOL><INDENT>return ZERO<EOL><DEDENT>amount, interval = re.match(r"<STR_LIT>", text).groups()<EOL>amount = int(amount) if amount else <NUM_LIT:1><EOL>if MILLI_VALUES[interval] == None:<EOL><INDENT>from mo_logs import Log<EOL>Log.error(<EOL>"<STR_LIT>",<EOL>interval=interval,<EOL>text=text<EOL>)<EOL><DEDENT>output = Duration(<NUM_LIT:0>)<EOL>if MONTH_VALUES[interval] == <NUM_LIT:0>:<EOL><INDENT>output.milli = amount * MILLI_VALUES[interval]<EOL><DEDENT>else:<EOL><INDENT>output.milli = amount * MONTH_VALUES[interval] * MILLI_VALUES.month<EOL>output.month = amount * MONTH_VALUES[interval]<EOL><DEDENT>return output<EOL>
|
CONVERT SIMPLE <float><type> TO A DURATION OBJECT
|
f5522:m1
|
def suite():
|
loader = unittest.TestLoader()<EOL>res = unittest.TestSuite()<EOL>for t in TESTS:<EOL><INDENT>mod = importlib.import_module(t)<EOL>res.addTest(loader.loadTestsFromModule(mod))<EOL><DEDENT>return res<EOL>
|
Returns a test suite.
|
f5525:m0
|
def main():
|
try:<EOL><INDENT>res = unittest.TextTestRunner(verbosity=<NUM_LIT:2>).run(suite())<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print("<STR_LIT>")<EOL>return -<NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0> if res.wasSuccessful() else <NUM_LIT:1><EOL><DEDENT>
|
The main function.
Returns:
Status code.
|
f5525:m1
|
def setUp(self):
|
self.graph = bipartite_sum.BipartiteGraph()<EOL>self.reviewers = [<EOL>self.graph.new_reviewer("<STR_LIT>".format(i)) for i in range(<NUM_LIT:2>)]<EOL>self.products = [<EOL>self.graph.new_product("<STR_LIT>".format(i)) for i in range(<NUM_LIT:3>)]<EOL>self.reviews = defaultdict(dict)<EOL>for i, r in enumerate(self.reviewers):<EOL><INDENT>for j in range(i, len(self.products)):<EOL><INDENT>self.reviews[i][j] = self.graph.add_review(<EOL>r, self.products[j], <NUM_LIT:0.1> if i == <NUM_LIT:0> else <NUM_LIT>)<EOL><DEDENT><DEDENT>
|
Set up for tests.
|
f5526:c0:m0
|
def setUp(self):
|
self.graph = bipartite.BipartiteGraph()<EOL>self.reviewers = [<EOL>self.graph.new_reviewer("<STR_LIT>".format(i)) for i in range(<NUM_LIT:2>)]<EOL>self.products = [<EOL>self.graph.new_product("<STR_LIT>".format(i)) for i in range(<NUM_LIT:3>)]<EOL>self.reviews = defaultdict(dict)<EOL>for i, r in enumerate(self.reviewers):<EOL><INDENT>for j in range(i, len(self.products)):<EOL><INDENT>self.reviews[i][j] = self.graph.add_review(<EOL>r, self.products[j], <NUM_LIT:0.1> if i == <NUM_LIT:0> else <NUM_LIT>)<EOL><DEDENT><DEDENT>
|
Set up for tests.
|
f5527:c0:m0
|
def setUp(self):
|
self.graph = bipartite.BipartiteGraph()<EOL>self.reviewers = [<EOL>self.graph.new_reviewer("<STR_LIT>".format(i)) for i in range(<NUM_LIT:2>)]<EOL>self.products = [<EOL>self.graph.new_product("<STR_LIT>".format(i)) for i in range(<NUM_LIT:3>)]<EOL>self.reviews = defaultdict(dict)<EOL>for i, r in enumerate(self.reviewers):<EOL><INDENT>for j in range(i, len(self.products)):<EOL><INDENT>self.reviews[i][j] = self.graph.add_review(<EOL>r, self.products[j], <NUM_LIT:0.1> if i == <NUM_LIT:0> else <NUM_LIT>)<EOL><DEDENT><DEDENT>
|
Set up for tests.
|
f5527:c1:m0
|
def setUp(self):
|
self.graph = bipartite.BipartiteGraph()<EOL>
|
Set up for tests.
|
f5527:c2:m0
|
def setUp(self):
|
self.graph = bipartite.BipartiteGraph()<EOL>self.reviewers = [<EOL>self.graph.new_reviewer("<STR_LIT>".format(i)) for i in range(<NUM_LIT:2>)]<EOL>self.products = [<EOL>self.graph.new_product("<STR_LIT>".format(i)) for i in range(<NUM_LIT:3>)]<EOL>self.reviews = defaultdict(dict)<EOL>for i, r in enumerate(self.reviewers):<EOL><INDENT>for j in range(i, len(self.products)):<EOL><INDENT>self.reviews[i][j] = self.graph.add_review(<EOL>r, self.products[j], <NUM_LIT:0.1> if i == <NUM_LIT:0> else <NUM_LIT>)<EOL><DEDENT><DEDENT>
|
Set up for tests.
|
f5527:c3:m0
|
def setUp(self):
|
self.alpha = <NUM_LIT:2><EOL>self.graph = bipartite.BipartiteGraph(alpha=self.alpha)<EOL>
|
Set up a bipartite graph.
|
f5527:c4:m0
|
def setUp(self):
|
self.graph = one.BipartiteGraph()<EOL>self.reviewers = [<EOL>self.graph.new_reviewer("<STR_LIT>".format(i)) for i in range(<NUM_LIT:2>)]<EOL>self.products = [<EOL>self.graph.new_product("<STR_LIT>".format(i)) for i in range(<NUM_LIT:3>)]<EOL>for i, r in enumerate(self.reviewers):<EOL><INDENT>for j in range(i, len(self.products)):<EOL><INDENT>self.graph.add_review(<EOL>r, self.products[j], <NUM_LIT:0.1> if i == <NUM_LIT:0> else <NUM_LIT>)<EOL><DEDENT><DEDENT>
|
Set up for tests.
|
f5528:c0:m0
|
def setUp(self):
|
self.graph = bipartite.BipartiteGraph()<EOL>
|
Set up a bipartite graph.
|
f5530:c0:m0
|
def setUp(self):
|
self.graph = bipartite.BipartiteGraph()<EOL>self.reviewers = [<EOL>self.graph.new_reviewer("<STR_LIT>".format(i)) for i in range(<NUM_LIT:2>)<EOL>]<EOL>self.products = [<EOL>self.graph.new_product("<STR_LIT>".format(i)) for i in range(<NUM_LIT:3>)<EOL>]<EOL>for i, r in enumerate(self.reviewers):<EOL><INDENT>for j in range(i, len(self.products)):<EOL><INDENT>self.graph.add_review(r, self.products[j], <NUM_LIT>)<EOL><DEDENT><DEDENT>self.credibility = credibility.GraphBasedCredibility(self.graph)<EOL>
|
Set up a sample graph.
|
f5530:c1:m0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.