示例#1
0
def Constructor(file, instance):
    """ Constructor function. Reads a file and builds the Instance Object.

        Args:
            file      (File)                 - The instance file to base the instance object off of.
            instance  (Instance.Instance)    - The instance object to be built

        Returns:
            instance  (Instance.Instance)    - The built instance object

        Globals:
            None

        Called By:
            init()

        Calls:
            parser()
    """
    start = file.readline()
    for id in range(int(start)):
        line = file.readline()
        x, y = parser(line)
        instance.Centers.append(Instance.Centers(id, x, y))
        print(str(instance.Centers[id].x) + ", " + str(instance.Centers[id].y))

    line = file.readline()
    for x in range(int(line)):
        line = file.readline()
        x, y = parser(line)
        instance.Pointers.append(Instance.Points(x, y))

    return instance
 def setUp(self):
     self.graph1 = createGraphFromString(
         "#########\n#[email protected]#\n#########\n")
     self.graph2 = createGraphFromString(
         "########################\n#[email protected].#\n######################.#\n#d.....................#\n########################\n"
     )
     self.graph3 = createGraphFromString(
         "########################\n#...............b.C.D.f#\n#.######################\n#[email protected]#\n########################\n"
     )
     self.graph4 = createGraphFromString(
         "#################\n#i.G..c...e..H.p#\n########.########\n#j.A..b...f..D.o#\n########@########\n#k.E..a...g..B.n#\n########.#########l.F..d...h..C.m#\n#################\n"
     )
     self.graph5 = createGraphFromString(
         "########################\n#@..............ac.GI.b#\n###d#e#f################\n###A#B#C################\n###g#h#i################\n########################\n"
     )
     self.instance1 = Instance(self.graph1)
     self.instance1.updateTokens()
     self.instance2 = Instance(self.graph2)
     self.instance2.updateTokens()
     self.instance3 = Instance(self.graph3)
     self.instance3.updateTokens()
     self.instance4 = Instance(self.graph4)
     self.instance4.updateTokens()
     self.instance5 = Instance(self.graph5)
     self.instance5.updateTokens()
示例#3
0
def senToInstan(S, ListInstance):
    sentence = S
    e1List = sentence.e1_List
    e2List = sentence.e2_List
    for e1 in e1List:
        for e2 in e2List:
            f = 0
            # e1在前面
            if e1[1] <= e2[1]:
                for word in sentence.segSentence2[e1[1] + 1:e2[1]]:
                    # 判断了这两个词是不是在一句话中
                    if word in ['.', '。', ';', ';']:
                        f = 1
                        break
                if f == 0:
                    # 添加一个实例
                    instance = Instance(S, e1, e2, flag=0)
                    ListInstance.append(instance)
            # e2在后面
            if e1[1] > e2[1]:
                for word in sentence.segSentence2[e2[1] + 1:e1[1]]:
                    if word in ['.', '。', ';', ';']:
                        f = 1
                        break
                if f == 0:
                    instance = Instance(S, e1, e2, flag=1)
                    ListInstance.append(instance)
    return ListInstance
示例#4
0
 def accept(self):
     self.preview.clean()
     # Create new ship instance
     obj = App.ActiveDocument.addObject("Part::FeaturePython", "Ship")
     ship = Instance.Ship(obj, self.solids)
     Instance.ViewProviderShip(obj.ViewObject)
     # Set main dimensions
     obj.Length = self.form.length.value()
     obj.Beam = self.form.beam.value()
     obj.Draft = self.form.draft.value()
     # Discretize it
     App.ActiveDocument.recompute()
     return True
示例#5
0
def parse_dimacs(instance_file):
    instance = Instance()
    current = []
    read = 0
    for instance_line in instance_file:
        if instance.variables == -1 or instance.weights == []:
            if instance_line[0] == 'c':
                continue
            elif instance_line[0] == 'p':
                tokens = instance_line.split()
                if len(tokens) != 4:
                    raise BadDIMACSFormatError(f"Not enough parameters in problem line, found {len(tokens)}") 

                if tokens[1] != "cnf":
                    raise BadDIMACSFormatError(f"Not cnf format, is {tokens[0]}") 

                instance.variables = int(tokens[2])
                instance.clauses = int(tokens[3])
                continue
            elif instance_line[0] == 'w':
                tokens = instance_line.split()

                for token in tokens[1:]:
                    # print(token)
                    instance.weights.append(int(token))
                continue
            else:
                raise BadDIMACSFormatError(f"Invalid start of line char: {instance_line[0]}")


        end = False
        tokens = instance_line.split()
        for token in tokens:

            if token == "0":
                end = True
                break
            current.append(int(token))


        if end:
            instance.formula.append(current)
            current = []

            read += 1
            if read >= instance.clauses:
                break


    return instance
示例#6
0
def init(instanceDir, file):
    """ Setup function. Calls the Instance Constructor.

        Args:
            instanceDir    (Dir)                  - The Directory containig the instance files to use to build the instance objects.
            file           (Str)                  - The file to use.

        Returns:
            instance        (Instance.Instance)     - The instance object built

        Globals:
            None

        Called By:
            Main.init()

        Calls:
            Constructor
    """
    instance = Instance.Instance()
    filepath = instanceDir + "\\" + file
    with open(filepath, 'r') as inst:
        Constructor(inst, instance)

    inst.close()
    return instance
示例#7
0
 def accept(self):
     """Create the ship instance"""
     self.preview.clean()
     obj = App.ActiveDocument.addObject("Part::FeaturePython", "Ship")
     ship = Instance.Ship(obj, self.solids)
     Instance.ViewProviderShip(obj.ViewObject)
     mw = self.getMainWindow()
     form = mw.findChild(QtGui.QWidget, "TaskPanel")
     form.length = self.widget(QtGui.QDoubleSpinBox, "Length")
     form.breadth = self.widget(QtGui.QDoubleSpinBox, "Breadth")
     form.draft = self.widget(QtGui.QDoubleSpinBox, "Draft")
     obj.Length = '{} m'.format(form.length.value())
     obj.Breadth = '{} m'.format(form.breadth.value())
     obj.Draft = '{} m'.format(form.draft.value())
     App.ActiveDocument.recompute()
     return True
def parametrized(instance_file, algorithm):
    instances = {}
    solutions = {}
    relative_errors = []

    for instance_line in instance_file:
        instance = Instance(instance_line.rstrip('\n'))
        instances.update({instance.get_id(): instance})

    print("knapsack_id,algorithm,no_items,price,time_ms")

    # backpack_size = next(iter(solutions.values())).get_no_items()
    for id_inst, instance in instances.items():
        if algorithm == "heuristic":
            computed = instance.with_heuristic()
        elif algorithm == "branch_bound":
            method = BranchBound()
            computed = method.solve(instance)
        elif algorithm == "genetic":
            method = Genetic()
            computed = method.solve(instance)
        elif algorithm == "dynamic":
            computed = instance.dynamic()
        elif algorithm == "fptas":
            computed = instance.fptas(75)
        elif algorithm == "brute_force":
            computed = instance.brute_force()
        time = measured_time[-1]['time']
        print(
            f'{id_inst},{algorithm},{instance.no_items},{computed.get_cost()},{time}'
        )
示例#9
0
 def add_instance(self,instance):
    if self.get_instances() is None:
       self._instances = [instance]
    elif instance not in self.get_instances():
       self._instances.append(instance)
    else:
       for i in range(0,len(self.get_instances())):
          if self.get_instances()[i] == instance:
             self._instances[i] = Instance.load_aws_data(instance.to_json())
             break
示例#10
0
    def parse_instances(self, raw_instances):
        instances = []
        for raw_instance in raw_instances:
            start_time = self.parse_time(raw_instance, 'start')
            end_time = self.parse_time(raw_instance, 'end')

            if "colorId" in raw_instance.keys():
                colorId=raw_instance["colorId"]
            else:
                colorId="1"
            instances.append(ins.GoogleInstance(raw_instance['summary'], raw_instance['summary'], start_time, end_time, raw_instance["id"],colorId))
        return instances
def genetic(instance_file,
            xover_probability=0.4,
            mutation_probability=0.1,
            elitism_count=10,
            tournament_count=16,
            tournament_pool_size=2,
            generations=1000):
    instances = {}

    # print("xover_probability", xover_probability,
    #     "mutation_probability", mutation_probability,
    #     "elitism_count", elitism_count,
    #     "tournament_count", tournament_count,
    #     "tournament_pool_size", tournament_pool_size,
    #     "generations", generations)

    for instance_line in instance_file:
        instance = Instance(instance_line.rstrip('\n'))
        instances.update({instance.get_id(): instance})

    for id_inst, instance in instances.items():

        method = Genetic(xover_probability=xover_probability,
                         mutation_probability=mutation_probability,
                         elitism_count=elitism_count,
                         tournament_count=tournament_count,
                         tournament_pool_size=tournament_pool_size,
                         generations=generations,
                         verbose=True)
        computed = method.solve(instance)
        # print(f'{id_inst},genetic,{instance.no_items},{computed.get_cost()}')
        # print ("ge:", computed)

        method = BranchBound()
        computed = method.solve(instance)
        # print(f'{id_inst},branch,{instance.no_items},{computed.get_cost()}')
        # print ("Bb:", computed)
        # print("-----")

    pass
示例#12
0
def initLargeApp():
    global instances
    instances = []
    instances.append(Instance.Instance('C1.Medium Spot',      252, 60, 0.00046, True))
    instances.append(Instance.Instance('C1.XLarge Spot',      100,  28, 0.00186, True))
    instances.append(Instance.Instance('C1.Medium On-Demand', 252, 60, 0.00241, False))
    instances.append(Instance.Instance('C1.XLarge On-Demand', 100,  28, 0.00967, False))
    #TODO adjust number of slaves
    # setSlaves(500)

    global shortageMultiplier
    shortageMultiplier = 16.0

    global S3
    S3 = Storage.Storage(0,8) # copies per GB
    
    global FastestOnDemandRate
    FastestOnDemandRate = 500/29
    global CheapestOnDemandRate
    CheapestOnDemandRate = 500/61
    global FastestSpotRate
    FastestSpotRate = FastestOnDemandRate/2
示例#13
0
 def getList(self, conf):
     try:
         instList = helper.getInstList(self.conn, self.conf.filterMap)
     except:
         self.expList.append(sys.exc_info())
         return False
     #convert the instance dictionary into intrenal format
     for keys in instList.keys():
         for i, inst in enumerate(instList[keys]):
             tempInst = Instance.InstanceClass(inst, conf)
             instList[keys][i] = tempInst
             self.total += 1
     self.insts = instList
     return True
