Example #1
0
def main():
	n= int(input("How many stars do you want on your Dragon Ball? (enter a number from 1-7, anything greater will stop at 7)"))
	t = turtle.Turtle()
	w = turtle.Screen()
	w.setup(1000,700)
	t.hideturtle()
	t.speed(0)
	bg.background(t)
	Jimmy.dball(t)
	Star.stars(t, 65,"red", n)
	w.exitonclick()
Example #2
0
 def generate_stars(self):
     self.c_star = None
     for keys in self.obj_values():
         star = Star(keys)
         self.ALL_OBJECTS.append(star)
         self.MASS += self.star_mass
     if self.v_method == "complete":
         self.adjust_vel()
Example #3
0
    def getStar(self, index):
        """
        Parameters
        ----------
        index: int
            Index of requested star in the star catalog.
        
        Returns
        -------
        Star: instance
            Instance of class Star.
        """

        try:
            tempVmag = self.StarCatalog.SC[index]['Vmag']
        except:
            tempVmag = None
        try:
            tempJmag = self.StarCatalog.SC[index]['Jmag']
        except:
            tempJmag = None
        try:
            tempHmag = self.StarCatalog.SC[index]['Hmag']
        except:
            tempHmag = None
        try:
            tempWDSsep = self.StarCatalog.SC[index]['WDSsep']
        except:
            tempWDSsep = None
        try:
            tempWDSdmag = self.StarCatalog.SC[index]['WDSdmag']
        except:
            tempWDSdmag = None
        try:
            templGal = self.StarCatalog.SC[index]['lGal']
        except:
            templGal = None
        try:
            tempbGal = self.StarCatalog.SC[index]['bGal']
        except:
            tempbGal = None

        return Star.Star(self.StarCatalog.SC[index]['Name'],
                         self.StarCatalog.SC[index]['Dist'],
                         self.StarCatalog.SC[index]['Stype'],
                         self.StarCatalog.SC[index]['Rad'],
                         self.StarCatalog.SC[index]['Teff'],
                         self.StarCatalog.SC[index]['Mass'],
                         self.StarCatalog.SC[index]['RA'],
                         self.StarCatalog.SC[index]['Dec'], tempVmag, tempJmag,
                         tempHmag, tempWDSsep, tempWDSdmag, templGal, tempbGal)
def loadmap(screen):
    wall_list = pygame.sprite.Group()  # 벽들을 모아둘 그룹
    #star_list = pygame.sprite.Group()  #구현이 안됨
    #ball_list = pygame.sprite.Group()  #구현이 안됨
    thorn_list = pygame.sprite.Group()

    move_image = pygame.image.load('mapeditimage/move.png')
    wall_image = pygame.image.load('mapeditimage/wall.png')
    thorn_image = pygame.image.load('mapeditimage/thorn.png')
    star_image = pygame.image.load('mapeditimage/star.png')
    ball_image = pygame.image.load('mapeditimage/ball.png')

    try:
        f = open('map.txt', 'r')
    except:
        print("불러올 맵이 존재하지 않습니다.\a")
        return -1

    size = f.readline().split(' ')
    width = int(size[0])
    height = int(size[1])
    pixel_size = int(size[2])
    while True:
        line = f.readline()
        if not line:
            break
        if line == 0:
            continue
        #temp = ['블럭형태', 'x좌표','y좌표','픽셀크기(정사각형임)']
        temp = line.split(' ')
        if temp[0].find('wall') != -1:
            wall_list.add(
                Wall.Wall(wall_image, (int(temp[1]), int(temp[2])),
                          (int(temp[3]), int(temp[3]))))
        #가시는 구현이 안돼있어서 뺐음
        # elif temp[0].find('thorn') != -1:
        #     thorn_list.add(Thorn.Thorn(thorn_image, (temp[1], temp[2]), (temp[3], temp[3])))
        elif temp[0].find('star') != -1:
            star = Star.Star(star_image, (int(temp[1]), int(temp[2])),
                             (int(temp[3]), int(temp[3])))
        elif temp[0].find('ball') != -1:
            ball = Ball.Ball(ball_image, (int(temp[1]), int(temp[2])),
                             (int(temp[3]), int(temp[3])))
        else:
            continue
    f.close()

    #여기는 나중에 어떻게 해야될것 같다
    return [wall_list, star, ball]
