示例#1
0
def MoveRight(board):
    #Moves blank tile right, if possible
    #Convert to a square array
    board = flat2square(board)

    num_rows = len(board)  #one side of the puzzle
    num_cols = len(board)

    [blank_row,
     blank_col] = np.where(board == 0)  #Find the location of the blank space

    if (blank_col == num_cols -
            1):  #Blank spot is on the right edge; cannot be moved right
        if verbose == True:
            print(
                "Blank space is at the right edge of the board and cannot be moved right."
            )
        return  #board

    else:
        verbose("Moving 1 square to the right")
        newBoard = np.copy(board)
        newBoard[blank_row, blank_col] = board[blank_row, blank_col + 1]
        newBoard[blank_row, blank_col + 1] = 0  #board[blank_row,blank_col]
        newBoard = square2flat(newBoard)
        return newBoard
示例#2
0
def simplify(equation):

    # si il n'y a pas de "=" c'est pas une equation si il y en a plus d'un c'est pas bon aussi
    splitted = re.split("=", equation)
    if len(splitted) == 1:
        v.ft_missing_equal()
    if len(splitted) > 2:
        v.too_much_equal()

    pattern = re.compile("[\^xX]\s*([+-])\s*(\d+(?:(\.\d+)?))\s*($|[\+\-\=])")
    match = re.findall(pattern, equation)
    if len(match) != 0:
        v.no_sign()

    pattern = re.compile("([\^xX])\s*(\d+?(\.(\d+)*?))\s*($|[\+\-\=])")
    match = re.findall(pattern, equation)
    if len(match) != 0:
        v.no_float()

    tmp1 = re.sub(r"([,])", r".", equation)  # change "," to "."
    tmp1 = re.sub(r"([^0-9.+\-*xX^=])", r"",
                  tmp1)  # remove unwanted caracteres and spaces
    tmp2 = ""
    while tmp1 != tmp2:
        tmp2 = tmp1
        tmp1 = simplifier(tmp2)
    v.verbose("[Verbose]Formated: " + tmp2)
    return tmp2
示例#3
0
def MoveDown(board):
    #Moves blank tile down, if possible
    #Convert to a square array
    board = flat2square(board)

    num_rows = len(board)  #one side of the puzzle
    num_cols = len(board)

    [blank_row,
     blank_col] = np.where(board == 0)  #Find the location of the blank space

    #print(num_rows)
    if (blank_row == num_rows -
            1):  #Blank spot is on the bottom edge; cannot be moved down
        verbose(
            "Blank space is at the bottom edge of the board and cannot be moved down."
        )
        return  #board

    else:
        verbose("Moving 1 square down")
        newBoard = np.copy(board)
        newBoard[blank_row, blank_col] = board[blank_row + 1, blank_col]
        newBoard[blank_row + 1, blank_col] = 0
        newBoard = square2flat(newBoard)
        return newBoard
示例#4
0
def BFS(board, attempt, attempt_num, parent, k):
    myboard[0] = actions.MoveLeft(board)
    myboard[1] = actions.MoveRight(board)
    myboard[2] = actions.MoveUp(board)
    myboard[3] = actions.MoveDown(board)

    for i in range(0, 4):
        print(myboard[i])

    for i in range(0, 4):
        if (square2flat(myboard[i]) in board_tracker
            ):  # board configuration is already saved. Move on
            verbose("Board configuration is already saved.")
            return
        else:
            verbose("Adding board to list")
            board_tracker[k] = square2flat(myboard[i])
            k = k + 1
            #print(attempt_num)

            attempt[attempt_num] = attempt[parent].copy()
            attempt[attempt_num].append(square2flat(myboard[i]))
            parent = attempt_num
            attempt_num += 1
            # print(attempt[parent])
            BFS(myboard[i], attempt, attempt_num + i, parent, k)
示例#5
0
def delete(judo, input):
    """wrapper for judo class read function.
    """
    verbose("{} command initiated".format(input.command), input.verbose)
    verbose("judo file: {}".format(input.command_arg), input.verbose)

    judo.delete(input.command_arg)
示例#6
0
 def getImage(self):
     try:
         image=self.images.get(True,0.1)
         self.lastImage=image
         return image
     except Queue.Empty:
         verbose('MJPG image queue is empty!')
     return self.lastImage
