コード例 #1
0
class Extract:
    def __init__(self):
        print 'Starting extraction'
        self.instagram = Instagram()
        self.load = Load()

    def extract_twitter(self, accounts):
        print 'Starting Twitter extraction'
        for account in accounts:
            twitter = Twitter(account=account)
            for tweet in twitter.home_timeline():
                self.load.save_tweet(text = tweet.text)

    def extract_instagram(self,accounts):
        print 'Starting Instagram extraction'
        for account in accounts:
            user = self.instagram.get_user(name = account)
            media = self.instagram.get_media(user_id = user.id)
コード例 #2
0
class Run:
    """
    Handles the running of the simulation through its yearly cycles
    """
    log = Logger("Run", "Low")

    def __init__(self):
        """
        Makes a new instance of the run class
        """
        self.new = Load("Feudalism Simulation", True)
        self.log.tracktext("Now Loading")
        self.board = self.new.initialize()
        self.log.tracktext("Loading done")
        cont = 1
        while cont == 1:
            cont = self.cycle()
        self.log.track_popup_only("Simulation complete")

    def cycle(self):
        """
        Goes through the turn for each lord for every year
        :return: a zero when the number of runs is complete
        """
        i = 0
        while i < self.board[2]:
            self.log.trackconsoleonly("Yearly cycle", i)
            lordturn = 0
            wincondition = self.how_many_are_left()
            if wincondition != 1:
                while lordturn < len(self.board[1]):
                    self.board[1][lordturn].dead = self.board[1][lordturn].checkifdead()
                    if not self.board[1][lordturn].dead:
                        self.board[1][lordturn].land.calculatewealth()
                        self.board[1][lordturn].land.placeserf()
                        self.board[1][lordturn].land.findborders(self.board[0], self.board[3], self.board[4])
                        self.board[1][lordturn].decision()
                        lordturn += 1
                    else:
                        self.log.tracktext(str(self.board[1][lordturn].name) + " is defeated")
                        lordturn += 1
            i += 1
            if wincondition == 1:
                self.log.track_popup_only("Simulation ended in year " + str(i))
                i = self.board[2]
        return 0

    def how_many_are_left(self):
        i = 0
        c = len(self.board[1])
        while i < len(self.board[1]):
            if self.board[1][i].dead:
                c -= 1
            i += 1
        return c
コード例 #3
0
ファイル: Environment.py プロジェクト: pranavsb/RL_smart_grid
    def add_load_to_source(self, loadParams = None, sourceID = None):
        if loadParams is None:
            loadParams = {}
        load = Load(**loadParams)

        if sourceID is None:
            sourceID = Source.num_sources - 1

        if load.loadID not in self.load_dict.keys():
            self._add_load(load)

        self.source_dict[sourceID].add_load(load.loadID)
コード例 #4
0
 def __init__(self):
     """
     Makes a new instance of the run class
     """
     self.new = Load("Feudalism Simulation", True)
     self.log.tracktext("Now Loading")
     self.board = self.new.initialize()
     self.log.tracktext("Loading done")
     cont = 1
     while cont == 1:
         cont = self.cycle()
     self.log.track_popup_only("Simulation complete")
コード例 #5
0
    def __init__(self):

        # Load/Read kymograph track data from files
        dinfo = Load()

        # Harvest total times
        self.GetStrainTotalTimes(dinfo.data['strain'])

        # Initialize kymograph objects
        self.InitializeKymographs(dinfo.data['strain'])

        # Process kymograph
        self.ProcessKymographs()

        # Filter bad tracks
        self.bad_count = self.FilterTracks()
        print('There were {} bad tracks'.format(self.bad_count))

        # total switching count
        self.DisplayTracksStatistics()
        self.Graph()
        pdb.set_trace()
コード例 #6
0
ファイル: Bath.py プロジェクト: danse-inelastic/pyre-all
 def __init__(self):
     Load.__init__(self, "bath")
     self.ambient = None
     self.surface = None
     self.density = None
     return
コード例 #7
0
    def init_Start():
        Load.load_Title()
        responce = Load.__init__()
        gc.collect()
        return responce

    def init_Load_Pro():
        gc.collect()
        return Load.load_Project()