Example #5
0
 def __init__(self):
     import Drawing
     self.__starColl = Star.StarCollection()  #天体集合
     self.__updateSpan = 100000  #每次计算对应虚拟世界的时间长度
     self.__scale = 7E-11  #空间的比例尺
     self.__canvas = None  #用于绘制的画布
     self.__drawInterval = 0.016  #两次绘制的间隔
     self.__updateInterval = 0.001  #两次计算的间隔
     self.__updateLoop = Loop(self.__updateInterval, self.__onUpdate)  #计算线程
     self.__drawLoop = Loop(self.__drawInterval, self.__onDraw)  #绘制线程
     self.__drawing = Drawing.Drawing()
     self.__drawTime1 = datetime.now()  #前一次绘制的时间
     self.__drawTime2 = datetime.now()  #后一次绘制的时间(用于计算帧频)
     self.__updateTime1 = datetime.now()  #前一次计算的时间
     self.__updateTime2 = datetime.now()  #后一次计算的时间(用于计算时间比例尺)
     self.__followedNumber = -1
Example #6
0
    def loadCatalog(self, starFile=None):
        print "Loading Catalog\n"
        numStarsAdded = 0
        newList = []

        # Exception Test: Is file valid?
        try:
            File = open(starFile, 'r')
        except IOError:
            print "Exception Raised: Invalid File\n Loading Failed"
            raise ValueError("Exception Raised: Invalid File\n Loading Failed")

        for line in File:  # For each line in the file, parse line and create new Star object
            inStringList = line.strip('\n').split('\t')
            inID = int(inStringList[0])
            inMagn = float(inStringList[1])
            inRA = float(inStringList[2])
            inDec = float(inStringList[3])

            if (inRA > 2 * math.pi):
                inRA -= 2 * math.pi
            newStar = Star.Star(inID, inMagn, inRA, inDec)

            # Exception Test: Is Star duplicate?
            try:
                for star in self.StarList:
                    if newStar.getID() == star.getID():
                        raise ValueError
            except ValueError:
                print "Exception Raised: Duplicate Star Found\n Loading Failed"
                raise ValueError

            # Add new Star to new List and run Magnitude Tests
            newList.append(newStar)
            numStarsAdded = numStarsAdded + 1
            if newStar.getMagn() > self.highestMagn:
                self.highestMagn = newStar.getMagn()
            elif newStar.getMagn() < self.lowestMagn:
                self.lowestMagn = newStar.getMagn()

            # Close File and Concatenate Old List with New List
        File.close()
        self.StarList = self.StarList + newList

        print "Loading Completed Successfully"
        return numStarsAdded
 def fillWithEnemiesAndStar(self):
     for c in range(self.params['num_enemies']):
         enemy = Enemy.EnemySprite(width=self.params['enemy_size'], 
                                   height=self.params['enemy_size'], 
                                   x = self.params['x'] , 
                                   y=self.params['y']+ 30, 
                                   density=1 )
         self.bodies += enemy.render()[0]
         self.joints += enemy.render()[1]
     self.contacts += enemy.render()[2]
         
     star = Star.StarSprite(x = self.params['x'],
                            y=self.params['y'],
                            width=self.params['enemy_size'], 
                            height=self.params['enemy_size'])
     self.bodies += star.render()[0]
     self.joints += star.render()[1]
     self.contacts += star.render()[2]
def create():
    # star(name, color, size, min_orbit, max_orbit, hab_orbit, orbits)
    star = Star.Star("Alhazred", None, None, None, None, None, None)
    star.color = get_star_color()
    star.size = get_star_size(star.color)
    if star.size == 'Dwarf':
        star.color = 'D' + star.color[0]
        print(star.color)
    star.orbits = get_stellar_orbits(star.size, star.color)
    star.max_orbit = get_max_orbits(star.size, star.color) - 1
    if star.max_orbit >= len(star.orbits):
        star.max_orbit = len(star.orbits) - 1
    star.orbits = star.orbits[:star.max_orbit]
    star.min_orbit = get_min_orbit(star.orbits)
    star.hab_orbit = get_hab_orbit(star.orbits)
    # print("{} {} {} \nOrbits: {}\nMinimum: {}\nHabitable: {}\nMaximum: {}".format(star.name, star.color, star.size,
    #                                                                             star.orbits, star.min_orbit, star.hab_orbit,
    #                                                                              star.max_orbit))
    return star