示例#7
0
def td_superoperator(N, E, J, gamma, gammabar, maxtime, dt):
    import numpy as np
    import scipy.linalg.lapack as lapack
    import scipy.linalg as la
    from superoperator import get_superoperator
    from verbose import verbose

    # Generate super density matrix time evolution operator
    L = get_superoperator(N, E, J, gamma, gammabar)

    # Diagonalize L
    Lw = lapack.flapack.zgeev(np.asfortranarray(L, dtype='cfloat'))
    w = Lw[0]
    v = Lw[2]
    #w,v = la.eig(L)
    #w = -1j*w
    # Make sure v is normalized
    # norm = np.zeros((N**2,1))
    # for n in range(N**2):
    #     for m in range(N**2):
    #         norm[n] = norm[n] + np.abs(v[m,n]*np.conj(v[m,n]))
    #     v[:,n] = v[:,n]/np.sqrt(norm[n])

    # Find weights based on initial condition p(t=0) = |1>
    alpha = np.sqrt(np.multiply(v[0, :], np.conj(v[0, :])))
    alpha = np.zeros((N**2, 1))
    alpha[:, 0] = np.divide(1, v[0, :])
    alpha[:, 0] = np.divide(
        alpha[:, 0], np.sum(np.multiply(alpha[0, :], np.conj(alpha[0, :]))))
    # Check initial condition
    Init = np.zeros((N**2, 1), dtype=complex)

    for n in range(N**2):
        Init[:, 0] = Init[:, 0] + alpha[n] * v[:, n]

    # Write info if N<3
    verbose(N, L, w, v, alpha, Init)

    # Setup super density matrix
    p = np.zeros((maxtime, N**2), dtype=complex)
    pe = np.zeros((maxtime, N**2))  # Stores expectation value

    # Calculate dynamics based on eigenvalues and vectors
    for t in range(maxtime):
        for m in range(N**2):
            fact = alpha[m] * np.exp(w[m] * dt * t)
            p[t, :] = p[t, :] + np.transpose(np.multiply(fact, v[:, m]))
        for m in range(N**2):
            pe[t, m] = np.sqrt(p[t, m].real**2 + p[t, m].imag**2)

    # Take trace
    pop = np.zeros((maxtime, N))
    for n in range(N):
        pop[:, n] = pe[:, n * N + n]

    return (pop)
示例#8
0
def degree_one(polynomes):
    print("Polynomial degree: 1")
    b = polynomes.get(1, 0)
    c = polynomes.get(0, 0)
    if c == 0:
        v.verbose("[Verbose] bx = 0 => " + tools.ft_ftoa(b) +
                  "x = 0\n[Verbose] x can only be 0")
        print("The solution is:")
        print("0")
    else:
        v.verbose("[Verbose] bx + c = 0 => " + tools.ft_ftoa(b) + "x + " +
                  tools.ft_ftoa(c) + " = 0\n[Verbose] x = -c / b => x = -" +
                  tools.ft_ftoa(c) + " / " + tools.ft_ftoa(b))
        print("The solution is:")
        print(tools.ft_round(-c / b))
示例#9
0
 def __runClient(self,url):
     self.url=url
     try:
         self.stream=urllib.urlopen(url)
     except IOError:
         self.startFlag.set()
         return
     self.imgbytes=''
     self.startFlag.set()
     while not self.stopFlag.is_set():
         image=self.__readImage()
         try:
             self.images.put(image,True,0.1)
         except Queue.Full:
             verbose('MJPG image dropped - queue is full!')
示例#10
0
    def __init__(self):

        # Set logging
        verbose(self, self.__class__.__name__, loglevel=10, screen=True)
        self.vout.debug("Logging enabled.")

        self.pagedata = None
        self.err = errors(self)

        # Set browser session
        self.br = requests.Session()

        #Set session headers
        headers = {}
        headers['content-type'] = "application/json"
        headers['User-agent'] = (
            'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1)' +
            ' Gecko/2008071615' + ' Fedora/3.0.1-1.fc9' + ' Firefox/3.0.1')
        self.br.headers.update(headers)
示例#11
0
def findAllPerms(board, k, attempt):
    #4 ways to move
    myboard[0] = actions.MoveLeft(board)
    myboard[1] = actions.MoveRight(board)
    myboard[2] = actions.MoveUp(board)
    myboard[3] = actions.MoveDown(board)
    for i in range(0, 4):
        verbose("Flatboard is: " + flatboard_spaceless(myboard[i]))
        if (flatboard_spaceless(myboard[i]) in board_tracker
            ):  # board configuration is already saved. Move on
            verbose("Board configuration is already saved.")
            #return
        elif (flatboard_spaceless(
                myboard[i]) == flatboard_spaceless(goal)):  #goal found
            print("Goal found!")
            print(flatboard_spaceless(myboard[i]))
            board_tracker[k] = flatboard_spaceless(myboard[i])
            k = k + 1
            return
        else:
            verbose("Adding board to list")
            board_tracker[k] = flatboard_spaceless(
                myboard[i])  # board configuration is not saved yet. Save it
            k = k + 1
            findAllPerms(myboard[i], k)
