Python math.isnan() Examples

The following are 30 code examples for showing how to use math.isnan(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module math , or try the search function .

Example 1
Project: DOTA_models   Author: ringringyi   File: accountant.py    License: Apache License 2.0 6 votes vote down vote up
def _compute_delta(self, log_moments, eps):
    """Compute delta for given log_moments and eps.

    Args:
      log_moments: the log moments of privacy loss, in the form of pairs
        of (moment_order, log_moment)
      eps: the target epsilon.
    Returns:
      delta
    """
    min_delta = 1.0
    for moment_order, log_moment in log_moments:
      if math.isinf(log_moment) or math.isnan(log_moment):
        sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
        continue
      if log_moment < moment_order * eps:
        min_delta = min(min_delta,
                        math.exp(log_moment - moment_order * eps))
    return min_delta 
Example 2
Project: DOTA_models   Author: ringringyi   File: gaussian_moments.py    License: Apache License 2.0 6 votes vote down vote up
def _compute_delta(log_moments, eps):
  """Compute delta for given log_moments and eps.

  Args:
    log_moments: the log moments of privacy loss, in the form of pairs
      of (moment_order, log_moment)
    eps: the target epsilon.
  Returns:
    delta
  """
  min_delta = 1.0
  for moment_order, log_moment in log_moments:
    if moment_order == 0:
      continue
    if math.isinf(log_moment) or math.isnan(log_moment):
      sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
      continue
    if log_moment < moment_order * eps:
      min_delta = min(min_delta,
                      math.exp(log_moment - moment_order * eps))
  return min_delta 
Example 3
Project: DOTA_models   Author: ringringyi   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def GenerateBinomialTable(m):
  """Generate binomial table.

  Args:
    m: the size of the table.
  Returns:
    A two dimensional array T where T[i][j] = (i choose j),
    for 0<= i, j <=m.
  """

  table = numpy.zeros((m + 1, m + 1), dtype=numpy.float64)
  for i in range(m + 1):
    table[i, 0] = 1
  for i in range(1, m + 1):
    for j in range(1, m + 1):
      v = table[i - 1, j] + table[i - 1, j -1]
      assert not math.isnan(v) and not math.isinf(v)
      table[i, j] = v
  return tf.convert_to_tensor(table) 
Example 4
Project: End-to-end-ASR-Pytorch   Author: Alexander-H-Liu   File: solver.py    License: MIT License 6 votes vote down vote up
def backward(self, loss):
        '''
        Standard backward step with self.timer and debugger
        Arguments
            loss - the loss to perform loss.backward()
        '''
        self.timer.set()
        loss.backward()
        grad_norm = torch.nn.utils.clip_grad_norm_(
            self.model.parameters(), self.GRAD_CLIP)
        if math.isnan(grad_norm):
            self.verbose('Error : grad norm is NaN @ step '+str(self.step))
        else:
            self.optimizer.step()
        self.timer.cnt('bw')
        return grad_norm 
Example 5
Project: End-to-end-ASR-Pytorch   Author: Alexander-H-Liu   File: solver.py    License: MIT License 6 votes vote down vote up
def write_log(self, log_name, log_dict):
        '''
        Write log to TensorBoard
            log_name  - <str> Name of tensorboard variable 
            log_value - <dict>/<array> Value of variable (e.g. dict of losses), passed if value = None
        '''
        if type(log_dict) is dict:
            log_dict = {key: val for key, val in log_dict.items() if (
                val is not None and not math.isnan(val))}
        if log_dict is None:
            pass
        elif len(log_dict) > 0:
            if 'align' in log_name or 'spec' in log_name:
                img, form = log_dict
                self.log.add_image(
                    log_name, img, global_step=self.step, dataformats=form)
            elif 'text' in log_name or 'hyp' in log_name:
                self.log.add_text(log_name, log_dict, self.step)
            else:
                self.log.add_scalars(log_name, log_dict, self.step) 
Example 6
Project: jawfish   Author: war-and-code   File: fractions.py    License: MIT License 6 votes vote down vote up
def from_float(cls, f):
        """Converts a finite float to a rational number, exactly.

        Beware that Fraction.from_float(0.3) != Fraction(3, 10).

        """
        if isinstance(f, numbers.Integral):
            return cls(f)
        elif not isinstance(f, float):
            raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
                            (cls.__name__, f, type(f).__name__))
        if math.isnan(f):
            raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
        if math.isinf(f):
            raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__))
        return cls(*f.as_integer_ratio()) 
