signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def __init__(self, max_size=<NUM_LIT> * <NUM_LIT>):
|
self.max_size = max_size<EOL>self.queue = Queue()<EOL>self.received_bytes = self.queue.put_nowait<EOL>self.synchronizing = False<EOL>self.residual = b'<STR_LIT>'<EOL>
|
max_size - an anti-DoS measure. If, after processing an incoming message, buffered
data would exceed max_size bytes, that buffered data is dropped entirely and the
framer waits for a newline character to re-synchronize the stream.
Set to zero to not limit the buffer size.
|
f5364:c1:m0
|
def __init__(self,<EOL>jvm_started=False,<EOL>parse_datetime=False,<EOL>minimum_heap_size='<STR_LIT>',<EOL>maximum_heap_size='<STR_LIT>'):
|
self.parse_datetime = parse_datetime<EOL>self._is_loaded = False<EOL>self._lock = threading.Lock()<EOL>if not jvm_started:<EOL><INDENT>self._classpath = self._create_classpath()<EOL>self._start_jvm(minimum_heap_size, maximum_heap_size)<EOL><DEDENT>try:<EOL><INDENT>if threading.activeCount() > <NUM_LIT:1>:<EOL><INDENT>if not jpype.isThreadAttachedToJVM():<EOL><INDENT>jpype.attachThreadToJVM()<EOL><DEDENT><DEDENT>self._lock.acquire()<EOL>self.clojure = jpype.JClass('<STR_LIT>')<EOL>require = self.clojure.var("<STR_LIT>", "<STR_LIT>")<EOL>require.invoke(self.clojure.read("<STR_LIT>"))<EOL><DEDENT>finally:<EOL><INDENT>self._lock.release()<EOL><DEDENT>
|
Initializes Duckling.
|
f5372:c0:m0
|
def load(self, languages=[]):
|
duckling_load = self.clojure.var("<STR_LIT>", "<STR_LIT>")<EOL>clojure_hashmap = self.clojure.var("<STR_LIT>", "<STR_LIT>")<EOL>clojure_list = self.clojure.var("<STR_LIT>", "<STR_LIT:list>")<EOL>if languages:<EOL><INDENT>iso_languages = [Language.convert_to_iso(lang) for lang in languages]<EOL>duckling_load.invoke(<EOL>clojure_hashmap.invoke(<EOL>self.clojure.read('<STR_LIT>'),<EOL>clojure_list.invoke(*iso_languages)<EOL>)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>duckling_load.invoke()<EOL><DEDENT>self._is_loaded = True<EOL>
|
Loads the Duckling corpus.
Languages can be specified, defaults to all.
Args:
languages: Optional parameter to specify languages,
e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"])
|
f5372:c0:m3
|
def parse(self, input_str, language=Language.ENGLISH, dim_filter=None, reference_time='<STR_LIT>'):
|
if self._is_loaded is False:<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>')<EOL><DEDENT>if threading.activeCount() > <NUM_LIT:1>:<EOL><INDENT>if not jpype.isThreadAttachedToJVM():<EOL><INDENT>jpype.attachThreadToJVM()<EOL><DEDENT><DEDENT>language = Language.convert_to_duckling_language_id(language)<EOL>duckling_parse = self.clojure.var("<STR_LIT>", "<STR_LIT>")<EOL>duckling_time = self.clojure.var("<STR_LIT>", "<STR_LIT:t>")<EOL>clojure_hashmap = self.clojure.var("<STR_LIT>", "<STR_LIT>")<EOL>filter_str = '<STR_LIT>'<EOL>if isinstance(dim_filter, string_types):<EOL><INDENT>filter_str = '<STR_LIT>'.format(filter=dim_filter)<EOL><DEDENT>elif isinstance(dim_filter, list):<EOL><INDENT>filter_str = '<STR_LIT>'.format(filter='<STR_LIT>'.join(dim_filter))<EOL><DEDENT>if reference_time:<EOL><INDENT>duckling_result = duckling_parse.invoke(<EOL>language,<EOL>input_str,<EOL>self.clojure.read(filter_str),<EOL>clojure_hashmap.invoke(<EOL>self.clojure.read('<STR_LIT>'),<EOL>duckling_time.invoke(<EOL>*self._parse_reference_time(reference_time))<EOL>)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>duckling_result = duckling_parse.invoke(<EOL>language, input_str, self.clojure.read(filter_str))<EOL><DEDENT>return self._parse_result(duckling_result)<EOL>
|
Parses datetime information out of string input.
It invokes the Duckling.parse() function in Clojure.
A language can be specified, default is English.
Args:
input_str: The input as string that has to be parsed.
language: Optional parameter to specify language,
e.g. Duckling.ENGLISH or supported ISO 639-1 Code (e.g. "en")
dim_filter: Optional parameter to specify a single filter or
list of filters for dimensions in Duckling.
reference_time: Optional reference time for Duckling.
Returns:
A list of dicts with the result from the Duckling.parse() call.
Raises:
RuntimeError: An error occurres when Duckling model is not loaded
via load().
|
f5372:c0:m4
|
@classmethod<EOL><INDENT>def is_supported(cls, lang):<DEDENT>
|
return lang in cls.SUPPORTED_LANGUAGES<EOL>
|
Check if a language is supported by the current duckling version.
|
f5374:c0:m0
|
@classmethod<EOL><INDENT>def convert_to_duckling_language_id(cls, lang):<DEDENT>
|
if lang is not None and cls.is_supported(lang):<EOL><INDENT>return lang<EOL><DEDENT>elif lang is not None and cls.is_supported(lang + "<STR_LIT>"): <EOL><INDENT>return lang + "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>lang, "<STR_LIT:U+002CU+0020>".join(cls.SUPPORTED_LANGUAGES)))<EOL><DEDENT>
|
Ensure a language identifier has the correct duckling format and is supported.
|
f5374:c0:m1
|
def parse(self, input_str, reference_time='<STR_LIT>'):
|
return self._parse(input_str, reference_time=reference_time)<EOL>
|
Parses input with Duckling for all dims.
Args:
input_str: An input string, e.g. 'You owe me twenty bucks, please
call me today'.
reference_time: Optional reference time for Duckling.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"number",
"end":17,
"start":11,
"value":{
"value":20.0
},
"text":"twenty"
},
{
"dim":"time",
"end":45,
"start":40,
"value":{
"value":"2016-10-10T00:00:00.000-07:00",
"others":[
"2016-10-10T00:00:00.000-07:00"
]
},
"text":"today"
},
{
"dim":"amount-of-money",
"end":23,
"start":11,
"value":{
"unit":null,
"value":20.0
},
"text":"twenty bucks"
},
{
"dim":"distance",
"end":17,
"start":11,
"value":{
"unit":null,
"value":20.0
},
"text":"twenty"
},
{
"dim":"volume",
"end":17,
"start":11,
"value":{
"latent":true,
"unit":null,
"value":20.0
},
"text":"twenty"
},
{
"dim":"temperature",
"end":17,
"start":11,
"value":{
"unit":null,
"value":20.0
},
"text":"twenty"
},
{
"dim":"time",
"end":17,
"start":11,
"value":{
"value":"2020-01-01T00:00:00.000-08:00",
"others":[
"2020-01-01T00:00:00.000-08:00"
]
},
"text":"twenty"
}
]
|
f5375:c0:m10
|
def parse_time(self, input_str, reference_time='<STR_LIT>'):
|
return self._parse(input_str, dim=Dim.TIME,<EOL>reference_time=reference_time)<EOL>
|
Parses input with Duckling for occurences of times.
Args:
input_str: An input string, e.g. 'Let's meet at 11:45am'.
reference_time: Optional reference time for Duckling.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"time",
"end":21,
"start":11,
"value":{
"value":"2016-10-11T11:45:00.000-07:00",
"others":[
"2016-10-11T11:45:00.000-07:00",
"2016-10-12T11:45:00.000-07:00",
"2016-10-13T11:45:00.000-07:00"
]
},
"text":"at 11:45am"
}
]
|
f5375:c0:m11
|
def parse_timezone(self, input_str):
|
return self._parse(input_str, dim=Dim.TIMEZONE)<EOL>
|
Parses input with Duckling for occurences of timezones.
Args:
input_str: An input string, e.g. 'My timezone is pdt'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"timezone",
"end":18,
"start":15,
"value":{
"value":"PDT"
},
"text":"pdt"
}
]
|
f5375:c0:m12
|
def parse_temperature(self, input_str):
|
return self._parse(input_str, dim=Dim.TEMPERATURE)<EOL>
|
Parses input with Duckling for occurences of temperatures.
Args:
input_str: An input string, e.g. 'Let's change the temperature from
thirty two celsius to 65 degrees'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"temperature",
"end":65,
"start":55,
"value":{
"unit":"degree",
"value":65.0
},
"text":"65 degrees"
},
{
"dim":"temperature",
"end":51,
"start":33,
"value":{
"unit":"celsius",
"value":32.0
},
"text":"thirty two celsius"
}
]
|
f5375:c0:m13
|
def parse_number(self, input_str):
|
return self._parse(input_str, dim=Dim.NUMBER)<EOL>
|
Parses input with Duckling for occurences of numbers.
Args:
input_str: An input string, e.g. 'I'm 25 years old'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"number",
"end":6,
"start":4,
"value":{
"value":25.0
},
"text":"25"
}
]
|
f5375:c0:m14
|
def parse_ordinal(self, input_str):
|
return self._parse(input_str, dim=Dim.ORDINAL)<EOL>
|
Parses input with Duckling for occurences of ordinals.
Args:
input_str: An input string, e.g. 'I'm first, you're 2nd'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"ordinal",
"end":9,
"start":4,
"value":{
"value":1
},
"text":"first"
},
{
"dim":"ordinal",
"end":21,
"start":18,
"value":{
"value":2
},
"text":"2nd"
}
]
|
f5375:c0:m15
|
def parse_distance(self, input_str):
|
return self._parse(input_str, dim=Dim.DISTANCE)<EOL>
|
Parses input with Duckling for occurences of distances.
Args:
input_str: An input string, e.g. 'I commute 5 miles everyday'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"distance",
"end":17,
"start":10,
"value":{
"unit":"mile",
"value":5.0
},
"text":"5 miles"
}
]
|
f5375:c0:m16
|
def parse_volume(self, input_str):
|
return self._parse(input_str, dim=Dim.VOLUME)<EOL>
|
Parses input with Duckling for occurences of volumes.
Args:
input_str: An input string, e.g. '1 gallon is 3785ml'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"volume",
"end":18,
"start":12,
"value":{
"latent":false,
"unit":"millilitre",
"value":3785.0
},
"text":"3785ml"
},
{
"dim":"volume",
"end":8,
"start":0,
"value":{
"latent":false,
"unit":"gallon",
"value":1.0
},
"text":"1 gallon"
}
]
|
f5375:c0:m17
|
def parse_money(self, input_str):
|
return self._parse(input_str, dim=Dim.AMOUNTOFMONEY)<EOL>
|
Parses input with Duckling for occurences of moneys.
Args:
input_str: An input string, e.g. 'You owe me 10 dollars'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"amount-of-money",
"end":21,
"start":11,
"value":{
"unit":"$",
"value":10.0
},
"text":"10 dollars"
}
]
|
f5375:c0:m18
|
def parse_duration(self, input_str):
|
return self._parse(input_str, dim=Dim.DURATION)<EOL>
|
Parses input with Duckling for occurences of durations.
Args:
input_str: An input string, e.g. 'I ran for 2 hours today'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"duration",
"end":17,
"start":10,
"value":{
"hour":2,
"value":2.0,
"month":null,
"second":null,
"minute":null,
"year":null,
"day":null,
"unit":"hour"
},
"text":"2 hours"
}
]
|
f5375:c0:m19
|
def parse_email(self, input_str):
|
return self._parse(input_str, dim=Dim.EMAIL)<EOL>
|
Parses input with Duckling for occurences of emails.
Args:
input_str: An input string, e.g. 'Shoot me an email at
contact@frank-blechschmidt.com'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"email",
"end":51,
"start":21,
"value":{
"value":"contact@frank-blechschmidt.com"
},
"text":"contact@frank-blechschmidt.com"
}
]
|
f5375:c0:m20
|
def parse_url(self, input_str):
|
return self._parse(input_str, dim=Dim.URL)<EOL>
|
Parses input with Duckling for occurences of urls.
Args:
input_str: An input string, e.g. 'http://frank-blechschmidt.com is
under construction, but you can check my github
github.com/FraBle'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"url",
"end":98,
"start":81,
"value":{
"value":"github.com/FraBle"
},
"text":"github.com/FraBle"
},
{
"dim":"url",
"end":29,
"start":0,
"value":{
"value":"http://frank-blechschmidt.com"
},
"text":"http://frank-blechschmidt.com"
}
]
|
f5375:c0:m21
|
def parse_phone_number(self, input_str):
|
return self._parse(input_str, dim=Dim.PHONENUMBER)<EOL>
|
Parses input with Duckling for occurences of phone numbers.
Args:
input_str: An input string, e.g. '424-242-4242 is obviously a fake
number'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"phone-number",
"end":13,
"start":0,
"value":{
"value":"424-242-4242 "
},
"text":"424-242-4242 "
}
]
|
f5375:c0:m22
|
def parse_leven_product(self, input_str):
|
return self._parse(input_str, dim=Dim.LEVENPRODUCT)<EOL>
|
Parses input with Duckling for occurences of products.
Args:
input_str: An input string, e.g. '5 cups of sugar'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim": "leven-product",
"end": 15,
"start": 10,
"value":
{
"value": "sugar"
},
"text": "sugar"
}
]
|
f5375:c0:m23
|
def parse_leven_unit(self, input_str):
|
return self._parse(input_str, dim=Dim.LEVENUNIT)<EOL>
|
Parses input with Duckling for occurences of leven units.
Args:
input_str: An input string, e.g. 'two pounds of meat'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim": "leven-unit",
"start": 4,
"end": 10,
"value":
{
"value": "pound"
},
"text": "pounds"
}
]
|
f5375:c0:m24
|
def parse_quantity(self, input_str):
|
return self._parse(input_str, dim=Dim.QUANTITY)<EOL>
|
Parses input with Duckling for occurences of quantities.
Args:
input_str: An input string, e.g. '5 cups of sugar'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim": "quantity",
"text": "5 cups of sugar",
"start": 0,
"end": 15,
"value":
{
"value": 5,
"unit": "cup",
"product": "sugar"
}
}
]
|
f5375:c0:m25
|
def parse_cycle(self, input_str):
|
return self._parse(input_str, dim=Dim.CYCLE)<EOL>
|
Parses input with Duckling for occurences of cycles.
Args:
input_str: An input string, e.g. 'coming week'.
Returns:
A preprocessed list of results (dicts) from Duckling output.
|
f5375:c0:m26
|
def parse_unit(self, input_str):
|
return self._parse(input_str, dim=Dim.UNIT)<EOL>
|
Parses input with Duckling for occurences of units.
Args:
input_str: An input string, e.g. '6 degrees outside'.
Returns:
A preprocessed list of results (dicts) from Duckling output.
|
f5375:c0:m27
|
def parse_unit_of_duration(self, input_str):
|
return self._parse(input_str, dim=Dim.UNITOFDURATION)<EOL>
|
Parses input with Duckling for occurences of units of duration.
Args:
input_str: An input string, e.g. '1 second'.
Returns:
A preprocessed list of results (dicts) from Duckling output.
|
f5375:c0:m28
|
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,<EOL>retry_log_level=logging.INFO,<EOL>retry_log_message="<STR_LIT>"<EOL>"<STR_LIT>",<EOL>max_failures=None, interval=<NUM_LIT:0>,<EOL>max_failure_log_level=logging.ERROR,<EOL>max_failure_log_message="<STR_LIT>"):
|
exc_classes = tuple(exc_classes)<EOL>@wraps(f)<EOL>def deco(*args, **kwargs):<EOL><INDENT>failures = <NUM_LIT:0><EOL>while True:<EOL><INDENT>try:<EOL><INDENT>return f(*args, **kwargs)<EOL><DEDENT>except exc_classes as e:<EOL><INDENT>if logger is not None:<EOL><INDENT>logger.log(retry_log_level,<EOL>retry_log_message.format(f=f.func_name, e=e))<EOL><DEDENT>gevent.sleep(interval)<EOL>failures += <NUM_LIT:1><EOL>if max_failures is not Noneand failures > max_failures:<EOL><INDENT>if logger is not None:<EOL><INDENT>logger.log(max_failure_log_level,<EOL>max_failure_log_message.format(<EOL>f=f.func_name, e=e))<EOL><DEDENT>raise<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return deco<EOL>
|
Decorator to automatically reexecute a function if the connection is
broken for any reason.
|
f5378:m0
|
def _new_connection(self):
|
raise NotImplementedError<EOL>
|
Estabilish a new connection (to be implemented in subclasses).
|
f5378:c0:m1
|
def _keepalive(self, c):
|
raise NotImplementedError()<EOL>
|
Implement actual application-level keepalive (to be
reimplemented in subclasses).
:raise: socket.error if the connection has been closed or is broken.
|
f5378:c0:m2
|
@contextmanager<EOL><INDENT>def get(self):<DEDENT>
|
self.lock.acquire()<EOL>try:<EOL><INDENT>c = self.conn.popleft()<EOL>yield c<EOL><DEDENT>except self.exc_classes:<EOL><INDENT>gevent.spawn_later(<NUM_LIT:1>, self._addOne)<EOL>raise<EOL><DEDENT>except:<EOL><INDENT>self.conn.append(c)<EOL>self.lock.release()<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>self.conn.append(c)<EOL>self.lock.release()<EOL><DEDENT>
|
Get a connection from the pool, to make and receive traffic.
If the connection fails for any reason (socket.error), it is dropped
and a new one is scheduled. Please use @retry as a way to automatically
retry whatever operation you were performing.
|
f5378:c0:m5
|
def timeparse(sval):
|
match = re.match(r'<STR_LIT>' + TIMEFORMAT + r'<STR_LIT>', sval, re.I)<EOL>if not match or not match.group(<NUM_LIT:0>).strip():<EOL><INDENT>return<EOL><DEDENT>mdict = match.groupdict()<EOL>return sum(<EOL>MULTIPLIERS[k] * cast(v) for (k, v) in mdict.items() if v is not None)<EOL>
|
Parse a time expression, returning it as a number of seconds. If
possible, the return value will be an `int`; if this is not
possible, the return will be a `float`. Returns `None` if a time
expression cannot be parsed from the given string.
Arguments:
- `sval`: the string value to parse
>>> timeparse('1m24s')
84
>>> timeparse('1.2 minutes')
72
>>> timeparse('1.2 seconds')
1.2
|
f5380:m1
|
def out_path_of(self, in_path):
|
raise Exception("<STR_LIT>")<EOL>
|
given the input path of a file, return the ouput path
|
f5383:c0:m1
|
def compile_file(self, path):
|
raise Exception("<STR_LIT>")<EOL>
|
given the path of a file, compile it and return the result
|
f5383:c0:m2
|
@capture_exception<EOL><INDENT>@zip_with_output(skip_args=[<NUM_LIT:0>])<EOL>def compile_and_process(self, in_path):<DEDENT>
|
out_path = self.path_mapping[in_path]<EOL>if not self.embed:<EOL><INDENT>pdebug("<STR_LIT>" % (<EOL>self.compiler_name,<EOL>self.name,<EOL>os.path.relpath(in_path),<EOL>os.path.relpath(out_path)),<EOL>groups=["<STR_LIT>"],<EOL>autobreak=True)<EOL><DEDENT>else:<EOL><INDENT>pdebug("<STR_LIT>" % (<EOL>self.compiler_name,<EOL>self.name,<EOL>os.path.relpath(in_path)),<EOL>groups=["<STR_LIT>"],<EOL>autobreak=True)<EOL><DEDENT>compiled_string = self.compile_file(in_path)<EOL>if not self.embed:<EOL><INDENT>if compiled_string != "<STR_LIT>":<EOL><INDENT>with open(out_path, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(compiled_string)<EOL><DEDENT><DEDENT><DEDENT>return compiled_string<EOL>
|
compile a file, save it to the ouput file if the inline flag true
|
f5383:c0:m3
|
def collect_output(self):
|
if self.embed:<EOL><INDENT>if self.concat:<EOL><INDENT>concat_scripts = [self.compiled_scripts[path]<EOL>for path in self.build_order]<EOL>return [self.embed_template_string % '<STR_LIT:\n>'.join(concat_scripts)]<EOL><DEDENT>else:<EOL><INDENT>return [self.embed_template_string %<EOL>self.compiled_scripts[path]<EOL>for path in self.build_order]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return [self.external_template_string %<EOL>os.path.join(<EOL>self.relative_directory,<EOL>os.path.relpath(<EOL>self.out_path_of(path),<EOL>self.output_directory))<EOL>for path in self.build_order<EOL>if self.compiled_scripts[path] != "<STR_LIT>"]<EOL><DEDENT>
|
helper function to gather the results of `compile_and_process` on
all target files
|
f5383:c0:m4
|
def build(self):
|
if not self.embed:<EOL><INDENT>mkdir_recursive(self.output_directory)<EOL><DEDENT>self.build_order = remove_dups(<EOL>reduce(lambda a, b: a + glob.glob(b),<EOL>self.build_targets,<EOL>[]))<EOL>self.build_order_output = [self.out_path_of(t)<EOL>for (t) in self.build_order]<EOL>self.path_mapping = dict(zip(<EOL>self.build_order,<EOL>self.build_order_output))<EOL>self.compiled_scripts = {}<EOL>exceptions, values = partition(<EOL>lambda x: isinstance(x, Exception),<EOL>[self.compile_and_process(target)<EOL>for target in self.build_order])<EOL>self.compiled_scripts.update(dict(values))<EOL>saneExceptions, insaneExceptions = partition(<EOL>lambda x: isinstance(x, TaskExecutionException),<EOL>exceptions)<EOL>if len(insaneExceptions) != <NUM_LIT:0>:<EOL><INDENT>raise insaneExceptions[<NUM_LIT:0>]<EOL><DEDENT>if len(exceptions) != <NUM_LIT:0>:<EOL><INDENT>raise TaskExecutionException(<EOL>"<STR_LIT>" % type(self).__name__,<EOL>"<STR_LIT:\n>".join([<EOL>x.header + "<STR_LIT>" +<EOL>x.message.replace("<STR_LIT:\n>", "<STR_LIT>")<EOL>for x in exceptions]))<EOL><DEDENT>return self.collect_output()<EOL>
|
build the scripts and return a string
|
f5383:c0:m5
|
def update_build(self, updated_files):
|
for f in updated_files:<EOL><INDENT>self.compiled_scripts[f] = self.compile_and_process(f)<EOL><DEDENT>return self.collect_output()<EOL>
|
updates a build based on updated files
TODO implement this pls
|
f5383:c0:m6
|
def print_helptext():
|
pout("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % sys.argv[<NUM_LIT:0>])<EOL>
|
print helptext for command-line interface
|
f5387:m0
|
def main():
|
options = None<EOL>try:<EOL><INDENT>options, args = getopt.gnu_getopt(<EOL>sys.argv[<NUM_LIT:1>:],<EOL>"<STR_LIT>",<EOL>["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL><DEDENT>except getopt.GetoptError as e:<EOL><INDENT>print(e)<EOL>print_helptext()<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>should_watch = False<EOL>query_skeleton = False<EOL>verbose = False<EOL>for opt, arg in options:<EOL><INDENT>if opt == "<STR_LIT>" or opt == '<STR_LIT>':<EOL><INDENT>should_watch = True<EOL><DEDENT>elif opt == "<STR_LIT>" or opt == '<STR_LIT>':<EOL><INDENT>query_skeleton = True<EOL><DEDENT>elif opt == "<STR_LIT>" or opt == '<STR_LIT>':<EOL><INDENT>print_helptext()<EOL>exit(<NUM_LIT:0>)<EOL><DEDENT>elif opt == "<STR_LIT>" or opt == '<STR_LIT>':<EOL><INDENT>verbose = True<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % opt)<EOL>print_helptext()<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>helpers.set_verbosity("<STR_LIT>")<EOL><DEDENT>if query_skeleton:<EOL><INDENT>print("<STR_LIT:U+0020>".join(ligament.query_skeleton("<STR_LIT>")))<EOL>helpers.set_verbosity()<EOL><DEDENT>else:<EOL><INDENT>helpers.add_verbosity_groups("<STR_LIT>")<EOL>ligament.run_skeleton(<EOL>"<STR_LIT>",<EOL>["<STR_LIT:default>"] if len(args) == <NUM_LIT:0> else args,<EOL>watch=should_watch)<EOL><DEDENT>
|
parse command line opts and run a skeleton file
when called from the command line, ligament looks in the current
working directory for a file called `skeleton.py`. Tasks specified from
the command line are then executed in order, and if the -w flag was
specified, ligament then watches the filesystem for changes to
prompt task re-execution;
|
f5387:m1
|
def partition(pred, iterable):
|
trues = []<EOL>falses = []<EOL>for item in iterable:<EOL><INDENT>if pred(item):<EOL><INDENT>trues.append(item)<EOL><DEDENT>else:<EOL><INDENT>falses.append(item)<EOL><DEDENT><DEDENT>return trues, falses<EOL>
|
split the results of an iterable based on a predicate
|
f5388:m0
|
def zip_with_output(skip_args=[]):
|
def decorator(fn):<EOL><INDENT>def wrapped(*args, **vargs):<EOL><INDENT>g = [arg for i, arg in enumerate(args) if i not in skip_args]<EOL>if len(g) == <NUM_LIT:1>:<EOL><INDENT>return(g[<NUM_LIT:0>], fn(*args, **vargs))<EOL><DEDENT>else:<EOL><INDENT>return (g, fn(*args, **vargs))<EOL><DEDENT><DEDENT>return wrapped<EOL><DEDENT>return decorator<EOL>
|
decorater that zips the input of a function with its output
only zips positional arguments.
skip_args : list
a list of indexes of arguments to exclude from the skip
@zip_with_output(skip_args=[0])
def foo(bar, baz):
return baz
will decorate foo s.t.
foo(x, y) = y
|
f5388:m1
|
def capture_exception(fn):
|
def wrapped(*args):<EOL><INDENT>try:<EOL><INDENT>return fn(*args)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return e<EOL><DEDENT><DEDENT>return wrapped<EOL>
|
decorator that catches and returns an exception from wrapped function
|
f5388:m2
|
def compose(*funcs):
|
return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)<EOL>
|
compose a list of functions
|
f5388:m3
|
def build_lst(a, b):
|
if type(a) is list:<EOL><INDENT>return a + [b]<EOL><DEDENT>elif a:<EOL><INDENT>return [a, b]<EOL><DEDENT>else:<EOL><INDENT>return b<EOL><DEDENT>
|
function to be folded over a list (with initial value `None`)
produces one of:
1. `None`
2. A single value
3. A list of all values
|
f5388:m4
|
def map_over_glob(fn, path, pattern):
|
return [fn(x) for x in glob.glob(os.path.join(path, pattern))]<EOL>
|
map a function over a glob pattern, relative to a directory
|
f5388:m6
|
def mkdir_recursive(dirname):
|
parent = os.path.dirname(dirname)<EOL>if parent != "<STR_LIT>":<EOL><INDENT>if not os.path.exists(parent):<EOL><INDENT>mkdir_recursive(parent)<EOL><DEDENT>if not os.path.exists(dirname):<EOL><INDENT>os.mkdir(dirname)<EOL><DEDENT><DEDENT>elif not os.path.exists(dirname):<EOL><INDENT>os.mkdir(dirname)<EOL><DEDENT>
|
makes all the directories along a given path, if they do not exist
|
f5388:m7
|
def indent_text(*strs, **kwargs):
|
<EOL>indent = kwargs["<STR_LIT>"] if "<STR_LIT>" in kwargs else"<STR_LIT>"<EOL>autobreak = kwargs.get("<STR_LIT>", False)<EOL>char_limit = kwargs.get("<STR_LIT>", <NUM_LIT>)<EOL>split_char = kwargs.get("<STR_LIT>", "<STR_LIT:U+0020>")<EOL>strs = list(strs)<EOL>if autobreak:<EOL><INDENT>for index, s in enumerate(strs):<EOL><INDENT>if len(s) > char_limit:<EOL><INDENT>strs[index] = []<EOL>spl = s.split(split_char)<EOL>result = []<EOL>collect = "<STR_LIT>"<EOL>for current_block in spl:<EOL><INDENT>if len(current_block) + len(collect) > char_limit:<EOL><INDENT>strs[index].append(collect[:-<NUM_LIT:1>] + "<STR_LIT:\n>") <EOL>collect = "<STR_LIT:U+0020>"<EOL><DEDENT>collect += current_block + split_char<EOL><DEDENT>strs[index].append(collect + "<STR_LIT:\n>")<EOL><DEDENT><DEDENT>strs = flatten_list(strs)<EOL><DEDENT>global lasting_indent<EOL>if indent.startswith("<STR_LIT>"):<EOL><INDENT>lasting_indent = lasting_indent + int(indent[<NUM_LIT:2>:])<EOL>cur_indent = lasting_indent<EOL><DEDENT>elif indent.startswith("<STR_LIT:+>"):<EOL><INDENT>cur_indent = lasting_indent + int(indent[<NUM_LIT:1>:])<EOL><DEDENT>elif indent.startswith("<STR_LIT>"):<EOL><INDENT>lasting_indent = lasting_indent - int(indent[<NUM_LIT:2>:])<EOL>cur_indent = lasting_indent<EOL><DEDENT>elif indent.startswith("<STR_LIT:->"):<EOL><INDENT>cur_indent = lasting_indent - int(indent[<NUM_LIT:1>:])<EOL><DEDENT>elif indent.startswith("<STR_LIT>"):<EOL><INDENT>lasting_indent = int(indent[<NUM_LIT:2>:])<EOL>cur_indent = lasting_indent<EOL><DEDENT>elif indent.startswith("<STR_LIT:=>"):<EOL><INDENT>lasting_indent = int(indent[<NUM_LIT:1>:])<EOL>cur_indent = int(indent[<NUM_LIT:1>:])<EOL><DEDENT>else:<EOL><INDENT>raise Exception(<EOL>"<STR_LIT>")<EOL><DEDENT>return tuple(["<STR_LIT:U+0020>" * cur_indent] + [elem.replace("<STR_LIT:\n>", "<STR_LIT:\n>" + "<STR_LIT:U+0020>" * cur_indent) <EOL>for elem in strs])<EOL>
|
indents text according to an operater string and a global indentation
level. returns a tuple of all passed args, indented according to the
operator string
indent: [defaults to +0]
The operator string, of the form
++n : increments the global indentation level by n and indents
+n : indents with the global indentation level + n
--n : decrements the global indentation level by n
-n : indents with the global indentation level - n
==n : sets the global indentation level to exactly n and indents
=n : indents with an indentation level of exactly n
|
f5388:m11
|
def perror(*args, **kwargs):
|
if should_msg(kwargs.get("<STR_LIT>", ["<STR_LIT:error>"])):<EOL><INDENT>global colorama_init<EOL>if not colorama_init:<EOL><INDENT>colorama_init = True<EOL>colorama.init()<EOL><DEDENT>args = indent_text(*args, **kwargs)<EOL>sys.stderr.write(colorama.Fore.RED)<EOL>sys.stderr.write("<STR_LIT>".join(args))<EOL>sys.stderr.write(colorama.Fore.RESET)<EOL>sys.stderr.write("<STR_LIT:\n>")<EOL><DEDENT>
|
print formatted output to stderr with indentation control
|
f5388:m12
|
def pwarning(*args, **kwargs):
|
if should_msg(kwargs.get("<STR_LIT>", ["<STR_LIT>"])):<EOL><INDENT>global colorama_init<EOL>if not colorama_init:<EOL><INDENT>colorama_init = True<EOL>colorama.init()<EOL><DEDENT>args = indent_text(*args, **kwargs)<EOL>sys.stderr.write(colorama.Fore.YELLOW)<EOL>sys.stderr.write("<STR_LIT>".join(args))<EOL>sys.stderr.write(colorama.Fore.RESET)<EOL>sys.stderr.write("<STR_LIT:\n>")<EOL><DEDENT>
|
print formatted output to stderr with indentation control
|
f5388:m13
|
def pdebug(*args, **kwargs):
|
if should_msg(kwargs.get("<STR_LIT>", ["<STR_LIT>"])):<EOL><INDENT>global colorama_init<EOL>if not colorama_init:<EOL><INDENT>colorama_init = True<EOL>colorama.init()<EOL><DEDENT>args = indent_text(*args, **kwargs)<EOL>sys.stderr.write(colorama.Fore.CYAN)<EOL>sys.stderr.write("<STR_LIT>".join(args))<EOL>sys.stderr.write(colorama.Fore.RESET)<EOL>sys.stderr.write("<STR_LIT:\n>")<EOL><DEDENT>
|
print formatted output to stdout with indentation control
|
f5388:m14
|
def pout(*args, **kwargs):
|
if should_msg(kwargs.get("<STR_LIT>", ["<STR_LIT>"])):<EOL><INDENT>args = indent_text(*args, **kwargs)<EOL>sys.stderr.write("<STR_LIT>".join(args))<EOL>sys.stderr.write("<STR_LIT:\n>")<EOL><DEDENT>
|
print to stdout, maintaining indent level
|
f5388:m15
|
def urlretrieve(url, dest, write_mode="<STR_LIT:w>"):
|
response = urllib2.urlopen(url)<EOL>mkdir_recursive(os.path.dirname(dest))<EOL>with open(dest, write_mode) as f:<EOL><INDENT>f.write(response.read())<EOL>f.close()<EOL><DEDENT>
|
save a file to disk from a given url
|
f5388:m16
|
def remove_dups(seq):
|
seen = set()<EOL>seen_add = seen.add<EOL>return [x for x in seq if not (x in seen or seen_add(x))]<EOL>
|
remove duplicates from a sequence, preserving order
|
f5388:m17
|
def run_skeleton(skeleton_path, tasks, watch=True):
|
build_context = load_context_from_skeleton(skeleton_path);<EOL>for task in tasks:<EOL><INDENT>build_context.build_task(task)<EOL><DEDENT>if watch:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL>observer = Observer()<EOL>buildcontexteventhandler = BuildContextFsEventHandler(build_context)<EOL>built_tasks = ((taskname, task) <EOL>for taskname, task in build_context.tasks.items()<EOL>if task.last_build_time > <NUM_LIT:0>)<EOL>for taskname, task in built_tasks:<EOL><INDENT>for f in task.task.file_watch_targets:<EOL><INDENT>if os.path.isdir(f):<EOL><INDENT>print("<STR_LIT>" % (taskname, f))<EOL>observer.schedule(<EOL>buildcontexteventhandler,<EOL>f,<EOL>recursive=True)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % (taskname, os.path.dirname(f),<EOL>os.path.basename(f)))<EOL>dirname = os.path.dirname(f)<EOL>observer.schedule(<EOL>buildcontexteventhandler,<EOL>dirname if dirname != "<STR_LIT>" else "<STR_LIT:.>",<EOL>recursive=True)<EOL><DEDENT><DEDENT><DEDENT>print()<EOL>print("<STR_LIT>")<EOL>observer.start()<EOL>try:<EOL><INDENT>while True:<EOL><INDENT>sleep(<NUM_LIT:0.5>)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>observer.stop()<EOL><DEDENT>observer.join()<EOL><DEDENT>
|
loads and executes tasks from a given skeleton file
skeleton_path:
path to the skeleton file
tasks:
a list of string identifiers of tasks to be executed
watch:
boolean flag of if the skeleton should be watched for changes and
automatically updated
|
f5389:m1
|
def register_with_context(self, myname, context):
|
if self.context is not None:<EOL><INDENT>raise Exception("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>context.register_task(myname, self)<EOL>self._name = myname<EOL>self.context = context<EOL>for key in self.data_dependencies:<EOL><INDENT>if type(self.data_dependencies[key]) is DeferredDependency:<EOL><INDENT>self.data_dependencies[key].parent = myname<EOL>self.data_dependencies[key].context = context<EOL>for tnmame in self.data_dependencies[key].target_names:<EOL><INDENT>context.register_dependency(tnmame, myname)<EOL><DEDENT><DEDENT><DEDENT>
|
registers this build target (exclusively) with a given context
|
f5390:c0:m3
|
def resolve_dependencies(self):
|
return dict(<EOL>[((key, self.data_dependencies[key])<EOL>if type(self.data_dependencies[key]) != DeferredDependency<EOL>else (key, self.data_dependencies[key].resolve()))<EOL>for key in self.data_dependencies])<EOL>
|
evaluate each of the data dependencies of this build target,
returns the resulting dict
|
f5390:c0:m4
|
def resolve_and_build(self):
|
pdebug("<STR_LIT>" % self.name,<EOL>groups=["<STR_LIT>"])<EOL>indent_text(indent="<STR_LIT>")<EOL>toret = self.build(**self.resolve_dependencies())<EOL>indent_text(indent="<STR_LIT>")<EOL>return toret<EOL>
|
resolves the dependencies of this build target and builds it
|
f5390:c0:m5
|
def build(self):
|
raise Exception("<STR_LIT>" % type(self))<EOL>pass<EOL>
|
(abstract) perform some task and return the result.
Also assigns the value f self.file_watch_targets
|
f5390:c0:m6
|
def update_build(self, changedfiles):
|
raise Exception("<STR_LIT>" % type(self))<EOL>pass<EOL>
|
(abstract) updates the task given a list of changed files
|
f5390:c0:m7
|
def register_dependency(self, data_src, data_sink):
|
pdebug("<STR_LIT>" % (data_src, data_sink))<EOL>if (data_src not in self._gettask(data_sink).depends_on):<EOL><INDENT>self._gettask(data_sink).depends_on.append(data_src)<EOL><DEDENT>if (data_sink not in self._gettask(data_src).provides_for):<EOL><INDENT>self._gettask(data_src).provides_for.append(data_sink)<EOL><DEDENT>
|
registers a dependency of data_src -> data_sink
by placing appropriate entries in provides_for and depends_on
|
f5391:c1:m2
|
def build_task(self, name):
|
try:<EOL><INDENT>self._gettask(name).value = (<EOL>self._gettask(name).task.resolve_and_build())<EOL><DEDENT>except TaskExecutionException as e:<EOL><INDENT>perror(e.header, indent="<STR_LIT>")<EOL>perror(e.message, indent="<STR_LIT>")<EOL>self._gettask(name).value = e.payload<EOL><DEDENT>except Exception as e:<EOL><INDENT>perror("<STR_LIT>" %<EOL>(name, type(self._gettask(name).task)))<EOL>perror(traceback.format_exc(e), indent='<STR_LIT>')<EOL>self._gettask(name).value = None<EOL><DEDENT>self._gettask(name).last_build_time = time.time()<EOL>
|
Builds a task by name, resolving any dependencies on the way
|
f5391:c1:m3
|
def is_build_needed(self, data_sink, data_src):
|
return (self._gettask(data_src).last_build_time == <NUM_LIT:0> or<EOL>self._gettask(data_src).last_build_time <<EOL>self._gettask(data_sink).last_build_time)<EOL>
|
returns true if data_src needs to be rebuilt, given that data_sink
has had a rebuild requested.
|
f5391:c1:m4
|
def verify_valid_dependencies(self):
|
unobserved_dependencies = set(self.tasks.keys())<EOL>target_queue = []<EOL>while len(unobserved_dependencies) > <NUM_LIT:0>:<EOL><INDENT>target_queue = [unobserved_dependencies.pop()]<EOL>while target_queue is not []:<EOL><INDENT>target_queue += unobserved_dependencies<EOL><DEDENT><DEDENT>
|
Checks if the assigned dependencies are valid
valid dependency graphs are:
- noncyclic (i.e. no `A -> B -> ... -> A`)
- Contain no undefined dependencies
(dependencies referencing undefined tasks)
|
f5391:c1:m5
|
def deep_dependendants(self, target):
|
direct_dependents = self._gettask(target).provides_for<EOL>return (direct_dependents +<EOL>reduce(<EOL>lambda a, b: a + b,<EOL>[self.deep_dependendants(x) for x in direct_dependents],<EOL>[]))<EOL>
|
Recursively finds the dependents of a given build target.
Assumes the dependency graph is noncyclic
|
f5391:c1:m6
|
def resolve_dependency_graph(self, target):
|
targets = self.deep_dependendants(target)<EOL>return sorted(targets,<EOL>cmp=lambda a, b:<EOL><NUM_LIT:1> if b in self.deep_dependendants(a) else<EOL>-<NUM_LIT:1> if a in self.deep_dependendants(b) else<EOL><NUM_LIT:0>)<EOL>
|
resolves the build order for interdependent build targets
Assumes no cyclic dependencies
|
f5391:c1:m7
|
def resolve(self):
|
values = {}<EOL>for target_name in self.target_names:<EOL><INDENT>if self.context.is_build_needed(self.parent, target_name):<EOL><INDENT>self.context.build_task(target_name)<EOL><DEDENT>if len(self.keyword_chain) == <NUM_LIT:0>:<EOL><INDENT>values[target_name] = self.context.tasks[target_name].value<EOL><DEDENT>else:<EOL><INDENT>values[target_name] = reduce(<EOL>lambda task, name: getattr(task, name),<EOL>self.keyword_chain,<EOL>self.context.tasks[target_name].task)<EOL><DEDENT><DEDENT>return self.function(**values)<EOL>
|
Builds all targets of this dependency and returns the result
of self.function on the resulting values
|
f5391:c2:m1
|
def __init__(self, header, *args, **vargs):
|
self.header = header<EOL>"""<STR_LIT>"""<EOL>if "<STR_LIT>" in vargs:<EOL><INDENT>self.payload = vargs["<STR_LIT>"]<EOL>del vargs["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self.payload = Nones<EOL>"""<STR_LIT>"""<EOL><DEDENT>Exception.__init__(self, *args, **vargs)<EOL>
|
header : str
a short description of the error message
(kwarg) payload : (any)
A value to return in place of a normal return value
|
f5393:c0:m0
|
def bind_sockets(port, address=None, family=socket.AF_UNSPEC,<EOL>backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False):
|
if reuse_port and not hasattr(socket, '<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>sockets = []<EOL>if not address:<EOL><INDENT>address = None<EOL><DEDENT>if not socket.has_ipv6 and family == socket.AF_UNSPEC:<EOL><INDENT>family = socket.AF_INET<EOL><DEDENT>if flags is None:<EOL><INDENT>flags = socket.AI_PASSIVE<EOL><DEDENT>bound_port = None<EOL>for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,<EOL><NUM_LIT:0>, flags)):<EOL><INDENT>af, socktype, proto, canonname, sockaddr = res<EOL>if (sys.platform == '<STR_LIT>' and address == '<STR_LIT:localhost>' and<EOL>af == socket.AF_INET6 and sockaddr[<NUM_LIT:3>] != <NUM_LIT:0>):<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>sock = socket.socket(af, socktype, proto)<EOL><DEDENT>except socket.error as e:<EOL><INDENT>if e.errno == errno.EAFNOSUPPORT:<EOL><INDENT>continue<EOL><DEDENT>raise<EOL><DEDENT>if os.name != '<STR_LIT>':<EOL><INDENT>sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, <NUM_LIT:1>)<EOL><DEDENT>if reuse_port:<EOL><INDENT>sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, <NUM_LIT:1>)<EOL><DEDENT>if af == socket.AF_INET6:<EOL><INDENT>if hasattr(socket, "<STR_LIT>"):<EOL><INDENT>sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, <NUM_LIT:1>)<EOL><DEDENT><DEDENT>host, requested_port = sockaddr[:<NUM_LIT:2>]<EOL>if requested_port == <NUM_LIT:0> and bound_port is not None:<EOL><INDENT>sockaddr = tuple([host, bound_port] + list(sockaddr[<NUM_LIT:2>:]))<EOL><DEDENT>sock.setblocking(<NUM_LIT:0>)<EOL>sock.bind(sockaddr)<EOL>bound_port = sock.getsockname()[<NUM_LIT:1>]<EOL>sock.listen(backlog)<EOL>sockets.append(sock)<EOL><DEDENT>return sockets<EOL>
|
Creates listening sockets bound to the given port and address.
Returns a list of socket objects (multiple sockets are returned if
the given address maps to multiple IP addresses, which is most common
for mixed IPv4 and IPv6 use).
Address may be either an IP address or hostname. If it's a hostname,
the server will listen on all IP addresses associated with the
name. Address may be an empty string or None to listen on all
available interfaces. Family may be set to either `socket.AF_INET`
or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
both will be used if available.
The ``backlog`` argument has the same meaning as for
`socket.listen() <socket.socket.listen>`.
``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.
``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket
in the list. If your platform doesn't support this option ValueError will
be raised.
|
f5394:m4
|
def bind_unix_socket(file_, mode=<NUM_LIT>, backlog=_DEFAULT_BACKLOG):
|
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)<EOL>sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, <NUM_LIT:1>)<EOL>sock.setblocking(<NUM_LIT:0>)<EOL>try:<EOL><INDENT>st = os.stat(file_)<EOL><DEDENT>except OSError as err:<EOL><INDENT>if err.errno != errno.ENOENT:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if stat.S_ISSOCK(st.st_mode):<EOL><INDENT>os.remove(file_)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>', file_)<EOL><DEDENT><DEDENT>sock.bind(file_)<EOL>os.chmod(file_, mode)<EOL>sock.listen(backlog)<EOL>return sock<EOL>
|
Creates a listening unix socket.
If a socket with the given name already exists, it will be deleted.
If any other file with that name exists, an exception will be
raised.
Returns a socket object (not a list of socket objects like
`bind_sockets`)
|
f5394:m5
|
def circles_pil(width, height, color):
|
image = Image.new("<STR_LIT>", (width, height), color=None)<EOL>draw = ImageDraw.Draw(image)<EOL>draw.ellipse((<NUM_LIT:0>, <NUM_LIT:0>, width - <NUM_LIT:1>, height - <NUM_LIT:1>), fill=color)<EOL>image.save('<STR_LIT>')<EOL>
|
Implementation of circle border with PIL.
|
f5403:m0
|
def circles_pycairo(width, height, color):
|
cairo_color = color / rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)<EOL>surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>ctx.new_path()<EOL>ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue)<EOL>ctx.arc(width / <NUM_LIT:2>, height / <NUM_LIT:2>, width / <NUM_LIT:2>, <NUM_LIT:0>, <NUM_LIT:2> * pi)<EOL>ctx.fill()<EOL>surface.write_to_png('<STR_LIT>')<EOL>
|
Implementation of circle border with PyCairo.
|
f5403:m1
|
def circles(width=<NUM_LIT:12>, height=<NUM_LIT:12>, color=rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)):
|
circles_pycairo(width, height, color)<EOL>
|
Draws a repeatable circle border pattern.
|
f5403:m2
|
def vertical_strip(width=<NUM_LIT:10>, height=<NUM_LIT:100>, color=rgb(<NUM_LIT:100>, <NUM_LIT:100>, <NUM_LIT:100>),<EOL>subtlety=<NUM_LIT:0.1>):
|
cairo_color = color / rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)<EOL>surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>ctx.scale(width / <NUM_LIT:1.0>, height / <NUM_LIT:1.0>)<EOL>pat = cairo.LinearGradient(<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:1.0>)<EOL>pat.add_color_stop_rgba(<EOL><NUM_LIT:0>,<EOL>cairo_color.red,<EOL>cairo_color.green,<EOL>cairo_color.blue,<EOL><NUM_LIT:0><EOL>)<EOL>pat.add_color_stop_rgba(<EOL><NUM_LIT:1>,<EOL>cairo_color.red,<EOL>cairo_color.green,<EOL>cairo_color.blue,<EOL><NUM_LIT:1><EOL>)<EOL>ctx.rectangle(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>ctx.set_source(pat)<EOL>ctx.fill()<EOL>surface.write_to_png('<STR_LIT>')<EOL>
|
Draws a subtle vertical gradient strip.
|
f5404:m0
|
def vertical_white(width=<NUM_LIT:10>, height=<NUM_LIT:100>, subtlety=<NUM_LIT:0.1>):
|
start = <NUM_LIT:0.5> - subtlety<EOL>end = <NUM_LIT:0.5> + subtlety<EOL>surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>ctx.scale(width/<NUM_LIT:1.0>, height/<NUM_LIT:1.0>)<EOL>pat = cairo.LinearGradient(<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:1.0>)<EOL>pat.add_color_stop_rgba(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, start)<EOL>pat.add_color_stop_rgba(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, end)<EOL>ctx.rectangle(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>ctx.set_source(pat)<EOL>ctx.fill()<EOL>surface.write_to_png('<STR_LIT>')<EOL>
|
Draws a subtle vertical gradient strip: white with varying alpha.
|
f5404:m1
|
def draw_img_button(width=<NUM_LIT:200>, height=<NUM_LIT:50>, text='<STR_LIT>', color=rgb(<NUM_LIT:200>,<NUM_LIT:100>,<NUM_LIT:50>)):
|
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>ctx.rectangle(<NUM_LIT:0>, <NUM_LIT:0>, width - <NUM_LIT:1>, height - <NUM_LIT:1>)<EOL>ctx.set_source_rgb(color.red/<NUM_LIT>, color.green/<NUM_LIT>, color.blue/<NUM_LIT>)<EOL>ctx.fill()<EOL>ctx.set_source_rgb(<NUM_LIT:1.0>, <NUM_LIT:1.0>, <NUM_LIT:1.0>)<EOL>ctx.select_font_face(<EOL>"<STR_LIT>",<EOL>cairo.FONT_SLANT_NORMAL,<EOL>cairo.FONT_WEIGHT_BOLD<EOL>)<EOL>ctx.set_font_size(<NUM_LIT>)<EOL>ctx.move_to(<NUM_LIT:15>, <NUM_LIT:2> * height / <NUM_LIT:3>)<EOL>ctx.show_text(text)<EOL>surface.write_to_png('<STR_LIT>')<EOL>
|
Draws a simple image button.
|
f5405:m0
|
def draw_css_button(width=<NUM_LIT:200>, height=<NUM_LIT:50>, text='<STR_LIT>', color=rgb(<NUM_LIT:200>,<NUM_LIT:100>,<NUM_LIT:50>)):
|
<EOL>from scss import Scss<EOL>css_class = '<STR_LIT>'<EOL>html = '<STR_LIT>'.format(css_class, text)<EOL>css = Scss()<EOL>scss_str = "<STR_LIT>".format(css_class)<EOL>css.compile(scss_str)<EOL>
|
Draws a simple CSS button.
|
f5405:m1
|
def draw_circle(ctx, x, y, radius, cairo_color):
|
ctx.new_path()<EOL>ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue)<EOL>ctx.arc(x, y, radius, <NUM_LIT:0>, <NUM_LIT:2> * pi)<EOL>ctx.fill()<EOL>
|
Draw a circle.
:param radius: radius in pixels
:param cairo_color: normalized rgb color
|
f5406:m0
|
def draw_cloud(width=<NUM_LIT>, height=<NUM_LIT>, color=rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)):
|
cairo_color = color / rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)<EOL>surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>draw_circle(ctx, width / <NUM_LIT:3>, height / <NUM_LIT:2>, height / <NUM_LIT:3>, cairo_color)<EOL>draw_circle(ctx, <NUM_LIT:2> * width / <NUM_LIT:3>, height / <NUM_LIT:2>, height / <NUM_LIT:3>, cairo_color)<EOL>draw_circle(ctx, width / <NUM_LIT:2>, height / <NUM_LIT:3>, height / <NUM_LIT:3>, cairo_color)<EOL>draw_circle(ctx, width / <NUM_LIT:2>, <NUM_LIT:2> * height / <NUM_LIT:3>, height / <NUM_LIT:3>, cairo_color)<EOL>surface.write_to_png('<STR_LIT>')<EOL>
|
Draw a cloud with the given width, height, and color.
|
f5406:m1
|
def verify_gate_bqm(self, bqm, nodes, get_gate_output, ground_energy=<NUM_LIT:0>, min_gap=<NUM_LIT:2>):
|
for a, b, c in product([-<NUM_LIT:1>, <NUM_LIT:1>], repeat=<NUM_LIT:3>):<EOL><INDENT>spin_state = {nodes[<NUM_LIT:0>]: a, nodes[<NUM_LIT:1>]: b, nodes[<NUM_LIT:2>]: c}<EOL>energy = bqm.energy(spin_state)<EOL>if c == get_gate_output(a, b):<EOL><INDENT>self.assertEqual(ground_energy, energy, "<STR_LIT>".format(spin_state))<EOL><DEDENT>else:<EOL><INDENT>self.assertGreaterEqual(energy, ground_energy + min_gap,<EOL>"<STR_LIT>".format(spin_state))<EOL><DEDENT><DEDENT>
|
Check that all equally valid gate inputs are at ground and that invalid values meet
threshold (min_gap) requirement.
|
f5410:c0:m0
|
def get_item(dictionary, tuple_key, default_value):
|
u, v = tuple_key<EOL>tuple1 = dictionary.get((u, v), None)<EOL>tuple2 = dictionary.get((v, u), None)<EOL>return tuple1 or tuple2 or default_value<EOL>
|
Grab values from a dictionary using an unordered tuple as a key.
Dictionary should not contain None, 0, or False as dictionary values.
Args:
dictionary: Dictionary that uses two-element tuple as keys
tuple_key: Unordered tuple of two elements
default_value: Value that is returned when the tuple_key is not found in the dictionary
|
f5411:m0
|
def _get_lp_matrix(spin_states, nodes, edges, offset_weight, gap_weight):
|
if len(spin_states) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>n_states = len(spin_states)<EOL>m_linear = len(nodes)<EOL>m_quadratic = len(edges)<EOL>matrix = np.empty((n_states, m_linear + m_quadratic + <NUM_LIT:2>)) <EOL>if spin_states.ndim == <NUM_LIT:1>:<EOL><INDENT>spin_states = np.expand_dims(spin_states, <NUM_LIT:1>)<EOL><DEDENT>matrix[:, :m_linear] = spin_states<EOL>node_indices = dict(zip(nodes, range(m_linear)))<EOL>for j, (u, v) in enumerate(edges):<EOL><INDENT>u_ind = node_indices[u]<EOL>v_ind = node_indices[v]<EOL>matrix[:, j + m_linear] = np.multiply(matrix[:, u_ind], matrix[:, v_ind])<EOL><DEDENT>matrix[:, -<NUM_LIT:2>] = offset_weight<EOL>matrix[:, -<NUM_LIT:1>] = gap_weight<EOL>return matrix<EOL>
|
Creates an linear programming matrix based on the spin states, graph, and scalars provided.
LP matrix:
[spin_states, corresponding states of edges, offset_weight, gap_weight]
Args:
spin_states: Numpy array of spin states
nodes: Iterable
edges: Iterable of tuples
offset_weight: Numpy 1-D array or number
gap_weight: Numpy 1-D array or a number
|
f5411:m1
|
def generate_bqm(graph, table, decision_variables,<EOL>linear_energy_ranges=None, quadratic_energy_ranges=None, min_classical_gap=<NUM_LIT:2>):
|
<EOL>if len(graph) != len(decision_variables):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not linear_energy_ranges:<EOL><INDENT>linear_energy_ranges = {}<EOL><DEDENT>if not quadratic_energy_ranges:<EOL><INDENT>quadratic_energy_ranges = {}<EOL><DEDENT>nodes = decision_variables<EOL>edges = graph.edges<EOL>m_linear = len(nodes) <EOL>m_quadratic = len(edges) <EOL>n_noted = len(table) <EOL>n_unnoted = <NUM_LIT:2>**m_linear - n_noted <EOL>noted_states = table.keys() if isinstance(table, dict) else table<EOL>noted_states = list(noted_states)<EOL>noted_matrix = _get_lp_matrix(np.asarray(noted_states), nodes, edges, <NUM_LIT:1>, <NUM_LIT:0>)<EOL>spin_states = product([-<NUM_LIT:1>, <NUM_LIT:1>], repeat=m_linear) if m_linear > <NUM_LIT:1> else [-<NUM_LIT:1>, <NUM_LIT:1>]<EOL>unnoted_states = [state for state in spin_states if state not in noted_states]<EOL>unnoted_matrix = _get_lp_matrix(np.asarray(unnoted_states), nodes, edges, <NUM_LIT:1>, -<NUM_LIT:1>)<EOL>if unnoted_matrix is not None:<EOL><INDENT>unnoted_matrix *= -<NUM_LIT:1> <EOL><DEDENT>if isinstance(table, dict):<EOL><INDENT>noted_bound = np.asarray([table[state] for state in noted_states])<EOL>unnoted_bound = np.full((n_unnoted, <NUM_LIT:1>), -<NUM_LIT:1> * max(table.values())) <EOL><DEDENT>else:<EOL><INDENT>noted_bound = np.zeros((n_noted, <NUM_LIT:1>))<EOL>unnoted_bound = np.zeros((n_unnoted, <NUM_LIT:1>))<EOL><DEDENT>linear_range = (MIN_LINEAR_BIAS, MAX_LINEAR_BIAS)<EOL>quadratic_range = (MIN_QUADRATIC_BIAS, MAX_QUADRATIC_BIAS)<EOL>bounds = [linear_energy_ranges.get(node, linear_range) for node in nodes]<EOL>bounds += [get_item(quadratic_energy_ranges, edge, quadratic_range) for edge in edges]<EOL>max_gap = <NUM_LIT:2> * sum(max(abs(lbound), abs(ubound)) for lbound, ubound in bounds)<EOL>bounds.append((None, None)) <EOL>bounds.append((min_classical_gap, max_gap)) <EOL>cost_weights = np.zeros((<NUM_LIT:1>, m_linear + m_quadratic + <NUM_LIT:2>))<EOL>cost_weights[<NUM_LIT:0>, -<NUM_LIT:1>] = -<NUM_LIT:1> <EOL>result = linprog(cost_weights.flatten(), A_eq=noted_matrix, b_eq=noted_bound,<EOL>A_ub=unnoted_matrix, b_ub=unnoted_bound, bounds=bounds)<EOL>if not result.success:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>x = result.x<EOL>h = x[:m_linear]<EOL>j = x[m_linear:-<NUM_LIT:2>]<EOL>offset = x[-<NUM_LIT:2>]<EOL>gap = x[-<NUM_LIT:1>]<EOL>if gap <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)<EOL>bqm.add_variables_from((v, bias) for v, bias in zip(nodes, h))<EOL>bqm.add_interactions_from((u, v, bias) for (u, v), bias in zip(edges, j))<EOL>bqm.add_offset(offset)<EOL>return bqm, gap<EOL>
|
Args:
graph: A networkx.Graph
table: An iterable of valid spin configurations. Each configuration is a tuple of
variable assignments ordered by `decision`.
decision_variables: An ordered iterable of the variables in the binary quadratic model.
linear_energy_ranges: Dictionary of the form {v: (min, max), ...} where min and
max are the range of values allowed to v. The default range is [-2, 2].
quadratic_energy_ranges: Dict of the form {(u, v): (min, max), ...} where min and max are
the range of values allowed to (u, v). The default range is [-1, 1].
min_classical_gap: A float. The minimum energy gap between the highest feasible state and
the lowest infeasible state.
|
f5411:m2
|
@pm.penaltymodel_factory(<NUM_LIT:50>)<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 iteritems(feasible_configurations)}<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>try:<EOL><INDENT>bqm, gap = generate_bqm(specification.graph, feasible_configurations,<EOL>specification.decision_variables,<EOL>linear_energy_ranges=specification.ising_linear_ranges,<EOL>quadratic_energy_ranges=quadratic_ranges,<EOL>min_classical_gap=specification.min_classical_gap)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise pm.exceptions.FactoryException("<STR_LIT>")<EOL><DEDENT>return pm.PenaltyModel.from_specification(specification, bqm, gap, <NUM_LIT:0.0>)<EOL>
|
Factory function for penaltymodel-lp.
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
|
f5413:m0
|
def check_bqm_table(self, bqm, gap, table, decision):
|
response = dimod.ExactSolver().sample(bqm)<EOL>highest_feasible_energy = max(table.values()) if isinstance(table, dict) else <NUM_LIT:0><EOL>seen_gap = float('<STR_LIT>')<EOL>seen_table = set()<EOL>for sample, energy in response.data(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>self.assertAlmostEqual(bqm.energy(sample), energy) <EOL>config = tuple(sample[v] for v in decision)<EOL>if energy < highest_feasible_energy + <NUM_LIT>:<EOL><INDENT>self.assertIn(config, table)<EOL>if isinstance(table, dict):<EOL><INDENT>self.assertAlmostEqual(table[config], energy)<EOL><DEDENT>seen_table.add(config)<EOL><DEDENT>elif config not in table:<EOL><INDENT>seen_gap = min(seen_gap, energy - highest_feasible_energy)<EOL><DEDENT><DEDENT>for config in table:<EOL><INDENT>self.assertIn(config, seen_table)<EOL><DEDENT>self.assertEqual(seen_gap, gap)<EOL>self.assertGreater(gap, <NUM_LIT:0>)<EOL>
|
check that the bqm has ground states matching table
|
f5417:c0:m0
|
def check_bqm_graph(self, bqm, graph):
|
self.assertEqual(len(bqm.linear), len(graph.nodes))<EOL>self.assertEqual(len(bqm.quadratic), len(graph.edges))<EOL>for v in bqm.linear:<EOL><INDENT>self.assertIn(v, graph)<EOL><DEDENT>for u, v in bqm.quadratic:<EOL><INDENT>self.assertIn(u, graph.adj[v])<EOL><DEDENT>
|
bqm and graph have the same structure
|
f5417:c0:m1
|
def check_generated_ising_model(self, feasible_configurations, decision_variables,<EOL>linear, quadratic, ground_energy, infeasible_gap):
|
if not feasible_configurations:<EOL><INDENT>return<EOL><DEDENT>from dimod import ExactSolver<EOL>response = ExactSolver().sample_ising(linear, quadratic)<EOL>sample, ground = next(iter(response.data(['<STR_LIT>', '<STR_LIT>'])))<EOL>gap = float('<STR_LIT>')<EOL>self.assertIn(tuple(sample[v] for v in decision_variables), feasible_configurations)<EOL>seen_configs = set()<EOL>for sample, energy in response.data(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>config = tuple(sample[v] for v in decision_variables)<EOL>if config in seen_configs:<EOL><INDENT>continue<EOL><DEDENT>if config in feasible_configurations:<EOL><INDENT>self.assertAlmostEqual(energy, ground)<EOL>seen_configs.add(config)<EOL><DEDENT>else:<EOL><INDENT>gap = min(gap, energy - ground)<EOL><DEDENT><DEDENT>self.assertAlmostEqual(ground_energy, ground)<EOL>self.assertAlmostEqual(gap, infeasible_gap)<EOL>
|
Check that the given Ising model has the correct energy levels
|
f5418:c0:m4
|
def generate_bqm(graph, table, decision,<EOL>linear_energy_ranges=None, quadratic_energy_ranges=None, min_classical_gap=<NUM_LIT:2>,<EOL>precision=<NUM_LIT:7>, max_decision=<NUM_LIT:8>, max_variables=<NUM_LIT:10>,<EOL>return_auxiliary=False):
|
<EOL>if not isinstance(graph, nx.Graph):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not set().union(*table).issubset({-<NUM_LIT:1>, <NUM_LIT:1>}):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not isinstance(decision, list):<EOL><INDENT>decision = list(decision) <EOL><DEDENT>if not all(v in graph for v in decision):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>num_var = len(decision)<EOL>if any(len(config) != num_var for config in table):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(decision) > max_decision:<EOL><INDENT>raise ValueError(("<STR_LIT>"<EOL>"<STR_LIT>"))<EOL><DEDENT>if len(graph) > max_variables:<EOL><INDENT>raise ValueError(("<STR_LIT>"<EOL>"<STR_LIT>"))<EOL><DEDENT>if linear_energy_ranges is None:<EOL><INDENT>linear_energy_ranges = defaultdict(lambda: (-<NUM_LIT:2>, <NUM_LIT:2>))<EOL><DEDENT>if quadratic_energy_ranges is None:<EOL><INDENT>quadratic_energy_ranges = defaultdict(lambda: (-<NUM_LIT:1>, <NUM_LIT:1>))<EOL><DEDENT>if not isinstance(table, Mapping):<EOL><INDENT>table = {config: <NUM_LIT:0.> for config in table}<EOL><DEDENT>h, J, offset, gap, aux = _generate_ising(graph, table, decision, min_classical_gap,<EOL>linear_energy_ranges, quadratic_energy_ranges)<EOL>bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)<EOL>bqm.add_variables_from((v, round(bias, precision)) for v, bias in h.items())<EOL>bqm.add_interactions_from((u, v, round(bias, precision)) for (u, v), bias in J.items())<EOL>bqm.add_offset(round(offset, precision))<EOL>if return_auxiliary:<EOL><INDENT>return bqm, round(gap, precision), aux<EOL><DEDENT>else:<EOL><INDENT>return bqm, round(gap, precision)<EOL><DEDENT>
|
Get a binary quadratic model with specific ground states.
Args:
graph (:obj:`~networkx.Graph`):
Defines the structure of the generated binary quadratic model.
table (iterable):
Iterable of valid configurations (of spin-values). Each configuration is a tuple of
variable assignments ordered by `decision`.
decision (list/tuple):
The variables in the binary quadratic model which have specified configurations.
linear_energy_ranges (dict, optional):
Dict of the form {v: (min, max, ...} where min and max are the range of values allowed
to v. The default range is [-2, 2].
quadratic_energy_ranges (dict, optional):
Dict of the form {(u, v): (min, max), ...} where min and max are the range of values
allowed to (u, v). The default range is [-1, 1].
min_classical_gap (float):
The minimum energy gap between the highest feasible state and the lowest infeasible
state.
precision (int, optional, default=7):
Values returned by the optimization solver are rounded to `precision` digits of
precision.
max_decision (int, optional, default=4):
Maximum number of decision variables allowed. The algorithm is valid for arbitrary
sizes of problem but can be extremely slow.
max_variables (int, optional, default=4):
Maximum number of variables allowed. The algorithm is valid for arbitrary
sizes of problem but can be extremely slow.
return_auxiliary (bool, optional, False):
If True, the auxiliary configurations are returned for each configuration in table.
Returns:
If return_auxiliary is False:
:obj:`dimod.BinaryQuadraticModel`: The binary quadratic model.
float: The classical gap.
If return_auxiliary is True:
:obj:`dimod.BinaryQuadraticModel`: The binary quadratic model.
float: The classical gap.
dict: The auxiliary configurations, keyed on the configurations in table.
Raises:
ImpossiblePenaltyModel: If the penalty model cannot be built. Normally due
to a non-zero infeasible gap.
|
f5419:m0
|
@pm.penaltymodel_factory(-<NUM_LIT>)<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 iteritems(feasible_configurations)}<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>try:<EOL><INDENT>bqm, gap = generate_bqm(specification.graph, feasible_configurations,<EOL>specification.decision_variables,<EOL>linear_energy_ranges=specification.ising_linear_ranges,<EOL>quadratic_energy_ranges=quadratic_ranges,<EOL>min_classical_gap=specification.min_classical_gap)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise pm.exceptions.FactoryException("<STR_LIT>")<EOL><DEDENT>return pm.PenaltyModel.from_specification(specification, bqm, gap, <NUM_LIT:0.0>)<EOL>
|
Factory function for penaltymodel-mip.
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
|
f5421:m0
|
def cache_connect(database=None):
|
if database is None:<EOL><INDENT>database = cache_file()<EOL><DEDENT>if os.path.isfile(database):<EOL><INDENT>conn = sqlite3.connect(database)<EOL><DEDENT>else:<EOL><INDENT>conn = sqlite3.connect(database)<EOL>conn.executescript(schema)<EOL><DEDENT>with conn as cur:<EOL><INDENT>cur.execute("<STR_LIT>")<EOL><DEDENT>conn.row_factory = sqlite3.Row<EOL>return conn<EOL>
|
Returns a connection object to a sqlite database.
Args:
database (str, optional): The path to the database the user wishes
to connect to. If not specified, a default is chosen using
:func:`.cache_file`. If the special database name ':memory:'
is given, then a temporary database is created in memory.
Returns:
:class:`sqlite3.Connection`
|
f5426:m0
|
def insert_graph(cur, nodelist, edgelist, encoded_data=None):
|
if encoded_data is None:<EOL><INDENT>encoded_data = {}<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = len(nodelist)<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = len(edgelist)<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = json.dumps(edgelist, separators=('<STR_LIT:U+002C>', '<STR_LIT::>'))<EOL><DEDENT>insert ="""<STR_LIT>"""<EOL>cur.execute(insert, encoded_data)<EOL>
|
Insert a graph into the cache.
A graph is stored by number of nodes, number of edges and a
json-encoded list of edges.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
nodelist (list): The nodes in the graph.
edgelist (list): The edges in the graph.
encoded_data (dict, optional): If a dictionary is provided, it
will be populated with the serialized data. This is useful for
preventing encoding the same information many times.
Notes:
This function assumes that the nodes are index-labeled and range
from 0 to num_nodes - 1.
In order to minimize the total size of the cache, it is a good
idea to sort the nodelist and edgelist before inserting.
Examples:
>>> nodelist = [0, 1, 2]
>>> edgelist = [(0, 1), (1, 2)]
>>> with pmc.cache_connect(':memory:') as cur:
... pmc.insert_graph(cur, nodelist, edgelist)
>>> nodelist = [0, 1, 2]
>>> edgelist = [(0, 1), (1, 2)]
>>> encoded_data = {}
>>> with pmc.cache_connect(':memory:') as cur:
... pmc.insert_graph(cur, nodelist, edgelist, encoded_data)
>>> encoded_data['num_nodes']
3
>>> encoded_data['num_edges']
2
>>> encoded_data['edges']
'[[0,1],[1,2]]'
|
f5426:m1
|
def iter_graph(cur):
|
select = """<STR_LIT>"""<EOL>for num_nodes, num_edges, edges in cur.execute(select):<EOL><INDENT>yield list(range(num_nodes)), json.loads(edges)<EOL><DEDENT>
|
Iterate over all graphs in the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
Yields:
tuple: A 2-tuple containing:
list: The nodelist for a graph in the cache.
list: the edgelist for a graph in the cache.
Examples:
>>> nodelist = [0, 1, 2]
>>> edgelist = [(0, 1), (1, 2)]
>>> with pmc.cache_connect(':memory:') as cur:
... pmc.insert_graph(cur, nodelist, edgelist)
... list(pmc.iter_graph(cur))
[([0, 1, 2], [[0, 1], [1, 2]])]
|
f5426:m2
|
def insert_feasible_configurations(cur, feasible_configurations, encoded_data=None):
|
if encoded_data is None:<EOL><INDENT>encoded_data = {}<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = len(next(iter(feasible_configurations)))<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = len(feasible_configurations)<EOL><DEDENT>if '<STR_LIT>' not in encoded_data or '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded = {_serialize_config(config): en for config, en in 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><DEDENT>insert = """<STR_LIT>"""<EOL>cur.execute(insert, encoded_data)<EOL>
|
Insert a group of feasible configurations into the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
feasible_configurations (dict[tuple[int]): The set of feasible
configurations. Each key should be a tuple of variable assignments.
The values are the relative energies.
encoded_data (dict, optional): If a dictionary is provided, it
will be populated with the serialized data. This is useful for
preventing encoding the same information many times.
Examples:
>>> feasible_configurations = {(-1, -1): 0.0, (+1, +1): 0.0}
>>> with pmc.cache_connect(':memory:') as cur:
... pmc.insert_feasible_configurations(cur, feasible_configurations)
|
f5426:m3
|
def _serialize_config(config):
|
out = <NUM_LIT:0><EOL>for bit in config:<EOL><INDENT>out = (out << <NUM_LIT:1>) | (bit > <NUM_LIT:0>)<EOL><DEDENT>return out<EOL>
|
Turns a config into an integer treating each of the variables as spins.
Examples:
>>> _serialize_config((0, 0, 1))
1
>>> _serialize_config((1, 1))
3
>>> _serialize_config((1, 0, 0))
4
|
f5426:m4
|
def iter_feasible_configurations(cur):
|
select ="""<STR_LIT>"""<EOL>for num_variables, feasible_configurations, energies in cur.execute(select):<EOL><INDENT>configs = json.loads(feasible_configurations)<EOL>energies = json.loads(energies)<EOL>yield {_decode_config(config, num_variables): energy<EOL>for config, energy in zip(configs, energies)}<EOL><DEDENT>
|
Iterate over all of the sets of feasible configurations in the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
Yields:
dict[tuple(int): number]: The feasible_configurations.
|
f5426:m5
|
def _decode_config(c, num_variables):
|
def bits(c):<EOL><INDENT>n = <NUM_LIT:1> << (num_variables - <NUM_LIT:1>)<EOL>for __ in range(num_variables):<EOL><INDENT>yield <NUM_LIT:1> if c & n else -<NUM_LIT:1><EOL>n >>= <NUM_LIT:1><EOL><DEDENT><DEDENT>return tuple(bits(c))<EOL>
|
inverse of _serialize_config, always converts to spin.
|
f5426:m6
|
def insert_ising_model(cur, nodelist, edgelist, linear, quadratic, offset, encoded_data=None):
|
if encoded_data is None:<EOL><INDENT>encoded_data = {}<EOL><DEDENT>insert_graph(cur, nodelist, edgelist, encoded_data=encoded_data)<EOL>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = _serialize_linear_biases(linear, nodelist)<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = _serialize_quadratic_biases(quadratic, edgelist)<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = offset<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = max(itervalues(quadratic))<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = min(itervalues(quadratic))<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = max(itervalues(linear))<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = min(itervalues(linear))<EOL><DEDENT>insert ="""<STR_LIT>"""<EOL>cur.execute(insert, encoded_data)<EOL>
|
Insert an Ising model into the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
nodelist (list): The nodes in the graph.
edgelist (list): The edges in the graph.
linear (dict): The linear bias associated with each node in nodelist.
quadratic (dict): The quadratic bias associated with teach edge in edgelist.
offset (float): The constant offset applied to the ising problem.
encoded_data (dict, optional): If a dictionary is provided, it
will be populated with the serialized data. This is useful for
preventing encoding the same information many times.
|
f5426:m7
|
def _serialize_linear_biases(linear, nodelist):
|
linear_bytes = struct.pack('<STR_LIT:<>' + '<STR_LIT:d>' * len(linear), *[linear[i] for i in nodelist])<EOL>return base64.b64encode(linear_bytes).decode('<STR_LIT:utf-8>')<EOL>
|
Serializes the linear biases.
Args:
linear: a interable object where linear[v] is the bias
associated with v.
nodelist (list): an ordered iterable containing the nodes.
Returns:
str: base 64 encoded string of little endian 8 byte floats,
one for each of the biases in linear. Ordered according
to nodelist.
Examples:
>>> _serialize_linear_biases({1: -1, 2: 1, 3: 0}, [1, 2, 3])
'AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA'
>>> _serialize_linear_biases({1: -1, 2: 1, 3: 0}, [3, 2, 1])
'AAAAAAAAAAAAAAAAAADwPwAAAAAAAPC/'
|
f5426:m8
|
def _serialize_quadratic_biases(quadratic, edgelist):
|
<EOL>quadratic_list = [quadratic[(u, v)] if (u, v) in quadratic else quadratic[(v, u)]<EOL>for u, v in edgelist]<EOL>quadratic_bytes = struct.pack('<STR_LIT:<>' + '<STR_LIT:d>' * len(quadratic), *quadratic_list)<EOL>return base64.b64encode(quadratic_bytes).decode('<STR_LIT:utf-8>')<EOL>
|
Serializes the quadratic biases.
Args:
quadratic (dict): a dict of the form {edge1: bias1, ...} where
each edge is of the form (node1, node2).
edgelist (list): a list of the form [(node1, node2), ...].
Returns:
str: base 64 encoded string of little endian 8 byte floats,
one for each of the edges in quadratic. Ordered by edgelist.
Example:
>>> _serialize_quadratic_biases({(0, 1): -1, (1, 2): 1, (0, 2): .4},
... [(0, 1), (1, 2), (0, 2)])
'AAAAAAAA8L8AAAAAAADwP5qZmZmZmdk/'
|
f5426:m9
|
def iter_ising_model(cur):
|
select ="""<STR_LIT>"""<EOL>for linear_biases, quadratic_biases, num_nodes, edges, offset in cur.execute(select):<EOL><INDENT>nodelist = list(range(num_nodes))<EOL>edgelist = json.loads(edges)<EOL>yield (nodelist, edgelist,<EOL>_decode_linear_biases(linear_biases, nodelist),<EOL>_decode_quadratic_biases(quadratic_biases, edgelist),<EOL>offset)<EOL><DEDENT>
|
Iterate over all of the Ising models in the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
Yields:
tuple: A 5-tuple consisting of:
list: The nodelist for a graph in the cache.
list: the edgelist for a graph in the cache.
dict: The linear biases of an Ising Model in the cache.
dict: The quadratic biases of an Ising Model in the cache.
float: The constant offset of an Ising Model in the cache.
|
f5426:m10
|
def _decode_linear_biases(linear_string, nodelist):
|
linear_bytes = base64.b64decode(linear_string)<EOL>return dict(zip(nodelist, struct.unpack('<STR_LIT:<>' + '<STR_LIT:d>' * (len(linear_bytes) // <NUM_LIT:8>), linear_bytes)))<EOL>
|
Inverse of _serialize_linear_biases.
Args:
linear_string (str): base 64 encoded string of little endian
8 byte floats, one for each of the nodes in nodelist.
nodelist (list): list of the form [node1, node2, ...].
Returns:
dict: linear biases in a dict.
Examples:
>>> _decode_linear_biases('AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA', [1, 2, 3])
{1: -1.0, 2: 1.0, 3: 0.0}
>>> _decode_linear_biases('AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA', [3, 2, 1])
{1: 0.0, 2: 1.0, 3: -1.0}
|
f5426:m11
|
def _decode_quadratic_biases(quadratic_string, edgelist):
|
quadratic_bytes = base64.b64decode(quadratic_string)<EOL>return {tuple(edge): bias for edge, bias in zip(edgelist,<EOL>struct.unpack('<STR_LIT:<>' + '<STR_LIT:d>' * (len(quadratic_bytes) // <NUM_LIT:8>), quadratic_bytes))}<EOL>
|
Inverse of _serialize_quadratic_biases
Args:
quadratic_string (str) : base 64 encoded string of little
endian 8 byte floats, one for each of the edges.
edgelist (list): a list of edges of the form [(node1, node2), ...].
Returns:
dict: J. A dict of the form {edge1: bias1, ...} where each
edge is of the form (node1, node2).
Example:
>>> _decode_quadratic_biases('AAAAAAAA8L8AAAAAAADwP5qZmZmZmdk/',
... [(0, 1), (1, 2), (0, 2)])
{(0, 1): -1.0, (0, 2): 0.4, (1, 2): 1.0}
|
f5426:m12
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.