#try:
code, msg = ___init___.init_Start()
#print (code)
#print (msg)
path = Load.load_Path() + "Sudarshana"
if code == "1" and not os.getcwd() == path:
    Load.load_Pro_Pros()
    print(msg)
    Load.load_FileDir()
    ROOT, D_NAME, F_NAME = ___init___.init_Load_Pro()
    count = 0
    if D_NAME != []:
        for directory in D_NAME:
            count += 1
            print(str(count) + ".) " + directory)

    if F_NAME != []:
        for file in F_NAME:
            count += 1
            print(str(count) + ".) " + file)
コード例 #8
0
 def __init__(self):
     Load.__init__(self, "heaviside")
     self.position = None
     self.velocity = None
     self.amplitude = None
     return
コード例 #9
0
ファイル: HeavisidePulse.py プロジェクト: bmi-forum/bmi-pyre
 def __init__(self):
     Load.__init__(self, "heaviside")
     self.position = None
     self.velocity = None
     self.amplitude = None
     return
コード例 #10
0
ファイル: TestLoad.py プロジェクト: pranavsb/RL_smart_grid
from Load import Load
from DemandRange import DemandRange
l = Load()
dr = DemandRange()
l.set_demand_ranges(130)
dr.set_lower_bound(50)
dr.set_upper_bound(60)

コード例 #11
0
ファイル: Bath.py プロジェクト: bmi-forum/bmi-pyre
 def __init__(self):
     Load.__init__(self, "bath")
     self.ambient = None
     self.surface = None
     self.density = None
     return
コード例 #12
0
 def load(self, event=None):
     _ = Load(self.subj_frame, self.SubjectList)
コード例 #13
0
ファイル: Environment.py プロジェクト: pranavsb/RL_smart_grid
 def add_load(self, loadParams=None):
     if loadParams is None:
         loadParams = {}
     load = Load(**loadParams)
     self._add_load(load)
コード例 #14
0
def load():
    global payload
    loadCml = Load("commandline")
    loadXss = Load("xss")
    payload['cml'] = loadCml.get()
    payload['xss'] = loadXss.get()
コード例 #15
0
from Load import Load

if __name__ == '__main__':
    load = Load()
    load.insert_restaurant_to_graph()
    load.insert_geojson_to_mongodb()