Example 7
Project: jawfish   Author: war-and-code   File: fractions.py    License: MIT License 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, numbers.Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 8
Project: jawfish   Author: war-and-code   File: fractions.py    License: MIT License 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, numbers.Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 9
Project: kivy-smoothie-host   Author: wolfmanjm   File: dial-gauge.py    License: GNU General Public License v3.0 6 votes vote down vote up
def draw_setpoint(self, *args):
        # draw a setpoint
        if self.setpoint_canvas:
            self.canvas.after.remove(self.setpoint_canvas)
            self.setpoint_canvas = None

        if math.isnan(self.setpoint_value) or math.isinf(self.setpoint_value):
            return

        v = self.value_to_angle(self.setpoint_value)
        length = self.dial_diameter / 2.0 - self.tic_length if not self.setpoint_length else self.setpoint_length
        self.setpoint_canvas = InstructionGroup()

        self.setpoint_canvas.add(PushMatrix())
        self.setpoint_canvas.add(Color(*self.setpoint_color))
        self.setpoint_canvas.add(Rotate(angle=v, axis=(0, 0, -1), origin=self.dial_center))
        self.setpoint_canvas.add(Translate(self.dial_center[0], self.dial_center[1]))
        self.setpoint_canvas.add(Line(points=[0, 0, 0, length], width=self.setpoint_thickness, cap='none'))
        # self.setpoint_canvas.add(SmoothLine(points=[0, 0, 0, length], width=self.setpoint_thickness))
        self.setpoint_canvas.add(PopMatrix())

        self.canvas.after.add(self.setpoint_canvas) 
Example 10
Project: hadrian   Author: modelop   File: testParse.py    License: Apache License 2.0 6 votes vote down vote up
def testParseFloat(self):
        engine, = PFAEngine.fromYaml('''
input: string
output: float
action: {parse.float: input}
''')
        self.assertEqual(engine.action("   123   "), 123.0)
        self.assertEqual(engine.action("   -123   "), -123.0)
        self.assertEqual(engine.action("   3.4028234e38   "), 3.4028234e38)
        self.assertEqual(engine.action("   -3.4028234e38   "), -3.4028234e38)
        self.assertEqual(engine.action("   3.4028236e38   "), float("inf"))
        self.assertEqual(engine.action("   -3.4028236e38   "), float("-inf"))
        self.assertEqual(engine.action("   1.4e-45   "), 1.4e-45)
        self.assertEqual(engine.action("   -1.4e-45   "), -1.4e-45)
        self.assertEqual(engine.action("   1e-46   "), 0.0)
        self.assertEqual(engine.action("   -1e-46   "), 0.0)
        self.assertTrue(math.isnan(engine.action("   nAN   ")))
        self.assertEqual(engine.action("   inf   "), float("inf"))
        self.assertEqual(engine.action("   +inf   "), float("inf"))
        self.assertEqual(engine.action("   -inf   "), float("-inf")) 
Example 11
Project: hadrian   Author: modelop   File: testParse.py    License: Apache License 2.0 6 votes vote down vote up
def testParseDouble(self):
        engine, = PFAEngine.fromYaml('''
input: string
output: double
action: {parse.double: input}
''')
        self.assertEqual(engine.action("   123   "), 123.0)
        self.assertEqual(engine.action("   -123   "), -123.0)
        self.assertEqual(engine.action("   1.7976931348623157e308   "), 1.7976931348623157e308)
        self.assertEqual(engine.action("   -1.7976931348623157e308   "), -1.7976931348623157e308)
        self.assertEqual(engine.action("   1.7976931348623159e308   "), float("inf"))
        self.assertEqual(engine.action("   -1.7976931348623159e308   "), float("-inf"))
        self.assertEqual(engine.action("   4.9e-324   "), 4.9e-324)
        self.assertEqual(engine.action("   -4.9e-324   "), -4.9e-324)
        self.assertEqual(engine.action("   1e-324   "), 0.0)
        self.assertEqual(engine.action("   1e-324   "), 0.0)
        self.assertTrue(math.isnan(engine.action("   nAN   ")))
        self.assertEqual(engine.action("   inf   "), float("inf"))
        self.assertEqual(engine.action("   +inf   "), float("inf"))
        self.assertEqual(engine.action("   -inf   "), float("-inf")) 
