def calculate_invariant_rows(self):
    """Calculate the rows of the invariant matrix"""
    inv_rows = self.calculate_initial_rows()
    # Lets begin by just trying to remove 
    for index in range(self.kig.get_num_reactions()):
      num_rows = len(inv_rows)
      new_inv_rows = []
      for i in range(num_rows):
        i_row   = inv_rows[i]
        i_value = int(i_row.row[index])
        if i_value == 0:
          new_inv_rows.append(i_row)
        else: 
          for j in range(i+1, num_rows):
            j_row   = inv_rows[j]
            j_value = int(j_row.row[index])
            if ((i_value < 0 and j_value > 0) or 
                (i_value > 0 and j_value < 0)):
              target_value = utils.lcm (abs(i_value), abs(j_value)) 
              i_coeff = target_value / abs(i_value)
              j_coeff = target_value / abs(j_value)

              new_row = self.combine_invariant_rows(i_row, j_row, 
                                                    coeff1=i_coeff,
                                                    coeff2=j_coeff)
              new_inv_rows.append(new_row)
      # new_inv_rows = [ r for r in inv_rows if r.row[index] == 0 ]
      inv_rows = new_inv_rows
    return inv_rows
Example #2
0
def solve(r):
    ans = 1
    for i in range(2, r + 1):
        print ans,
        ans = lcm(ans, i)
        print i, ans
    return ans
def cmvns_l(cur_val, B, y, Bl, n_neg, p_find, pri_S = None, pri_M = None, n_cycles=1, pri_S_type='square'):
    """
    Metropolis samples cur_val, under the constraint that B*cur_val < y, 
    with likelihood term corresponding to n_neg negative observations independent
    with probabilities p_find if Bl*cur_val>0, else 0.
    """
    
    cur_val = np.asarray(cur_val).squeeze()
    B = np.asarray(B)
    Bl = np.asarray(Bl)
    
    # Change coordinates so that the elements of cur_val are standard normal.
    if pri_M is not None:
        pri_M =np.asarray(pri_M).squeeze()
        cur_val = cur_val - pri_M
    
    if pri_S is not None:
        pri_S = np.asarray(pri_S).squeeze()
        if pri_S_type == 'square':
            new_val = np.linalg.solve(pri_S, cur_val)
            B = np.dot(B,pri_S)
            Bl = np.dot(Bl, pri_S)
        elif pri_S_type == 'diag':
            new_val = cur_val / pri_S
            B = B*pri_S
            Bl = Bl*pri_S
        elif pri_S_type == 'tri':
            new_val = pm.gp.trisolve(pri_S, cur_val, uplo='L', transa='N')
            B = np.dot(B,pri_S)            
            Bl = np.dot(Bl,pri_S)
        else:
            raise ValueError, 'Prior matrix square root type %s not recognized.'%pri_S_type
    else:
        new_val = cur_val.copy()
    
    if np.any(np.dot(B,new_val) > y):
        # Adjust in case of numerical problems.
        new_val = new_val + 1e-5
        if np.any(np.dot(B,new_val) > y):
            raise ValueError, 'Starting values do not satisfy constraints.'
    
    # Do the specified number of cycles.
    n = len(cur_val)
    y_ = y-np.dot(B,new_val)
    lop = np.dot(Bl,new_val)
    u=np.random.random(size=(n,n_cycles)).copy('F')
    um=np.random.random(size=(n,n_cycles)).copy('F')
    # Call to Fortran routine lcg, which overwrites new_val in-place. Number of
    # cycles is determined by size of u.
    acc, rej = lcm(np.asarray(B,order='F'), y_, new_val, u, np.asarray(Bl,order='F'), n_neg, p_find, um, lop)
    
    # Change back to original coordinates and return.
    if pri_S is not None:
        if pri_S_type == 'square' or pri_S_type == 'tri':
            new_val = np.dot(pri_S, new_val)
        else:
            new_val *= pri_S    
    
    return new_val, acc, rej
Example #4
0
def make_common_divisor(numerators,denominators):
    if len(numerators) != len(denominators):
        raise Exception("Numerators (%s) must have the same length as "\
                "denominators (%s)"%(len(numerators),len(denominators)))
    this_lcm = lcm(*denominators)
    for idx, den in enumerate(denominators):
        numerators[idx] = (this_lcm / den) * numerators[idx]
    return numerators,[this_lcm]*len(numerators)
