markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
4. Alice, Bob and Carol have agreed to pool their Halloween candy and split it evenly among themselves.For the sake of their friendship, any candies left over will be smashed. For example, if they collectivelybring home 91 candies, they'll take 30 each and smash 1.Write an arithmetic expression below to calculate how ...
# Variables representing the number of candies collected by alice, bob, and carol alice_candies = 121 bob_candies = 77 carol_candies = 109 # Your code goes here! Replace the right-hand side of this assignment with an expression # involving alice_candies, bob_candies, and carol_candies to_smash = (alice_candies + bob_c...
_____no_output_____
MIT
1 - Python/1 - Python Syntax [exercise-syntax-variables-and-number].ipynb
AkashKumarSingh11032001/Kaggle_Course_Repository
Assignment Data Description- covid data of daily cummulative cases of India as reported from January 2020 to 8th August 2020- Source: https://www.kaggle.com/sudalairajkumar/covid19-in-india Conduct below Insight investigation1. Find which state has highest mean of cummulative confirmed cases since reported from Jan 20...
import pandas as pd # for cleaning and loading data from csv file import numpy as np from matplotlib import pyplot as plt # package for plotting graphs import datetime import seaborn as sns; sns.set(color_codes=True) %matplotlib inline
_____no_output_____
MIT
covid_data_analysis_solution.ipynb
rahulkumbhar8888/DataScience
Load data
df = pd.read_csv("covid_19_india.csv") df.head() # Preview first 5 rows of dataframe # Convert Date column which is a string into datetime object df["Date"] = pd.to_datetime(df["Date"], format = "%d/%m/%y") df.head()
_____no_output_____
MIT
covid_data_analysis_solution.ipynb
rahulkumbhar8888/DataScience
Cleaning of data- The dataset consists of cummulative values, aim is to create columns with daily reported deaths and confirmed cases.- Below method is helper function to create column consisting of daily cases reported from Cummulative freq column
ex = np.unique(df['State/UnionTerritory']) ex
_____no_output_____
MIT
covid_data_analysis_solution.ipynb
rahulkumbhar8888/DataScience
From above unique values of states it is clear that Telangana is represented in multiple ways. We will change each occurrence of Telangna state with standard spelling
def clean_stateName(stateName): if stateName == 'Telangana***': stateName = 'Telangana' elif stateName == 'Telengana': stateName = 'Telangana' elif stateName == 'Telengana***': stateName = 'Telangana' return stateName
_____no_output_____
MIT
covid_data_analysis_solution.ipynb
rahulkumbhar8888/DataScience
- Apply method is used to apply either user defined or builtin function across every cell of dataframe- Commonly lambda function is used to apply method across each cell- A lambda function is a small anonymous function.- A lambda function can take any number of arguments, but can only have one expression.
df["State/UnionTerritory"] = df["State/UnionTerritory"].apply(lambda x: clean_stateName(x)) np.unique(df["State/UnionTerritory"]) # to identify all unique values in a column of dataframe or array def daily_cases(dframe, stateColumn,dateColumn, cummColumn): # Sort column containing state and then by date in ascendin...
_____no_output_____
MIT
covid_data_analysis_solution.ipynb
rahulkumbhar8888/DataScience
Q1. Find which state has highest mean of cummulative confirmed cases since reported from Jan 2020
# Hint : Groupby state names to find their means for confirmed cases df_group = df_new.groupby(["State/UnionTerritory"])['daily_Confirmed'].mean() df_group = df_group.sort_values(ascending= False)[0:10] df_group df_group.index ax = sns.lineplot(x=df_group.index, y= df_group.values) plt.scatter(x=df_group.index, y= df_...
_____no_output_____
MIT
covid_data_analysis_solution.ipynb
rahulkumbhar8888/DataScience
Q2. Which state has highest Death Rate for the month of June, July & Aug
# Hint - explore how a datetime column of dataframe can be filtered using specific months df_months = df_new['Date'].apply(lambda x: x.month in [6,7,8]) # this will create boolean basis comparison of months df_final = df_new[df_months] # Filtered dataframe consisting of data from June, July & Aug df_final.tail() df_fin...
_____no_output_____
MIT
covid_data_analysis_solution.ipynb
rahulkumbhar8888/DataScience
Q3. Explore Trend in Confirmed Cases for the state of Maharashtra- Plot line graph with x axis as Date column and y axis as daily confirmed cases. - such a graph is also calledas Time Series Plot Hint - explore on google or in matplotlib for Time series graph from a dataframe
df_mah = df_new[df_new["State/UnionTerritory"]=='Maharashtra'] fig, ax = plt.subplots() fig.set_figwidth(15) fig.set_figheight(6) ax.plot(df_mah["Date"],df_mah["daily_Confirmed"]) df_mah = df_final[df_final["State/UnionTerritory"]=='Maharashtra'] fig, ax = plt.subplots() fig.set_figwidth(15) fig.set_figheight(6) ax.plo...
_____no_output_____
MIT
covid_data_analysis_solution.ipynb
rahulkumbhar8888/DataScience
print((4 + 8) / 2)
6.0
MIT
solar-learn.ipynb
anasir514/colab
Check values before feature selection in both training and test data- nan- different enough values
import pandas as pd import glob import os training_df = pd.concat(map(pd.read_csv, glob.glob(os.path.join('../Data/Train', "*.csv"))), ignore_index=True) test_df = test_data = pd.read_csv('../data/test.csv') training_df_shape = training_df.shape test_df_shape = test_df.shape all_stations = set(training_df['station']) ...
_____no_output_____
BSD-2-Clause
notebooks/TestAndTrainingDataForFeatureSelection.ipynb
isabelladegen/mlp-2021
Weather Data
precipitation = 'precipitation.l.m2' precipitation_nan = nan_analysis(precipitation) value_analysis(precipitation) # -> Training data has no values for precipitation not a good feature column = 'temperature.C' temperature_nan = nan_analysis(column) value_analysis(column) # min temperature is quite different between t...
_____no_output_____
BSD-2-Clause
notebooks/TestAndTrainingDataForFeatureSelection.ipynb
isabelladegen/mlp-2021
Is Holiday
column = 'isHoliday' nan_analysis(column) value_analysis(column)
Number of Nan for isHoliday: (0, 25) of (55875, 25) Number of Nan for isHoliday: (0, 25) of (2250, 25)
BSD-2-Clause
notebooks/TestAndTrainingDataForFeatureSelection.ipynb
isabelladegen/mlp-2021
Bikes Profile Data
column = 'full_profile_3h_diff_bikes' nan_analysis(column) station_ids_for_non_nan(column) value_analysis(column) # each station has none null values! column = 'full_profile_bikes' nan_analysis(column) station_ids_for_non_nan(column) value_analysis(column) #select the none nan column = 'short_profile_3h_diff_bikes' nan...
Number of Nan for short_profile_bikes: (12600, 25) of (55875, 25) Number of Nan for short_profile_bikes: (0, 25) of (2250, 25) Not nan for short_profile_bikes: (43275, 25) of (55875, 25) Station with only null values: set()
BSD-2-Clause
notebooks/TestAndTrainingDataForFeatureSelection.ipynb
isabelladegen/mlp-2021
17. Module, Package, Try_except, Numpy1_20191011_014_Day4_2๋ถ€ Magic method ์ •๋ฆฌ- ํด๋ž˜์Šค ์ƒ์„ฑ ํ›„, ํด๋ž˜์Šค object์˜ ๊ธฐ๋ณธ ์—ฐ์‚ฐ๊ธฐ๋Šฅ ๋ณด๊ฐ•ํ•  ๋•Œ ํ™œ์šฉ ๊ฐ€๋Šฅ ์ฃผ๋ชฉ!- object๋ฅผ ๋”ํ•  ๋•Œ, plus(1,2) ํ•จ์ˆ˜ ์“ฐ์ง€ ์•Š๊ณ , num1 + num2 ๋กœ๋„ ์—ฐ์‚ฐ์ด ๊ฐ€๋Šฅ!- ๋น„๊ต - \__eq__(==), \__ne__(!=) - \__lt__(, greater than), \__le__(=, gre or equal)- ์—ฐ์‚ฐ - \__add__(+), \__sub__(-), \__mul__(*),...
# Magic method ์‚ฌ์šฉํ•œ ํด๋ž˜์Šค ์ •์˜ ๋ฐ object ์—ฐ์‚ฐ # ์˜ˆ) integer ํด๋ž˜์Šค ์ƒ์„ฑ
_____no_output_____
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
class Integer: def __init__(self,number): self.num = number def __add__(self,unit): return self.num + unit.num def __str__(self): return str(self.num) def __repr__(self): return str(self.num)num1 = Integer(1)num2 = Integer(2)num1+num2 ๊ทธ๋ƒฅ num1 + num2 ํ•˜๋ฉด,, ๊ฐ ๋ณ€์ˆ˜์—๋Š” ...
a = 1 a.__add__(2) # ====> a.num + 2.num ==== self.num + unit.num ===== def __add__(self, unit): num1 print(num1)
<__main__.Integer object at 0x104eb7c90>
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
1. ํด๋ž˜์Šค ์˜ˆ์ œ- ๊ณ„์ขŒ ํด๋ž˜์Šค ๋งŒ๋“ค๊ธฐ- ๋ณ€์ˆ˜ : ์ž์‚ฐ(asset), ์ด์ž์œจ(interest)- ํ•จ์ˆ˜ : ์ธ์ถœ(draw), ์ž…๊ธˆ(interest), ์ด์ž์ถ”๊ฐ€(add_interest)- ์ธ์ถœ ์‹œ, ์ž์‚ฐ ์ด์ƒ์˜ ๋ˆ์„ ์ธ์ถœํ•  ์ˆ˜ ์—†๋‹ค.
class Account: def __init__(self,asset,interest=1.05): self.asset = asset self.interest = interest def draw(self,amount): if self.asset >= amount: self.asset -= amount print("{}์›์ด ์ธ์ถœ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.".format(amount)) else: print('{}์›...
630.0000000000006์›์˜ ์ด์ž๊ฐ€ ์ž…๊ธˆ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
Module package* ๋ณ€์ˆ˜, ํ•จ์ˆ˜ < ํด๋ž˜์Šค < ๋ชจ๋“ˆ < ํŒจํ‚ค์ง€- ๋ชจ๋“ˆ : ๋ณ€์ˆ˜์™€ ํ•จ์ˆ˜, ํด๋ž˜์Šค๋ฅผ ๋ชจ์•„๋†“์€ ( .py ) ํ™•์žฅ์ž๋ฅผ ๊ฐ€์ง„ ํŒŒ์ผ ( ํด๋ž˜์Šค ๋ณด๋‹ค ์กฐ๊ธˆ ๋” ํฐ ๋ฒ”์œ„ )- ํŒจํ‚ค์ง€ : ๋ชจ๋“ˆ๋ณด๋‹ค ํ•œ ๋‹จ๊ณ„ ํฐ ๊ธฐ๋Šฅ. ๋ชจ๋“ˆ์˜ ๊ธฐ๋Šฅ์„ ๋””๋ ‰ํ† ๋ฆฌ ๋ณ„๋กœ ์ •๋ฆฌํ•ด๋†“์€ ๊ฐœ๋… 1. ๋ชจ๋“ˆ ์ƒ์„ฑ2. ๋ชจ๋“ˆ ํ˜ธ์ถœ 1. ๋ชจ๋“ˆ ์ƒ์„ฑ(ํŒŒ์ผ ์ƒ์„ฑ)
!ls %%writefile dss.py # ๋ชจ๋“ˆ ํŒŒ์ผ ์ƒ์„ฑ (๋งค์ง ์ปค๋งจ๋“œ ์‚ฌ์šฉ) # 1) %% -> ์ด ์…€์— ์žˆ๋Š” ๋‚ด์šฉ์— ์ „๋ถ€๋‹ค writefile ์„ ์ ์šฉํ•˜๊ฒ ๋‹ค. # 2) dss.py ๋ผ๋Š” ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด์„œ, ์จ์žˆ๋Š” ์ฝ”๋“œ๋“ค์„ ์ด ํŒŒ์ผ์— ์ €์žฅํ•˜๊ฒ ๋‹ค. # ๋ชจ๋“ˆ ์ƒ์„ฑ -> ํŒŒ์ผ ์ €์žฅ # 1. ๋ชจ๋“ˆ ์ƒ์„ฑ (๋ชจ๋“ˆ = ํด๋ž˜์Šค, ํ•จ์ˆ˜, ๋ณ€์ˆ˜์˜ set) num = 1234 def disp1(msg): print("disp1", msg) def disp2(msg): print('disp2', msg) class Calc: def plu...
Variable Type Data/Info ------------------------------ dss module <module 'school.dss.data1<...>แ„‹แ…ฅแ†ธ/school/dss/data1.py'> school module <module 'school' (namespace)> url module <module 'school.web.url' <...>แ„‰แ…ฎแ„‹แ…ฅแ†ธ/school/web/url.py'>
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
2. ๋ชจ๋“ˆ ํ˜ธ์ถœ
# ๋ชจ๋“ˆ ํ˜ธ์ถœ : import ( .py ์ œ์™ธํ•œ ํŒŒ์ผ๋ช… ) import dss %whos dss.num dss.disp1('์•ˆ๋…•') calc = dss.Calc() calc.plus(1,2,3,4,5,6)
_____no_output_____
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
3. ๋ชจ๋“ˆ ๋‚ด ํŠน์ • ๋ณ€์ˆ˜, ํ•จ์ˆ˜ ํ˜ธ์ถœ
# import random --> random ๋ชจ๋“ˆ์„ ๋ถˆ๋Ÿฌ์˜จ ๊ฒƒ (random.py ๋ผ๋Š” ํŒŒ์ผ์˜ ์ฝ”๋“œ(๋ชจ๋“ˆ ์ ์–ด๋†“์€) ๊ฐ€์ ธ์˜จ ๊ฒƒ) # random.randint(1,5) --> random ๋ชจ๋“ˆ ๋‚ด randint๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ๊ฐ€์ ธ์˜จ ๊ฒƒ. # calc.plus --> dss ๋ผ๋Š” ๋ชจ๋“ˆ์˜ plus๋ผ๋Š” ํ•จ์ˆ˜ ๊ฐ€์ ธ์˜จ ๊ฒƒ. # ๋ชจ๋“ˆ ์•ˆ์— ํŠน์ • ํ•จ์ˆ˜, ๋ณ€์ˆ˜, ํด๋ž˜์Šค ํ˜ธ์ถœ # '๋ชจ๋“ˆ.๋ณ€์ˆ˜' ๋กœ ์ ์ง€ ์•Š๊ณ , '๋ชจ๋“ˆ' ๋กœ ๋ฐ”๋กœ ํ˜ธ์ถœ ๊ฐ€๋Šฅ from dss import num, disp2 %whos dss.num num
_____no_output_____
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
4. ๋ชจ๋“ˆ ๋‚ด ๋ชจ๋“  ๋ณ€์ˆ˜, ํ•จ์ˆ˜ ํ˜ธ์ถœ
%reset from dss import * %whos
Variable Type Data/Info -------------------------------- Calc type <class 'dss.Calc'> calc Calc <dss.Calc object at 0x109baed10> disp1 function <function disp1 at 0x109a88ef0> disp2 function <function disp2 at 0x109ab75f0> dss module <module 'dss' from '/Us...
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
5. ํŒจํ‚ค์ง€- ํŒจํ‚ค์ง€ ์ƒ์„ฑ- ํŒจํ‚ค์ง€ ํ˜ธ์ถœ- setup.py ํŒจํ‚ค์ง€ ์„ค์น˜ ํŒŒ์ผ ๋งŒ๋“ค๊ธฐ - ํŒจํ‚ค์ง€(๋””๋ ‰ํ† ๋ฆฌ) : ๋ชจ๋“ˆ(ํŒŒ์ผ) 1) ํŒจํ‚ค์ง€ ( ๋””๋ ‰ํ† ๋ฆฌ (dss / web) ) ์ƒ์„ฑ
# !mkdir p- ---> school ๋ฐ‘์— dss ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ !mkdir -p school/dss # !mkdir p- ---> school ๋ฐ‘์— web ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ !mkdir -p school/web !tree school
school โ”œโ”€โ”€ dss โ”‚ย ย  โ”œโ”€โ”€ __init__.py โ”‚ย ย  โ”œโ”€โ”€ data1.py โ”‚ย ย  โ””โ”€โ”€ data2.py โ””โ”€โ”€ web โ”œโ”€โ”€ __init__.py โ””โ”€โ”€ url.py 2 directories, 5 files
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
tree ์„ค์น˜- homebrew ์„ค์น˜ - homebrew : https://brew.sh/index_ko - homebrew : osx ํŒจํ‚ค์ง€ ๊ด€๋ฆฌ ์„ค์น˜ ํˆด - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" - brew install tree 2) ๋ชจ๋“ˆ(ํŒŒ์ผ) ์ƒ์„ฑ
# ์ด ๋‹จ๊ณ„๋Š” ํŒŒ์ด์ฌ 3.8๋ฒ„์ ผ ์ดํ›„ ๋ถ€ํ„ฐ๋Š” ์•ˆํ•ด๋„ ๋จ # !touch --> ํŒŒ์ผ ์ƒ์„ฑ !touch school/dss/__init__.py !touch school/web/__init__.py !tree school %%writefile school/dss/data1.py # dss๋ผ๋Š” ํŒจํ‚ค์ง€ ์•ˆ์— ๋ชจ๋“ˆ(ํŒŒ์ผ)์„ ์ถ”๊ฐ€ # web์ด๋ผ๋Š” ๋””๋ ‰ํ† ๋ฆฌ ์•ˆ์— ๋ชจ๋“ˆ(ํŒŒ์ผ)์„ ์ถ”๊ฐ€ def plus(*args): print('data1') return sum(args) %%writefile school/dss/data2.py def plus2(*args): ...
school โ”œโ”€โ”€ dss โ”‚ย ย  โ”œโ”€โ”€ __init__.py โ”‚ย ย  โ”œโ”€โ”€ data1.py โ”‚ย ย  โ””โ”€โ”€ data2.py โ””โ”€โ”€ web โ”œโ”€โ”€ __init__.py โ””โ”€โ”€ url.py 2 directories, 5 files
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
3) ํŒจํ‚ค์ง€ ๊ฒฝ๋กœ ์•ˆ์— ์žˆ๋Š” ๋ชจ๋“ˆ์„ ์ฐพ์•„๋“ค์–ด๊ฐ€ ์‚ฌ์šฉ
import school.dss.data1 %whos # school ๋””๋ ‰ํ† ๋ฆฌ - dss ๋””๋ ‰ํ† ๋ฆฌ - data1 ๋ชจ๋“ˆ - plus ํ•จ์ˆ˜ ํ˜ธ์ถœ school.dss.data1.plus(1,2,3) # ๋ชจ๋“ˆ ํ˜ธ์ถœ ๋ช…๋ น์–ด ๋„ˆ๋ฌด ๊ธธ๋‹ค import school.dss.data1 # alias ๋กœ ๋‹จ์ถ•๋ช… ์ƒ์„ฑ import school.dss.data1 as dss dss.plus(1,2,3) # school web : ๋””๋ ‰ํ† ๋ฆฌ # url : ๋ชจ๋“ˆ from school.web import url url.make('google.com') # ํŒจํ‚ค์ง€์˜ ์œ„์น˜ : ํŠน์ • ๋””๋ ‰ํ† ๋ฆฌ์— ์žˆ๋Š” ...
_____no_output_____
MIT
1.Study/2. with computer/4.Programming/2.Python/3. Study/01_Python/0408_1_Lecture_python.ipynb
jskim0406/Study
**Desafio 030****Python 3 - 1ยบ Mundo**Descriรงรฃo: Crie um programa que leia um nรบmero inteiro e mostre na tela se ele รฉ PAR ou รMPAR.Link: https://www.youtube.com/watch?v=4vFCzKuHOn4&t=4s
num = int(input('Digite um nรบmero: ')) if num % 2 == 0: print('O nรบmero รฉ par.') else: print('O nรบmero รฉ รญmpar.')
_____no_output_____
Apache-2.0
Mundo01/Desafio030.ipynb
BrunaKuntz/PythonMundo01
Example 5 - Open-loop simulation An open-loop simulation is the case where no state-feedback control is used. It means that only time-dependent control is used or not control at all. This kind of simulation is mainly useful for stability analysis and for cheching the trimmed behaviior (including perturbations around t...
from pyaat.atmosphere import atmosCOESA atm = atmosCOESA()
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Import gravity model
from pyaat.gravity import VerticalConstant grav = VerticalConstant()
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Import Aircraft model
from pyaat.aircraft import Aircraft airc = Aircraft()
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Import propulsion model
from pyaat.propulsion import SimpleModel prop = SimpleModel()
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Create a system
from pyaat.system import system Complete_system = system(atmosphere = atm, propulsion = prop, aircraft = airc, gravity = grav)
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Trimm at cruize condition
Xe, Ue = Complete_system.trimmer(condition='cruize', HE = 10000., VE = 200)
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Printing equilibrium states and controls
from pyaat.tools import printInfo printInfo(Xe, Ue, frame ='body') printInfo(Xe, Ue, frame ='aero') printInfo(Xe, Ue, frame='controls')
-------------------------------- ----------- CONTROLS ----------- -------------------------------- delta_p 34.65222851433093 ------------- delta_e -2.208294991778133 ------------- delta_a 4.978810759532202e-22 ------------- delta_r -8.268303092392625e-22
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Simulation The open-loop simulation is carried out using the method 'propagate'. Mandatory inputs are the time of simulation TF, the equilibrium states Xe, the equilibrium control Ue, and a bolean variable called 'perturbation' which defines is applied during the simulation or not. Equilibrium simulation
solution, control = Complete_system.propagate(Xe, Ue, TF = 180, perturbation = False)
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
The outputs are two multidimentional arrays, containing the states over time and control over time.
print('Solution') solution print('control') control
control
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
The time array can be accessed directly on the system.
time = Complete_system.time time
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Check out the documentation for more information about the outputs. Ploting the resultsSome plots can be generated directly using the plotter util embeeded within PyAAT.
from pyaat.tools import plotter pltr = plotter() pltr.states = solution pltr.time = Complete_system.time pltr.control = control pltr.LinVel(frame = 'body') pltr.LinPos() pltr.Attitude() pltr.AngVel() pltr.Controls() pltr.LinPos3D()
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
All states and controls remain constant over time, as expected. Out-of-equilibrium simulationsSometimes we may be interested in verifying the behavior of the aircraft out of the equilibrium states. It can be done by applying perturbations.Note that you would obtain the same result if you input a vector Xe out of equil...
solution, control = Complete_system.propagate(Xe, Ue, T0 = 0.0, TF = 30.0, dt = 0.01, perturbation = True, state = {'beta':2., 'alpha':2.}) pltr.states = solution pltr.time = Complete_system.time pltr.control = control pltr.LinVel(frame = 'aero') pltr.LinPos() pltr.Attitude() pltr.AngVel() pltr.Controls()
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
open-loop control Some usual control inputs are also embeeded within the toolbox, such as the doublet and step.
from pyaat.control import doublet, step
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Doublet input on elevator
doub = doublet() doub.command = 'elevator' doub.amplitude = 3 doub.T = 1 doub.t_init = 2
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
Step input on aileron
st =step() st.command = 'aileron' st.amplitude = 1 st.t_init = 2 solution, control = Complete_system.propagate(Xe, Ue, TF = 50, perturbation=True, control = [doub, st])
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
One can input as many control perturbation as we want, and we can combine it with states perturbations is desired.
pltr.states = solution pltr.time = Complete_system.time pltr.control = control pltr.Controls() pltr.LinVel(frame = 'aero') pltr.LinPos() pltr.Attitude() pltr.AngVel() pltr.LinPos3D()
_____no_output_____
MIT
examples/open-loop_simulation_example.ipynb
KenedyMatiasso/PyAAT
___ ___ Pandas Built-in Data VisualizationIn this lecture we will learn about pandas built-in capabilities for data visualization! It's built-off of matplotlib, but it baked into pandas for easier usage! Let's take a look! Imports
import numpy as np import pandas as pd %matplotlib inline
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
The DataThere are some fake data csv files you can read in as dataframes:
df1 = pd.read_csv('df1',index_col=0) df2 = pd.read_csv('df2')
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Style SheetsMatplotlib has [style sheets](http://matplotlib.org/gallery.htmlstyle_sheets) you can use to make your plots look a little nicer. These style sheets include plot_bmh,plot_fivethirtyeight,plot_ggplot and more. They basically create a set of style rules that your plots follow. I recommend using them, they ma...
df1['A'].hist()
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Call the style:
import matplotlib.pyplot as plt plt.style.use('ggplot')
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Now your plots look like this:
df1['A'].hist() plt.style.use('bmh') df1['A'].hist() plt.style.use('dark_background') df1['A'].hist() plt.style.use('fivethirtyeight') df1['A'].hist() plt.style.use('ggplot')
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Let's stick with the ggplot style and actually show you how to utilize pandas built-in plotting capabilities! Plot TypesThere are several plot types built-in to pandas, most of them statistical plots by nature:* df.plot.area * df.plot.barh * df.plot.density * df.plot.hist * df.plot.line * df.plot.scat...
df2.plot.area(alpha=0.4)
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Barplots
df2.head() df2.plot.bar() df2.plot.bar(stacked=True)
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Histograms
df1['A'].plot.hist(bins=50)
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Line Plots
df1.plot.line(x=df1.index,y='B',figsize=(12,3),lw=1)
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Scatter Plots
df1.plot.scatter(x='A',y='B')
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
You can use c to color based off another column valueUse cmap to indicate colormap to use. For all the colormaps, check out: http://matplotlib.org/users/colormaps.html
df1.plot.scatter(x='A',y='B',c='C',cmap='coolwarm')
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Or use s to indicate size based off another column. s parameter needs to be an array, not just the name of a column:
df1.plot.scatter(x='A',y='B',s=df1['C']*200)
C:\Users\Marcial\Anaconda3\lib\site-packages\matplotlib\collections.py:877: RuntimeWarning: invalid value encountered in sqrt scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
BoxPlots
df2.plot.box() # Can also pass a by= argument for groupby
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Hexagonal Bin PlotUseful for Bivariate Data, alternative to scatterplot:
df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b']) df.plot.hexbin(x='a',y='b',gridsize=25,cmap='Oranges')
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
____ Kernel Density Estimation plot (KDE)
df2['a'].plot.kde() df2.plot.density()
_____no_output_____
Apache-2.0
04-Visualization-Matplotlib-Pandas/04-02-Pandas Visualization/Pandas Built-in Data Visualization.ipynb
rikimarutsui/Python-for-Finance-Repo
Amazon Shure MV7 EDA and Sentement Analysis- toc: true- branch: master- badges: true- comments: true- categories: [Fastpages, Jupyter, Python, Selenium, Stoc]- annotations: true- hide: false- image: images/diagram.png- layout: post- search_exclude: true Required Packages[wordcloud](https://github.com/amueller/word_cl...
import pandas as pd from matplotlib import pyplot as plt import numpy as np from wordcloud import WordCloud from wordcloud import STOPWORDS import re import plotly.graph_objects as go import seaborn as sns
_____no_output_____
Apache-2.0
_notebooks/2022-02-01-EDA-test.ipynb
christopherGuan/sample-ds-blog
Read the Data
#Import Data df = pd.read_csv("/Users/zeyu/Desktop/DS/Ebay & Amazon/Amazon_reviews_scraping/Amazon_reviews_scraping/full_reviews.csv")
_____no_output_____
Apache-2.0
_notebooks/2022-02-01-EDA-test.ipynb
christopherGuan/sample-ds-blog
![Screen Shot 2022-02-09 at 5.50.41 PM.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABScAAAHXCAYAAABOEe/aAAABQWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSCwoyGFhYGDIzSspCnJ3UoiIjFJgf8bAxMDJIMigwyCRmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis+RsmxR7jWqLeXvN+x9bUiDhM9SiAKyW1OBlI/wHipOSCohIGBsYEIFu5vKQAxG4BskWKgI4CsmeA2OkQ9hoQOwnCPgBWExLkDG...
#Clean Data info = [] for i in df["date"]: x = re.sub("Reviewed in ", "", i) x1 = re.sub(" on ", "*", x) info.append(x1) df["date"] = pd.DataFrame({"date": info}) df[['country','date']] = df.date.apply( lambda x: pd.Series(str(x).split("*"))) star = [] star = df.stars1.combine_first(df.stars2) df["star...
_____no_output_____
Apache-2.0
_notebooks/2022-02-01-EDA-test.ipynb
christopherGuan/sample-ds-blog
Step 2:- Two methods to verify if column "star" contain any NaN- Converted the type of column "star" from string to Int
"nan" in df['star'] df_no_star = df[df['star'].isna()] df_no_star #Convert 2.0 out of 5 stars to 2 df_int = [] #df_with_star["stars"] = [str(x).replace(':',' ') for x in df["stars"]] for i in df["star"]: x = re.sub(".0 out of 5 stars", "", i) df_int.append(x) df["rating"] = pd.DataFrame({"rating": df_int}) df...
_____no_output_____
Apache-2.0
_notebooks/2022-02-01-EDA-test.ipynb
christopherGuan/sample-ds-blog
This is the data looks like after cleaning.![Screen Shot 2022-02-09 at 6.00.07 PM.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDQAAAE6CAYAAADp3AKtAAABQWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSCwoyGFhYGDIzSspCnJ3UoiIjFJgf8bAxMDJIMigwyCRmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis+RsmxR7jWqLeXvN+x9bUiDhM9SiAKyW1OBlI/wHipOSCohIGBsYEIFu...
temp = df['rating'].value_counts() fig = go.Figure(go.Bar( x=temp, y=temp.index, orientation='h')) fig.show() df_country = df['country'].value_counts() fig = go.Figure(go.Bar( x=df_country, y=df_country.index, orientation='h')) fig.show() mean_ra...
_____no_output_____
Apache-2.0
_notebooks/2022-02-01-EDA-test.ipynb
christopherGuan/sample-ds-blog
Sentiment Analysis
def remove_punctuation(text): final = "".join(u for u in text if u not in ("?", ".", ";", ":", "!",'"')) return final df['review'] = df['review'].apply(remove_punctuation) df = df.dropna(subset=['title']) df['title'] = df['title'].apply(remove_punctuation) dfNew = df[['title','sentiment']] dfNew.head() dfLong...
_____no_output_____
Apache-2.0
_notebooks/2022-02-01-EDA-test.ipynb
christopherGuan/sample-ds-blog
[Vectorizer](https://towardsdatascience.com/hacking-scikit-learns-vectorizers-9ef26a7170af) &[Bag-of-Words](https://towardsdatascience.com/hacking-scikit-learns-vectorizers-9ef26a7170af)
train_matrix = vectorizer.fit_transform(train['title']) test_matrix = vectorizer.transform(test['title']) train_matrix_l = vectorizer.fit_transform(train['review']) test_matrix_l = vectorizer.transform(test['review']) from sklearn.linear_model import LogisticRegression lr = LogisticRegression() X_train = train_matrix X...
precision recall f1-score support -1 0.00 0.00 0.00 0 1 1.00 0.89 0.94 116 accuracy 0.89 116 macro avg 0.50 0.44 0.47 116 weighted avg 1.00 0.89 0.94 ...
Apache-2.0
_notebooks/2022-02-01-EDA-test.ipynb
christopherGuan/sample-ds-blog
**Part 1:** Event Selection Optimization 1) Make a stacked histogram plot for the feature variable: mass
fig, ax = plt.subplots(1,1) ax.hist(higgs_events['mass'],density = True,alpha = 0.8, label = 'higgs') ax.hist(qcd_events['mass'],density = True,alpha = 0.8, label = 'qcd') plt.legend(fontsize = 18) plt.show()
_____no_output_____
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
Expected events in background is 20,000 and is poisson distirbuted $\cdot$ Use Poisson statistics for significance calculation
np.random.seed(123) dist = stats.poisson.rvs(20000, size = 10000) plt.hist(dist,density = True, bins = np.linspace(19450,20550,50), label = 'Expected Yield Distribution') plt.axvline(20100,color = 'red',label = 'Observed Yield') plt.legend(fontsize = 18) plt.show() print('Significance of 20100 events:', np.round(stats....
Significance of 20100 events: 0.711 sigma
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
$\frac{\textbf{N}_{Higgs}}{\sqrt{\textbf{N}_{QCD}}} = \frac{100}{\sqrt{20000}} = 0.707$This value is different than the value obtained in the previous calculation. This is because the value $\frac{\textbf{N}_{Higgs}}{\sqrt{\textbf{N}_{QCD}}}$ is the number of standard deviations away from the mean the measurment is, wh...
def mult_cut(qcd,higgs,features,cuts): ''' Parameters: qcd - qcd data dictionary higgs - higgs data dictionary features (list) - the features to apply cuts to cuts (list of touples) - in format ((min,max),(min,max)) Returns: number of qcd and higgs events cut...
_____no_output_____
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
2) Identify mass cuts to optimize the expected significance
s = 120 for n in range(0,7): mult_cut(qcd_dict,new_dict,['mass'],[(s,150)]) s+=1 s = 132 for n in range(0,7): mult_cut(qcd_dict,new_dict,['mass'],[(124,s)]) s-=1
['mass'] cuts [(124, 132)] leaves 724.6 expected qcd events and 69.554 expected higgs events Significance of 794.154 events: 2.563 sigma --------------------------------------------- ['mass'] cuts [(124, 131)] leaves 640.6 expected qcd events and 68.992 expected higgs events Significance of 709.592 events: 2.682 sigma...
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
Cut optimization was performed on the unsampled data in order to not overfit the cuts to the sample selected. The optimal cuts kept data with a mass between 124 and 128, and with those cuts yielded a measurement significance of 3.034 sigma. 3) Make stacked histogram plots for the rest of the features With and without ...
plt.rcParams["figure.figsize"] = (20,50) fig, ((ax1,ax2),(ax3,ax4),(ax5,ax6),(ax7,ax8),(ax9,ax10),(ax11,ax12),(ax13,ax14),(ax15,ax16),(ax17,ax18),(ax19,ax20),(ax21,ax22),(ax23,ax24),(ax25,ax26),(ax27,ax28)) = plt.subplots(14,2) axes = ((ax1,ax2),(ax3,ax4),(ax5,ax6),(ax7,ax8),(ax9,ax10),(ax11,ax12),(ax13,ax14),(ax15,ax1...
_____no_output_____
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
4) Optimize event selections using multiple features
mult_cut(qcd_dict,new_dict,['d2'],[(0,1.42)]) mult_cut(qcd_dict,new_dict,['t3'],[(0,0.17)]) mult_cut(qcd_dict,new_dict,['KtDeltaR'],[(0.48,0.93)]) mult_cut(qcd_dict,new_dict,['ee2'],[(0.11,0.21)]) mult_cut(qcd_dict,new_dict,['d2'],[(0,1.42)]) mult_cut(qcd_events,higgs_events,['mass','d2'],[(124,128),(0,1.42)]) mult_cut...
['mass', 'd2', 'KtDeltaR'] cuts [(124, 128), (0, 1.42), (0.48, 0.93)] leaves 18.0 expected qcd events and 51.0 expected higgs events Significance of 69.0 events: 9.238 sigma ---------------------------------------------
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
5) Plot 2-dimensional scattering plots between top two most discriminative features
plt.rcParams["figure.figsize"] = (20,10) fig, (ax1,ax2) = plt.subplots(1,2) ax1.plot(qcd_dict['mass'],qcd_dict['d2'],color = 'red', label = 'QCD',ls='',marker='.',alpha=0.5) ax1.plot(new_dict['mass'],qcd_dict['d2'],color = 'blue',label = 'Higgs',ls='',marker='.',alpha=0.5) ax1.legend(fontsize = 18) ax1.set_xlabel('mass...
_____no_output_____
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
Using Maching Learning to predict
sample_train, sample_test = train_test_split(sample,test_size = 0.2) X_train = sample_train.drop('label',axis = 1) y_train = sample_train['label'] X_test = sample_test.drop('label',axis = 1) y_test = sample_test['label'] mdl = MLPClassifier(hidden_layer_sizes = (8,20,20,8,8,4),max_iter=200,alpha = 10**-6,learning_rat...
significance using neural network is 2.132 sigma
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
Machine learning model chosen was less effective than the cuts that I had determined. With a more optimized loss function I'm sure machine learning would out perform manually selected cuts, but in this instance it didn't. **Part 2:** Pseudo-experiment data analysis
#Defining a function to make cuts and return the cut data, not calculating significance like previous function def straight_cut(data,features,cuts): for i in range(0,len(features)): a = np.array(data[features[i]]) data = data[:][np.logical_and(a>cuts[i][0], a<cuts[i][1])] return data
_____no_output_____
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
1) High Luminosity
plt.rcParams["figure.figsize"] = (20,30) fig, ((ax1,ax2),(ax3,ax4),(ax5,ax6)) = plt.subplots(3,2) axes = (ax1,ax2,ax3,ax4,ax5,ax6) features = ['mass','d2','KtDeltaR','ee2','t3','ee3'] for i in range(0,6): counts,bins = np.histogram(new_dict[features[i]],bins = 50) axes[i].hist(bins[:-1],bins, weights = counts*4...
Significance of 128 events: 10.724 sigma
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
The same cuts made on the simulated data gave a lower significance of $9.2\sigma$ 2) Low Luminosity
plt.rcParams["figure.figsize"] = (20,30) fig, ((ax1,ax2),(ax3,ax4),(ax5,ax6)) = plt.subplots(3,2) axes = (ax1,ax2,ax3,ax4,ax5,ax6) features = ['mass','d2','KtDeltaR','ee2','t3','ee3'] for i in range(0,6): counts,bins = np.histogram(new_dict[features[i]],bins = 50) axes[i].hist(bins[:-1],bins, weights = counts*4...
Significance of 9 events: 2.273 sigma
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
3) Confidence Levels of signal yield95% Upper limit for signal yield low luminosity$$\sum_{k = 9}^{\infty}P(\mu,k) = 0.95$$$$P(\mu,k) = \frac{e^{-\mu}\mu^k}{k!}$$$$\sum_{k = 0}^{9}\frac{e^{-\mu}\mu^k}{k!} = 0.05$$$$\mu = 15.71$$
print('With a true signal of 15.71, the probability seeing something stronger than 9 events is:',np.round(stats.poisson.sf(9,15.71),4))
With a true signal of 15.71, the probability seeing something stronger than 9 events is: 0.9501
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
This means that 95% of the time would see more than 9 events if there were a true signal strength of 15.71 events. For the low luminosity data we expected to see 4.22 events, since the data is poisson distributed we will round up to 5 events in order to get more than 95%$$\sum_{k = 5}^{\infty}P(\mu,k) = 0.95$$$$P(\mu,k...
prob = 0 mu = 128 while prob>0.05: prob = stats.poisson.cdf(128,mu) mu+=0.02 print(mu,prob) print('With a true signal of 10.513, the probability seeing something stronger than 4.22 events is:',np.round(stats.poisson.sf(4.22,10.513),4))
With a true signal of 10.513, the probability seeing something stronger than 4.22 events is: 0.9791
MIT
Labs/Labs5-8/Lab7.ipynb
jeff-abe/PHYS434
Weighting in taxcalc_helpers Setup
import numpy as np import pandas as pd import taxcalc as tc import microdf as mdf tc.__version__
_____no_output_____
MIT
docs/weighting.ipynb
MaxGhenis/taxcalc-helpers
Load dataStart with a `DataFrame` with `nu18` and `XTOT`, and also calculate `XTOT_m`.
df = mdf.calc_df(group_vars=['nu18'], metric_vars=['XTOT']) df.columns
_____no_output_____
MIT
docs/weighting.ipynb
MaxGhenis/taxcalc-helpers
From this we can calculate the number of people and tax units by the tax unit's number of children.
df.groupby('nu18')[['s006_m', 'XTOT_m']].sum()
_____no_output_____
MIT
docs/weighting.ipynb
MaxGhenis/taxcalc-helpers
What if we also want to calculate the total number of *children* by the tax unit's number of children?For this we can use `add_weighted_metrics`, the function called within `calc_df`.
mdf.add_weighted_metrics(df, ['nu18'])
_____no_output_____
MIT
docs/weighting.ipynb
MaxGhenis/taxcalc-helpers
Now we can do the same thing as before, with the new `nu18_m` column.
df.groupby('nu18')[['nu18_m']].sum()
_____no_output_____
MIT
docs/weighting.ipynb
MaxGhenis/taxcalc-helpers
We can also calculate weighted sums without adding the weighted metric.
total_children = mdf.weighted_sum(df, 'nu18', 's006') # Fix this decimal. 'Total children: ' + str(round(total_children / 1e6)) + 'M.'
_____no_output_____
MIT
docs/weighting.ipynb
MaxGhenis/taxcalc-helpers
We can also calculate the weighted mean and median.
mdf.weighted_mean(df, 'nu18', 's006') mdf.weighted_median(df, 'nu18', 's006')
_____no_output_____
MIT
docs/weighting.ipynb
MaxGhenis/taxcalc-helpers
We can also look at more quantiles.*Note that weighted quantiles have a different interface.*
decile_bounds = np.arange(0, 1.1, 0.1) deciles = mdf.weighted_quantile(df, 'nu18', 's006', decile_bounds) pd.DataFrame(deciles, index=decile_bounds)
_____no_output_____
MIT
docs/weighting.ipynb
MaxGhenis/taxcalc-helpers
Natural and artificial perturbations
import functools import numpy as np import matplotlib.pyplot as plt plt.ion() from astropy import units as u from astropy.time import Time from astropy.coordinates import solar_system_ephemeris from poliastro.twobody.propagation import propagate, cowell from poliastro.ephem import build_ephem_interpolant from polias...
_____no_output_____
MIT
docs/source/examples/Natural and artificial perturbations.ipynb
helgee/poliastro
Atmospheric drag The poliastro package now has several commonly used natural perturbations. One of them is atmospheric drag! See how one can monitor decay of the near-Earth orbit over time using our new module poliastro.twobody.perturbations!
R = Earth.R.to(u.km).value k = Earth.k.to(u.km**3 / u.s**2).value orbit = Orbit.circular(Earth, 250 * u.km, epoch=Time(0.0, format='jd', scale='tdb')) # parameters of a body C_D = 2.2 # dimentionless (any value would do) A = ((np.pi / 4.0) * (u.m**2)).to(u.km**2).value # km^2 m = 100 # kg B = C_D * A / m # parame...
_____no_output_____
MIT
docs/source/examples/Natural and artificial perturbations.ipynb
helgee/poliastro
Evolution of RAAN due to the J2 perturbation We can also see how the J2 perturbation changes RAAN over time!
r0 = np.array([-2384.46, 5729.01, 3050.46]) * u.km v0 = np.array([-7.36138, -2.98997, 1.64354]) * u.km / u.s orbit = Orbit.from_vectors(Earth, r0, v0) tof = 48.0 * u.h # This will be easier with propagate # when this is solved: # https://github.com/poliastro/poliastro/issues/257 rr, vv = cowell( Earth.k, orb...
_____no_output_____
MIT
docs/source/examples/Natural and artificial perturbations.ipynb
helgee/poliastro
3rd body Apart from time-independent perturbations such as atmospheric drag, J2/J3, we have time-dependend perturbations. Lets's see how Moon changes the orbit of GEO satellite over time!
# database keeping positions of bodies in Solar system over time solar_system_ephemeris.set('de432s') j_date = 2454283.0 * u.day # setting the exact event date is important tof = (60 * u.day).to(u.s).value # create interpolant of 3rd body coordinates (calling in on every iteration will be just too slow) body_r = bu...
_____no_output_____
MIT
docs/source/examples/Natural and artificial perturbations.ipynb
helgee/poliastro
Thrusts Apart from natural perturbations, there are artificial thrusts aimed at intentional change of orbit parameters. One of such changes is simultaineous change of eccenricy and inclination.
from poliastro.twobody.thrust import change_inc_ecc ecc_0, ecc_f = 0.4, 0.0 a = 42164 # km inc_0 = 0.0 # rad, baseline inc_f = (20.0 * u.deg).to(u.rad).value # rad argp = 0.0 # rad, the method is efficient for 0 and 180 f = 2.4e-6 # km / s2 k = Earth.k.to(u.km**3 / u.s**2).value s0 = Orbit.from_classical( Ea...
_____no_output_____
MIT
docs/source/examples/Natural and artificial perturbations.ipynb
helgee/poliastro
Reason for these testsA PR is raised in [ISSUE_1](https://github.com/frankaging/Reason-SCAN/issues/1), the reporter finds some discrepancies in split numbers. Specifically, the `test` split in our main data frame, is not matching up with our sub-test splits as `p1`, `p2` and `p3`. This PR further exposes another issue...
import os, json p1_test_path_to_data = "../../ReaSCAN-v1.0/ReaSCAN-compositional-p1-test/data-compositional-splits.txt" print(f"Reading dataset from file: {p1_test_path_to_data}...") p1_test_data = json.load(open(p1_test_path_to_data, "r")) print(len(p1_test_data["examples"]["test"])) p2_test_path_to_data = "../../Rea...
_____no_output_____
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
For instance, as you can see `p1 test example count` should be equal to `921`, but it is not. However, you can see that the total number of test examples matches up. The **root cause** potentially is that our sub-test splits are created asynchronously with the test split in the main data. Before confirming the **root c...
train_command_set = set([]) for example in ReaSCAN_data["examples"]["train"]: train_command_set.add(example["command"]) for example in p1_test_data["examples"]["test"]: assert example["command"] in train_command_set for example in p2_test_data["examples"]["test"]: assert example["command"] in train_command_...
Test-1 Passed
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
Test-2: Overestimating?What about the shape world? Are there overlaps between train and test?
import hashlib train_example_hash = set([]) for example in ReaSCAN_data["examples"]["train"]: example_hash_object = hashlib.md5(json.dumps(example).encode('utf-8')) train_example_hash.add(example_hash_object.hexdigest()) assert len(train_example_hash) == len(ReaSCAN_data["examples"]["train"]) p1_test_example_ha...
main_p1_test_dup_count=0
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
**Conclusion**: Yes. As you can see, we have many duplicated examples in our random tests. This means that, we need to use updated testing splits for evaluating performance. As a result, the **table 3** in the paper needs to be updated since it is now overestimating model performance for non-generalizing test splits (e...
def get_example_hash_set(split): split_test_path_to_data = f"../../ReaSCAN-v1.0/ReaSCAN-compositional-{split}/data-compositional-splits.txt" print(f"Reading dataset from file: {split_test_path_to_data}...") split_test_data = json.load(open(split_test_path_to_data, "r")) split_test_data_test_example_hash...
c1_dup_count=0 c2_dup_count=0
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
**Conclusion**: No. Test-4: What about correctness of generalization splits in general?We see there is no duplicate, but what about general correctness? Are their created correctly? In this section, we add more sanity checks to show correctness of each generalization split.For each split, we verify two things:* the ge...
split_test_path_to_data = f"../../ReaSCAN-v1.0/ReaSCAN-compositional-a1/data-compositional-splits.txt" print(f"Reading dataset from file: {split_test_path_to_data}...") split_test_data = json.load(open(split_test_path_to_data, "r")) for example in split_test_data["examples"]["test"]: assert "yellow,square" in examp...
_____no_output_____
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
A2: novel color attribute
# this test may be a little to weak for now. maybe improve it to verify the shape world? split_test_path_to_data = f"../../ReaSCAN-v1.0/ReaSCAN-compositional-a2/data-compositional-splits.txt" print(f"Reading dataset from file: {split_test_path_to_data}...") split_test_data = json.load(open(split_test_path_to_data, "r")...
_____no_output_____
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
A3: novel size attribute
# this test may be a little to weak for now. maybe improve it to verify the shape world? split_test_path_to_data = f"../../ReaSCAN-v1.0/ReaSCAN-compositional-a3/data-compositional-splits.txt" print(f"Reading dataset from file: {split_test_path_to_data}...") split_test_data = json.load(open(split_test_path_to_data, "r")...
_____no_output_____
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
B1: novel co-occurrence of objects
# this test may be a little to weak for now. maybe improve it to verify the shape world? split_test_path_to_data = f"../../ReaSCAN-v1.0/ReaSCAN-compositional-b1/data-compositional-splits.txt" print(f"Reading dataset from file: {split_test_path_to_data}...") split_test_data = json.load(open(split_test_path_to_data, "r")...
_____no_output_____
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
B2: novel co-occurrence of relations
# this test may be a little to weak for now. maybe improve it to verify the shape world? split_test_path_to_data = f"../../ReaSCAN-v1.0/ReaSCAN-compositional-b2/data-compositional-splits.txt" print(f"Reading dataset from file: {split_test_path_to_data}...") split_test_data = json.load(open(split_test_path_to_data, "r")...
_____no_output_____
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
C1:novel conjunctive clause length
# this test may be a little to weak for now. maybe improve it to verify the shape world? split_test_path_to_data = f"../../ReaSCAN-v1.0/ReaSCAN-compositional-c1/data-compositional-splits.txt" print(f"Reading dataset from file: {split_test_path_to_data}...") split_test_data = json.load(open(split_test_path_to_data, "r")...
_____no_output_____
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN
C2:novel relative clauses
# this test may be a little to weak for now. maybe improve it to verify the shape world? split_test_path_to_data = f"../../ReaSCAN-v1.0/ReaSCAN-compositional-c2/data-compositional-splits.txt" print(f"Reading dataset from file: {split_test_path_to_data}...") split_test_data = json.load(open(split_test_path_to_data, "r")...
_____no_output_____
CC-BY-4.0
code/dataset/verify_split_tests.ipynb
frankaging/Reason-SCAN