def MoveLeft(board):
    #Moves blank tile left, if possible
    #board=CurrentNode

    num_rows = len(board)  #one side of the puzzle
    num_cols = len(board)

    [blank_row,
     blank_col] = np.where(board == 0)  #Find the location of the blank space

    if (blank_col == 0):  #Blank spot is on the left edge; cannot be moved left
        verbose(
            "Blank space is at the left edge of the board and cannot be moved left."
        )
        return board

    else:
        verbose("Moving 1 square to the left")
        newBoard = np.copy(board)
        newBoard[blank_row, blank_col] = board[blank_row, blank_col - 1]
        newBoard[blank_row, blank_col - 1] = 0  #board[blank_row,blank_col]
        return newBoard
示例#13
0
文件: model.py 项目: pf4d/issm
    def __init__(self):  #{{{

        # classtype=model.properties

        # for classe in dict.keys(classtype):
        # 	print classe
        # 	self.__dict__[classe] = classtype[str(classe)]

        self.mesh = mesh2d()
        self.mask = mask()
        self.geometry = geometry()
        self.constants = constants()
        self.smb = SMBforcing()
        self.basalforcings = basalforcings()
        self.materials = matice()
        self.damage = damage()
        self.friction = friction()
        self.flowequation = flowequation()
        self.timestepping = timestepping()
        self.initialization = initialization()
        self.rifts = rifts()
        self.slr = slr()

        self.debug = debug()
        self.verbose = verbose()
        self.settings = settings()
        self.toolkits = toolkits()
        self.cluster = generic()

        self.balancethickness = balancethickness()
        self.stressbalance = stressbalance()
        self.groundingline = groundingline()
        self.hydrology = hydrologyshreve()
        self.masstransport = masstransport()
        self.thermal = thermal()
        self.steadystate = steadystate()
        self.transient = transient()
        self.levelset = levelset()
        self.calving = calving()
        self.gia = giaivins()

        self.autodiff = autodiff()
        self.inversion = inversion()
        self.qmu = qmu()
        self.amr = amr()

        self.results = results()
        self.outputdefinition = outputdefinition()
        self.radaroverlay = radaroverlay()
        self.miscellaneous = miscellaneous()
        self.private = private()
示例#14
0
def MoveUp(board):
    #Moves blank tile up, if possible
    #Convert to a square array
    board = flat2square(board)

    num_rows = len(board)  #one side of the puzzle
    num_cols = len(board)

    [blank_row,
     blank_col] = np.where(board == 0)  #Find the location of the blank space

    if (blank_row == 0):  #Blank spot is on the top edge; cannot be moved up
        verbose(
            "Blank space is at the top edge of the board and cannot be moved up."
        )
        return  #board

    else:
        verbose("Moving 1 square up")
        newBoard = np.copy(board)
        newBoard[blank_row, blank_col] = board[blank_row - 1, blank_col]
        newBoard[blank_row - 1, blank_col] = 0
        newBoard = square2flat(newBoard)
        return newBoard
示例#15
0
def k_anonymity_top_down(table_group: Group, k: int) -> List[Group]:
    if table_group.size() <= k:
        return [table_group]

    verbose('--- Calculating k-anonymity top-down ---')
    groups_to_anonymize = [table_group]
    less_than_k_anonymized_groups = []
    k_or_more_anonymized_groups = []
    min_max_diff_g = table_group.get_min_max_diff()
    while len(groups_to_anonymize) > 0:
        group_to_anonymize = groups_to_anonymize.pop(0)
        group_list = group_partition(group_to_anonymize, k, min_max_diff_g)

        both_have_less = True
        for group in group_list:
            if group.size() >= k:
                both_have_less = False
        if not both_have_less:
            for group in group_list:
                if group.size() > k:
                    groups_to_anonymize.append(group)
                elif group.size() == k:
                    k_or_more_anonymized_groups.append(group)
                else:
                    less_than_k_anonymized_groups.append(group)
        else:
            k_or_more_anonymized_groups.append(group_to_anonymize)

    verbose('--- Postprocessing k-anonymity top-down')
    for ag in k_or_more_anonymized_groups:
        verbose('k or more:' + str(ag.shape()) + '; company codes:' +
                str(ag.ids))
    for ag in less_than_k_anonymized_groups:
        verbose('less than k:' + str(ag.shape()) + '; company codes:' +
                str(ag.ids))

    k_anonymity_top_down_postprocessing(less_than_k_anonymized_groups,
                                        k_or_more_anonymized_groups,
                                        min_max_diff_g, k)

    return k_or_more_anonymized_groups