示例#14
0
def initFirefox():
    global instances
    instances = []
    instances.append(Instance.Instance('C1.Medium Spot',      63, 15, 0.00046, True))
    instances.append(Instance.Instance('C1.XLarge Spot',      25,  7, 0.00186, True))
    instances.append(Instance.Instance('C1.Medium On-Demand', 63, 15, 0.00241, False))
    instances.append(Instance.Instance('C1.XLarge On-Demand', 25,  7, 0.00967, False))
    #TODO adjust number of slaves
    # setSlaves(500)


    global shortageMultiplier
    shortageMultiplier = 4.0

    global S3
    S3 = Storage.Storage(0,33) # copies per GB
    
    global FastestOnDemandRate
    FastestOnDemandRate = 500/8
    global CheapestOnDemandRate
    CheapestOnDemandRate = 500/15
    global FastestSpotRate
    FastestSpotRate = FastestOnDemandRate/2
示例#15
0
def createShip(solids, L, B, T):
    """Create a new ship instance

    Position arguments:
    solids -- List of hull solid shapes
    L -- Ship length between perpendiculars
    B -- Ship Breadth
    T -- Ship design draft

    Returned value:
    The new ship object

    The solids can be easily extracted from an already existing object. For
    instance, to get the solids from the selected object simply type the
    following command:

    solids = Gui.ActiveDocument.ActiveObject.Object.Shape.Solids

    Regarding the Length, Breadth, and Draft, it is strongly recommended to use
    Units.parseQuantity method, e.g. The following obfuscated code snippet build
    such variables:

    import Units
    L = Units.parseQuantity("25.5 m")
    B = Units.parseQuantity("3.9 m")
    T = Units.parseQuantity("1.0 m")
    """
    obj = App.ActiveDocument.addObject("Part::FeaturePython", "Ship")
    ship = Instance.Ship(obj, solids)
    Instance.ViewProviderShip(obj.ViewObject)

    obj.Length = L
    obj.Breadth = B
    obj.Draft = T

    App.ActiveDocument.recompute()
    return obj
示例#16
0
                            rs.filter.surface)
get_obj = sort.scanObjectSort(num_timber, get_center_line, get_surface)

program_start = time.time()

# メンバ変数に格納する
center_line = get_obj[0]
all_surface = get_obj[1]
# all_mark = get_obj[2]

for i in range(0, num_timber):
    name_list.append(i)

# Step1: サーフィスと中心線を(個体数*Timberの種類)だけ複製。後でインスタンス変数に取り込むため、リストに格納する
#-----------------------------------------------------------------------------------------------------------------------
temp_center_line = inst.axis_instance(pop_num, center_line)
temp_surface = inst.surface_instance(pop_num, all_surface)
# temp_mark = inst.mark_instance(pop_num, all_mark)

# print("temp_surface", temp_surface)
print("temp_center_line", temp_center_line)

# Step2: Generateクラスのインスタンスを個体数だけ作成
#-----------------------------------------------------------------------------------------------------------------------
dic = {}
for foo in range(pop_num):
    dic['generate' + str(foo)] = foo

for i in range(pop_num):
    timber_num.append(i)
示例#17
0
# listfile = ['10hk48.clt']
# listfile = ['6i300.clt']
# listfile = ['10eil76.clt']
def secondsToStr(t):
    return "%d:%02d:%02d.%03d" % \
        reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
            [(t*1000,),1000,60,60])


for file in listfile:
    seeds = range(0, 30)
    for seed in seeds:
        start_time = time.time()

        instance = Instance(file, seed)

        if not instance.use:
            continue
        print(instance.name)
        population = instance.init(pop)
        result_file = open(instance.resultname, 'w')
        result_file.write("Generation \t" + instance.name + '\n')
        for x in range(gen):
            teacher = min(population, key=attrgetter('fitness'))
            #write to file
            result_file.write(str(x) + ' \t' + str(teacher.fitness) + '\n')
            diff = np.random.rand() * (teacher.subjects - np.random.randint(
                1, 3) * np.mean([x.subjects for x in population], axis=0))
            # buoc 1
            for y in range(pop):
示例#18
0
def FloatingArea(ship, draft, trim):
    """ Calculate ship floating area.
    @param ship Selected ship instance
    @param draft Draft.
    @param trim Trim in degrees.
    @return Ship floating area, and floating coefficient.
    """
    angle = math.radians(trim)
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    lines = []
    area = 0.0
    minX = None
    maxX = None
    maxY = 0.0
    cf = 0.0
    if not sections:
        return [0.0, 0.0]
    for i in range(0, len(sections)):
        # Get the section
        section = sections[i]
        if len(section) < 2:  # Empty section
            lines.append(0.0)
            continue
        # Get the position of the section
        x = xCoord[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            lines.append(0.0)
            continue
        maxX = x
        if not minX:
            minX = x
        # Get floating line length
        line = 0.0
        flag = True  # Even lines compute for floating areas, odd no
        j = len(section) - 1
        k = len(section[j]) - 1
        while k > 0:
            k = k - 1
            if flag:
                y0 = abs(section[j][k - 1].y)
                y1 = abs(section[j][k].y)
                line = line + (y1 - y0)
                maxY = max([maxY, y1, y0])
            flag = not flag
        if flag:  # Central body computation lefts
            y = abs(section[j][0].y)
            line = line + y
            maxY = max([maxY, y])
        lines.append(2.0 * line)  # 2x because only half ship is represented
        # Add area if proceed
        if i > 0:
            dx = xCoord[i] - xCoord[i - 1]
            x = 0.5 * (xCoord[i] + xCoord[i - 1])
            line = 0.5 * (lines[i] + lines[i - 1])
            area = area + line * dx
    if area:
        cf = area / ((maxX - minX) * 2.0 * maxY)
    return [area, cf]
        's', 'onto', 'over', 'since', 'than', 'through', 'to', 'under',\
        'until', 'up', 'upon', 'the',  'with', 'without']
etc_pivots = create_shallow_pivot_dict(ETC)
pivots_list.append(etc_pivots)

# go through all episodes
for ep_num in range(1, NUM_EPS + 1):
    print('Processing episode: ' + str(ep_num) + '/' + \
        str(NUM_EPS))

    # get instance text for this episode
    instance_text_filename = INSTANCES_FOLDER + (EP_NUMBER_FORMAT % ep_num)
    instance_texts = []
    with open(instance_text_filename, 'r') as instance_text_file:
        instance_texts = instance_text_file.readlines()

    # clear vector file for this episode
    vector_filename = VECTORS_FOLDER + (EP_NUMBER_FORMAT % ep_num)
    with open(vector_filename, 'w') as vector_file:
        vector_file.close()

    instance_i = 0
    # go through all instance text lines
    for instance_text in instance_texts:
        print('\tProcessing instance: ' + str(instance_i + 1) + '/' + \
            str(len(instance_texts)))
        # write vector for this instance to file
        instance = Instance(instance_text, label_to_nums, pivots_list)
        instance.write_vector_to_file(vector_filename)
        instance_i += 1
