Exemplo n.º 1
0
 def _normalize_init(self, init):
     if init is None:
         init = self.get_random_prestate()
     elif self.order == 1 and not isiterable(init):
         init = [init]
     elif self.order > 1 and not isiterable(init):
         init = self.get_random_prestate_startingwith([init])
     elif isiterable(init) and self.order > len(init):
         init = self.get_random_prestate_startingwith(list(init))
     return init
Exemplo n.º 2
0
def EXCLUDE_FUNC(prestate, poststate):
    if isiterable(prestate):
        intersection = EXCLUDED_STATES.intersection(set(prestate))
        if intersection:
            return True
        return False
    return prestate in EXCLUDED_STATES
Exemplo n.º 3
0
def _aslist(x: t.Iter) -> t.List:
    if isinstance(x, list):
        return x
    elif isiterable(x):
        return list(x)
    else:
        raise TypeError("x should be iterable")
Exemplo n.º 4
0
def windowed_moving_average(sequence, windowSize, weights=1, complete=True):
    """
    return the weighted moving average of sequence with a
    window size = windowSize.
    weights can be a tuple defining the weighting in the window
    for instance if windowSize = 5, weights could be (0.1, 0.5, 1, 0.5, 0.1)
    if only one number is defined, a tupled is generated following a 
    interpol.halfcos curve
    """
    import interpoltools
    import numpy

    def parse_coefs(n, coef):
        # Asume que coef es un numero , definiendo una curva
        n = n - 1 + n % 2
        if n == 3:
            return numpy.array((1., coef, 1.), 'd')
        middle = int(n / 2)
        coefs = []
        for i in range(middle):
            coefs.append(interpoltools.interpol_halfcos(i, 0, 1, middle, coef))
        for i in range(middle, n):
            coefs.append(interpoltools.interpol_halfcos(i, middle, coef, n - 1, 1))
        return numpy.array(coefs)
    l = len(sequence)
    if not isiterable(weights):
        weights = parse_coefs(windowSize, weights)
    seq = numpy.array([sequence[i:l - (windowSize - i) + 1]
                      for i in range(windowSize)], 'd').transpose()
    return (seq * weights).sum(1) / sum(weights)
Exemplo n.º 5
0
def solve(solver: Solver,
          numslots: t.Union[int, List[int]],
          rater: Rater = None,
          report=False,
          reportMaxRows=10) -> List[Solution]:
    """
    numslots: the number of slots to use, or a list of possible numslots

    Example
    ~~~~~~~

    values = [0.5, 1, 1.5, 2, 3, 5, 8]
    solver = Solver(values=values, dur=3, relError=0.1, monotonous='up')
    rater = Rater(relcurve=1.5)
    solutions = solve(solver=solver, numslots=4, rater=rater, report=True)
    best = solutions[0]

    """
    allsolutions = []
    possibleNumslots = numslots if misc.isiterable(numslots) else [numslots]
    for numslots in possibleNumslots:
        solutions = solver.solve(numslots)
        allsolutions.extend(solutions)
    ratedSolutions = []
    for sol in allsolutions:
        if rater is not None:
            sol = rater(sol)
        else:
            sol = Solution(sol, 0, None)
        ratedSolutions.append(sol)
    if rater is not None:
        ratedSolutions.sort(reverse=True, key=lambda solution: solution.score)
    if report:
        reportSolutions(ratedSolutions[:reportMaxRows])
    return ratedSolutions
Exemplo n.º 6
0
    def get_random_prestate_startingwith(self, state):
        """
        state can be a single state, a sequence of states or a
        string as STATE1:STATE2:etc

        It returns None if no state found that starts with the given state
        """
        states = _parse_state(state)
        assert isiterable(states)
        if len(states) > self.order:
            raise ValueError(
                "The state given has a higher order than this chain")
        order = self.order
        prestates = [
            prestate for prestate in self.get_prestates()
            if prestate[:order] == states
        ]
        return random.choice(prestates) if prestates else None
Exemplo n.º 7
0
def _parse_state(state: t.U[str, t.Seq]) -> t.List[str]:
    if isiterable(state):
        return _aslist(state)
    return state.split(":")
Exemplo n.º 8
0
def plotDurs(durs: List[float],
             y0=0.0,
             x0=0.0,
             height=1.0,
             labels: List[str] = None,
             color=None,
             ax=None,
             groupLabel: str = None,
             profile: dict = None,
             stacked=False) -> plt.Axes:
    """
    Plot durations as contiguous rectangles

    Args:
        durs: the durations expressed in seconds
        y0: y of origin
        x0: x of origin
        height: the height of the drawn rectangles
        labels: if given, a label for each rectangle
        color: the color used for the rectangles
        ax: the axes to draw on. If not given, a new axes is created (and returned)
        groupLabel: a label for the group
        profile: the profile used, or None to use a default
        stacked: if True, the rectangles are drawn stacked vertically (the duration
            is still drawn horizontally). The result is then similar to a bars plot

    Returns:
        the plot axes. If *ax* was given, then it is returned; otherwise the new
        axes is returned.

    """
    if ax is None:
        ax = makeAxis()
    numitems = len(durs)
    labels = labels if isiterable(labels) else [labels] * numitems
    color = _fallbackColor(color, profile, 'facecolor')
    if not stacked:
        x = x0
        data = []
        for i, dur in enumerate(durs):
            data.append((x, y0, x + dur, y0 + height))
            x += dur
        drawRects(ax, data, facecolor=color)
        if groupLabel is not None:
            sep = height * 0.05
            y1 = y0 + height
            x1 = x0 + sum(durs)
            drawBracket(ax,
                        x0,
                        y1 + sep,
                        x1,
                        y1 + sep * 2,
                        color=_get(profile, 'annotation_color'))
            alpha = (_get(profile, 'annotation_alpha') + 1) * 0.5
            drawLabel(ax, (x0 + x1) * 0.5,
                      y1 + sep,
                      text=groupLabel,
                      alpha=alpha)
    else:
        data = []
        y = y0
        for dur in durs:
            data.append((x0, y, x0 + dur, y + height))
            y += height
        drawRects(ax, data, facecolor=color)
    return ax
Exemplo n.º 9
0
def _many(value, numitems: int, key: str = None, profile: dict = None) -> list:
    if isiterable(value):
        return value
    elif value is None:
        return [_get(profile, key)] * numitems
    return [value] * numitems