示例#16
0
def degree_two(polynomes):
    print("Polynomial degree: 2")
    a = 0
    b = 0
    c = 0
    if 2 in polynomes:
        a = polynomes[2]
    if 1 in polynomes:
        b = polynomes[1]
    if 0 in polynomes:
        c = polynomes[0]
    v.verbose('Discriminant formule: b^2 - 4ac')
    v.verbose('Discriminant equation: ' + str(b) + '^2 - 4 * ' + str(a) +
              ' * ' + str(c))
    discriminant = (b * b) - 4 * a * c
    v.verbose('Discriminant : ' + str(discriminant))
    if discriminant < 0:
        print(
            'Discriminant is strictly negatif, there is no real solution but two complex :'
        )
        v.verbose(
            'Solution formules : x1 = (-b-i√∆)/(2a) et x2 = (-b+i√∆)/(2a)')
        x1 = "(" + str(-b) + " − i" + str(
            tools.sqrt(1, discriminant * -1, None, 0)) + ") / " + str(2 * a)
        x2 = "(" + str(-b) + " + i" + str(
            tools.sqrt(1, discriminant * -1, None, 0)) + ") / " + str(2 * a)
        print(x1)
        print(x2)
    if discriminant == 0:
        print('Discriminant is equal to zero, there is one solution :')
        v.verbose('Solution formule : x = -b/(2a)')
        v.verbose('Solution equation : x = -' + str(b) + '/ ( 2 * ' + str(a) +
                  ' )')
        x = (-b) / (2 * a)
        print('The solution is :\n', tools.ft_round(x))
    if discriminant > 0:
        print('Discriminant is strictly positive, the two solutions are :')
        v.verbose('Solution formules : x1 = (-b-√∆)/(2a) et x2 = (-b+√∆)/(2a)')
        x1 = (-b - (tools.sqrt(1, discriminant, None, 0))) / (2 * a)
        x2 = (-b + (tools.sqrt(1, discriminant, None, 0))) / (2 * a)
        print(tools.ft_round(x1))
        print(tools.ft_round(x2))
