Search is not available for this dataset
text
stringlengths
75
104k
def set_name_lists(ethnicity=None): """Set three globally available lists of names.""" if not ethnicity: ethnicity = random.choice(get_ethnicities()) print("Loading names from: " + ethnicity) filename = names_dir + ethnicity + '.json' try: with open(filename, 'r') as injson: dat...
def set_chromosomes(self, chromosomes=None): """This model uses the XY sex-determination system. Sex != gender. Assign either XX or XY randomly with a 50/50 chance of each, unless <chromosomes> are passed as an argument. """ if chromosomes and chromosomes in valid_chromosomes: ...
def set_gender(self, gender=None): """This model recognizes that sex chromosomes don't always line up with gender. Assign M, F, or NB according to the probabilities in p_gender. """ if gender and gender in genders: self.gender = gender else: if not self.ch...
def set_inherited_traits(self, egg_donor, sperm_donor): """Accept either strings or Gods as inputs.""" if type(egg_donor) == str: self.reproduce_asexually(egg_donor, sperm_donor) else: self.reproduce_sexually(egg_donor, sperm_donor)
def reproduce_asexually(self, egg_word, sperm_word): """Produce two gametes, an egg and a sperm, from the input strings. Combine them to produce a genome a la sexual reproduction. """ egg = self.generate_gamete(egg_word) sperm = self.generate_gamete(sperm_word) self.geno...
def reproduce_sexually(self, egg_donor, sperm_donor): """Produce two gametes, an egg and a sperm, from input Gods. Combine them to produce a genome a la sexual reproduction. Assign divinity according to probabilities in p_divinity. The more divine the parents, the more divine their offsp...
def set_name(self): """Pick a random name from the lists loaded with the model. For Gods that identify as neither M nor F, the model attempts to retrieve an androgynous name. Note: not all of the scraped name lists contain androgynous names. """ if not self.gender: self.set_gende...
def set_epithet(self): """Divine an appropriate epithet for this God. (See what I did there?)""" if self.divinity == human: obsession = random.choice(self.genome) if self.gender == female: self.epithet = 'ordinary woman' elif self.gender == male: ...
def generate_gamete(self, egg_or_sperm_word): """Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens by searching the list of tokens for words that are related to the given egg_or_sperm_word. """ p_rate_of_mutation = [0.9, 0.1] should_use_mutant_pool = ...
def print_parents(self): """Print parents' names and epithets.""" if self.gender == female: title = 'Daughter' elif self.gender == male: title = 'Son' else: title = 'Child' p1 = self.parents[0] p2 = self.parents[1] template = ...
def instance(self, counter=None, pipeline_counter=None): """Returns all the information regarding a specific stage run See the `Go stage instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-stage-instance Args: counter (int): The stage instance to fet...
def is_json(self): """ Returns: bool: True if `content_type` is `application/json` """ return (self.content_type.startswith('application/json') or re.match(r'application/vnd.go.cd.v(\d+)\+json', self.content_type))
def payload(self): """ Returns: `str` when not json. `dict` when json. """ if self.is_json: if not self._body_parsed: if hasattr(self._body, 'decode'): body = self._body.decode('utf-8') else: ...
def request(self, path, data=None, headers=None, method=None): """Performs a HTTP request to the Go server Args: path (str): The full path on the Go server to request. This includes any query string attributes. data (str, dict, bool, optional): If any data is present thi...
def add_logged_in_session(self, response=None): """Make the request appear to be coming from a browser This is to interact with older parts of Go that doesn't have a proper API call to be made. What will be done: 1. If no response passed in a call to `go/api/pipelines.xml` is ...
def stage(self, pipeline_name, stage_name, pipeline_counter=None): """Returns an instance of :class:`Stage` Args: pipeline_name (str): Name of the pipeline the stage belongs to stage_name (str): Name of the stage to act on pipeline_counter (int): The pipeline instanc...
def flatten(d): """Return a dict as a list of lists. >>> flatten({"a": "b"}) [['a', 'b']] >>> flatten({"a": [1, 2, 3]}) [['a', [1, 2, 3]]] >>> flatten({"a": {"b": "c"}}) [['a', 'b', 'c']] >>> flatten({"a": {"b": {"c": "e"}}}) [['a', 'b', 'c', 'e']] >>> flatten({"a": {"b": "c", "...
def instance(self, counter=None): """Returns all the information regarding a specific pipeline run See the `Go pipeline instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-pipeline-instance Args: counter (int): The pipeline instance to fetch. ...
def schedule(self, variables=None, secure_variables=None, materials=None, return_new_instance=False, backoff_time=1.0): """Schedule a pipeline run Aliased as :meth:`run`, :meth:`schedule`, and :meth:`trigger`. Args: variables (dict, optional): Variables to set/overri...
def artifact(self, counter, stage, job, stage_counter=1): """Helper to instantiate an :class:`gocd.api.artifact.Artifact` object Args: counter (int): The pipeline counter to get the artifact for stage: Stage name job: Job name stage_counter: Defaults to 1 ...
def console_output(self, instance=None): """Yields the output and metadata from all jobs in the pipeline Args: instance: The result of a :meth:`instance` call, if not supplied the latest of the pipeline will be used. Yields: tuple: (metadata (dict), output (str)...
def stage(self, name, pipeline_counter=None): """Helper to instantiate a :class:`gocd.api.stage.Stage` object Args: name: The name of the stage pipeline_counter: Returns: """ return Stage( self.server, pipeline_name=self.name, ...
def edit(self, config, etag): """Update template config for specified template name. .. __: https://api.go.cd/current/#edit-template-config Returns: Response: :class:`gocd.api.response.Response` object """ data = self._json_encode(config) headers = self._defa...
def create(self, config): """Create template config for specified template name. .. __: https://api.go.cd/current/#create-template-config Returns: Response: :class:`gocd.api.response.Response` object """ assert config["name"] == self.name, "Given config is not for th...
def delete(self): """Delete template config for specified template name. .. __: https://api.go.cd/current/#delete-a-template Returns: Response: :class:`gocd.api.response.Response` object """ headers = self._default_headers() return self._request(self.name, ...
def pipelines(self): """Returns a set of all pipelines from the last response Returns: set: Response success: all the pipelines available in the response Response failure: an empty set """ if not self.response: return set() elif self._pipelin...
def get_directory(self, path_to_directory, timeout=30, backoff=0.4, max_wait=4): """Gets an artifact directory by its path. See the `Go artifact directory documentation`__ for example responses. .. __: http://api.go.cd/current/#get-artifact-directory .. note:: Getting a dire...
def ask(self): """ Return the wait time in seconds required to retrieve the item currently at the head of the queue. Note that there is no guarantee that a call to `get()` will succeed even if `ask()` returns 0. By the time the calling thread reacts, other thread...
def p_transition(p): """ transition : START_KWD KEY NULL_KWD FLOAT transition : KEY KEY NULL_KWD FLOAT transition : KEY END_KWD NULL_KWD FLOAT transition : START_KWD KEY KEY FLOAT transition : KEY KEY KEY FLOAT transition : KEY END_KWD KEY FLOAT transition : START_KWD KEY NULL_KWD INTEGE...
def p_action_blocks(p): """ action_blocks : action_blocks action_block """ if isinstance(p[1], list): if isinstance(p[1][0], list): p[0] = p[1][0] + [p[2]] else: p[0] = p[1] + p[2] else: p[0] = [p[1], p[2]]
def p_action_block(p): """ action_block : ACTION_KWD KEY COLON actions """ p[0] = [] for i in range(len(p[4])): p[0] += [marionette_tg.action.MarionetteAction(p[2], p[4][i][0], p[4][i][1], ...
def p_action(p): """ action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MATCH_INCOMING_KWD LPAREN p_string_arg RPAREN action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MAT...
def config_loader(app, **kwargs_config): """Configuration loader. Adds support for loading templates from the Flask application's instance folder (``<instance_folder>/templates``). """ # This is the only place customize the Flask application right after # it has been created, but before all ext...
def app_class(): """Create Flask application class. Invenio-Files-REST needs to patch the Werkzeug form parsing in order to support streaming large file uploads. This is done by subclassing the Flask application class. """ try: pkg_resources.get_distribution('invenio-files-rest') ...
def init_app(self, app, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. """ # Init the configuration self.init_config(app) # Enable Rate limiter self.limiter = Limiter(app, key_func=get_ipaddr) # Enable secur...
def init_config(self, app): """Initialize configuration. :param app: An instance of :class:`~flask.Flask`. """ config_apps = ['APP_', 'RATELIMIT_'] flask_talisman_debug_mode = ["'unsafe-inline'"] for k in dir(config): if any([k.startswith(prefix) for prefix i...
def remove_leading(needle, haystack): """Remove leading needle string (if exists). >>> remove_leading('Test', 'TestThisAndThat') 'ThisAndThat' >>> remove_leading('Test', 'ArbitraryName') 'ArbitraryName' """ if haystack[:len(needle)] == needle: return haystack[len(needle):] retur...
def remove_trailing(needle, haystack): """Remove trailing needle string (if exists). >>> remove_trailing('Test', 'ThisAndThatTest') 'ThisAndThat' >>> remove_trailing('Test', 'ArbitraryName') 'ArbitraryName' """ if haystack[-len(needle):] == needle: return haystack[:-len(needle)] ...
def camel2word(string): """Covert name from CamelCase to "Normal case". >>> camel2word('CamelCase') 'Camel case' >>> camel2word('CaseWithSpec') 'Case with spec' """ def wordize(match): return ' ' + match.group(1).lower() return string[0] + re.sub(r'([A-Z])', wordize, string[1:]...
def complete_english(string): """ >>> complete_english('dont do this') "don't do this" >>> complete_english('doesnt is matched as well') "doesn't is matched as well" """ for x, y in [("dont", "don't"), ("doesnt", "doesn't"), ("wont", "won't"), ...
def format_seconds(self, n_seconds): """Format a time in seconds.""" func = self.ok if n_seconds >= 60: n_minutes, n_seconds = divmod(n_seconds, 60) return "%s minutes %s seconds" % ( func("%d" % n_minutes), func("%.3f" % n_...
def ppdict(dict_to_print, br='\n', html=False, key_align='l', sort_keys=True, key_preffix='', key_suffix='', value_prefix='', value_suffix='', left_margin=3, indent=2): """Indent representation of a dict""" if dict_to_print: if sort_keys: dic = dict_to_print.copy() key...
def eq_(result, expected, msg=None): """ Shadow of the Nose builtin which presents easier to read multiline output. """ params = {'expected': expected, 'result': result} aka = """ --------------------------------- aka ----------------------------------------- Expected: %(expected)r Got: %(result)...
def _assert_contains(haystack, needle, invert, escape=False): """ Test for existence of ``needle`` regex within ``haystack``. Say ``escape`` to escape the ``needle`` if you aren't really using the regex feature & have special characters in it. """ myneedle = re.escape(needle) if escape else nee...
def parse_config_file(): """ Find the .splunk_logger config file in the current directory, or in the user's home and parse it. The one in the current directory has precedence. :return: A tuple with: - project_id - access_token """ for filename in ('.splunk_lo...
def _parse_config_file_impl(filename): """ Format for the file is: credentials: project_id: ... access_token: ... api_domain: ... :param filename: The filename to parse :return: A tuple with: - project_id - access_...
def dem_url_dia(dt_day='2015-06-22'): """Obtiene las urls de descarga de los datos de demanda energética de un día concreto.""" def _url_tipo_dato(str_dia, k): url = SERVER + '/archives/{}/download_json?locale=es'.format(D_TIPOS_REQ_DEM[k]) if type(str_dia) is str: return url + '&da...
def dem_procesa_datos_dia(key_day, response): """Procesa los datos descargados en JSON.""" dfs_import, df_import, dfs_maxmin, hay_errores = [], None, [], 0 for r in response: tipo_datos, data = _extract_func_json_data(r) if tipo_datos is not None: if ('IND_MaxMin' in tipo_datos) ...
def dem_data_dia(str_dia='2015-10-10', str_dia_fin=None): """Obtiene datos de demanda energética en un día concreto o un intervalo, accediendo directamente a la web.""" params = {'date_fmt': DATE_FMT, 'usar_multithread': False, 'num_retries': 1, "timeout": 10, 'func_procesa_data_dia': dem_procesa_...
def flag_inner_classes(obj): """ Mutates any attributes on ``obj`` which are classes, with link to ``obj``. Adds a convenience accessor which instantiates ``obj`` and then calls its ``setup`` method. Recurses on those objects as well. """ for tup in class_members(obj): tup[1]._pare...
def autohide(obj): """ Automatically hide setup() and teardown() methods, recursively. """ # Members on obj for name, item in six.iteritems(vars(obj)): if callable(item) and name in ('setup', 'teardown'): item = hide(item) # Recurse into class members for name, subclass i...
def trap(func): """ Replace sys.std(out|err) with a wrapper during execution, restored after. In addition, a new combined-streams output (another wrapper) will appear at ``sys.stdall``. This stream will resemble what a user sees at a terminal, i.e. both out/err streams intermingled. """ @wr...
def pvpc_url_dia(dt_day): """Obtiene la url de descarga de los datos de PVPC de un día concreto. Anteriormente era: 'http://www.esios.ree.es/Solicitar?fileName=pvpcdesglosehorario_' + str_dia + '&fileType=xml&idioma=es', pero ahora es en JSON y requiere token_auth en headers. """ if type(dt_day) is...
def pvpc_calc_tcu_cp_feu_d(df, verbose=True, convert_kwh=True): """Procesa TCU, CP, FEU diario. :param df: :param verbose: :param convert_kwh: :return: """ if 'TCU' + TARIFAS[0] not in df.columns: # Pasa de €/MWh a €/kWh: if convert_kwh: cols_mwh = [c + t for c i...
def pvpc_procesa_datos_dia(_, response, verbose=True): """Procesa la información JSON descargada y forma el dataframe de los datos de un día.""" try: d_data = response['PVPC'] df = _process_json_pvpc_hourly_data(pd.DataFrame(d_data)) return df, 0 except Exception as e: if ver...
def pvpc_data_dia(str_dia, str_dia_fin=None): """Obtiene datos de PVPC en un día concreto o un intervalo, accediendo directamente a la web.""" params = {'date_fmt': DATE_FMT, 'usar_multithread': False, 'func_procesa_data_dia': pvpc_procesa_datos_dia, 'func_url_data_dia': pvpc_url_dia, ...
def _compress(self, input_str): """ Compress the log message in order to send less bytes to the wire. """ compressed_bits = cStringIO.StringIO() f = gzip.GzipFile(fileobj=compressed_bits, mode='wb') f.write(input_str) f.close() return com...
def get_data_coeficientes_perfilado_2017(force_download=False): """Extrae la información de las dos hojas del Excel proporcionado por REE con los perfiles iniciales para 2017. :param force_download: Descarga el fichero 'raw' del servidor, en vez de acudir a la copia local. :return: perfiles_2017, coefs_...
def get_data_perfiles_estimados_2017(force_download=False): """Extrae perfiles estimados para 2017 con el formato de los CSV's mensuales con los perfiles definitivos. :param force_download: bool para forzar la descarga del excel de la web de REE. :return: perfiles_2017 :rtype: pd.Dataframe """ g...
def main_cli(): """ Actualiza la base de datos de PVPC/DEMANDA almacenados como dataframe en local, creando una nueva si no existe o hubiere algún problema. Los datos registrados se guardan en HDF5 """ def _get_parser_args(): p = argparse.ArgumentParser(description='Gestor de DB de PVPC/D...
def registerGoodClass(self, class_): """ Internal bookkeeping to handle nested classes """ # Class itself added to "good" list self._valid_classes.append(class_) # Recurse into any inner classes for name, cls in class_members(class_): if self.isValidCl...
def isValidClass(self, class_): """ Needs to be its own method so it can be called from both wantClass and registerGoodClass. """ module = inspect.getmodule(class_) valid = ( module in self._valid_modules or ( hasattr(module, '__fil...
def procesa_data_dia(self, key_dia, datos_para_procesar): """Procesa los datos descargados correspondientes a un día `key_dia`.""" return pvpc_procesa_datos_dia(key_dia, datos_para_procesar, verbose=self.verbose)
def get_resample_data(self): """Obtiene los dataframes de los datos de PVPC con resampling diario y mensual.""" if self.data is not None: if self._pvpc_mean_daily is None: self._pvpc_mean_daily = self.data['data'].resample('D').mean() if self._pvpc_mean_monthly is...
def last_entry(self, data_revisar=None, key_revisar=None): """ Definición específica para filtrar por datos de demanda energética (pues los datos se extienden más allá del tiempo presente debido a las columnas de potencia prevista y programada. :param data_revisar: (OPC) Se puede pasar ...
def integridad_data(self, data_integr=None, key=None): """ Definición específica para comprobar timezone y frecuencia de los datos, además de comprobar que el index de cada dataframe de la base de datos sea de fechas, único (sin duplicados) y creciente :param data_integr: :param ...
def busca_errores_data(self): """ Busca errores o inconsistencias en los datos adquiridos :return: Dataframe de errores encontrados """ data_busqueda = self.append_delta_index(TS_DATA_DEM, data_delta=self.data[self.masterkey].copy()) idx_desconex = (((data_busqueda.index ...
def sanitize_path(path): """Performs sanitation of the path after validating :param path: path to sanitize :return: path :raises: - InvalidPath if the path doesn't start with a slash """ if path == '/': # Nothing to do, just return return path if path[:1] != '/': ...
def _validate_schema(obj): """Ensures the passed schema instance is compatible :param obj: object to validate :return: obj :raises: - IncompatibleSchema if the passed schema is of an incompatible type """ if obj is not None and not isinstance(obj, Schema): raise IncompatibleSch...
def route(bp, *args, **kwargs): """Journey route decorator Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow. :param bp: :class:`flask.Blueprint` object :param args: args to pass along to `Blueprint.route` :param kwargs: - :strict_sla...
def attach_bp(self, bp, description=''): """Attaches a flask.Blueprint to the bundle :param bp: :class:`flask.Blueprint` object :param description: Optional description string :raises: - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint` """ ...
def move_dot(self): """Returns the DottedRule that results from moving the dot.""" return self.__class__(self.production, self.pos + 1, self.lookahead)
def first(self, symbols): """Computes the intermediate FIRST set using symbols.""" ret = set() if EPSILON in symbols: return set([EPSILON]) for symbol in symbols: ret |= self._first[symbol] - set([EPSILON]) if EPSILON not in self._first[symbol]: ...
def _compute_first(self): """Computes the FIRST set for every symbol in the grammar. Tenatively based on _compute_first in PLY. """ for terminal in self.terminals: self._first[terminal].add(terminal) self._first[END_OF_INPUT].add(END_OF_INPUT) while True: ...
def _compute_follow(self): """Computes the FOLLOW set for every non-terminal in the grammar. Tenatively based on _compute_follow in PLY. """ self._follow[self.start_symbol].add(END_OF_INPUT) while True: changed = False for nonterminal, productions in se...
def initial_closure(self): """Computes the initial closure using the START_foo production.""" first_rule = DottedRule(self.start, 0, END_OF_INPUT) return self.closure([first_rule])
def goto(self, rules, symbol): """Computes the next closure for rules based on the symbol we got. Args: rules - an iterable of DottedRules symbol - a string denoting the symbol we've just seen Returns: frozenset of DottedRules """ return self.closure( ...
def closure(self, rules): """Fills out the entire closure based on some initial dotted rules. Args: rules - an iterable of DottedRules Returns: frozenset of DottedRules """ closure = set() todo = set(rules) while todo: rule = todo.pop()...
def closures(self): """Computes all LR(1) closure sets for the grammar.""" initial = self.initial_closure() closures = collections.OrderedDict() goto = collections.defaultdict(dict) todo = set([initial]) while todo: closure = todo.pop() closures[c...
def init_app(self, app): """Initializes Journey extension :param app: App passed from constructor or directly to init_app :raises: - NoBundlesAttached if no bundles has been attached attached """ if len(self._attached_bundles) == 0: raise NoBundlesAttac...
def routes_simple(self): """Returns simple info about registered blueprints :return: Tuple containing endpoint, path and allowed methods for each route """ routes = [] for bundle in self._registered_bundles: bundle_path = bundle['path'] for blueprint in...
def _bundle_exists(self, path): """Checks if a bundle exists at the provided path :param path: Bundle path :return: bool """ for attached_bundle in self._attached_bundles: if path == attached_bundle.path: return True return False
def attach_bundle(self, bundle): """Attaches a bundle object :param bundle: :class:`flask_journey.BlueprintBundle` object :raises: - IncompatibleBundle if the bundle is not of type `BlueprintBundle` - ConflictingPath if a bundle already exists at bundle.path ...
def _register_blueprint(self, app, bp, bundle_path, child_path, description): """Register and return info about the registered blueprint :param bp: :class:`flask.Blueprint` object :param bundle_path: the URL prefix of the bundle :param child_path: blueprint relative to the bundle path ...
def get_blueprint_routes(app, base_path): """Returns detailed information about registered blueprint routes matching the `BlueprintBundle` path :param app: App instance to obtain rules from :param base_path: Base path to return detailed route info for :return: List of route detail dicts...
def compute_precedence(terminals, productions, precedence_levels): """Computes the precedence of terminal and production. The precedence of a terminal is it's level in the PRECEDENCE tuple. For a production, the precedence is the right-most terminal (if it exists). The default precedenc...
def make_tables(grammar, precedence): """Generates the ACTION and GOTO tables for the grammar. Returns: action - dict[state][lookahead] = (action, ...) goto - dict[state][just_reduced] = new_state """ ACTION = {} GOTO = {} labels = {} d...
def KB_AgentProgram(KB): """A generic logical knowledge-based agent program. [Fig. 7.1]""" steps = itertools.count() def program(percept): t = steps.next() KB.tell(make_percept_sentence(percept, t)) action = KB.ask(make_action_query(t)) KB.tell(make_action_sentence(action, t...
def expr(s): """Create an Expr representing a logic expression by parsing the input string. Symbols and numbers are automatically converted to Exprs. In addition you can use alternative spellings of these operators: 'x ==> y' parses as (x >> y) # Implication 'x <== y' parses as (x << ...
def variables(s): """Return a set of the variables in expression s. >>> ppset(variables(F(x, A, y))) set([x, y]) >>> ppset(variables(F(G(x), z))) set([x, z]) >>> ppset(variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, z)'))) set([x, y, z]) """ result = set([]) def walk(s): ...
def is_definite_clause(s): """returns True for exprs s of the form A & B & ... & C ==> D, where all literals are positive. In clause form, this is ~A | ~B | ... | ~C | D, where exactly one clause is positive. >>> is_definite_clause(expr('Farmer(Mac)')) True >>> is_definite_clause(expr('~Farmer(...
def parse_definite_clause(s): "Return the antecedents and the consequent of a definite clause." assert is_definite_clause(s) if is_symbol(s.op): return [], s else: antecedent, consequent = s.args return conjuncts(antecedent), consequent
def tt_entails(kb, alpha): """Does kb entail the sentence alpha? Use truth tables. For propositional kb's and sentences. [Fig. 7.10] >>> tt_entails(expr('P & Q'), expr('Q')) True """ assert not variables(alpha) return tt_check_all(kb, alpha, prop_symbols(kb & alpha), {})
def tt_check_all(kb, alpha, symbols, model): "Auxiliary routine to implement tt_entails." if not symbols: if pl_true(kb, model): result = pl_true(alpha, model) assert result in (True, False) return result else: return True else: P, rest...
def prop_symbols(x): "Return a list of all propositional symbols in x." if not isinstance(x, Expr): return [] elif is_prop_symbol(x.op): return [x] else: return list(set(symbol for arg in x.args for symbol in prop_symbols(arg)))
def pl_true(exp, model={}): """Return True if the propositional logic expression is true in the model, and False if it is false. If the model does not specify the value for every proposition, this may return None to indicate 'not obvious'; this may happen even when the expression is tautological.""" ...
def to_cnf(s): """Convert a propositional logical sentence s to conjunctive normal form. That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) [p. 253] >>> to_cnf("~(B|C)") (~B & ~C) >>> to_cnf("B <=> (P1|P2)") ((~P1 | B) & (~P2 | B) & (P1 | P2 | ~B)) >>> to_cnf("a | (b & c) | d") ...
def eliminate_implications(s): """Change >>, <<, and <=> into &, |, and ~. That is, return an Expr that is equivalent to s, but has only &, |, and ~ as logical operators. >>> eliminate_implications(A >> (~B << C)) ((~B | ~C) | ~A) >>> eliminate_implications(A ^ B) ((A & ~B) | (~A & B)) """ ...
def move_not_inwards(s): """Rewrite sentence s by moving negation sign inward. >>> move_not_inwards(~(A | B)) (~A & ~B) >>> move_not_inwards(~(A & B)) (~A | ~B) >>> move_not_inwards(~(~(A | ~B) | ~~C)) ((A | ~B) & ~C) """ if s.op == '~': NOT = lambda b: move_not_inwards(~b) ...
def distribute_and_over_or(s): """Given a sentence s consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. >>> distribute_and_over_or((A & B) | C) ((A | C) & (B | C)) """ if s.op == '|': s = associate('|', s.args) if s.op != '|': ...