Example #9
0
    def creatStar(self):
        '''创建行星的函数'''
        try:
            mass = eval(self.top1_v_m.get())  #获得系列参数
            r = eval(self.top1_v_r.get())
            list_p = self.top1_v_p.get().split(",")
            list_v = self.top1_v_v.get().split(",")
            x_p = eval(list_p[0])
            y_p = eval(list_p[1])
            x_v = eval(list_v[0])
            y_v = eval(list_v[1])
            self.star1 = Star.Star(mass, r)  #创建新的star对象并设置参数
            self.star1.setColor(self.top1_v_c.get())
            self.star1.setPos(Vector.Vector(x_p, y_p))
            self.star1.setV(Vector.Vector(x_v, y_v))
            starColl = self.__starPanel.getStarColl()  #将新的star对象添加进starColl列表中
            starColl.append(self.star1)
            self.__starPanel.startGraphic()  #重新开始绘制线程
            self.clear_top1()
            showinfo("Success", "A star has been created")  #显示行星已经被创建的信息

        except:
            showwarning("Error", "enter failed")  #错误输入时弹出窗口报错
            self.clear_top1()  #清空输入框中的信息以便重新输入
Example #10
0
def makeASolarSystem(starPanel):
    '''
    创建一个示例的太阳系
    '''
    starColl = starPanel.getStarColl()

    sun = Star.Star(1.9891E30, 6.96E8)
    sun.setColor("red")
    starColl.append(sun)

    mercury = Star.Star(3.3022E23, 2.44E6)
    mercury.setPos(Vector.Vector(4.60E10, 0))
    mercury.setV(Vector.Vector(0, 5.479E4))
    mercury.setColor("blue")
    starColl.append(mercury)

    venus = Star.Star(4.8676E24, 6.052E6)
    venus.setPos(Vector.Vector(1.07477E11, 0))
    venus.setV(Vector.Vector(0, 3.527E4))
    venus.setColor("orange")
    starColl.append(venus)

    earth = Star.Star(5.9742E24, 6.372797E6)
    earth.setPos(Vector.Vector(1.47098074E11, 0))
    earth.setV(Vector.Vector(0, 3.0296E4))
    earth.setColor("navy")
    starColl.append(earth)

    moon = Star.Star(7.3477E22, 1.737E6)
    moon.setPos(Vector.Vector(1.47461178E11, 0))
    moon.setV(Vector.Vector(0, 3.1373E4))
    moon.setColor("gray")
    starColl.append(moon)

    mars = Star.Star(6.4185E24, 3.389E6)
    mars.setPos(Vector.Vector(2.0662E11, 0))
    mars.setV(Vector.Vector(0, 2.651E4))
    mars.setColor("darkred")
    starColl.append(mars)

    jupiter = Star.Star(1.8986E27, 6.9911E7)
    jupiter.setPos(Vector.Vector(7.405736E11, 0))
    jupiter.setV(Vector.Vector(0, 1.371E4))
    jupiter.setColor("brown")
    starColl.append(jupiter)

    uranus = Star.Star(8.6810E25, 2.5559E7)
    uranus.setPos(Vector.Vector(2.748938461E12, 0))
    uranus.setV(Vector.Vector(0, 7.103E3))
    uranus.setColor("lightblue")
    starColl.append(uranus)

    neptune = Star.Star(1.0243E26, 2.4767E7)
    neptune.setPos(-Vector.Vector(4.452940833E12, 0))
    neptune.setV(-Vector.Vector(0, 5.49154E3))
    neptune.setColor("blue")
    starColl.append(neptune)

    pluto = Star.Star(1.305E22, 1.186E6)
    pluto.setPos(Vector.Vector(4.437E12, 0))
    pluto.setV(Vector.Vector(0, 6.103E3))
    pluto.setColor("blue")
    starColl.append(pluto)

    starColl.calibrate()
Example #11
0
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
FRAMES_PER_SECOND = 30
BGCOLOR = (0, 128, 128)

# 3 - Initialize the world
pygame.init()
window = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
clock = pygame.time.Clock()

# 4 - Load assets: images(s), sounds, etc.

# 5 - Initialize variables
oResetButton = pygwidgets.TextButton(window, (300, 420), 'Reset star')

oStar = Star(window, (280, 200))
oFrisbee = Frisbee(window, (180, 200))
oSquare = Square(window, (280, 300))
oCar = Car(window, (280, 100))
oDinosaur = Dinosaur(window, (280, 300))

myList = [oStar, oFrisbee, oSquare, oCar, oDinosaur]

# 6 - Loop forever
while True:

    # 7 - Check for and handle events
    for event in pygame.event.get():
        # check if the event is the X button
        if event.type == QUIT:
            pygame.quit()