Example 12
Project: hadrian   Author: modelop   File: interp.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, *args):
        if len(args) == 3:
            numbins, low, high = args
            if low >= high or math.isnan(low) or math.isnan(high):
                raise PFARuntimeException("bad histogram range", self.errcodeBase + 0, self.name, pos)
            if numbins < 1:
                raise PFARuntimeException("bad histogram scale", self.errcodeBase + 1, self.name, pos)
            if math.isnan(x) or x < low or x >= high:
                raise PFARuntimeException("x out of range", self.errcodeBase + 2, self.name, pos)

            out = int(math.floor(numbins * div((x - low), (high - low))))

            if out < 0 or out >= numbins:
                raise PFARuntimeException("x out of range", self.errcodeBase + 2, self.name, pos)
            return out
        else:
            origin, width = args
            if math.isnan(origin) or math.isinf(origin):
                raise PFARuntimeException("bad histogram range", self.errcodeBase + 0, self.name, pos)
            if width <= 0.0 or math.isnan(width):
                raise PFARuntimeException("bad histogram scale", self.errcodeBase + 1, self.name, pos)
            if math.isnan(x) or math.isinf(x):
                raise PFARuntimeException("x out of range", self.errcodeBase + 2, self.name, pos)
            else:
                return int(math.floor(div((x - origin), width))) 
Example 13
Project: hadrian   Author: modelop   File: parse.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, str):
        try:
            out = float(str)
        except ValueError:
            raise PFARuntimeException("not a single-precision float", self.errcodeBase + 0, self.name, pos)
        if math.isnan(out):
            return out
        elif math.isinf(out):
            return out
        elif out > FLOAT_MAX_VALUE:
            return float("inf")
        elif -out > FLOAT_MAX_VALUE:
            return float("-inf")
        elif abs(out) < FLOAT_MIN_VALUE:
            return 0.0
        else:
            return out 
Example 14
Project: hadrian   Author: modelop   File: parse.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, str):
        try:
            out = float(str)
        except ValueError:
            raise PFARuntimeException("not a double-precision float", self.errcodeBase + 0, self.name, pos)
        if math.isnan(out):
            return out
        elif math.isinf(out):
            return out
        elif out > DOUBLE_MAX_VALUE:
            return float("inf")
        elif -out > DOUBLE_MAX_VALUE:
            return float("-inf")
        elif abs(out) < DOUBLE_MIN_VALUE:
            return 0.0
        else:
            return out 
Example 15
Project: hadrian   Author: modelop   File: core.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, y):
        if y == 0:
            if paramTypes[-1] == "int" or paramTypes[-1] == "long":
                raise PFARuntimeException("integer division by zero", self.errcodeBase + 0, self.name, pos)
            else:
                return float("nan")
        else:
            if not math.isnan(x) and not math.isinf(x) and math.isinf(y):
                return x
            else:
                out = x % y
                if x < 0 and out > 0:
                    return out - abs(y)
                elif x > 0 and out < 0:
                    return out + abs(y)
                else:
                    return out 
Example 16
Project: hadrian   Author: modelop   File: array.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, a, p):
        if len(a) == 0:
            raise PFARuntimeException("empty array", self.errcodeBase + 0, self.name, pos)
        if math.isnan(p):
            raise PFARuntimeException("p not a number", self.errcodeBase + 1, self.name, pos)
        if p <= 0.0:
            return lowestN(a, 1, lambda x, y: compare(jsonNodeToAvroType(paramTypes[0]).items, x, y) < 0)[0]
        if p >= 1.0:
            return highestN(a, 1, lambda x, y: compare(jsonNodeToAvroType(paramTypes[0]).items, x, y) < 0)[0]
        sa = sorted(a, lambda x, y: compare(jsonNodeToAvroType(paramTypes[0]).items, x, y))
        k = (len(a) - 1.0)*p
        f = math.floor(k)
        dataType = paramTypes[-1]
        if (dataType is "float") or (dataType is "double"):
            c = math.ceil(k)
            if f == c:
                return sa[int(k)]
            d0 = sa[int(f)] * (c - k)
            d1 = sa[int(c)] * (k - f)
            return d0 + d1
        else:
            if len(sa) % 2 == 1:
                return sa[int(f)]
            else:
                return sa[int(k)] 
Example 17
Project: hadrian   Author: modelop   File: pfatest.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, state_):
        chi2 = state_["chi2"]
        dof = state_["dof"]
        if dof < 0:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif dof == 0:
            if chi2 > 0:
                return 1.0
            else:
                return 0.0
        elif math.isnan(chi2):
            return float("nan")
        elif math.isinf(chi2):
            if chi2 > 0:
                return 1.0
            else:
                return 0.0
        else:
            return float(Chi2Distribution(dof, self.errcodeBase + 0, self.name, pos).CDF(chi2)) 