示例#17
0
def create_p_anonymity_tree(group: Group, p: int, max_level: int,
                            pr_len: int) -> Dict[str, List[Node]]:
    """
    The algorithm is implemented in a non-recursive way because keeping the entire tree structure is not needed
    as we only use the leaf nodes.
    The nodes_to_process is the list of nodes which have not already been processed.
    As nodes are labeled as good or bad leaves, they are added to the good_leaves or bad_leaves lists, respectively.
    The new_nodes_to_process flag indicates whether during the current cycle are new nodes are created by splits.
    If there are new nodes, the nodes_to_process list is updated and those new nodes are processed.
    A dictionary containing two keys is returned:
    - the first key is "good leaves" and contains the list of good leaf nodes, and
    - the second key is "bad leaves" and contains the list of bad leaf nodes.
    """
    verbose(
        'Starting "create tree" step (p: {}, max PR level: {}, PR length: {}) on the following rows:'
        .format(p, max_level, pr_len))
    for i, row in enumerate(group.group_table):
        verbose("{}: {}".format(group.ids[i], row))
    # Initialize nodes list with the starting node, corresponding to the group
    nodes_to_process = [create_node_from_group(group, pr_len)]
    new_nodes_to_process: List[Node] = []
    good_leaves: List[Node] = []
    bad_leaves: List[Node] = []

    # Node splitting
    while nodes_to_process:
        debug("New nodes to process found")
        new_nodes_to_process = []
        for n in nodes_to_process:
            n_id = n.id
            n_size = n.size()
            if n_size < p:
                debug("Node {} labeled bad leaf (size: {})".format(
                    n_id, n_size))
                bad_leaves.append(n)
            elif n.level == max_level:
                debug(
                    "Node {} labeled good leaf for reaching maximum PR level (size: {})"
                    .format(n_id, n_size))
                good_leaves.append(n)
            elif n_size < 2 * p:
                debug("Node {} labeled good leaf for size (size: {})".format(
                    n_id, n_size))
                good_leaves.append(n)
                n.maximize_level(max_level)
            else:
                debug("Node {} big enough to be split (size: {})".format(
                    n_id, n_size))
                child_nodes = n.split()
                # Split not possible
                if len(child_nodes) < 2 or max(child.size()
                                               for child in child_nodes) < p:
                    debug(
                        "Node {} labeled good leaf: split produced only one node or no child node had size >= p"
                        .format(n_id))
                    good_leaves.append(n)
                # Split possible
                else:
                    debug("Split was successful")
                    TG_nodes: List[Node] = []
                    TB_nodes: List[Node] = []
                    total_TB_size = 0
                    debug("Checking tentative node sizes:")
                    for child in child_nodes:
                        if child.size() < p:
                            TB_nodes.append(child)
                            total_TB_size += child.size()
                            debug(
                                "Node {} is a tentative bad node (size: {}), total TB nodes size: {}"
                                .format(child.id, child.size(), total_TB_size))
                        else:
                            TG_nodes.append(child)
                            debug(
                                "Node {} is a tentative good node (size: {})".
                                format(child.id, child.size()))

                    new_nodes_to_process.extend(TG_nodes)

                    if total_TB_size >= p:
                        debug(
                            "Tentative bad nodes are big enough to be merged")
                        child_merge = merge_child_nodes(TB_nodes)
                        new_nodes_to_process.append(child_merge)
                    else:
                        debug(
                            "Tentative bad nodes are not big enough to be merged"
                        )
                        new_nodes_to_process.extend(TB_nodes)
        nodes_to_process = new_nodes_to_process

    verbose(
        'The "create tree" step produced the following good leaves:\n{}\nand the following bad leaves:\n{}'
        .format([n.id for n in good_leaves], [n.id for n in bad_leaves]))
    return good_leaves, bad_leaves
示例#18
0
def recycle_bad_leaves(good_leaves: List[Node], bad_leaves: List[Node],
                       p: int) -> List[Node]:
    """
    "Recycle bad leaves" step of the KAPRA algorithm, which merges bad leaves creating good ones.
    This function returns a list of all good leaf nodes.
    """
    verbose('Starting "recycle bad leaves" phase')
    # If there are no bad leaves, then this step is not needed
    if not bad_leaves:
        verbose('No bad leaves found: no "recycle bad leaves" step needed')
        return good_leaves

    # Preparation: bad leaves are sorted in different lists depending on their level
    bad_leaves_by_level: Dict[int, List[Node]] = {}
    debug("Sorting bad leaves by level:")
    for bad_leaf in bad_leaves:
        if bad_leaf.level in bad_leaves_by_level:
            bad_leaves_by_level[bad_leaf.level].append(bad_leaf)
        else:
            bad_leaves_by_level[bad_leaf.level] = [bad_leaf]
    for level in bad_leaves_by_level:
        debug("Level {} bad leaves: {}".format(
            level, [n.id for n in bad_leaves_by_level[level]]))

    current_level = max(bad_leaves_by_level)

    # Adding empty lists for levels with no leaves to prevent errors
    for level in range(current_level):
        if level not in bad_leaves_by_level:
            bad_leaves_by_level[level] = []

    debug("Maximum bad leaf level: {}".format(current_level))
    bad_rows = sum(bad_leaf.size() for bad_leaf in bad_leaves)
    while bad_rows >= p:
        debug("{} bad rows to process".format(bad_rows))
        debug("Processing bad leaves of level {}:".format(current_level))
        for n in bad_leaves_by_level[current_level]:
            debug('Leaf {}: size {}, pr "{}"'.format(n.id, n.size(), n.pr))
        leaves_by_pr: Dict[str, Node] = {}
        for bad_leaf in bad_leaves_by_level[current_level]:
            if bad_leaf.pr not in leaves_by_pr:
                debug('New PR "{}" found in bad leaf {}'.format(
                    bad_leaf.pr, bad_leaf.id))
                leaves_by_pr[bad_leaf.pr] = bad_leaf
            # If there are other bad leaves with the same PR, merge them
            else:
                merging_leaf = leaves_by_pr[bad_leaf.pr]
                verbose('Merging leaf {} to leaf {} (PR: "{}")'.format(
                    bad_leaf.id, merging_leaf.id, merging_leaf.pr))
                merging_leaf.extend_table_with_node(bad_leaf)

        debug("The following leaves were produced:")
        for leaf in leaves_by_pr.values():
            debug("Leaf {}: size {}, ids {}".format(leaf.id, leaf.size(),
                                                    leaf.row_ids))

        for leaf in leaves_by_pr.values():
            # If the leaf is not smaller than p, then it is a good leaf
            if leaf.size() >= p:
                good_leaves.append(leaf)
                bad_rows -= leaf.size()
                debug("Leaf {} is a good leaf, {} bad rows remaining".format(
                    leaf.id, bad_rows))
            # Otherwise its level is decreased and it will be checked in the next step for a possible merge
            else:
                debug(
                    "Leaf {} is a bad leaf: its SAX level is decreased".format(
                        leaf.id, bad_rows))
                leaf.level -= 1
                row = leaf.table[0]
                leaf.pr = SAX(row, leaf.level, leaf.pr_len())
                bad_leaves_by_level[leaf.level].append(leaf)
        current_level -= 1

    if bad_rows == 0:
        verbose('No rows were suppressed in the "recycle bad leaves" phase')
    else:
        verbose(
            str(bad_rows) +
            ' rows were suppressed in the "recycle bad leaves" phase: they could not be merged'
        )

    verbose(
        'The "recycle bad leaves" phase produced the following good leaves:')
    for n in good_leaves:
        verbose('Node {}: size {}, level {}, PR "{}", ids {}'.format(
            n.id, n.size(), n.level, n.pr, n.row_ids))
    return good_leaves