Example #12
0
    def SummaryPlot(
            self,
            Ntest=100000,
            Rp_range=None,  # Rearth
            Porb_range=None,  # d
            FigDir=None,
            block=True):
        """
        Parameters
        ----------
        Ntest: int
            Number of test draws for summary plot.
        Rp_range: list
            Requested planet radius range (Rearth).
        Porb_range: list
            Requested planet orbital period range (d).
        FigDir: str
            Directory to which summary plots are saved.
        block: bool
            If True, blocks plots when showing.
        """

        Rp = []
        Porb = []
        Sun = Star.Star(
            'Sun',
            10.,  # pc
            'G',
            1.,  # Rsun
            5780.,  # K
            1.,  # Msun
            0.,  # deg
            0.)  # deg
        for i in range(Ntest):
            tempRp, tempPorb = self.draw(Rp_range, Porb_range, Star=Sun)
            Rp += [tempRp]
            Porb += [tempPorb]
        Rp = np.concatenate(Rp)
        Porb = np.concatenate(Porb)

        print(
            '--> HabitableNominal:\n%.2f planets/star in [%.1f, %.1f] Rearth and [%.1f, %.1f] d'
            % (len(Rp) / float(Ntest), np.min(Rp), np.max(Rp), np.min(Porb),
               np.max(Porb)))

        Weight = 1. / len(Rp)
        f, ax = plt.subplots(1, 2)
        ax[0].hist(Rp, bins=25, weights=np.ones_like(Rp) * Weight)
        ax[0].grid(axis='y')
        ax[0].set_xlabel('Planet radius [$R_\oplus$]')
        ax[0].set_ylabel('Fraction')
        ax[1].hist(Porb, bins=25, weights=np.ones_like(Porb) * Weight)
        ax[1].grid(axis='y')
        ax[1].set_xlabel('Planet orbital period [d]')
        ax[1].set_ylabel('Fraction')
        plt.suptitle('HabitableNominal')
        plt.tight_layout(rect=[0, 0, 1, 0.95])
        if (FigDir is not None):
            plt.savefig(FigDir + 'PlanetDistribution_HabitableNominal.pdf')
        plt.show(block=block)
        plt.close()

        pass
Example #13
0
def game():
    size = (900, 910)
    screen = initialize(size)

    rocketYSpeed = 3
    rocketXSpeed = 3
    opponentSpeed = 3
    opponentLives = 5
    done = False
    bulletSpeed = 5
    noOfMovesSinceLastOpponent = 0

    rocket = Rocket(size[0]/2, size[1]-100)
    bullets = []
    opponents = [Opponent((i+1)*80,25,size[0],size[1],opponentLives) for i in range(math.floor(size[0]/80),0,10)]
    stars = [Star(randrange(size[0]), randrange(size[1]), size[1]) for i in range(200)]
    score = Score(size[1])


    pygame.display.set_caption("Spiel")

    # =================
    # = Main Programm =
    # =================
 
    clock = pygame.time.Clock()
    while not done:
        # Main event loop
        for event in pygame.event.get():
            if (event.type == pygame.KEYDOWN and event.key == pygame.K_q) or (event.type == pygame.QUIT):
                print ("The game was quit")
                done = True
            if event.type == pygame.KEYDOWN and event.key == pygame.K_p:
                print ("Color changed")
                rocket.switchColor()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                bullets.append(Bullet(rocket.x - 17, rocket.y - 5))
                bullets.append(Bullet(rocket.x + 58, rocket.y - 5))
            if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
                score.addScore()

        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_UP]:
            rocket.moveY(-rocketYSpeed)
        if pressed[pygame.K_DOWN]:
            rocket.moveY(+rocketYSpeed)
        if pressed[pygame.K_LEFT]:
            rocket.moveX(-rocketXSpeed)
        if pressed[pygame.K_RIGHT]:
            rocket.moveX(+rocketXSpeed)

            
        # Game dynamics
        for b in bullets:
            b.move(bulletSpeed)
            if (b.isOffScreen()):
                bullets.remove(b)
            for o in opponents:
                if (o.isHitByBullet(b)):
                    bullets.remove(b)
                    if (o.isDead()):
                        opponents.remove(o)
                        score.addScore()
                    break
            
        for s in stars:
            s.move()

        for o in opponents:
            o.move(opponentSpeed)
                            
        noOfMovesSinceLastOpponent += 1
        if (noOfMovesSinceLastOpponent == 45):
            noOfMovesSinceLastOpponent = 0
            opponents.append(Opponent(size[0]-25,25,size[0],size[1],opponentLives))
        
        # Draw loop
        drawGameScreen(screen, rocket, bullets, opponents, stars, score)
        
        pygame.display.flip()
        clock.tick(60)