Example 18
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, *others):
        if len(others) == 2:
            mu, sigma = others
        else:
            mu = others[0]["mean"]
            if math.isnan(others[0]["variance"]) or others[0]["variance"] < 0.0:
                raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
            else:
                sigma = math.sqrt(others[0]["variance"])
        if math.isinf(mu) or math.isnan(mu) or math.isinf(sigma) or math.isnan(sigma) or sigma < 0.0:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif math.isinf(x) or math.isnan(x):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif sigma == 0.0:
            if x != mu:
                return float("-inf")
            else:
                return float("inf")
        else:
            return GaussianDistribution(mu, sigma, self.errcodeBase + 0, self.name, pos).LL(x) 
Example 19
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, *others):
        if len(others) == 2:
            mu, sigma = others
        else:
            mu = others[0]["mean"]
            if math.isnan(others[0]["variance"]) or others[0]["variance"] < 0.0:
                raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
            else:
                sigma = math.sqrt(others[0]["variance"])
        if math.isinf(mu) or math.isnan(mu) or math.isinf(sigma) or math.isnan(sigma) or sigma < 0.0:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif math.isinf(x) or math.isnan(x):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif sigma == 0.0:
            if x < mu:
                return 0.0
            else:
                return 1.0
        else:
            return GaussianDistribution(mu, sigma, self.errcodeBase + 0, self.name, pos).CDF(x) 
Example 20
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, p, *others):
        if len(others) == 2:
            mu, sigma = others
        else:
            mu = others[0]["mean"]
            if math.isnan(others[0]["variance"]) or others[0]["variance"] < 0.0:
                raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
            else:
                sigma = math.sqrt(others[0]["variance"])
        if math.isinf(mu) or math.isnan(mu) or math.isinf(sigma) or math.isnan(sigma) or sigma < 0.0:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif not (0.0 <= p <= 1.0):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif p == 1.0:
            return float("inf")
        elif p == 0.0:
            return float("-inf")
        elif sigma == 0.0:
            return mu
        else:
            return GaussianDistribution(mu, sigma, self.errcodeBase + 0, self.name, pos).QF(p) 
Example 21
Project: hadrian   Author: modelop   File: dist.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, size, prob):
        if math.isinf(prob) or math.isnan(prob) or size <= 0 or prob < 0 or prob > 1:
            raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos)
        elif math.isinf(x) or math.isnan(x):
            raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos)
        elif x < 0:
            return 0.0
        elif x >= size:
            return 1.0
        elif prob == 1:
            if x < size:
                return 0.0
            else:
                return 1.0
        elif prob == 0:
            return 1.0
        else:
            return BinomialDistribution(size, prob, self.errcodeBase + 0, self.name, pos).CDF(x) 
Example 22
Project: incubator-spot   Author: apache   File: dns_oa.py    License: Apache License 2.0 5 votes vote down vote up
def _ingest_summary(self):
        # get date parameters.
        yr = self._date[:4]
        mn = self._date[4:6]
        dy = self._date[6:]

        self._logger.info("Getting ingest summary data for the day")
        
        ingest_summary_cols = ["date","total"]		
        result_rows = []        
        df_filtered =  pd.DataFrame()

        query_to_load = ("""
            SELECT frame_time, COUNT(*) as total FROM {0}.{1}
            WHERE y={2} AND m={3} AND d={4} AND unix_tstamp IS NOT NULL
            AND frame_time IS NOT NULL AND frame_len IS NOT NULL
            AND dns_qry_name IS NOT NULL AND ip_src IS NOT NULL
            AND (dns_qry_class IS NOT NULL AND dns_qry_type IS NOT NULL
            AND dns_qry_rcode IS NOT NULL ) GROUP BY frame_time;
        """).format(self._db,self._table_name, yr, mn, dy)

        results = impala.execute_query_as_list(query_to_load)
        df = pd.DataFrame(results)

        # Forms a new dataframe splitting the minutes from the time column
        df_new = pd.DataFrame([["{0}-{1}-{2} {3}:{4}".format(yr, mn, dy,\
            val['frame_time'].replace("  "," ").split(" ")[3].split(":")[0].zfill(2),\
            val['frame_time'].replace("  "," ").split(" ")[3].split(":")[1].zfill(2)),\
            int(val['total']) if not math.isnan(val['total']) else 0 ] for key,val in df.iterrows()],columns = ingest_summary_cols)

        #Groups the data by minute
        sf = df_new.groupby(by=['date'])['total'].sum()
        df_per_min = pd.DataFrame({'date':sf.index, 'total':sf.values})

        df_final = df_filtered.append(df_per_min, ignore_index=True).to_records(False,False)

        if len(df_final) > 0:
            query_to_insert=("""
                INSERT INTO {0}.dns_ingest_summary PARTITION (y={1}, m={2}, d={3}) VALUES {4};
            """).format(self._db, yr, mn, dy, tuple(df_final))
            impala.execute_query(query_to_insert) 