示例#20
0
def KBT(ship, draft, trim, roll=0.0):
    """ Calculate ship Keel to Bouyance center transversal distance.
    @param ship Selected ship instance
    @param draft Draft.
    @param trim Trim in degrees.
    @param roll Roll angle in degrees.
    @return [KBTy, KBTz]: \n
    KBTy : Transversal KB y coordinate \n
    KBTz : Transversal KB z coordinate
    """
    angle = math.radians(trim)
    rAngle = math.radians(roll)
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    areas = []
    vol = 0.0
    vMy = 0.0
    vMz = 0.0
    My = []
    Mz = []
    kb = [0.0, 0.0]
    if not sections:
        return [[], 0.0, 0.0]
    for i in range(0, len(sections)):
        # ------------------------------------
        # Board
        # ------------------------------------
        # Get the section
        section = sections[i]
        if len(section) < 2:  # Empty section
            areas.append(0.0)
            continue
        # Get the position of the section
        x = xCoord[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        aux = convertSection(section, x, Z)
        if not aux:
            areas.append(0.0)
            My.append(0.0)
            Mz.append(0.0)
            continue
        # Correct by roll angle
        pts = aux[len(aux) - 1]
        beam = pts[0].y
        for i in range(1, len(pts)):
            beam = max(beam, pts[i].y)
        Z = Z - beam * math.tan(rAngle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            areas.append(0.0)
            My.append(0.0)
            Mz.append(0.0)
            continue
        # Integrate area
        area = 0.0
        momy = 0.0
        momz = 0.0
        for j in range(0, len(section) - 1):
            for k in range(0,
                           min(len(section[j]) - 1,
                               len(section[j + 1]) - 1)):
                # y11,z11 ------- y01,z01
                #    |               |
                #    |               |
                #    |               |
                # y10,z10 ------- y00,z00
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = 0.5 * ((y00 - y10) + (y01 - y11))
                dz = 0.5 * ((z01 - z00) + (z11 - z10))
                y = 0.25 * (y00 + y10 + y01 + y11)
                z = 0.25 * (z01 + z00 + z11 + z10)
                area = area + dy * dz
                momy = momy + y * dy * dz
                momz = momz + z * dy * dz
            if (len(section[j]) < len(section[j + 1])):
                # y01,z01 ------- y11,z11
                #    |        __/
                #    |     __/
                #    |    /
                # y00,z00
                k = len(section[j]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y01 - y11
                dz = z01 - z00
                y = 0.33 * (y00 + y01 + y11)
                z = 0.33 * (z01 + z00 + z11)
                area = area + 0.5 * dy * dz
                momy = momy + y * 0.5 * dy * dz
                momz = momz + z * 0.5 * dy * dz
            elif (len(section[j]) > len(section[j + 1])):
                # y01,z01
                #    |    \__
                #    |       \__
                #    |          \
                # y00,z00 ------- y10,z10
                k = len(section[j + 1]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                dy = y00 - y10
                dz = z01 - z00
                y = 0.33 * (y00 + y01 + y10)
                z = 0.33 * (z01 + z00 + z10)
                area = area + 0.5 * dy * dz
                momy = momy + y * 0.5 * dy * dz
                momz = momz + z * 0.5 * dy * dz
            elif (len(section[j]) == 1):
                # y1,z1 -------
                #    |
                #    |
                #    |
                # y0,z0 -------
                k = 0
                y0 = abs(section[j][k].y)
                z0 = section[j][k].z
                y1 = abs(section[j + 1][k].y)
                z1 = section[j + 1][k].z
                dy = 0.5 * (y0 + y1)
                dz = z1 - z0
                y = 0.25 * (y1 + y0)
                z = 0.25 * (z1 + z0)
                area = area + dy * dz
                momy = momy + y * dy * dz
                momz = momz + z * dy * dz
        # ------------------------------------
        # StarBoard
        # ------------------------------------
        # Get the section
        section = sections[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        aux = convertSection(section, x, Z)
        if not aux:
            areas.append(0.0)
            My.append(0.0)
            Mz.append(0.0)
            continue
        # Correct by roll angle
        pts = aux[len(aux) - 1]
        beam = pts[0].y
        for i in range(1, len(pts)):
            beam = max(beam, pts[i].y)
        Z = Z + beam * math.tan(rAngle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            areas.append(0.0)
            My.append(0.0)
            Mz.append(0.0)
            continue
        # Integrate area
        for j in range(0, len(section) - 1):
            for k in range(0,
                           min(len(section[j]) - 1,
                               len(section[j + 1]) - 1)):
                # y11,z11 ------- y01,z01
                #    |               |
                #    |               |
                #    |               |
                # y10,z10 ------- y00,z00
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = 0.5 * ((y00 - y10) + (y01 - y11))
                dz = 0.5 * ((z01 - z00) + (z11 - z10))
                y = 0.25 * (y00 + y10 + y01 + y11)
                z = 0.25 * (z01 + z00 + z11 + z10)
                area = area + dy * dz
                momy = momy - y * dy * dz
                momz = momz + z * dy * dz
            if (len(section[j]) < len(section[j + 1])):
                # y01,z01 ------- y11,z11
                #    |        __/
                #    |     __/
                #    |    /
                # y00,z00
                k = len(section[j]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y01 - y11
                dz = z01 - z00
                y = 0.33 * (y00 + y01 + y11)
                z = 0.33 * (z01 + z00 + z11)
                area = area + 0.5 * dy * dz
                momy = momy - y * 0.5 * dy * dz
                momz = momz + z * 0.5 * dy * dz
            elif (len(section[j]) > len(section[j + 1])):
                # y01,z01
                #    |    \__
                #    |       \__
                #    |          \
                # y00,z00 ------- y10,z10
                k = len(section[j + 1]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                dy = y00 - y10
                dz = z01 - z00
                y = 0.33 * (y00 + y01 + y10)
                z = 0.33 * (z01 + z00 + z10)
                area = area + 0.5 * dy * dz
                momy = momy - y * 0.5 * dy * dz
                momz = momz + z * 0.5 * dy * dz
            elif (len(section[j]) == 1):
                # y1,z1 -------
                #    |
                #    |
                #    |
                # y0,z0 -------
                k = 0
                y0 = abs(section[j][k].y)
                z0 = section[j][k].z
                y1 = abs(section[j + 1][k].y)
                z1 = section[j + 1][k].z
                dy = 0.5 * (y0 + y1)
                dz = z1 - z0
                y = 0.25 * (y1 + y0)
                z = 0.25 * (z1 + z0)
                area = area + dy * dz
                momy = momy - y * dy * dz
                momz = momz + z * dy * dz
        areas.append(area)
        My.append(momy)
        Mz.append(momz)
        # Add volume & moment if proceed
        if i > 0:
            dx = xCoord[i] - xCoord[i - 1]
            x = 0.5 * (xCoord[i] + xCoord[i - 1])
            area = 0.5 * (areas[i] + areas[i - 1])
            momy = 0.5 * (My[i] + My[i - 1])
            momz = 0.5 * (Mz[i] + Mz[i - 1])
            vol = vol + area * dx
            vMy = vMy + momy * dx
            vMz = vMz + momz * dx
    # Compute KBT
    kb[0] = vMy / vol
    kb[1] = vMz / vol
    return kb
示例#21
0
def WettedArea(ship, draft, trim):
    """ Calculate wetted ship area.
    @param ship Selected ship instance
    @param draft Draft.
    @param trim Trim in degrees.
    @return Wetted ship area.
    """
    angle = math.radians(trim)
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    lines = []
    area = 0.0
    if not sections:
        return 0.0
    for i in range(0, len(sections)):
        # Get the section
        section = sections[i]
        if len(section) < 2:  # Empty section
            lines.append(0.0)
            continue
        # Get the position of the section
        x = xCoord[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            lines.append(0.0)
            continue
        # Integrate line area
        line = 0.0
        for j in range(0, len(section) - 1):
            for k in range(0,
                           min(len(section[j]) - 1,
                               len(section[j + 1]) - 1)):
                # y11,z11 ------- y01,z01
                #    |               |
                #    |               |
                #    |               |
                # y10,z10 ------- y00,z00
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y11 - y10
                dz = z11 - z10
                line = line + math.sqrt(dy * dy + dz * dz)
                dy = y01 - y00
                dz = z01 - z00
                line = line + math.sqrt(dy * dy + dz * dz)
            if (len(section[j]) < len(section[j + 1])):
                # y01,z01 ------- y11,z11
                #    |        __/
                #    |     __/
                #    |    /
                # y00,z00
                k = len(section[j]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y11 - y00
                dz = z11 - z00
                line = line + math.sqrt(dy * dy + dz * dz)
                dy = y01 - y00
                dz = z01 - z00
                line = line + math.sqrt(dy * dy + dz * dz)
            elif (len(section[j]) > len(section[j + 1])):
                # y01,z01
                #    |    \__
                #    |       \__
                #    |          \
                # y00,z00 ------- y10,z10
                k = len(section[j + 1]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                dy = y01 - y00
                dz = z01 - z00
                line = line + math.sqrt(dy * dy + dz * dz)
                dy = y01 - y10
                dz = z01 - z10
                line = line + math.sqrt(dy * dy + dz * dz)
            elif (len(section[j]) == 1):
                # y1,z1 -------
                #    |
                #    |
                #    |
                # y0,z0 -------
                k = 0
                y0 = abs(section[j][k].y)
                z0 = section[j][k].z
                y1 = abs(section[j + 1][k].y)
                z1 = section[j + 1][k].z
                dy = y1 - y0
                dz = z1 - z0
                line = line + math.sqrt(dy * dy + dz * dz)
        lines.append(2.0 * line)  # 2x because only half ship is represented
        # Add area if proceed
        if i > 0:
            dx = xCoord[i] - xCoord[i - 1]
            x = 0.5 * (xCoord[i] + xCoord[i - 1])
            line = 0.5 * (lines[i] + lines[i - 1])
            area = area + line * dx
    return area
示例#22
0
        {'id':3,'price':80,'inventory':40,'initial_inventory':40,'adjusted_initial_inventory':40,'extra_inventory':0,'inventory_in_transit':0},#200
        {'id':4,'price':70,'inventory':50,'initial_inventory':50,'adjusted_initial_inventory':50,'extra_inventory':0,'inventory_in_transit':0},#300
        #{'id':5,'price':60,'inventory':50,'initial_inventory':50,'adjusted_initial_inventory':50,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':6,'price':50,'inventory':30,'initial_inventory':30,'adjusted_initial_inventory':30,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':7,'price':40,'inventory':20,'initial_inventory':20,'adjusted_initial_inventory':20,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':8,'price':30,'inventory':15,'initial_inventory':15,'adjusted_initial_inventory':15,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':9,'price':20,'inventory':15,'initial_inventory':15,'adjusted_initial_inventory':15,'extra_inventory':0,'inventory_in_transit':0},
        #{'id':10,'price':10,'inventory':20,'initial_inventory':20,'adjusted_initial_inventory':20,'extra_inventory':0,'inventory_in_transit':0},
        ]
N_ITEM = len(ITEM)

CUSTOMER = [{'preference': [0] + list(random.normal(CUSTOMER_MEAN[k],CUSTOMER_SIGMA[k],size=N_ITEM)),'id':k }
            for k in range(CUSTOMER_NUM)            
            ]

instance = Instance(ITEM,CUSTOMER)

# Input parameters
T = 100


instance.Run(T,**SETTING)


#--- 用相同的customer sequence 跑一遍
SETTING['run_again'] = True

SETTING['IB_function_type'] = 'exponential'
instance.Run(T,**SETTING)

SETTING['IB_function_type'] = 'linear'
示例#23
0
def MainFrameCoeff(ship, draft):
    """ Calculate main frame coefficient.
    @param ship Selected ship instance
    @param draft Draft.
    @return Main frame coefficient
    """
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    cm = 0.0
    if not sections:
        return 0.0
    # Look for nearest to main frame section
    sectionID = 0
    X = xCoord[0]
    for i in range(1, len(sections)):
        # Get the position of the section
        x = xCoord[i]
        if abs(x) < abs(X):
            sectionID = i
            X = x
    # Get the section
    section = sections[sectionID]
    if len(section) < 2:  # Empty section
        return 0.0
    x = X
    # Get the maximum Z value
    Z = draft
    # Format section
    section = convertSection(section, x, Z)
    if not section:
        return 0.0
    # Integrate area
    area = 0.0
    maxY = 0.0
    for j in range(0, len(section) - 1):
        for k in range(0, min(len(section[j]) - 1, len(section[j + 1]) - 1)):
            # y11,z11 ------- y01,z01
            #    |               |
            #    |               |
            #    |               |
            # y10,z10 ------- y00,z00
            y00 = abs(section[j][k].y)
            z00 = section[j][k].z
            y10 = abs(section[j][k + 1].y)
            z10 = section[j][k + 1].z
            y01 = abs(section[j + 1][k].y)
            z01 = section[j + 1][k].z
            y11 = abs(section[j + 1][k + 1].y)
            z11 = section[j + 1][k + 1].z
            dy = 0.5 * ((y00 - y10) + (y01 - y11))
            dz = 0.5 * ((z01 - z00) + (z11 - z10))
            area = area + dy * dz
            maxY = max([maxY, y00, y10, y01, y11])
        if len(section[j]) < len(section[j + 1]):
            # y01,z01 ------- y11,z11
            #    |        __/
            #    |     __/
            #    |    /
            # y00,z00
            k = len(section[j]) - 1
            y00 = abs(section[j][k].y)
            z00 = section[j][k].z
            y01 = abs(section[j + 1][k].y)
            z01 = section[j + 1][k].z
            y11 = abs(section[j + 1][k + 1].y)
            z11 = section[j + 1][k + 1].z
            dy = y01 - y11
            dz = z01 - z00
            area = area + 0.5 * dy * dz
            maxY = max([maxY, y00, y01, y11])
        elif len(section[j]) > len(section[j + 1]):
            # y01,z01
            #    |    \__
            #    |       \__
            #    |          \
            # y00,z00 ------- y10,z10
            k = len(section[j + 1]) - 1
            y00 = abs(section[j][k].y)
            z00 = section[j][k].z
            y10 = abs(section[j][k + 1].y)
            z10 = section[j][k + 1].z
            y01 = abs(section[j + 1][k].y)
            z01 = section[j + 1][k].z
            dy = y00 - y10
            dz = z01 - z00
            area = area + 0.5 * dy * dz
            maxY = max([maxY, y00, y10, y01])
        elif len(section[j]) == 1:
            # y1,z1 -------
            #    |
            #    |
            #    |
            # y0,z0 -------
            k = 0
            y0 = abs(section[j][k].y)
            z0 = section[j][k].z
            y1 = abs(section[j + 1][k].y)
            z1 = section[j + 1][k].z
            dy = 0.5 * (y0 + y1)
            dz = z1 - z0
            area = area + dy * dz
            maxY = max([maxY, y0, y1])
    if maxY * draft > 0.0:
        cm = area / (maxY * draft)
    return cm
示例#24
0
async def on_message(text):
    """Handles all commands the bot considers valid. Scans all messages, so long as they are not from bots, to see if those messages start with a valid command."""
    report = ""  # report is usually what the bot sends in response to valid commands, and, in case a game is active, it is what the bot write to that game's log file.
    text.content = text.content.lower(
    )  # for ease of use, all commands are lowercase, and all messages scanned are converted to lowercase.
    current = text.channel.id
    exist = False
    heldGame = None
    botSpoke = False
    if not text.author.bot:
        for i in range(len(games)):
            if current == games[i].getChannel():
                exist = True
                print(
                    str(current) + " " + str(datetime.now())[:-5] + " " +
                    text.author.name + ": " + text.content
                )  # I disabled printing every message because it was just too much. Now it only prints if a game is active.
                heldGame = games[i]
                break

        if text.content.startswith('!setup'):
            print("Running setup...")
            botSpoke = True
            """Run this command once, after you add the bot the your server. It will handle all role and emoji creation, and set the bot's avatar.
            Please avoid running this command more than once, as doing so will create duplicate emojis. If for whatever reason you have to do so, that's fine, just be prepared to delete those emojis.'
            """
            report = "This command is only usable by server admins!"
            if text.author.guild_permissions.administrator:  # Bot setup requires admin perms.
                await text.channel.send("Starting setup...")
                report = "Successfully set up the bot!"

                # This block handles role creation. The bot requires these roles to function, so it will make them when you run !setup.
                willHoist = True  # Hoist makes it so that a given role is displayed separately on the sidebar. If for some reason you don't want teams displayed separately, set this to False.
                roles = {
                    "Reader": 0x01ffdd,
                    "Team red": 0xf70a0a,
                    "Team blue": 0x009ef7,
                    "Team green": 0x7bf70b,
                    "Team orange": 0xff6000,
                    "Team yellow": 0xfeed0e,
                    "Team purple": 0xb40eed
                }
                for x, y in roles.items():
                    if not get(text.guild.roles, name=x):
                        await text.guild.create_role(name=x,
                                                     colour=discord.Colour(y),
                                                     hoist=willHoist)
                        print("Created " + x + ".")
                print("Roles live!")

                # This block creates the emojis the bot accepts for points and buzzes. Credit for these wonderful emojis goes to Theresa Nyowheoma, President of Quiz Bowl at NYU, 2020-2021.
                try:
                    with open("templates/emoji/buzz.png", "rb") as buzzIMG:
                        img = buzzIMG.read()
                        buzz = await text.guild.create_custom_emoji(
                            name='buzz', image=img)
                    with open("templates/emoji/neg.png", "rb") as negIMG:
                        img = negIMG.read()
                        neg = await text.guild.create_custom_emoji(name='neg',
                                                                   image=img)
                    with open("templates/emoji/ten.png", "rb") as tenIMG:
                        img = tenIMG.read()
                        ten = await text.guild.create_custom_emoji(name='ten',
                                                                   image=img)
                    with open("templates/emoji/power.png", "rb") as powerIMG:
                        img = powerIMG.read()
                        power = await text.guild.create_custom_emoji(
                            name='power', image=img)
                    print("Emoji live!")
                    report += " Team roles now exist, as do the following emoji: " + str(
                        buzz) + ", " + str(neg) + ", " + str(ten) + ", " + str(
                            power) + "."
                    with open("templates/pfp.png", "rb") as pfp:
                        pic = pfp.read()
                        try:
                            await client.user.edit(
                                avatar=pic
                            )  # Running !setup too many times will cause the Discord API to deny API calls that try to change the profile picture.
                            print("Avatar live!")
                        except discord.HTTPException:  # In case of the above issue:
                            print("Avatar failed to update!")
                            report += " Failed to update the Bot's profile picture."
                except FileNotFoundError:
                    report = "Failed to load images for emoji or profile picture! Check your directory structure."

            await text.channel.send(report)
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if text.content.startswith('!summon') or text.content.startswith(
                '!call'):
            """Mentions everyone in the server, pinging them and informing them that it is time for practice."""
            print("calling summon")
            botSpoke = True
            report = "This command is only usable by server admins!"
            if text.author.guild_permissions.administrator:  # this makes sure people can't just ping everyone in the server whenever they want. Only admins can do that.
                report = summon(
                ) if verbosePings else "@everyone it's time for Quiz Bowl practice."  # For the full list of summon messages, check Summon.py.
            await text.channel.send(report)
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if text.content.startswith('!start') or text.content.startswith(
                '!begin') or text.content.startswith('!read'):
            botSpoke = True
            print("calling start")
            if exist:
                report = "You already have an active game in this channel."
            else:
                role = get(
                    text.guild.roles, name='Reader'
                )  # The bot needs you to make a role called "Reader" in order to function.
                if role:
                    report = "Starting a new game. Reader is " + text.author.mention + "."
                    x = Instance(current, text.channel)
                    x.reader = text.author
                    print(x.getChannel())
                    await text.author.add_roles(role)
                    heldGame = x
                    with open(x.logFile, "a") as log:
                        log.write("Start of game in channel " + str(current) +
                                  " at " +
                                  datetime.now().strftime("%H:%M:%S") +
                                  ".\r\n\r\n")
                    with open(x.csvScore, "a") as score:
                        #score.write("TU#,Red Bonus,Blue Bonus,Green Bonus,Orange Bonus,Yellow Bonus,Purple Bonus,")
                        # Currently creates the scoresheet and does nothing else.
                        pass
                    games.append(x)
                else:
                    report = "You need to run !setup before you can start a game."
            await text.channel.send(report)
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if exist:  # These commands only fire if a game is active in the channel in which they are being run.
            if text.content.startswith('!newreader'):
                print("calling newreader")
                botSpoke = True
                target = text.content.split('@', 1)[1]
                target = target[1:-1] if target.startswith(
                    '!') else target[:-1]
                role = get(text.guild.roles, name='Reader')
                await heldGame.reader.remove_roles(role)
                newReader = await text.guild.fetch_member(target)
                heldGame.reader = newReader
                await newReader.add_roles(role)
                report = "Made " + newReader.mention + " the new reader."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('!end') or text.content.startswith(
                    '!stop'):
                print("calling end")
                botSpoke = True
                for i in range(len(games)):
                    if current == games[i].getChannel():
                        if text.author.id == games[
                                i].reader.id or text.author.guild_permissions.administrator:
                            #with open(games[i].csvScore) as score:
                            #body = score.readlines()
                            #subMems = body[0]
                            #newLine = "Total:," + str(games[i].redBonus) + "," + str(games[i].blueBonus) + "," + str(games[i].greenBonus) + "," + str(games[i].orangeBonus) + "," + str(games[i].yellowBonus) + "," + str(games[i].purpleBonus) + ","
                            #with open(games[i].csvScore, "a") as score:
                            #for x, y in games[i].scores.items():
                            #newLine += str(y) + ","
                            #score.write(newLine)
                            csvName = games[i].csvScore
                            games.pop(i)
                            report = "Ended the game active in this channel. Here is the scoresheet (I am rewriting all the code involving the scoresheet; it will be extremely inaccurate for some time. Scoresheets are currently empty)."
                            #report = "Ended the game active in this channel."
                            role = get(text.guild.roles, name='Reader')
                            await heldGame.reader.remove_roles(
                                role
                            )  # The Reader is stored as a Member object in heldGame, so any admin can end the game and the Reader role will be removed.
                            await text.channel.send(report)
                            await text.channel.send(file=discord.File(
                                csvName, filename="scoresheet.csv"))
                        else:
                            report = "You are not the reader or a server admin!"
                            await text.channel.send(report)
                        break
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return
            """
            # DEPRECATED until I fully implement scoresheets and figure out the issue with TUnum tracking.
            if text.content.startswith('!undo'):
                print("calling undo")
                botSpoke = True
                if text.author.id == heldGame.reader.id:
                    if heldGame.bonusMode:
                        report = "Finish your bonus first!"
                    else:
                        if heldGame.active:
                            report = "Assign TU points first!"
                        else:
                            if heldGame.TUnum == 0 and len(heldGame.scores) == 0:
                                report = "Nothing to undo."
                            else:
                                heldGame.undo()
                                report = "Undid last Tossup scorechange."
                else:
                    report = "You are not the reader!"
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content, heldGame, report, botSpoke)
                return
            """

            if text.content.startswith('!dead'):
                print("calling dead")
                botSpoke = True
                report = "You are not the reader!"
                if text.author.id == heldGame.reader.id:
                    heldGame.dead()
                    report = "TU goes dead. Moving on to TU #" + str(
                        heldGame.TUnum + 1) + "."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('!clear'):
                print("calling clear")
                botSpoke = True
                report = "You are not the reader!"
                if text.author.id == heldGame.reader.id:
                    heldGame.clear()
                    report = "Buzzers cleared, anyone can buzz."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if isInt(text.content):  # Assigns points.
                print("calling points")
                print(text.content + " is an int")
                if text.content.startswith(
                        '<:neg:'
                ):  # This and the next two conditionals check to see if someone is using a valid emoji to assign points. While, to the user, an emoji looks like :emojiName:, to the bot it is also wrapped in <>.
                    text.content = "-5"
                elif text.content.startswith('<:ten:'):
                    text.content = "10"
                elif text.content.startswith('<:power:'):
                    text.content = "15"
                botSpoke = True
                report = "Null"  # if someone besides the reader types a number, this will do nothing
                if text.author.id == heldGame.reader.id:
                    if heldGame.bonusEnabled == False:
                        if heldGame.gain(int(text.content)):
                            report = "Awarded points. Moving on to TU #" + str(
                                heldGame.TUnum + 1) + "."
                            await text.channel.send(report)
                        else:
                            report = "No held buzzes."
                            while len(heldGame.buzzes) > 0:
                                if heldGame.canBuzz(heldGame.buzzes[0]):
                                    report = (
                                        heldGame.buzzes[0]
                                    ).mention + " buzzed. Pinging reader: " + str(
                                        heldGame.reader.mention)
                                    await text.channel.send(report)
                                    break
                                else:
                                    heldGame.buzzes.popleft(
                                    )  # Pop until we find someone who can buzz, or until the array of buzzes is empty.
                                    report = "Cannot buzz."
                    else:  # bonuses enabled
                        if heldGame.bonusMode == False:
                            storedMem = heldGame.buzzes[0]
                            if heldGame.gain(int(text.content)):
                                report = "Awarded TU points. "
                                getTeam = heldGame.inTeam(storedMem)
                                message = await text.channel.send(report)
                                if getTeam != None:
                                    report += "Bonus is for " + getTeam.mention + ". "
                                report += "Awaiting bonus points."
                                await asyncio.sleep(.1)
                                await message.edit(content=report)
                            else:
                                report = "No held buzzes."
                                while len(heldGame.buzzes) > 0:
                                    if heldGame.canBuzz(heldGame.buzzes[0]):
                                        report = (
                                            heldGame.buzzes[0]
                                        ).mention + " buzzed. Pinging reader: " + str(
                                            heldGame.reader.mention)
                                        await text.channel.send(report)
                                        break
                                    else:
                                        heldGame.buzzes.popleft(
                                        )  # Pop until we find someone who can buzz, or until the array of buzzes is empty.
                                        report = "Cannot buzz."
                                        # because I don't want to send a report here, I can't have the text.channel.send(report) at the end
                        else:  # bonusMode true
                            heldGame.bonusGain(int(text.content))
                            report = "Awarded bonus points. Moving on to TU #" + str(
                                heldGame.TUnum + 1) + "."
                            await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('wd') or text.content.startswith(
                    '!wd') or text.content.startswith(
                        'withdraw') or text.content.startswith('!withdraw'):
                print("calling withdraw")
                botSpoke = True
                report = "Only the currently recognized player can withdraw."
                if heldGame.buzzes[0] == text.author:
                    heldGame.buzzes.popleft()
                    newBuzzed = deque()
                    while len(heldGame.buzzed) > 0:
                        if heldGame.buzzed[0] == text.author:
                            heldGame.buzzed.popleft()
                        else:
                            newBuzzed.append(heldGame.buzzed.popleft())
                    heldGame.buzzed = newBuzzed
                    report = "Withdrew " + text.author.mention + "'s buzz. "
                    while len(heldGame.buzzes) > 0:
                        if heldGame.canBuzz(heldGame.buzzes[0]):
                            report += (
                                heldGame.buzzes[0]
                            ).mention + " buzzed. Pinging reader: " + str(
                                heldGame.reader.mention)
                            break
                        else:
                            heldGame.buzzes.popleft()
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith(
                    '!bonusmode') or text.content.startswith('!btoggle'):
                """Toggles whether bonus mode is enabled. It is enabled by default."""
                print("calling bonusmode")
                botSpoke = True
                report = "You are not the reader!"
                if text.author.id == heldGame.reader.id or text.author.guild_permissions.administrator:
                    heldGame.bonusStop()
                    heldGame.bonusEnabled = not heldGame.bonusEnabled
                    report = "Enabled bonus mode." if heldGame.bonusEnabled else "Disabled bonus mode."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('!bstop'):
                """Ends current bonus round. Use this to kill a bonus without giving points. Only use if something has gone wrong and you need to kill a bonus immediately."""
                print("calling bstop")
                botSpoke = True
                report = "You are not the reader!"
                if text.author.id == heldGame.reader.id:
                    heldGame.bonusStop()
                    report = "Killed active bonus. Next TU."
                await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if text.content.startswith('!score'):
                print("calling score")
                diction = {}
                botSpoke = True
                areTeams = False
                if len(heldGame.scores) == 0:
                    desc = "Score at start of game:"
                else:
                    desc = "Score after " + str(
                        heldGame.TUnum) + " completed TUs: "
                    #The following seven conditionals modify the scoreboard to include team scores, if those teams exist.
                    if heldGame.teamExist(heldGame.redTeam):
                        desc += "\r\nRed team: " + str(
                            heldGame.teamScore(heldGame.redTeam,
                                               heldGame.redBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.blueTeam):
                        desc += "\r\nBlue team: " + str(
                            heldGame.teamScore(heldGame.blueTeam,
                                               heldGame.blueBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.greenTeam):
                        desc += "\r\nGreen team: " + str(
                            heldGame.teamScore(heldGame.greenTeam,
                                               heldGame.greenBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.orangeTeam):
                        desc += "\r\nOrange team: " + str(
                            heldGame.teamScore(heldGame.orangeTeam,
                                               heldGame.orangeBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.yellowTeam):
                        desc += "\r\nYellow team: " + str(
                            heldGame.teamScore(heldGame.yellowTeam,
                                               heldGame.yellowBonus))
                        areTeams = True
                    if heldGame.teamExist(heldGame.purpleTeam):
                        desc += "\r\nPurple team: " + str(
                            heldGame.teamScore(heldGame.purpleTeam,
                                               heldGame.purpleBonus))
                        areTeams = True
                    if areTeams:
                        desc += "\r\n\r\nIndividuals:"
                emb = discord.Embed(title="Score",
                                    description=desc,
                                    color=0x57068C)
                for x, y in heldGame.scores.items():
                    diction[
                        x.name if x.nick == None else x.
                        nick] = y  # Tries to display the Member's Discord nickname if possible, but if none exists, displays their username.
                sortedDict = OrderedDict(
                    sorted(diction.items(), key=itemgetter(1)))
                print(sortedDict)
                for i in range(len(sortedDict.items())):
                    tup = sortedDict.popitem()
                    emb.add_field(name=(str(i + 1) + ". " + tup[0]),
                                  value=str(tup[1]),
                                  inline=True)
                await text.channel.send(embed=emb)
                report = "Embedded score."
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

            if isBuzz(
                    text.content
            ):  # Uses the isBuzz() helper method to dermine if somene is buzzing
                print("calling buzz")
                botSpoke = True
                # This block handles all team assignment that was done before the game started.
                red = get(text.guild.roles, name='Team red')
                blue = get(text.guild.roles, name='Team blue')
                green = get(text.guild.roles, name='Team green')
                orange = get(text.guild.roles, name='Team orange')
                yellow = get(text.guild.roles, name='Team yellow')
                purple = get(text.guild.roles, name='Team purple')
                if red in text.author.roles and not text.author in heldGame.redTeam:
                    heldGame.redTeam.append(text.author)
                    print("Added " + text.author.name + " to red on buzz")
                elif blue in text.author.roles and not text.author in heldGame.blueTeam:
                    heldGame.blueTeam.append(text.author)
                    print("Added " + text.author.name + " to blue on buzz")
                elif green in text.author.roles and not text.author in heldGame.greenTeam:
                    heldGame.greenTeam.append(text.author)
                    print("Added " + text.author.name + " to green on buzz")
                elif orange in text.author.roles and not text.author in heldGame.orangeTeam:
                    heldGame.orangeTeam.append(text.author)
                    print("Added " + text.author.name + " to orange on buzz")
                elif yellow in text.author.roles and not text.author in heldGame.yellowTeam:
                    heldGame.yellowTeam.append(text.author)
                    print("Added " + text.author.name + " to yellow on buzz")
                elif purple in text.author.roles and not text.author in heldGame.purpleTeam:
                    heldGame.purpleTeam.append(text.author)
                    print("Added " + text.author.name + " to purple on buzz")
                if heldGame.bonusMode == False:
                    if heldGame.hasBuzzed(text.author):
                        print("You have already buzzed, " +
                              text.author.mention + ".")
                    else:
                        if heldGame.canBuzz(text.author):
                            if len(heldGame.buzzes) < 1:
                                heldGame.buzz(text.author)
                                print("Buzzed!")
                                report = text.author.mention + " buzzed. Pinging reader: " + str(
                                    heldGame.reader.mention)
                                await text.channel.send(report)
                            else:
                                heldGame.buzz(text.author)
                                report = "Held a buzz."
                                print("Buzzed!")
                                # because I don't want the bot to say anything if you buzz when someone has been recognized, each conditional needs its own await send.
                        else:
                            report = "Your team is locked out of buzzing, " + text.author.mention + "."
                            await text.channel.send(report)
                else:
                    report = "We are currently playing a bonus. You cannot buzz, " + text.author.mention + "."
                    await text.channel.send(report)
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
                return

        if text.content.startswith('!github'):
            print("calling github")
            botSpoke = True
            emb = discord.Embed(title="Lev's Quizbowl Bot",
                                description="",
                                color=0x57068C)
            emb.add_field(
                name="View this bot's source code at:",
                value=
                "https://github.com/LevBernstein/LevQuizbowlBot/tree/pandasRewrite",
                inline=True)
            await text.channel.send(embed=emb)
            report = "Embedded github."
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if text.content.startswith('!report'):
            print("calling report")
            botSpoke = True
            emb = discord.Embed(title="Report bugs or suggest features",
                                description="",
                                color=0x57068C)
            emb.add_field(
                name="Report any issues at:",
                value="https://github.com/LevBernstein/LevQuizbowlBot/issues",
                inline=True)
            await text.channel.send(embed=emb)
            report = "Embedded report."
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if text.content.startswith('!help') or text.content.startswith(
                '!commands') or text.content.startswith('!tutorial'):
            print("calling tutorial")
            emb = discord.Embed(title="Lev's Quizbowl Bot Commands",
                                description="",
                                color=0x57068C)
            emb.add_field(
                name="!setup",
                value="Run this once, after the bot first joins the server.",
                inline=True)
            emb.add_field(name="!start",
                          value="Starts a new game.",
                          inline=True)
            emb.add_field(name="buzz", value="Buzzes in.", inline=True)
            emb.add_field(
                name="!clear",
                value="Clears buzzes without advancing the TU count.",
                inline=True)
            emb.add_field(
                name="!dead",
                value=
                "Clears buzzes after a dead TU and advances the TU count.",
                inline=True)
            emb.add_field(
                name="!score",
                value="Displays the score, sorted from highest to lowest.",
                inline=True)
            emb.add_field(
                name="Any whole number",
                value=
                "After a buzz or a bonus, the reader can enter a +/- whole number to assign points.",
                inline=True)
            emb.add_field(
                name="!call",
                value=
                "Mentions everyone in the server and informs them that it is time for practice. Usable only by admins.",
                inline=True)
            emb.add_field(name="!github",
                          value="Gives you a link to this bot's github page.",
                          inline=True)
            emb.add_field(
                name="!report",
                value="Gives you a link to this bot's issue-reporting page.",
                inline=True)
            emb.add_field(name="!tu",
                          value="Reports the current tossup number.",
                          inline=True)
            emb.add_field(
                name="!team [red/blue/green/orange/yellow/purple]",
                value=
                "Assigns you the team role corresponding to the color you entered.",
                inline=True)
            emb.add_field(
                name="!bonusmode",
                value=
                "Disables or enables bonuses. Bonuses are enabled by default.",
                inline=True)
            emb.add_field(name="!bstop",
                          value="Kills an active bonus without giving points.",
                          inline=True)
            emb.add_field(name="!newreader <@user>",
                          value="Changes a game's reader to another user.",
                          inline=True)
            emb.add_field(name="wd", value="Withdraws a buzz.", inline=True)
            # emb.add_field(name = "!undo", value = "Reverts the last score change.", inline = True) # DEPRECATED until I figure out the issue with TUnum tracking.
            emb.add_field(name="!end",
                          value="Ends the active game.",
                          inline=True)
            emb.add_field(name="!tutorial",
                          value="Shows you this list.",
                          inline=True)
            #emb.add_field(name = "_ _", value = "_ _", inline = True) # filler for formatting
            await text.channel.send(embed=emb)
            report = "Embedded commands list."
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return

        if exist and text.content.startswith(
                '!tu'
        ):  # Placed after !help so that it won't fire when someone does !tutorial, a synonym of !help
            print("calling tu")
            report = "Current TU: #" + str(heldGame.TUnum + 1) + "."
            await text.channel.send(report)
            writeOut(generateLogs, text.author.name, text.content, heldGame,
                     report, botSpoke)
            return

        if text.content.startswith('!team'):
            """ Adds the user to a given team.
            Teams require the following roles: Team red, Team blue, Team green, Team orange, Team yellow, Team purple.
            If you do not have those roles in your server, the bot will create them for you when you run !setup. 
            Depending on your role hierarchy, the bot-created roles might not show their color for each user.
            Make sure that, for non-admin users, the team roles are the highest they can have in the hierarchy.
            Admin roles should still be higher than the team roles.
            """
            print("calling team")
            botSpoke = True
            rolesFound = False
            roles = ["red", "blue", "green", "orange", "yellow", "purple"]
            report = "Uh-oh! The Discord role you are trying to add does not exist! If whoever is going to read does !start, I will create the roles for you."
            for role in roles:
                if text.content.startswith('!team ' + role):
                    rolesFound = True
                    givenRole = get(text.guild.roles, name='Team ' + role)
                    if givenRole:
                        await text.author.add_roles(givenRole)
                        report = "Gave you the Team " + role + " role, " + text.author.mention + "."
                    break
            if not rolesFound:
                report = "Please choose a valid team! Valid teams are red, blue, green, orange, yellow, and purple."
            await text.channel.send(report)
            if exist:
                writeOut(generateLogs, text.author.name, text.content,
                         heldGame, report, botSpoke)
            return
示例#25
0
def Displacement(ship, draft, trim):
    """ Calculate ship displacement.
    @param ship Selected ship instance
    @param draft Draft.
    @param trim Trim in degrees.
    @return [areas,disp,xcb]: \n
    areas : Area of each section \n
    disp: Ship displacement \n
    xcb: X bouyance center coordinate
    Cb: Block coefficient
    """
    angle = math.radians(trim)
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    minX = None
    maxX = None
    maxY = 0.0
    areas = []
    vol = 0.0
    moment = 0.0
    if not sections:
        return [[], 0.0, 0.0, 0.0]
    for i in range(0, len(sections)):
        # Get the section
        section = sections[i]
        if len(section) < 2:  # Empty section
            areas.append(0.0)
            continue
        # Get the position of the section
        x = xCoord[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            areas.append(0.0)
            continue
        maxX = x
        if not minX:
            minX = x
        # Integrate area
        area = 0.0
        for j in range(0, len(section) - 1):
            for k in range(0, min(len(section[j]) - 1, len(section[j + 1]) - 1)):
                # y11,z11 ------- y01,z01
                #    |               |
                #    |               |
                #    |               |
                # y10,z10 ------- y00,z00
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = 0.5 * ((y00 - y10) + (y01 - y11))
                dz = 0.5 * ((z01 - z00) + (z11 - z10))
                area = area + dy * dz
                maxY = max([maxY, y00, y10, y01, y11])
            if len(section[j]) < len(section[j + 1]):
                # y01,z01 ------- y11,z11
                #    |        __/
                #    |     __/
                #    |    /
                # y00,z00
                k = len(section[j]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y01 - y11
                dz = z01 - z00
                area = area + 0.5 * dy * dz
                maxY = max([maxY, y00, y01, y11])
            elif len(section[j]) > len(section[j + 1]):
                # y01,z01
                #    |    \__
                #    |       \__
                #    |          \
                # y00,z00 ------- y10,z10
                k = len(section[j + 1]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                dy = y00 - y10
                dz = z01 - z00
                area = area + 0.5 * dy * dz
                maxY = max([maxY, y00, y10, y01])
            elif len(section[j]) == 1:
                # y1,z1 -------
                #    |
                #    |
                #    |
                # y0,z0 -------
                k = 0
                y0 = abs(section[j][k].y)
                z0 = section[j][k].z
                y1 = abs(section[j + 1][k].y)
                z1 = section[j + 1][k].z
                dy = 0.5 * (y0 + y1)
                dz = z1 - z0
                area = area + dy * dz
                maxY = max([maxY, y0, y1])
        areas.append(2.0 * area)  # 2x because only half ship is represented
        # Add volume & moment if proceed
        if i > 0:
            dx = xCoord[i] - xCoord[i - 1]
            x = 0.5 * (xCoord[i] + xCoord[i - 1])
            area = 0.5 * (areas[i] + areas[i - 1])
            vol = vol + area * dx
            moment = moment + area * dx * x
    # Compute displacement and xcb
    disp = vol / 1.025  # rho = 1.025 ton/m3 (salt water density)
    xcb = 0.0
    cb = 0.0
    if vol > 0.0:
        xcb = moment / vol
        block = (maxX - minX) * 2.0 * maxY * draft
        cb = vol / block
    return [areas, disp, xcb, cb]
示例#26
0
文件: numeric.py 项目: evyadai/GSR
@author: Evyatar
"""

import time
from math import *
import numpy as np
from scipy import optimize
from Instance import *


def const1(x):
    return 1.0


def slope1(x):
    return x


csr = Instance(slope1, const1, 1.0)
detStr = csr.optDetStr()
if detStr[0] == float("Inf"):
    print "The optimal deterministic strategy never switch and has a competitive ratio of", detStr[
        1]
elif detStr[1] == 0.0:
    print "The optimal deterministic strategy start at buy state and has a competitive ratio of", detStr[
        1]
else:
    print "The optimal deterministic strategy switch at time", detStr[
        0], "and has a competitive ratio of", detStr[1]
示例#27
0
glossy = GlossyReflective(1, 1, 1, Sred, 50000, 1.0, Sred, r_sample)

#Objects

plane = Plane(Point(0, -15, 0), Vector(0, 1, -0.1), greymat)
world.addObject(plane)
plane2 = Plane(Point(0, 0, 20), Vector(0, 0, 1), bluemat)
world.addObject(plane2)

#Reflective Spheres
s3 =Sphere(Point(-22, 0, -3), 10.0, glossy)
world.addObject(s3)

#Instance
sphere = Sphere(Point( 0, 0, -5), 5.0, mat)
s_i = Instance(sphere)
s_i.translate(25, 10, 0)
s_i.scale(1, 2, 1)
world.addObject(s_i)

#Transparent Sphere
c = Point(0, 0, -5)
r = 10.0
s = Sphere(c, r, transparent)
world.addObject(s)

#Texture Sphere
image = Image.open("earthmap1k.jpg")
texels = image.load()
sphere_map = SphericalMapping(8.0)
sampler = Regular(25, 83)
示例#28
0
def WettedArea(ship, draft, trim):
    """ Calculate wetted ship area.
    @param ship Selected ship instance
    @param draft Draft.
    @param trim Trim in degrees.
    @return Wetted ship area.
    """
    angle = math.radians(trim)
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    lines = []
    area = 0.0
    if not sections:
        return 0.0
    for i in range(0, len(sections)):
        # Get the section
        section = sections[i]
        if len(section) < 2:  # Empty section
            lines.append(0.0)
            continue
        # Get the position of the section
        x = xCoord[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            lines.append(0.0)
            continue
        # Integrate line area
        line = 0.0
        for j in range(0, len(section) - 1):
            for k in range(0, min(len(section[j]) - 1, len(section[j + 1]) - 1)):
                # y11,z11 ------- y01,z01
                #    |               |
                #    |               |
                #    |               |
                # y10,z10 ------- y00,z00
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y11 - y10
                dz = z11 - z10
                line = line + math.sqrt(dy * dy + dz * dz)
                dy = y01 - y00
                dz = z01 - z00
                line = line + math.sqrt(dy * dy + dz * dz)
            if len(section[j]) < len(section[j + 1]):
                # y01,z01 ------- y11,z11
                #    |        __/
                #    |     __/
                #    |    /
                # y00,z00
                k = len(section[j]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y11 - y00
                dz = z11 - z00
                line = line + math.sqrt(dy * dy + dz * dz)
                dy = y01 - y00
                dz = z01 - z00
                line = line + math.sqrt(dy * dy + dz * dz)
            elif len(section[j]) > len(section[j + 1]):
                # y01,z01
                #    |    \__
                #    |       \__
                #    |          \
                # y00,z00 ------- y10,z10
                k = len(section[j + 1]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                dy = y01 - y00
                dz = z01 - z00
                line = line + math.sqrt(dy * dy + dz * dz)
                dy = y01 - y10
                dz = z01 - z10
                line = line + math.sqrt(dy * dy + dz * dz)
            elif len(section[j]) == 1:
                # y1,z1 -------
                #    |
                #    |
                #    |
                # y0,z0 -------
                k = 0
                y0 = abs(section[j][k].y)
                z0 = section[j][k].z
                y1 = abs(section[j + 1][k].y)
                z1 = section[j + 1][k].z
                dy = y1 - y0
                dz = z1 - z0
                line = line + math.sqrt(dy * dy + dz * dz)
        lines.append(2.0 * line)  # 2x because only half ship is represented
        # Add area if proceed
        if i > 0:
            dx = xCoord[i] - xCoord[i - 1]
            x = 0.5 * (xCoord[i] + xCoord[i - 1])
            line = 0.5 * (lines[i] + lines[i - 1])
            area = area + line * dx
    return area
iam = boto3.resource('iam')
role = None
try:
    role = Iam_Role.Iam_Role(iam.Role('cs5250-EC2-backend-role'))
    check_iam_role(role)
except:
    print('Error retrieving IAM Role')

ec2 = boto3.resource('ec2')
instances_from_aws = ec2.instances.all()
instances = list()

for instance in instances_from_aws:
    vpc_id = instance.vpc_id
    instances.append(Instance.Instance(instance))
try:
    vpc = VPC.VPC(vpc_id)
    print()
    check_vpc(vpc)
except:
    print(f'Error retrieving VPC {vpc_id}')

for instance in instances:
    instance.subnet = vpc.get_subnet_name(instance.subnet)

print()
check_instances(instances)

if len(argv) > 1 and argv[1] == '-p':
    if not role == None:
示例#30
0
    - Nmax : max nb of objects in a cluster
    - W^k in W : . matrix of profits for cluster k (in position (i,j), you got the sum of the similarities for the objects i and j)
            . shape : N*N
Result:
    - X^k in X : Matrix of objects (in position (i,j), you got x_i^k * x_j^k)

'''

#Global variables :

# K = 2
# N = 3
# Nmax = N-1
# W = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 2, 1], [0, 0, 0], [1, 2, 1]]]

I = Instance.LoadInstance("save3.txt")
K = I.K
N = I.N
Nmax = I.Nmax
W = I.Wmulti
M = I.M
Mmax = I.Mmax


def initProblem(N, K, Nmax):  #Cette version n'est pas aléatoire uniforme

    if (K < ceil(N / Nmax)):
        raise ValueError('Trop peu de clusters pour le Nmax donné')
        return

    if (K > N):
示例#31
0
#objects = [Entry(np.array([3.0,3.0]), np.array([4,4])), Obstacle(np.array([30.0,10.0]), np.array([20, 20])), Obstacle(np.array([60.0,60.0]), np.array([10, 20])), Obstacle(np.array([0.0,0.0]), np.array([2, 100])), Obstacle(np.array([0.0,0.0]), np.array([100, 2])), Obstacle(np.array([98.0,0.0]), np.array([2, 100])), Obstacle(np.array([0.0, 98.0]), np.array([100, 2])), Exit(np.array([96.0, 96.0]), np.array([2, 2]))]

in_terface = In_Terface()
in_terface.initialize_interface()
#in_terface.initialize_silent_interface()

saved_state = in_terface.get_state()
size = saved_state.screen_size // 5
objects = saved_state.objects
'''
size = np.array([80,80])
margin, people = 5, []


objects = [Entry(np.array([5.0,5.0]), np.array([4,4])), Obstacle(np.array([20.0,10.0]), np.array([10, 5])), Obstacle(np.array([60.0,60.0]), np.array([10, 10])), Obstacle(np.array([0.0,0.0]), np.array([2, 80])), Obstacle(np.array([0.0,0.0]), np.array([80, 2])), Obstacle(np.array([78.0,0.0]), np.array([2, 80])), Obstacle(np.array([0.0, 78.0]), np.array([80, 2])), Exit(np.array([76.0, 76.0]), np.array([2, 2]))]
objects.append(Obstacle(np.array([50.0,25.0]), np.array([20, 5])))
objects.append(Exit(np.array([75.0,3.0]), np.array([2, 3])))
objects.append(Entry(np.array([5.0,70.0]), np.array([4,4])))
objects.append(Entry(np.array([35.0,70.0]), np.array([4,4])))
objects.append(Obstacle(np.array([50.0,50.0]), np.array([10, 20])))
objects.append(Obstacle(np.array([20.0,25.0]), np.array([3, 18])))
objects.append(Obstacle(np.array([50.0,25.0]), np.array([5, 24])))
'''

setup = Setup(size, margin, objects, people)

instance = Instance(setup)

instance.init_show()
示例#32
0
def Displacement(ship, draft, trim):
    """ Calculate ship displacement.
    @param ship Selected ship instance
    @param draft Draft.
    @param trim Trim in degrees.
    @return [areas,disp,xcb,Cb]: \n
    areas : Area of each section \n
    disp: Ship displacement \n
    xcb: X bouyance center coordinate
    Cb: Block coefficient
    """
    angle = math.radians(trim)
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    minX = None
    maxX = None
    maxY = 0.0
    areas = []
    vol = 0.0
    moment = 0.0
    if not sections:
        return [[], 0.0, 0.0, 0.0]
    for i in range(0, len(sections)):
        # Get the section
        section = sections[i]
        if len(section) < 2:  # Empty section
            areas.append(0.0)
            continue
        # Get the position of the section
        x = xCoord[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            areas.append(0.0)
            continue
        maxX = x
        if not minX:
            minX = x
        # Integrate area
        area = 0.0
        for j in range(0, len(section) - 1):
            for k in range(0,
                           min(len(section[j]) - 1,
                               len(section[j + 1]) - 1)):
                # y11,z11 ------- y01,z01
                #    |               |
                #    |               |
                #    |               |
                # y10,z10 ------- y00,z00
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = 0.5 * ((y00 - y10) + (y01 - y11))
                dz = 0.5 * ((z01 - z00) + (z11 - z10))
                area = area + dy * dz
                maxY = max([maxY, y00, y10, y01, y11])
            if (len(section[j]) < len(section[j + 1])):
                # y01,z01 ------- y11,z11
                #    |        __/
                #    |     __/
                #    |    /
                # y00,z00
                k = len(section[j]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y01 - y11
                dz = z01 - z00
                area = area + 0.5 * dy * dz
                maxY = max([maxY, y00, y01, y11])
            elif (len(section[j]) > len(section[j + 1])):
                # y01,z01
                #    |    \__
                #    |       \__
                #    |          \
                # y00,z00 ------- y10,z10
                k = len(section[j + 1]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                dy = y00 - y10
                dz = z01 - z00
                area = area + 0.5 * dy * dz
                maxY = max([maxY, y00, y10, y01])
            elif (len(section[j]) == 1):
                # y1,z1 -------
                #    |
                #    |
                #    |
                # y0,z0 -------
                k = 0
                y0 = abs(section[j][k].y)
                z0 = section[j][k].z
                y1 = abs(section[j + 1][k].y)
                z1 = section[j + 1][k].z
                dy = 0.5 * (y0 + y1)
                dz = z1 - z0
                area = area + dy * dz
                maxY = max([maxY, y0, y1])
        areas.append(2.0 * area)  # 2x because only half ship is represented
        # Add volume & moment if proceed
        if i > 0:
            dx = xCoord[i] - xCoord[i - 1]
            x = 0.5 * (xCoord[i] + xCoord[i - 1])
            area = 0.5 * (areas[i] + areas[i - 1])
            vol = vol + area * dx
            moment = moment + area * dx * x
    # Compute displacement and xcb
    disp = vol / 1.025  # rho = 1.025 ton/m3 (salt water density)
    xcb = 0.0
    cb = 0.0
    if vol > 0.0:
        xcb = moment / vol
        block = (maxX - minX) * 2.0 * maxY * draft
        cb = vol / block
    return [areas, disp, xcb, cb]
示例#33
0
def KBT(ship, draft, trim, roll=0.0):
    """ Calculate ship Keel to Bouyance center transversal distance.
    @param ship Selected ship instance
    @param draft Draft.
    @param trim Trim in degrees.
    @param roll Roll angle in degrees.
    @return [KBTx, KBTy]: \n
    KBTy : TRansversal KB y coordinate \n
    KBTz : TRansversal KB z coordinate
    """
    angle = math.radians(trim)
    rAngle = math.radians(roll)
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    areas = []
    vol = 0.0
    vMy = 0.0
    vMz = 0.0
    My = []
    Mz = []
    kb = [0.0, 0.0]
    if not sections:
        return [[], 0.0, 0.0]
    for i in range(0, len(sections)):
        # ------------------------------------
        # Board
        # ------------------------------------
        # Get the section
        section = sections[i]
        if len(section) < 2:  # Empty section
            areas.append(0.0)
            continue
        # Get the position of the section
        x = xCoord[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        aux = convertSection(section, x, Z)
        if not aux:
            areas.append(0.0)
            My.append(0.0)
            Mz.append(0.0)
            continue
        # Correct by roll angle
        pts = aux[len(aux) - 1]
        beam = pts[0].y
        for i in range(1, len(pts)):
            beam = max(beam, pts[i].y)
        Z = Z - beam * math.tan(rAngle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            areas.append(0.0)
            My.append(0.0)
            Mz.append(0.0)
            continue
        # Integrate area
        area = 0.0
        momy = 0.0
        momz = 0.0
        for j in range(0, len(section) - 1):
            for k in range(0, min(len(section[j]) - 1, len(section[j + 1]) - 1)):
                # y11,z11 ------- y01,z01
                #    |               |
                #    |               |
                #    |               |
                # y10,z10 ------- y00,z00
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = 0.5 * ((y00 - y10) + (y01 - y11))
                dz = 0.5 * ((z01 - z00) + (z11 - z10))
                y = 0.25 * (y00 + y10 + y01 + y11)
                z = 0.25 * (z01 + z00 + z11 + z10)
                area = area + dy * dz
                momy = momy + y * dy * dz
                momz = momz + z * dy * dz
            if len(section[j]) < len(section[j + 1]):
                # y01,z01 ------- y11,z11
                #    |        __/
                #    |     __/
                #    |    /
                # y00,z00
                k = len(section[j]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y01 - y11
                dz = z01 - z00
                y = 0.33 * (y00 + y01 + y11)
                z = 0.33 * (z01 + z00 + z11)
                area = area + 0.5 * dy * dz
                momy = momy + y * 0.5 * dy * dz
                momz = momz + z * 0.5 * dy * dz
            elif len(section[j]) > len(section[j + 1]):
                # y01,z01
                #    |    \__
                #    |       \__
                #    |          \
                # y00,z00 ------- y10,z10
                k = len(section[j + 1]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                dy = y00 - y10
                dz = z01 - z00
                y = 0.33 * (y00 + y01 + y10)
                z = 0.33 * (z01 + z00 + z10)
                area = area + 0.5 * dy * dz
                momy = momy + y * 0.5 * dy * dz
                momz = momz + z * 0.5 * dy * dz
            elif len(section[j]) == 1:
                # y1,z1 -------
                #    |
                #    |
                #    |
                # y0,z0 -------
                k = 0
                y0 = abs(section[j][k].y)
                z0 = section[j][k].z
                y1 = abs(section[j + 1][k].y)
                z1 = section[j + 1][k].z
                dy = 0.5 * (y0 + y1)
                dz = z1 - z0
                y = 0.25 * (y1 + y0)
                z = 0.25 * (z1 + z0)
                area = area + dy * dz
                momy = momy + y * dy * dz
                momz = momz + z * dy * dz
        # ------------------------------------
        # StarBoard
        # ------------------------------------
        # Get the section
        section = sections[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        aux = convertSection(section, x, Z)
        if not aux:
            areas.append(0.0)
            My.append(0.0)
            Mz.append(0.0)
            continue
        # Correct by roll angle
        pts = aux[len(aux) - 1]
        beam = pts[0].y
        for i in range(1, len(pts)):
            beam = max(beam, pts[i].y)
        Z = Z + beam * math.tan(rAngle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            areas.append(0.0)
            My.append(0.0)
            Mz.append(0.0)
            continue
        # Integrate area
        for j in range(0, len(section) - 1):
            for k in range(0, min(len(section[j]) - 1, len(section[j + 1]) - 1)):
                # y11,z11 ------- y01,z01
                #    |               |
                #    |               |
                #    |               |
                # y10,z10 ------- y00,z00
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = 0.5 * ((y00 - y10) + (y01 - y11))
                dz = 0.5 * ((z01 - z00) + (z11 - z10))
                y = 0.25 * (y00 + y10 + y01 + y11)
                z = 0.25 * (z01 + z00 + z11 + z10)
                area = area + dy * dz
                momy = momy - y * dy * dz
                momz = momz + z * dy * dz
            if len(section[j]) < len(section[j + 1]):
                # y01,z01 ------- y11,z11
                #    |        __/
                #    |     __/
                #    |    /
                # y00,z00
                k = len(section[j]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                y11 = abs(section[j + 1][k + 1].y)
                z11 = section[j + 1][k + 1].z
                dy = y01 - y11
                dz = z01 - z00
                y = 0.33 * (y00 + y01 + y11)
                z = 0.33 * (z01 + z00 + z11)
                area = area + 0.5 * dy * dz
                momy = momy - y * 0.5 * dy * dz
                momz = momz + z * 0.5 * dy * dz
            elif len(section[j]) > len(section[j + 1]):
                # y01,z01
                #    |    \__
                #    |       \__
                #    |          \
                # y00,z00 ------- y10,z10
                k = len(section[j + 1]) - 1
                y00 = abs(section[j][k].y)
                z00 = section[j][k].z
                y10 = abs(section[j][k + 1].y)
                z10 = section[j][k + 1].z
                y01 = abs(section[j + 1][k].y)
                z01 = section[j + 1][k].z
                dy = y00 - y10
                dz = z01 - z00
                y = 0.33 * (y00 + y01 + y10)
                z = 0.33 * (z01 + z00 + z10)
                area = area + 0.5 * dy * dz
                momy = momy - y * 0.5 * dy * dz
                momz = momz + z * 0.5 * dy * dz
            elif len(section[j]) == 1:
                # y1,z1 -------
                #    |
                #    |
                #    |
                # y0,z0 -------
                k = 0
                y0 = abs(section[j][k].y)
                z0 = section[j][k].z
                y1 = abs(section[j + 1][k].y)
                z1 = section[j + 1][k].z
                dy = 0.5 * (y0 + y1)
                dz = z1 - z0
                y = 0.25 * (y1 + y0)
                z = 0.25 * (z1 + z0)
                area = area + dy * dz
                momy = momy - y * dy * dz
                momz = momz + z * dy * dz
        areas.append(area)
        My.append(momy)
        Mz.append(momz)
        # Add volume & moment if proceed
        if i > 0:
            dx = xCoord[i] - xCoord[i - 1]
            x = 0.5 * (xCoord[i] + xCoord[i - 1])
            area = 0.5 * (areas[i] + areas[i - 1])
            momy = 0.5 * (My[i] + My[i - 1])
            momz = 0.5 * (Mz[i] + Mz[i - 1])
            vol = vol + area * dx
            vMy = vMy + momy * dx
            vMz = vMz + momz * dx
    # Compute KBT
    kb[0] = vMy / vol
    kb[1] = vMz / vol
    return kb
示例#34
0
def FloatingArea(ship, draft, trim):
    """ Calculate ship floating area.
    @param ship Selected ship instance
    @param draft Draft.
    @param trim Trim in degrees.
    @return Ship floating area, and floating coefficient.
    """
    angle = math.radians(trim)
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    lines = []
    area = 0.0
    minX = None
    maxX = None
    maxY = 0.0
    cf = 0.0
    if not sections:
        return [0.0, 0.0]
    for i in range(0, len(sections)):
        # Get the section
        section = sections[i]
        if len(section) < 2:  # Empty section
            lines.append(0.0)
            continue
        # Get the position of the section
        x = xCoord[i]
        # Get the maximum Z value
        Z = draft - x * math.tan(angle)
        # Format section
        section = convertSection(section, x, Z)
        if not section:
            lines.append(0.0)
            continue
        maxX = x
        if not minX:
            minX = x
        # Get floating line length
        line = 0.0
        flag = True  # Even lines compute for floating areas, odd no
        j = len(section) - 1
        k = len(section[j]) - 1
        while k > 0:
            k = k - 1
            if flag:
                y0 = abs(section[j][k - 1].y)
                y1 = abs(section[j][k].y)
                line = line + (y1 - y0)
                maxY = max([maxY, y1, y0])
            flag = not flag
        if flag:  # Central body computation lefts
            y = abs(section[j][0].y)
            line = line + y
            maxY = max([maxY, y])
        lines.append(2.0 * line)  # 2x because only half ship is represented
        # Add area if proceed
        if i > 0:
            dx = xCoord[i] - xCoord[i - 1]
            x = 0.5 * (xCoord[i] + xCoord[i - 1])
            line = 0.5 * (lines[i] + lines[i - 1])
            area = area + line * dx
    if area:
        cf = area / ((maxX - minX) * 2.0 * maxY)
    return [area, cf]
示例#35
0
objects = [Entry(np.array([5.0,5.0]), np.array([4,4])), Obstacle(np.array([20.0,10.0]), np.array([10, 5])), Obstacle(np.array([60.0,60.0]), np.array([10, 10])), Obstacle(np.array([0.0,0.0]), np.array([2, 80])), Obstacle(np.array([0.0,0.0]), np.array([80, 2])), Obstacle(np.array([78.0,0.0]), np.array([2, 80])), Obstacle(np.array([0.0, 78.0]), np.array([80, 2])), Exit(np.array([76.0, 76.0]), np.array([2, 2]))]
objects.append(Obstacle(np.array([50.0,25.0]), np.array([20, 5])))
objects.append(Exit(np.array([75.0,3.0]), np.array([2, 3])))
objects.append(Entry(np.array([5.0,70.0]), np.array([4,4])))
objects.append(Entry(np.array([35.0,70.0]), np.array([4,4])))
objects.append(Obstacle(np.array([50.0,50.0]), np.array([10, 20])))
objects.append(Obstacle(np.array([20.0,25.0]), np.array([3, 18])))
objects.append(Obstacle(np.array([50.0,25.0]), np.array([5, 24])))
'''
paths = load_path("paths.txt")

F = []

for path in paths:
    F.append(Folower(path))
setup = Setup(size, margin, objects, people)

for k in range(2, 3):
    instance = Instance(setup, 1, k)
    instance.people[0].pos = np.copy(F[k].pos)
    instance.people[0].des_pos = np.copy(F[k].path[-1])
    instance.people[0].direction = np.copy(F[k].direction)
    instance.people[0].vel = np.copy(F[k].vel)
    instance.people[0].des_speed = np.copy(np.linalg.norm(F[k].vel))

    instance.people[0].rad = np.copy(F[k].rad)

    instance.agents = F

    instance.init_show()
示例#36
0
def MainFrameCoeff(ship, draft):
    """ Calculate main frame coefficient.
    @param ship Selected ship instance
    @param draft Draft.
    @return Main frame coefficient
    """
    sections = Instance.sections(ship)
    xCoord = ship.xSection[:]
    cm = 0.0
    if not sections:
        return 0.0
    # Look for nearest to main frame section
    sectionID = 0
    X = xCoord[0]
    for i in range(1, len(sections)):
        # Get the position of the section
        x = xCoord[i]
        if abs(x) < abs(X):
            sectionID = i
            X = x
    # Get the section
    section = sections[sectionID]
    if len(section) < 2:  # Empty section
        return 0.0
    x = X
    # Get the maximum Z value
    Z = draft
    # Format section
    section = convertSection(section, x, Z)
    if not section:
        return 0.0
    # Integrate area
    area = 0.0
    maxY = 0.0
    for j in range(0, len(section) - 1):
        for k in range(0, min(len(section[j]) - 1, len(section[j + 1]) - 1)):
            # y11,z11 ------- y01,z01
            #    |               |
            #    |               |
            #    |               |
            # y10,z10 ------- y00,z00
            y00 = abs(section[j][k].y)
            z00 = section[j][k].z
            y10 = abs(section[j][k + 1].y)
            z10 = section[j][k + 1].z
            y01 = abs(section[j + 1][k].y)
            z01 = section[j + 1][k].z
            y11 = abs(section[j + 1][k + 1].y)
            z11 = section[j + 1][k + 1].z
            dy = 0.5 * ((y00 - y10) + (y01 - y11))
            dz = 0.5 * ((z01 - z00) + (z11 - z10))
            area = area + dy * dz
            maxY = max([maxY, y00, y10, y01, y11])
        if (len(section[j]) < len(section[j + 1])):
            # y01,z01 ------- y11,z11
            #    |        __/
            #    |     __/
            #    |    /
            # y00,z00
            k = len(section[j]) - 1
            y00 = abs(section[j][k].y)
            z00 = section[j][k].z
            y01 = abs(section[j + 1][k].y)
            z01 = section[j + 1][k].z
            y11 = abs(section[j + 1][k + 1].y)
            z11 = section[j + 1][k + 1].z
            dy = y01 - y11
            dz = z01 - z00
            area = area + 0.5 * dy * dz
            maxY = max([maxY, y00, y01, y11])
        elif (len(section[j]) > len(section[j + 1])):
            # y01,z01
            #    |    \__
            #    |       \__
            #    |          \
            # y00,z00 ------- y10,z10
            k = len(section[j + 1]) - 1
            y00 = abs(section[j][k].y)
            z00 = section[j][k].z
            y10 = abs(section[j][k + 1].y)
            z10 = section[j][k + 1].z
            y01 = abs(section[j + 1][k].y)
            z01 = section[j + 1][k].z
            dy = y00 - y10
            dz = z01 - z00
            area = area + 0.5 * dy * dz
            maxY = max([maxY, y00, y10, y01])
        elif (len(section[j]) == 1):
            # y1,z1 -------
            #    |
            #    |
            #    |
            # y0,z0 -------
            k = 0
            y0 = abs(section[j][k].y)
            z0 = section[j][k].z
            y1 = abs(section[j + 1][k].y)
            z1 = section[j + 1][k].z
            dy = 0.5 * (y0 + y1)
            dz = z1 - z0
            area = area + dy * dz
            maxY = max([maxY, y0, y1])
    if maxY * draft > 0.0:
        cm = area / (maxY * draft)
    return cm
示例#37
0
glossy = GlossyReflective(1, 1, 1, Sred, 50000, 1.0, Sred, r_sample)

#Objects

plane = Plane(Point(0, -15, 0), Vector(0, 1, -0.1), greymat)
world.addObject(plane)
plane2 = Plane(Point(0, 0, 20), Vector(0, 0, 1), bluemat)
world.addObject(plane2)

#Reflective Spheres
s3 = Sphere(Point(-22, 0, -3), 10.0, glossy)
world.addObject(s3)

#Instance
sphere = Sphere(Point(0, 0, -5), 5.0, mat)
s_i = Instance(sphere)
s_i.translate(25, 10, 0)
s_i.scale(1, 2, 1)
world.addObject(s_i)

#Transparent Sphere
c = Point(0, 0, -5)
r = 10.0
s = Sphere(c, r, transparent)
world.addObject(s)

#Texture Sphere
image = Image.open("earthmap1k.jpg")
texels = image.load()
sphere_map = SphericalMapping(8.0)
sampler = Regular(25, 83)