コード例 #16
0
ファイル: Energy_System.py プロジェクト: tur-ium/CLOVER
    def simulation(self,
                   start_year=0,
                   end_year=4,
                   PV_size=10,
                   storage_size=10,
                   **options):
        '''
        Function:
            Simulates a minigrid system
        Inputs:
            start_year          Start year of this simulation period
            end_year            End year of this simulation period
            PV_size             Amount of PV in kWp
            storage_size        Amount of storage in kWh
            
        Outputs:
            tuple([system_performance_outputs,system_details]):
                system_performance_outputs          Hourly performance of the simulated system
                    load_energy                     Amount of energy (kWh) required to satisfy the loads
                    total_energy_used               Amount of energy (kWh) used by the system
                    unmet_energy                    Amount of energy (kWh) unmet by the system
                    blackout_times                  Times with power is available (0) or unavailable (1)
                    renewables_energy_used_directly Amount of energy (kWh) from renewables used directly to satisfy load (kWh)
                    storage_power_supplied          Amount of energy (kWh) supplied by battery storage
                    grid_energy                     Amount of energy (kWh) supplied by the grid
                    diesel_energy                   Amount of energy (kWh) supplied from diesel generator
                    diesel_times                    Times when diesel generator is on (1) or off (0)
                    diesel_fuel_usage               Amount of diesel (l) used by the generator
                    storage_profile                 Amount of energy (kWh) into (+ve) and out of (-ve) the battery
                    renewables_energy               Amount of energy (kWh) provided by renewables to the system
                    hourly_storage                  Amount of energy (kWh) in the battery
                    energy_surplus                  Amount of energy (kWh) dumped owing to overgeneration
                    battery_health                  Relative capactiy of the battery compared to new (0.0-1.0)
                    households                      Number of households in the community
                    kerosene_usage                  Number of kerosene lamps in use (if no power available)
                    kerosene_mitigation             Number of kerosene lamps not used (when power is available)
                system details                      Information about the installed system     
                    Start year                      Start year of the simulation
                    End year                        End year of the simulation
                    Initial PV size                 Capacity of PV installed (kWp)
                    Initial storage size            Capacity of battery storage installed (kWh)
                    Final PV size                   Equivalent capacity of PV (kWp) after simulation
                    Final storage size              Equivalent capacity of battery storage (kWh) after simulation
                    Diesel capacity                 Capacity of diesel generation installed (kW)
        '''
        #   Start timer to see how long simulation will take
        timer_start = datetime.datetime.now()

        #   Initialise values for simulation
        PV_size = float(PV_size)
        storage_size = float(storage_size)

        #   Get input profiles
        input_profiles = self.get_storage_profile(start_year, end_year,
                                                  PV_size, **options)
        load_energy = pd.DataFrame(input_profiles['Load energy (kWh)'])
        renewables_energy = pd.DataFrame(
            input_profiles['Renewables energy supplied (kWh)'])
        renewables_energy_used_directly = pd.DataFrame(
            input_profiles['Renewables energy used (kWh)'])
        grid_energy = pd.DataFrame(input_profiles['Grid energy (kWh)']).abs()
        storage_profile = pd.DataFrame(input_profiles['Storage profile (kWh)'])
        kerosene_profile = pd.DataFrame(input_profiles['Kerosene lamps'])
        households = pd.DataFrame(
            Load().population_hourly()[start_year * 8760:end_year *
                                       8760].values)

        #   Initialise battery storage parameters
        max_energy_throughput = storage_size * self.energy_system_inputs[1][
            'Battery cycle lifetime']
        initial_storage = storage_size * self.energy_system_inputs[1][
            'Battery maximum charge']
        max_storage = storage_size * self.energy_system_inputs[1][
            'Battery maximum charge']
        min_storage = storage_size * self.energy_system_inputs[1][
            'Battery minimum charge']
        battery_leakage = self.energy_system_inputs[1]['Battery leakage']
        battery_eff_in = self.energy_system_inputs[1]['Battery conversion in']
        battery_eff_out = self.energy_system_inputs[1][
            'Battery conversion out']
        battery_C_rate = self.energy_system_inputs[1]['Battery C rate']
        battery_lifetime_loss = self.energy_system_inputs[1][
            'Battery lifetime loss']
        cumulative_storage_power = 0.0
        hourly_storage = []
        new_hourly_storage = []
        battery_health = []

        #   Initialise simulation parameters
        diesel_backup_status = self.scenario_inputs[1]['Diesel backup']
        diesel_backup_threshold = float(
            self.scenario_inputs[1]['Diesel backup threshold'])

        #   Initialise energy accounting parameters
        energy_surplus = []
        energy_deficit = []
        storage_power_supplied = []

        #   Begin simulation, iterating over timesteps
        for t in range(0, int(storage_profile.size)):
            battery_energy_flow = storage_profile.iloc[t][0]
            if t == 0:
                new_hourly_storage = initial_storage + battery_energy_flow
            else:
                if battery_energy_flow >= 0.0:  # Battery charging
                    new_hourly_storage = hourly_storage[t - 1] * (
                        1.0 - battery_leakage) + battery_eff_in * min(
                            battery_energy_flow,
                            battery_C_rate * (max_storage - min_storage))
                else:  # Battery discharging
                    new_hourly_storage = hourly_storage[t - 1] * (
                        1.0 - battery_leakage) + (1.0 / battery_eff_out) * max(
                            battery_energy_flow, (-1.0) * battery_C_rate *
                            (max_storage - min_storage))

#   Dumped energy and unmet demand
            energy_surplus.append(max(new_hourly_storage - max_storage,
                                      0.0))  #Battery too full
            energy_deficit.append(max(min_storage - new_hourly_storage,
                                      0.0))  #Battery too empty

            #   Battery capacities and blackouts (if battery is too full or empty)
            if new_hourly_storage >= max_storage:
                new_hourly_storage = max_storage
            elif new_hourly_storage <= min_storage:
                new_hourly_storage = min_storage
#   Update hourly_storage
            hourly_storage.append(new_hourly_storage)

            #   Update battery health
            if t == 0:
                storage_power_supplied.append(0.0 - battery_energy_flow)
            else:
                storage_power_supplied.append(
                    max(
                        hourly_storage[t - 1] * (1.0 - battery_leakage) -
                        hourly_storage[t], 0.0))
            cumulative_storage_power = cumulative_storage_power + storage_power_supplied[
                t]

            storage_degradation = (
                1.0 - battery_lifetime_loss *
                (cumulative_storage_power / max_energy_throughput))
            max_storage = (
                storage_degradation * storage_size *
                self.energy_system_inputs[1]['Battery maximum charge'])
            min_storage = (
                storage_degradation * storage_size *
                self.energy_system_inputs[1]['Battery minimum charge'])
            battery_health.append(storage_degradation)