Example 23
Project: DOTA_models   Author: ringringyi   File: wiki_data.py    License: Apache License 2.0 5 votes vote down vote up
def is_nan_or_inf(number):
  return math.isnan(number) or math.isinf(number) 
Example 24
Project: DOTA_models   Author: ringringyi   File: accountant.py    License: Apache License 2.0 5 votes vote down vote up
def _compute_eps(self, log_moments, delta):
    min_eps = float("inf")
    for moment_order, log_moment in log_moments:
      if math.isinf(log_moment) or math.isnan(log_moment):
        sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order)
        continue
      min_eps = min(min_eps, (log_moment - math.log(delta)) / moment_order)
    return min_eps 
Example 25
Project: DOTA_models   Author: ringringyi   File: gaussian_moments.py    License: Apache License 2.0 5 votes vote down vote up
def _to_np_float64(v):
  if math.isnan(v) or math.isinf(v):
    return np.inf
  return np.float64(v)


######################
# FLOAT64 ARITHMETIC #
###################### 
Example 26
Project: gcp-variant-transforms   Author: googlegenomics   File: bigquery_sanitizer.py    License: Apache License 2.0 5 votes vote down vote up
def _get_sanitized_float(self, input_float):
    """Returns a sanitized float for BigQuery.

    This method replaces INF and -INF with positive and negative numbers with
    huge absolute values, and replaces NaN with None. It returns the same value
    for all other values.
    """
    if input_float == float('inf'):
      return _INF_FLOAT_VALUE
    elif input_float == float('-inf'):
      return -_INF_FLOAT_VALUE
    elif math.isnan(input_float):
      return None
    else:
      return input_float 
Example 27
Project: jawfish   Author: war-and-code   File: _struct.py    License: MIT License 5 votes vote down vote up
def isnan(v):
    return v != v*1.0 or (v == 1.0 and v == 2.0) 
Example 28
Project: python-esppy   Author: sassoftware   File: jmp_score.py    License: Apache License 2.0 5 votes vote down vote up
def is_missing(x):
    return math.isnan(x) or math.isinf(x) or x is None 
Example 29
Project: python-esppy   Author: sassoftware   File: jmp_score.py    License: Apache License 2.0 5 votes vote down vote up
def sum(S):
    """
    Return the sum of array elements treating missing (NaN) as zero.

    To match JMP's behavior, check if all elements are missing in
    which case missing is returned.
    """
    if np.all(np.isnan(S)):
        return np.nan
    return np.nansum(S) 
Example 30
Project: razzy-spinner   Author: rafasashi   File: util.py    License: GNU General Public License v3.0 5 votes vote down vote up
def check(self, classifier, train_toks):
        cutoffs = self.cutoffs
        self.iter += 1
        if 'max_iter' in cutoffs and self.iter >= cutoffs['max_iter']:
            return True # iteration cutoff.

        new_ll = nltk.classify.util.log_likelihood(classifier, train_toks)
        if math.isnan(new_ll):
            return True

        if 'min_ll' in cutoffs or 'min_lldelta' in cutoffs:
            if 'min_ll' in cutoffs and new_ll >= cutoffs['min_ll']:
                return True # log likelihood cutoff
            if ('min_lldelta' in cutoffs and self.ll and
                ((new_ll - self.ll) <= abs(cutoffs['min_lldelta']))):
                return True # log likelihood delta cutoff
            self.ll = new_ll

        if 'max_acc' in cutoffs or 'min_accdelta' in cutoffs:
            new_acc = nltk.classify.util.log_likelihood(
                classifier, train_toks)
            if 'max_acc' in cutoffs and new_acc >= cutoffs['max_acc']:
                return True # log likelihood cutoff
            if ('min_accdelta' in cutoffs and self.acc and
                ((new_acc - self.acc) <= abs(cutoffs['min_accdelta']))):
                return True # log likelihood delta cutoff
            self.acc = new_acc

            return False # no cutoff reached.

######################################################################
#{ Demos
######################################################################