Example #14
0
from Engine import Engine
import Planet
import Star
import Orbit
from GravComplex import Solarsystem

au = 149597870691.0

if __name__ == '__main__':
    e = Engine()
    # init bodies
    sun = Star.Star(2e30, [0, 0], "Sun")
    merk = Planet.Planet(mass=3.301e23, pos=[1, 0], name='Merkur')
    merk.set_orbit(Orbit.Orbit(sun, merk, exzentritaet=0.20563,
                               ga=0.387099273))
    venus = Planet.Planet(mass=4.869e24, pos=[2, 0], name='Venus')
    venus.set_orbit(Orbit.Orbit(sun, venus, exzentritaet=0.0067, ga=0.723))
    earth = Planet.Planet(mass=5.974e24, pos=[3, 0], name='Earth')
    earth.set_orbit(Orbit.Orbit(sun, earth, exzentritaet=0.0167, ga=1))
    mars = Planet.Planet(mass=6.419e23, pos=[4, 0], name='Mars')
    mars.set_orbit(Orbit.Orbit(sun, mars, exzentritaet=0.0935, ga=1.524))
    jupiter = Planet.Planet(mass=1.899e27, pos=[5, 0], name='Jupiter')
    jupiter.set_orbit(Orbit.Orbit(sun, jupiter, exzentritaet=0.0484, ga=5.203))
    jupiter.orbit.inklination = 2.277e-2
    s = Solarsystem()
    s.add_body(merk)
    s.add_body(venus)
    s.add_body(earth)
    s.add_body(mars)
    s.add_body(jupiter)
Example #15
0
 def __init__(self):
     #generate 1 or two stars
     star1 = ST.MakeRandomStar()
Example #16
0
def ln_likelihood(pars,
                  pars_walker,
                  pars_add,
                  data_spectra,
                  background_spectra,
                  wavelengths_spectra,
                  standard_deviation,
                  return_intensity=False):
    """
        Calculates the likelihood function of the model.

    Parameters
    ==========
    pars: dictionary
        All parameters
    pars_walker : np.array
        The model parameters of the walker
    pars_add : dictionary
        The additional parameters that have to be calculated
    data_spectra : dictionary
        The observed spectra ordered per phase
    background_spectra : dictionary
        The background spectra ordered per phase
    wavelengths_spectra : np.array
        The wavelength array
    standard_deviation : dictionary
        The standard deviation ordered per phase
    Returns
    =======
    chi_squared : float
        The chi-squared of the model
    Likelihood : float
        The log likelihood of the model
    model_spectra : dictionary
        The model spectra
    """
    ###### Create the post-AGB star with a Fibonacci grid
    postAGB = Star.Star(pars_walker[pars['MODEL']['primary_radius']['id']],
                        np.array([0, 0, 0]),
                        pars_walker[pars['MODEL']['inclination']['id']],
                        pars['OTHER']['gridpoints_primary'])

    ###### Create the jet
    jet = create_jet.create_jet(pars['OTHER']['jet_type'], pars, pars_walker)

    ###### create the binary orbit
    primary_orbit = {}
    secondary_orbit = {}

    chi_squared = 0
    ln_likelihood = 0

    if return_intensity == True:

        model_spectra = {}
    ndata = 0
    for phase in data_spectra.keys():
        ###### iterate over each orbital phase

        prim_pos, sec_pos, prim_vel, sec_vel = geometry_binary.pos_vel_primary_secondary(
            phase, pars['BINARY']['period'], pars['BINARY']['omega'],
            pars['BINARY']['ecc'], pars_add['primary_sma_AU'],
            pars_add['secondary_sma_AU'], pars['BINARY']['T_inf'],
            pars['BINARY']['T0'])

        postAGB.centre = prim_pos
        jet.jet_centre = sec_pos

        if pars['OTHER']['tilt'] == True:

            jet._set_orientation(np.array([sec_vel]))

        if pars['OTHER']['jet_type'] == 'sdisk_wind' or pars['OTHER'][
                'jet_type'] == 'sdisk_wind_strict':

            jet._set_centre_shift(pars_add['disk_radius_out'])

        postAGB._set_grid()
        postAGB._set_grid_location()

        intensity = model(pars, pars_walker, pars_add, wavelengths_spectra,
                          jet, postAGB)

        if return_intensity == True:

            model_spectra[phase] = {}

        for spectrum in data_spectra[phase].keys():
            ###### Iterate over all spectra with this phase

            sigma_squared = standard_deviation[phase][spectrum]**2
            model_spectrum = background_spectra[phase][spectrum] * intensity
            chi_squared_spectrum_array = (data_spectra[phase][spectrum] -
                                          model_spectrum)**2 / sigma_squared
            ln_likelihood_spectrum_array = -0.5 * (
                chi_squared_spectrum_array +
                np.log(2. * np.pi * sigma_squared))
            chi_squared_spectrum = np.sum(chi_squared_spectrum_array)
            ln_likelihood_spectrum = np.sum(ln_likelihood_spectrum_array)

            chi_squared += chi_squared_spectrum
            ln_likelihood += ln_likelihood_spectrum
            ndata += len(data_spectra[phase][spectrum])
            if return_intensity == True:

                model_spectra[phase][spectrum] = model_spectrum

    if return_intensity == True:

        return chi_squared, ln_likelihood, model_spectra

    else:

        return chi_squared, ln_likelihood