Example #5
0
    def add_task(self, task_name, **kwargs):

        # TODO ensure in path
        try:
            delta = timedelta(**kwargs)
        except TypeError:
            raise Exception('Bad arguments for timedelta')
        self._tasks.append((task_name, delta))
        print('task %s scheduled.' % task_name)

        deltas = [d.total_seconds() for _, d in self._tasks]
        self._reset_delta = lcm(deltas)
        print('setting reset_delta to %s' % self._reset_delta)
Example #6
0
 def pre_process(self):
     pfracs = []
     for pside in self.psides:
         pfracs.append(Fraction(Decimal(str(pside))))
     denominators = [pfrac.denominator for pfrac in pfracs]
     self.L = lcm(denominators)
     if self.L > MAX_LIST_SIZE:
         ex = OverflowError('The resulting value for L (least common multiplier)' \
                 ' for the given list of fractions is bigger than allowed.' \
                 '. Please try again with a different list of psides.')
         ex.L = self.L
         ex.MAX_LIST_SIZE = MAX_LIST_SIZE
         raise ex
     self.A = []
     for i,pfrac in enumerate(pfracs):
         size = int(self.L*pfrac)
         for j in range(size):
             self.A.append(i)
Example #7
0
def old_integer_coeff(float_list):
    relations = []
    possibilities = []
    for fl1 in float_list:
        if almost_equal(fl1, 0.0, tolerance=TOLERANCE):
            # No es un buen candidato para buscar MCM
            continue
        aux = []
        fl1 = '%s'%abs(fl1)
        rat1 = Fraction(fl1)
        for fl2 in float_list:
            if almost_equal(fl2, 0.0, tolerance=TOLERANCE):
                aux.append(0.0)
                continue
            modif2 = -1 if fl2 < 0 else 1
            fl2 = '%s'%(abs(fl2))
            rat2 = Fraction(fl2)
            rel = rat1/rat2
            rel = format(modif2*float(rel), '.%dg'%TRUNCATE)
            rel = Fraction(rel)
            aux.append(rel)
        relations.append(aux)
        mcm = float(lcm(*[abs(x) for x in aux if x!= 0]))
        integerified = [x and int(mcm/x) or 0  for x in aux]
        possibilities.append(integerified)
        #if all([x.is_integer() for x in integerified]):
        #    return [int(x) for x in integerified]
    ret = None
    sup = None
    # Busco la "mejor" inecuaciĆ³n
    # (en el sentido de menor +:abs() de los coef y el TI)
    # de entre las posibles
    for pos in possibilities:
        max_val = 0
        for coef in pos:
            max_val += abs(coef)
        if sup is None or max_val < sup:
            sup = max_val
            ret = pos
    return ret
Example #8
0
# Problem 5

# real 0m0.103s
# user 0m0.057s
# sys  0m0.017s

import math
from utils import lcm
cur_lcm = 1

for i in range(20,1,-1):
    cur_lcm = lcm(cur_lcm,i)