示例#19
0
#Calving
md.calving.calvingrate = np.zeros((md.mesh.numberofvertices))
md.levelset.spclevelset = np.nan * np.ones((md.mesh.numberofvertices))

#Friction
md.friction.coefficient = 20. * np.ones((md.mesh.numberofvertices))
md.friction.coefficient[np.where(md.mask.groundedice_levelset < 0.)[0]] = 0.
md.friction.p = np.ones((md.mesh.numberofelements))
md.friction.q = np.ones((md.mesh.numberofelements))

#Numerical parameters
md.stressbalance.viscosity_overshoot = 0.0
md.masstransport.stabilization = 1.
md.thermal.stabilization = 1.
md.verbose = verbose(0)
md.settings.waitonlock = 30
md.stressbalance.restol = 0.05
md.steadystate.reltol = 0.05
md.stressbalance.reltol = 0.05
md.stressbalance.abstol = np.nan
md.timestepping.time_step = 1.
md.timestepping.final_time = 3.

#GIA:
md.gia.lithosphere_thickness = 100. * np.ones((md.mesh.numberofvertices))
# in km
md.gia.mantle_viscosity = 1. * 10**21 * np.ones((md.mesh.numberofvertices))
# in Pa.s
md.materials.lithosphere_shear_modulus = 6.7 * 10**10
# in Pa
示例#20
0
def k_anonymity_bottom_up(table_group: Group, k: int) -> List[Group]:
    list_of_groups = []
    min_max_diff = table_group.get_min_max_diff()

    # create a group for each tuple
    for i in range(table_group.size()):
        group_with_single_tuple = create_empty_group()
        row, row_id, row_pr_val = table_group.get_all_attrs_at_index(i)
        group_with_single_tuple.add_row_to_group(row, row_id, row_pr_val)
        list_of_groups.append(group_with_single_tuple)

    # do k-anonymity on groups
    smallest_group_i = find_smallest_group_index(list_of_groups)
    while list_of_groups[smallest_group_i].size() < k:
        group_to_check = list_of_groups.pop(smallest_group_i)

        index_of_merging_group = find_index_of_group_to_be_merged(
            group_to_check, list_of_groups, min_max_diff)
        list_of_groups[index_of_merging_group].merge_group(group_to_check)
        smallest_group_i = find_smallest_group_index(list_of_groups)

    # visualize_envelopes(list_of_groups)
    list_of_groups_to_be_splitted = []
    for i in reversed(range(len(list_of_groups))):
        if list_of_groups[i].size() >= 2 * k:
            list_of_groups_to_be_splitted.append(list_of_groups.pop(i))

    verbose('Groups to split: {}'.format(list_of_groups_to_be_splitted))
    while len(list_of_groups_to_be_splitted) > 0:
        group_to_be_split = list_of_groups_to_be_splitted.pop()

        # group_to_be_split.size == 14, k == 4
        verbose('Current splitting group: {} {}'.format(
            group_to_be_split.size(), group_to_be_split))
        parts_into_split = int(group_to_be_split.size() / k)
        verbose(
            'Parts into group has to be split: {}'.format(parts_into_split))
        dim_of_splitted_parts = int(group_to_be_split.size() /
                                    parts_into_split)
        verbose('Dimension of parts into the group has to be split: '.format(
            dim_of_splitted_parts))

        for p in range(parts_into_split):
            index = group_to_be_split.size() - 1
            splitted_group = create_empty_group()

            for g in range(dim_of_splitted_parts):
                row, row_id, row_pr_val = group_to_be_split.pop_row(index)
                splitted_group.add_row_to_group(row, row_id, row_pr_val)
                verbose('Splitting group: {}, at index: {}'.format(
                    splitted_group, index))
                index -= 1

            if p == parts_into_split - 1:
                while group_to_be_split.size() > 0:
                    row, row_id, row_pr_val = group_to_be_split.pop_row(0)
                    splitted_group.add_row_to_group(row, row_id, row_pr_val)
                list_of_groups.append(splitted_group)
            else:
                list_of_groups.append(splitted_group)

    verbose('Updated list (after splitting): {} {}'.format(
        len(list_of_groups), list_of_groups))

    return list_of_groups