Example #17
0
def Meta_DPI(df, data_path, viz, code, start, results_path, predictors,
             print_out, vars, path, protein_viz):
    (depth, trees, ccp) = vars
    if print_out == True:
        # folder = "{}/META_DPI_RESULTS{}" .format(results_path,code)
        # os.mkdir(folder)
        folder = "{}/META_DPI_RESULTS{}/By_protein".format(results_path, code)
        os.mkdir(folder)
        os.mkdir("{}/META_DPI_RESULTS{}/Trees".format(results_path, code))
        os.mkdir("{}/META_DPI_RESULTS{}/Fscore_MCC".format(results_path, code))
    # set up DataFrame
    # col_names = ['residue', 'predus', 'ispred', 'dockpred', 'annotated']
    # load dataset which is a csv file containing all the residues in Nox and Benchmark as well as predus, ispred, and dockpred scores.
    # The last column is a binary annotated classifier, 0 is noninetrface 1 is interface.

    # df = pd.read_csv("/Users/evanedelstein/Desktop/Research_Evan/Raji_Summer2019_atom/Antogen/predictionvalue/res_pred/test.csv", header=0)
    # set the residue_protein ID as the index of the DataFrame
    df["protein"] = [x.split('_')[1] for x in df['residue']]
    proteins = df["protein"].unique()
    df.set_index('residue', inplace=True)
    # remove any null or missing data from the dataset and check that annoted is number
    df.isnull().any()
    data = df.fillna(method='ffill')
    data = data[data['annotated'] != "ERROR"]
    data["annotated"] = pd.to_numeric(data["annotated"])
    # setup params for process pool
    param_list = []
    for count, protein in enumerate(proteins):
        test = data[data["protein"] == protein]
        train = data[data["protein"] != protein]
        col_namestest = predictors + ["annotated"]
        test = test[col_namestest]
        feature_cols = predictors
        # Features, ie prediction scores from predus, ispred and dockpred
        X = test[feature_cols]
        # Target variable, noninterface or interface
        y = test.annotated
        params = (X, y, train, feature_cols, code, results_path, protein,
                  trees, depth, ccp, viz, data_path, test, print_out, count)
        param_list.append(params)
    frames = []

    with concurrent.futures.ProcessPoolExecutor() as executor:
        param_list = param_list
        results = executor.map(Run, param_list)
        for count, i in enumerate(results):
            (totalframe, treeparams, coefficients) = i
            frames.append(totalframe)
            if count == 1 and viz == True:
                Treeviz.treeviz(treeparams, results_path, code, feature_cols)

    result_frame = pd.concat(frames)
    if print_out == True:
        result_frame.to_csv("{}/META_DPI_RESULTS{}/Meta_DPI_result.csv".format(
            results_path, code),
                            float_format='{:f}'.format)
    result_frame.to_csv("{}/META_DPI_RESULTS{}/Meta_DPI_result.csv".format(
        results_path, code),
                        float_format='{:f}'.format)
    Star.Star_Leave_one_out(result_frame, path, results_path, code)
    predictors += ["logreg", "rfscore"]
    F_score_MCC_paralel.Main(predictors, result_frame, results_path, code)
    if protein_viz == True:
        pymol_visualization.Main(predictors, result_frame, results_path, code)
    params_list = [(i, result_frame) for i in predictors]
    # print(param_list)
    roc_cols = [[f"{key}_FPR", f"{key}_TPR"] for key in predictors]
    roc_excel = pd.DataFrame(columns=roc_cols)
    pr_cols = [[f"{key}_Recall", f"{key}_Precsion"] for key in predictors]
    pr_excel = pd.DataFrame(columns=pr_cols)
    result_list = []
    with concurrent.futures.ProcessPoolExecutor() as executor:
        params_list = params_list  #<- take out
        results = executor.map(ROC_wrapper, params_list)
        for i in results:
            (predictor, ROC_AUC, PR_AUC, PR_frame, results_frame) = i
            roc_excel[f"{predictor}_TPR"] = results_frame["TPR"]
            roc_excel[f"{predictor}_FPR"] = results_frame["FPR"]
            pr_excel[f"{predictor}_Precsion"] = PR_frame["Precision"]
            pr_excel[f"{predictor}_Recall"] = PR_frame["Recall"]
            results = (predictor, ROC_AUC, PR_AUC)
            result_list.append(results)
            # return ROC_AUC,PR_AUC,predictor
    return result_list, roc_excel, pr_excel