#   Consolidate outputs from iteration stage
        storage_power_supplied = pd.DataFrame(storage_power_supplied)

        #   Find unmet energy
        unmet_energy = pd.DataFrame(
            (load_energy.values - renewables_energy_used_directly.values -
             grid_energy.values - storage_power_supplied.values))
        blackout_times = ((unmet_energy > 0) * 1).astype(float)

        #   Use backup diesel generator
        if diesel_backup_status == "Y":
            diesel_energy, diesel_times = Diesel().get_diesel_energy_and_times(
                unmet_energy, blackout_times, diesel_backup_threshold)
            diesel_capacity = math.ceil(np.max(diesel_energy))
            diesel_fuel_usage = pd.DataFrame(Diesel().get_diesel_fuel_usage(
                diesel_capacity, diesel_energy, diesel_times).values)
            unmet_energy = pd.DataFrame(unmet_energy.values -
                                        diesel_energy.values)
            diesel_energy = diesel_energy.abs()
        else:
            diesel_energy = pd.DataFrame([0.0] * int(storage_profile.size))
            diesel_times = pd.DataFrame([0.0] * int(storage_profile.size))
            diesel_fuel_usage = pd.DataFrame([0.0] * int(storage_profile.size))
            diesel_capacity = 0.0

#   Find new blackout times, according to when there is unmet energy
        blackout_times = ((unmet_energy > 0) * 1).astype(float)
        #   Ensure all unmet energy is calculated correctly, removing any negative values
        unmet_energy = ((unmet_energy > 0) * unmet_energy).abs()

        #   Find how many kerosene lamps are in use
        kerosene_usage = pd.DataFrame(blackout_times.values *
                                      kerosene_profile.values)
        kerosene_mitigation = pd.DataFrame(
            (1 - blackout_times).values * kerosene_profile.values)

        #   System performance outputs
        blackout_times.columns = ['Blackouts']
        hourly_storage = pd.DataFrame(hourly_storage)
        hourly_storage.columns = ['Hourly storage (kWh)']
        energy_surplus = pd.DataFrame(energy_surplus)
        energy_surplus.columns = ['Dumped energy (kWh)']
        unmet_energy.columns = ['Unmet energy (kWh)']
        storage_power_supplied.columns = ['Storage energy supplied (kWh)']
        diesel_energy.columns = ['Diesel energy (kWh)']
        battery_health = pd.DataFrame(battery_health)
        battery_health.columns = ['Battery health']
        diesel_times.columns = ['Diesel times']
        diesel_fuel_usage.columns = ['Diesel fuel usage (l)']
        households.columns = ['Households']
        kerosene_usage.columns = ['Kerosene lamps']
        kerosene_mitigation.columns = ['Kerosene mitigation']

        #   Find total energy used by the system
        total_energy_used = pd.DataFrame(
            renewables_energy_used_directly.values +
            storage_power_supplied.values + grid_energy.values +
            diesel_energy.values)
        total_energy_used.columns = ['Total energy used (kWh)']

        #   System details
        system_details = pd.DataFrame(
            {
                'Start year':
                float(start_year),
                'End year':
                float(end_year),
                'Initial PV size':
                PV_size,
                'Initial storage size':
                storage_size,
                'Final PV size':
                PV_size *
                Solar().solar_degradation()[0][8760 * (end_year - start_year)],
                'Final storage size':
                storage_size * np.min(battery_health['Battery health']),
                'Diesel capacity':
                diesel_capacity
            },
            index=['System details'])

        #   End simulation timer
        timer_end = datetime.datetime.now()
        time_delta = timer_end - timer_start
        print("\nTime taken for simulation: " +
              "{0:.2f}".format((time_delta.microseconds * 0.000001) /
                               float(end_year - start_year)) +
              " seconds per year")

        #   Return all outputs
        system_performance_outputs = pd.concat([
            load_energy, total_energy_used, unmet_energy, blackout_times,
            renewables_energy_used_directly, storage_power_supplied,
            grid_energy, diesel_energy, diesel_times, diesel_fuel_usage,
            storage_profile, renewables_energy, hourly_storage, energy_surplus,
            battery_health, households, kerosene_usage, kerosene_mitigation
        ],
                                               axis=1)

        return tuple([system_performance_outputs, system_details])