示例#21
0
def degree_two(polynomes):
    print("Polynomial degree: 2")
    a = 0
    b = 0
    c = 0
    if 2 in polynomes:
        a = polynomes[2]
    if 1 in polynomes:
        b = polynomes[1]
    if 0 in polynomes:
        c = polynomes[0]
    v.verbose('Discriminant formule: b^2 - 4ac')
    v.verbose('Discriminant equation: ' + str(b) + '^2 - 4 * ' + str(a) +
              ' * ' + str(c))
    discriminant = (b * b) - 4 * a * c
    v.verbose('Discriminant : ' + str(discriminant))
    if discriminant < 0:
        print(
            "The discriminant is strictly negative, the equation has no real solution, only 2 complex solutions:"
        )
        v.verbose(
            'Solution formules : x1 = (-b-i√-∆)/(2a) et x2 = (-b+i√-∆)/(2a)')
        print("(" + str(-b) + " − i" + str(tools.sqrt(-discriminant)) +
              ") / " + str(2 * a))
        print("(" + str(-b) + " + i" + str(tools.sqrt(-discriminant)) +
              ") / " + str(2 * a))
        sys.exit()
    if discriminant == 0:
        print('Discriminant is equal to zero, there is one solution :')
        v.verbose('Solution formule : x = -b/(2a)')
        v.verbose('Solution equation : x = -' + str(b) + '/ ( 2 * ' + str(a) +
                  ' )')
        x = (-b) / (2 * a)
        print('The solution is :\n', x)
    if discriminant > 0:
        print('Discriminant is strictly positive, the two solutions are :')
        v.verbose('Solution formules : x1 = (-b-√∆)/(2a) et x2 = (-b+√∆)/(2a)')
        x1 = (-b - (tools.sqrt(discriminant))) / (2 * a)
        x2 = (-b + (tools.sqrt(discriminant))) / (2 * a)
        y1 = str(x1)
        y2 = str(x2)
        j = y1.find(".")
        k = y2.find(".")
        print(y1[:j + 5])
        print(y2[:k + 5])
示例#22
0
import verbose

verbose.setLevels(
    99)  # vlist can be a str: "2,readcmds,blah" or list [2,"readcmds","blah"]
verbose.openFile(
    "test_verbose.log",
    "w")  # output to a file (open with truncate); default: sys.stderr output
verbose.verbose(
    [2, "loop"],
    "message")  # output if verbose level >= 2 or one verbose string is "loop"
verbose.verbose(["info"], "message")  # output if one verbose string is "info"
verbose.verbose([99], "message")  # output if verbose level >= 99
verbose.verbose("99", "message")  # output if verbose level >= 99
verbose.verbose(99, "message")  # output if verbose level >= 99
verbose.isLevel(
    "99,blah")  # True if verbose level >= 99 or verbose str is "blah"