Example #18
0
from Tkinter import *
from Point import *
from Ornament import *
from Star import *
from Light import *
from BlinkingLight import *
import random

window = Tk()
window.title("Merry Christmas")
Background = PhotoImage(file="tree.gif")
width = Background.width()
height = Background.height()
canvas = Canvas(window, width = width, height = height)
canvas.grid(row=0, column=0)
canvas.create_image(width/2, height/2, image=Background)

Ornament = Ornament(canvas, width, height)
Star = Star(canvas, width, height)
Light = Light(canvas, width, height)
BlinkingLight = BlinkingLight(canvas, width, height)

Star.addStar("star.gif")
for i in range(7):
    Ornament.addOrnament("smallOrnament.gif")
    Light.addLight()
    BlinkingLight.addBlinkingLight()
    BlinkingLight.blink()

window.mainloop()
Example #19
0
def GetStarredPosts2():
    result = Star.getStarredPosts()
    return make_response(jsonify(result['result']), result['code'])
Example #20
0
        plt.show()

    def calc_given_things(self):
        for b in self.bodies:
            b.orbit.calc_speed()
            b.orbit.calc_period()
            if b.hasOrbit():
                b.orbit.calc_orbit()
            else:
                b.orbit = Orbit.Orbit(self.star, b)
                b.orbit.type = b.orbit.TYPE_SUGGESTED


if __name__ == '__main__':
    e = Engine()
    sun = Star.Star(2.0 * 10**30, [0, 0], name='sun')
    earth = Planet.Planet(5.972 * 10**24, [constants.astronomical_unit, 0],
                          name='earth')
    earth.set_orbit(orbit=Orbit.Orbit(
        orbital_body=sun, self_body=earth, ga=constants.astronomical_unit))
    e.add_body(sun)
    e.add_body(earth)
    erg = earth.orbit.calc_schwerpunkt()
    print(erg)
    earth.orbit.sp = erg
    erg = earth.orbit.calc_speed()
    earth.orbit.speed = erg
    erg = earth.orbit.calc_period()
    print(str(erg) + " sec -> " + str(erg / 31536000) + "years")
    e.print_status()
    print(earth.orbit.calc_simp_orbit())
delete from Star;

alter table Star add column ra float, add column decl float;

copy Star (kepler_id, t_eff, radius, ra, decl) from 'stars_full.csv' CSV
Example #22
0
typx = {'S':'good', 'O':'other'}
filx = {'u':'u', 'v':'v', 'b':'b', 'y':'y', 'w':'Hw', 'n':'Hn'}

for f in fs :
    (fileid, tel, typ, fil, fn, rc, ds) = (f[0], f[1], f[2], f[3], f[4], f[5], f[6])

    # call idl to reduce
    rawp = os.path.dirname(fn)
    redp = telx[tel]+filx[fil]+'/pass1/'+(rc[0:6] if rc[6] == '_' else rc[0:7])+'/'+ds+'/'+typx[typ]+ '/'
    bare = os.path.basename(fn)[:-5]

    cmd = 'idl pip_shell.pro -args %s %s %s %s' % (tel, rawp, redp, bare)
    print cmd
    os.system(cmd)
    if os.path.exists(redp+bare+'/'+bare+'.db.txt') :

        # insert reduced db file
        if tel == 'B' :
            laststep = bokr.insbokred (cur, fileid, int(fileid[0:4]), fil, fn)
        elif tel == 'N' :
            laststep = nowtr.insnowtred (cur, fileid, int(fileid[0:4]), fil, fn)
        db.commit()

        # insert reduced ldac file
        Star.insstar(cur, fileid, redp+bare+'/', laststep)
        db.commit()

db.close()
print 'DONE'