print(cur_lcm)
Example #9
0
def analyze_profile(required, provided, config, options):
    """
    * Calculates the hyperperiod of the profiles
    * Repeats the profiles for the specified number of hyperperiods in *options*
    * Analyzes the requested profiles
    * If more than one hyper-period has been specified it determines system stability
    * Optionally plots the bandwidths and data for the profiles

    :param in required: :class:`networkProfile.Profile` describing the required profile
    :param in provided: :class:`networkProfile.Profile` describing the provided profile
    :param in config: :class:`networkConfig.Config` describing the configuration of the network
    :param in options: :class:`Options` describing the program options for drawing and analysis

    Returns a list of analysis results consisting of::

      [ output, remaining, max delay, max buffer ]

    * The output profile as a :class:`networkProfile.Profile` generated by calling **required.** :func:`networkProfile.Profile.Convolve` ( provided )
    * The remaining capacity profile as a :class:`networkProfile.Profile` which is determined as :math:`remaining = (provided - output)`
    * The delay structure generated by calling **required.** :func:`networkProfile.Profile.CalcDelay` ( output )
    * The buffer structure generated by calling **required.** :func:`networkProfile.Profile.CalcBuffer` ( output )
    """
    num_periods = options.num_periods
    nc_mode = options.nc_mode
    nc_step_size = options.nc_step_size
    print_profiles = options.print_profiles
    plot_dict = options.plot_dict
    plot_line_width = options.plot_line_width

    topology = config.topology
    routes = config.routes
    multicast = config.multicast
    retransmit = config.retransmit

    # CALCULATE HYPERPERIOD
    hyperPeriod = lcm(required.period, provided.period)
    # print "\nCalculated hyperperiod as {} seconds".format(hyperPeriod)

    # REPEAT PROFILES FOR THE RIGHT NUMBER OF HYPERPERIODS
    required.Repeat((hyperPeriod / required.period) * num_periods)
    provided.Repeat((hyperPeriod / provided.period) * num_periods)

    # INTEGRATE THE PROFILES FOR ANALYSIS
    provided.Integrate(hyperPeriod * num_periods)
    required.Integrate(hyperPeriod * num_periods)

    # CONVOLVE REQUIRED WITH PROVIDED TO PRODUCE OUTPUT
    output = required.Convolve(provided)
    output.period = hyperPeriod
    # CALCULATE SENDER-SIDE BUFFER AND DELAY FROM OUTPUT AND REQUIRED
    maxBuffer = required.CalcBuffer(output)
    maxDelay = required.CalcDelay(output)

    # delay the output according to the latency of the node's link
    # this determines the characteristics of the data at the receiver end
    received = output.Delay(provided)
    received.Kind("received")
    received.period = hyperPeriod

    # calculate the remaining capacity of the node's link
    remaining = provided.SubtractProfile(output)
    remaining.Kind("leftover")
    remaining.period = hyperPeriod
    remaining.Integrate(hyperPeriod * num_periods)

    # optionally analyze this using NC:
    if nc_mode:
        provided_nc = provided.ConvertToNC(min, nc_step_size)
        required_nc = required.ConvertToNC(max, nc_step_size)
        output_nc = required_nc.Convolve(provided_nc)
        maxBuffer_nc = required_nc.CalcBuffer(output_nc)
        maxDelay_nc = required_nc.CalcDelay(output_nc)

    # Print out analysis info
    print bcolors.OKBLUE + "\tMax buffer (time, bits): [{}, {}]".format(maxBuffer[0], maxBuffer[2])
    print "\tMax delay (time, seconds): [{}, {}]".format(maxDelay[0], maxDelay[2]) + bcolors.ENDC

    if nc_mode:
        print bcolors.OKBLUE + "\tMax buffer NC (time, bits): [{}, {}]".format(maxBuffer_nc[0], maxBuffer_nc[2])
        print "\tMax delay NC (time, seconds): [{}, {}]".format(maxDelay_nc[0], maxDelay_nc[2]) + bcolors.ENDC

    # DETERMINE SYSTEM STABILITY IF WE HAVE MORE THAN ONE HYPERPERIOD TO ANALYZE
    if num_periods > 1:
        reqDataP1 = required.GetValueAtTime("data", hyperPeriod)
        reqDataP2 = required.GetValueAtTime("data", 2 * hyperPeriod)
        outDataP1 = output.GetValueAtTime("data", hyperPeriod)
        outDataP2 = output.GetValueAtTime("data", 2 * hyperPeriod)
        buff1 = reqDataP1 - outDataP1
        buff2 = reqDataP2 - outDataP2
        # If the buffer size increases between periods, the system is not stable.
        if buff2 > buff1:
            print bcolors.FAIL + "WARNING: BUFFER UTILIZATION NOT CONSISTENT THROUGH ANALYZED PERIODS"
            print "\t APPLICATION MAY HAVE UNBOUNDED BUFFER GROWTH ON NETWORK\n" + bcolors.ENDC

    if plot_dict["plot"]:
        profList = [required, provided, output, remaining, received]
        for key in plot_dict:
            profList = [x for x in profList if key not in x.kind]
        plot_bandwidth_and_data(profList, maxDelay, maxBuffer, num_periods, plot_line_width)
        if nc_mode:
            profList = [required_nc, provided_nc, output_nc]
            plot_bandwidth_and_data(profList, maxDelay_nc, maxBuffer_nc, num_periods, plot_line_width)

    # Shrink the profiles back down so that they can be composed with other profiles
    received.Shrink(received.period)
    output.Shrink(output.period)
    remaining.Shrink(remaining.period)
    provided.Shrink(provided.period)
    required.Shrink(required.period)

    return output, remaining, received, maxBuffer, maxDelay