コード例 #17
0
ファイル: Main.py プロジェクト: wyh0106/python_homework
#!/usr/bin/env python
# _*_ coding:utf-8 _*_

# Copyright © 2020 ROOM_3033
# All rights reserved.

# filename:$Homework_333$
# description:从名单中生成一份考勤列表,出勤次数为0-10的随机数。

# created by 魏懿航 at 04/09/2020
# QQ:770593981
pass

# ===============RUN_START===============

from Load import Load_stu_list as Load
from Header import Header
from Output import Output

# 加载名单文件到一个字典嵌套中
stu_list = Load('名单.txt')

# 生成考勤列表文件,并写入表头
Header()

# 生成随机数并输出
Output(stu_list)

# ======================RUN_END=========================
コード例 #18
0
 def __init__(self):
     print 'Starting extraction'
     self.instagram = Instagram()
     self.load = Load()
コード例 #19
0
 def init_Start():
     Load.load_Title()
     responce = Load.__init__()
     gc.collect()
     return responce
コード例 #20
0
 def init_Load_Pro():
     gc.collect()
     return Load.load_Project()
コード例 #21
0
#!/usr/bin/env python
'''@package docstring
Loads some numerical functions defined in a C++ file
'''

from os import getenv
from Load import Load
from ROOT import gROOT

Load('Functions')
gROOT.LoadMacro(
    getenv('CMSSW_BASE') + '/src/PandaCore/Tools/interface/Functions.h')
コード例 #22
0
ファイル: main.py プロジェクト: JanTSV/PyDrawer
def main():
    pygame.init()
    width = 600
    height = 900

    display = pygame.display.set_mode((width, height))
    pygame.display.set_caption("PyDrawer")

    save = Save()
    delete = Delete()
    load = Load()

    color = None
    draw = True
    drawRects = []
    drawing = False
    cs = [(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0),
          (0, 255, 255), (255, 0, 255), (51, 51, 51)]
    cw = 45
    d = 30
    colors = []

    for c in cs:
        col = Color(c)
        colors.append(col)

    while draw:
        display.fill((255, 255, 255))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                draw = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                x, y = pygame.mouse.get_pos()
                if x > cw and x < cw + 4 * cw:
                    if y > 15 * cw and y < 17 * cw:
                        for c in colors:
                            c.isSelected(x, y)

                if y > 15 * cw:
                    save.isClicked(x, y, drawRects)
                    drawRects = load.isClicked(x, y, drawRects)
                    drawRects = delete.isClicked(x, y, drawRects)

                if y < 14 * cw:
                    drawing = True
                    for c in colors:
                        if c.selected:
                            color = c.color
                    tx = x // d
                    ty = y // d
                    check = 0
                    for r in drawRects:
                        if r[0] == tx and r[1] == ty and r[2] == color:
                            check += 1
                    if check == 0:
                        drawRects.append([tx, ty, color])
                else:
                    drawing = False
            if event.type == pygame.MOUSEMOTION and drawing and color:
                x, y = pygame.mouse.get_pos()
                if y < 14 * cw:
                    x = x // d
                    y = y // d

                    for r in range(0, len(drawRects), 1):
                        try:
                            if drawRects[r][0] == x and drawRects[r][1] == y:
                                drawRects.pop(r)
                        except:
                            pass

                    drawRects.append([x, y, color])

                    print(len(drawRects))

            if event.type == pygame.MOUSEBUTTONUP:

                drawing = False
        i = 0
        for y in range(0, 2):
            for x in range(0, 4):
                try:
                    colors[i].draw(display, (x + 1) * cw, (y + 15) * cw, cw)
                    colors[i].update()
                except:
                    pass

                i += 1

        save.draw(display, 7 * cw, 15 * cw)
        load.draw(display, 9 * cw, 15 * cw)
        delete.draw(display, 11 * cw, 15 * cw)
        for r in drawRects:
            pygame.draw.rect(display, r[2], (r[0] * d, r[1] * d, d, d))

        pygame.display.update()

    pygame.quit()
    quit()