Example #23
0
    def SummaryPlot(self,
                    PlanetDistribution,
                    MassModel,
                    EccentricityModel,
                    Ntest=100000,
                    FigDir=None,
                    block=True):
        """
        Parameters
        ----------
        PlanetDistribution: instance
            Instance of class PlanetDistribution.
        MassModel: instance
            Instance of class MassModel.
        EccentricityModel: instance
            Instance of class EccentricityModel.
        Ntest: int
            Number of test draws for summary plot.
        FigDir: str
            Directory to which summary plots are saved.
        block: bool
            If True, blocks plots when showing.
        """

        Ntest = Ntest // 10
        Rp_in = []
        Porb_in = []
        Rp_out = []
        Porb_out = []
        Trials_out = []
        Sun = Star.Star(
            'Sun',
            10.,  # pc
            'G',
            1.,  # Rsun
            5780.,  # K
            1.,  # Msun
            0.,  # deg
            0.)  # deg
        for i in range(Ntest):
            if (PlanetDistribution.returns == ['Rp', 'Porb']):
                Rp, Porb = PlanetDistribution.draw(Star=Sun)
                Mp = MassModel.RadiusToMass(Rp)
                ep = EccentricityModel.getEccentricity(Porb)
                Rp_in += [Rp]
                Porb_in += [Porb]
            elif (PlanetDistribution.returns == ['Mp', 'Porb']):
                Mp, Porb = PlanetDistribution.draw(Star=Sun)
                Rp = MassModel.MassToRadius(Mp)
                ep = EccentricityModel.getEccentricity(Porb)
                Rp_in += [Rp]
                Porb_in += [Porb]
            else:
                raise UserWarning()
            Rp, Porb, Mp, ep, Trials = self.draw(Sun,
                                                 PlanetDistribution,
                                                 MassModel,
                                                 EccentricityModel,
                                                 returnTrials=True)
            Rp_out += [Rp]
            Porb_out += [Porb]
            Trials_out += [Trials]
        Rp_in = np.concatenate(Rp_in)
        Porb_in = np.concatenate(Porb_in)
        Rp_out = np.concatenate(Rp_out)
        Porb_out = np.concatenate(Porb_out)

        print(
            '--> He2019:\n%.2f (%.2f) Rearth median planet radius after (before) stabilization\n%.2f (%.2f) d median planet orbital period after (before) stabilization\n%.2f+-%.2f trials on average'
            % (np.median(Rp_out), np.median(Rp_in), np.median(Porb_out),
               np.median(Porb_in), np.mean(Trials_out), np.std(Trials_out)))

        Colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
        Weight = 1. / len(Rp_in)
        f, ax = plt.subplots(1, 2)
        temp = np.hstack((Rp_in, Rp_out))
        ax[0].hist(Rp_in,
                   bins=np.logspace(np.log10(np.min(temp)),
                                    np.log10(np.max(temp)), 25),
                   weights=np.ones_like(Rp_in) * Weight,
                   color=Colors[0],
                   alpha=0.5,
                   label='Before')
        ax[0].hist(Rp_out,
                   bins=np.logspace(np.log10(np.min(temp)),
                                    np.log10(np.max(temp)), 25),
                   weights=np.ones_like(Rp_out) * Weight,
                   color=Colors[1],
                   alpha=0.5,
                   label='After')
        ax[0].set_xscale('log')
        ax[0].grid(axis='y')
        ax[0].set_xlabel('Planet radius [$R_\oplus$]')
        ax[0].set_ylabel('Fraction')
        ax[0].legend()
        temp = np.hstack((Porb_in, Porb_out))
        ax[1].hist(Porb_in,
                   bins=np.logspace(np.log10(np.min(temp)),
                                    np.log10(np.max(temp)), 25),
                   weights=np.ones_like(Porb_in) * Weight,
                   color=Colors[0],
                   alpha=0.5,
                   label='Before')
        ax[1].hist(Porb_out,
                   bins=np.logspace(np.log10(np.min(temp)),
                                    np.log10(np.max(temp)), 25),
                   weights=np.ones_like(Porb_out) * Weight,
                   color=Colors[1],
                   alpha=0.5,
                   label='After')
        ax[1].set_xscale('log')
        ax[1].grid(axis='y')
        ax[1].set_xlabel('Planet orbital period [d]')
        ax[1].set_ylabel('Fraction')
        ax[1].legend()
        plt.suptitle('He2019')
        plt.tight_layout(rect=[0, 0, 1, 0.95])
        if (FigDir is not None):
            plt.savefig(FigDir + 'StabilityModel.pdf')
        plt.show(block=block)
        plt.close()

        pass