verbose.closeFile()
示例#23
0
def create(judo, input):
    """wrapper for judo class read function.
    """
    verbose("{} command initiated".format(input.command), input.verbose)
    verbose("secret name: {}".format(input.command_arg), input.verbose)
    if input.number:
        verbose("number of shards: {}".format(input.number), input.verbose)
    else:
        print("Please specify the number of shards with --number or -n")
        sys.exit(1)

    if input.input:
        verbose("secret to encrypt: {}".format(input.input), input.verbose)
    else:
        if not input.inputfile:
            print("No secret provided. specify either --input or --inputfile")
            sys.exit(1)

    if input.inputfile:
        verbose("file to encrypt: {}".format(input.inputfile), input.verbose)

    if input.quorum:
        verbose("quorum: {}".format(input.quorum), input.verbose)
    else:
        print("You must specify --quorum <value> or -m <value>")
        sys.exit(1)

    if input.expires:
        verbose("expiration: {}".format(input.expires), input.verbose)

    if input.ip:
        verbose("allowed_ips: {}".format(input.ip), input.verbose)

    judo.create(input.command_arg,
                shards=input.number,
                input=input.input,
                min_shards=input.quorum,
                input_file=input.inputfile,
                expiration=input.expires,
                allowed_ips=input.ip)
示例#24
0
    # Use a MacAyeal flow model
    md = setflowequation(md, "SSA", "all")

    # Save model
    savevars("Pig/Models/PIG_Parameterization_py.dat", {"md": md})

elif step == 4:
    md = loadmodel(path="Pig/Models/PIG_Parameterization_py.dat")

    # Control general
    md.inversion.iscontrol = 1
    md.inversion.maxsteps = 20
    md.inversion.maxiter = 40
    md.inversion.dxmin = 0.1
    md.inversion.gttol = 1.0e-4
    md.verbose = verbose("control", True)

    # Cost functions
    md.inversion.cost_functions = [101, 103, 501]
    md.inversion.cost_functions_coefficients = np.ones(
        shape=(md.mesh.numberofvertices, 3))
    md.inversion.cost_functions_coefficients[:, 0] = 1
    md.inversion.cost_functions_coefficients[:, 1] = 1
    md.inversion.cost_functions_coefficients[:, 2] = 8e-15

    # Controls
    md.inversion.control_parameters = ["FrictionCoefficient"]
    md.inversion.min_parameters = 1 * np.ones(shape=(md.mesh.numberofvertices,
                                                     1))
    md.inversion.max_parameters = 200 * np.ones(
        shape=(md.mesh.numberofvertices, 1))
示例#25
0
def postprocess(good_leaves: List[Node], bad_leaves: List[Node]) -> List[Node]:
    """
    The postprocessing phase takes care of the bad leaves integrating them into the good leaves.
    The modified good leaves are then returned.
    """
    if not good_leaves:
        print(
            "WARNING: no good leaves found, not enough rows in the anonymizing group?"
        )
    elif not bad_leaves:
        verbose("No bad leaves found: no postprocessing needed")
    elif len(good_leaves) == 1:
        verbose("Starting postprocessing phase")
        good = good_leaves[0]
        verbose(
            "Only 1 good leaf (node {}): adding all bad leaf rows to the only good leaf"
            .format(good.id))
        for bad in bad_leaves:
            debug("Processing bad leaf {}".format(bad.id))
            debug("Similarity to good node: {})".format(
                compute_pattern_similarity(bad.pr, good.pr, bad.level,
                                           good.level)))
            good.extend_table_with_node(bad)
    else:
        verbose("Starting postprocessing phase")
        bad_leaves.sort(key=lambda node: node.size())
        for bad in bad_leaves:
            debug("Processing bad leaf {}".format(bad.id))
            max_similarity = None
            most_similar_good = None
            for good in good_leaves:
                similarity = compute_pattern_similarity(
                    bad.pr, good.pr, bad.level, good.level)
                if max_similarity is None or similarity > max_similarity:
                    max_similarity = similarity
                    most_similar_good = good
                    debug(
                        "Updating most similar node to node {} (better similarity: {})"
                        .format(most_similar_good.id, max_similarity))
                elif similarity == max_similarity and good.size(
                ) < most_similar_good.size():
                    most_similar_good = good
                    debug(
                        "Updating most similar node to node {} (smaller size: {})"
                        .format(most_similar_good.id,
                                most_similar_good.size()))
            most_similar_good.extend_table_with_node(bad)

    verbose("The postprocessing phase produced the following good leaves:")
    for n in good_leaves:
        verbose('Node {}: size {}, level {}, PR "{}", ids {}'.format(
            n.id, n.size(), n.level, n.pr, n.row_ids))
    return good_leaves