markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Subcategories Pages are only members of the direct category they are in. If a page is in a category, and that category is a member of another category, then it will not be shown through the members() function. The basic rule is that if you're on a category's Wikipedia page (like http://enwp.org/Category:Universities_an...
bay_cat = pywikibot.Category(site,'Category:Universities and colleges in California') bay_gen = bay_cat.members() for page in bay_gen: print(page.title(), page.isCategory(), page.coordinates())
scraping_wikipedia/wikipedia-api-query.ipynb
katyhuff/berkeley
bsd-3-clause
Other interesting information from pages Backlinks are all the pages that link to a page. Note: this can get very, very long with even minorly popular articles.
telegraph_page = pywikibot.Page(site, u"Telegraph Avenue") telegraph_backlinks = telegraph_page.backlinks telegraph_backlinks() for bl_page in telegraph_backlinks(): if(bl_page.namespace()==1): print(bl_page.title())
scraping_wikipedia/wikipedia-api-query.ipynb
katyhuff/berkeley
bsd-3-clause
Who has contributed to a page, and how many times have they edited?
telegraph_page.contributors()
scraping_wikipedia/wikipedia-api-query.ipynb
katyhuff/berkeley
bsd-3-clause
Templates are all the extensions to wikimarkup that give you things like citations, tables, infoboxes, etc. You can iterate over all the templates in a page. Templates Wikipedia articles are filled with templates, which are kinds of scripts written in wikimarkup. Everything you see in a Wikipedia article that isn't a m...
bky_page = pywikibot.Page(site, "Berkeley, California") bky_page.text
scraping_wikipedia/wikipedia-api-query.ipynb
katyhuff/berkeley
bsd-3-clause
If you go to the raw text on the Wikipedia (by clicking the edit button), you can see that this is a little bit more ordered: <img src="berkeley-wikitext.png"> We use the textlib module from pywikibot, which has a function that parses an article's wikitext into a list of templates. Each item in the list is an OrderedDi...
from pywikibot import textlib import pandas as pd bky_templates = textlib.extract_templates_and_params_regex(bky_page.text) bky_templates[:5]
scraping_wikipedia/wikipedia-api-query.ipynb
katyhuff/berkeley
bsd-3-clause
We iterate through all the templates on the page until we find the one containing the "Infobox settlement" template.
for template in bky_templates: if(template[0]=="Infobox settlement"): infobox = template[1] infobox.keys() print(infobox['elevation_ft']) print(infobox['area_total_sq_mi']) print(infobox['utc_offset_DST']) print(infobox['population_total'])
scraping_wikipedia/wikipedia-api-query.ipynb
katyhuff/berkeley
bsd-3-clause
However, sometimes parameters contain templates, such as citations or references.
print(infobox['government_type']) print(infobox['website'])
scraping_wikipedia/wikipedia-api-query.ipynb
katyhuff/berkeley
bsd-3-clause
Putting it all together This script gets data about all the cities in the Bay Area -- only traversing through this category, because all the pages are direct members of this with no subcategories.
bay_cat = pywikibot.Category(site,'Category:Cities_in_the_San_Francisco_Bay_Area') bay_gen = bay_cat.members() for page in bay_gen: # If the page is not a category if(page.isCategory()==False): print(page.title()) page_templates = textlib.extract_templates_and_params_regex(page.text) for...
scraping_wikipedia/wikipedia-api-query.ipynb
katyhuff/berkeley
bsd-3-clause
This is a script for Katy, getting data about U.S. Nuclear power plants. Wikipedia articles on nuclear power plants have many subcategories: https://en.wikipedia.org/wiki/Category:Nuclear_power_stations_by_country https://en.wikipedia.org/wiki/Category:Nuclear_power_stations_in_the_United_States https://en.wikipedia.o...
power_cat = pywikibot.Category(site,'Category:Nuclear power stations in the United States by state') power_gen = power_cat.members() for page in power_gen: print(page.title()) # If the page is not a category if(page.isCategory()==False): print("\n",page.title(),"\n") page_templates = textlib...
scraping_wikipedia/wikipedia-api-query.ipynb
katyhuff/berkeley
bsd-3-clause
Replication notebook Using this notebook, we replicate the 2002 model by Ciarelli and Lori (2002). Based on code from agentFin website by Blake Lebaron.
# set default parameters number_of_agents = 1000 init_time = 100 max_time = 500 av_return_interval_min = 5 av_return_interval_max = 50 # previously Lmax fundamental_value = 1000. # previously pf allowed_price_steps = 0.1 # deltaP variance_noise_forecast = 0.01 # prev sigmae order_noise_max = 0.5 # prev kMax order_expir...
comparablemodels/chiarellaIori/chialori2002.ipynb
LCfP/abm
mit
Simulation:
day_price, day_volume, day_return, price, returns, total_volume = ciarellilori2002(seed, max_time, init_time, number_of_agents, av_return_interval_min, av_return_interval_max, fundamental_value, allowed_price_steps, variance_noise_forecast, order_noise_max, order_expiration_time, fund...
comparablemodels/chiarellaIori/chialori2002.ipynb
LCfP/abm
mit
Some utility functions
def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0]) # Reformat the dataset for the convolutional networks def reformat(dataset): dataset = dataset.reshape((-1, image_size, image_size, num_channels)).astype(np.float32) ...
.ipynb_checkpoints/Diploma_munka_notebook_0-checkpoint.ipynb
Kkari/bsc_thesis
apache-2.0
This notebook demonstrates the generation of a propensity audience for a remarketing use case. It relies on the sample size calculations from the 6.media_experiment_design.ipynb notebook to create the Test and Control audiences which are written to a new BigQuery table. This data can then be uploaded via measurement pr...
# Uncomment to install required python modules # !sh ../utils/setup.sh # Add custom utils module to Python environment import os import sys sys.path.append(os.path.abspath(os.pardir)) import numpy as np import pandas as pd import random from gps_building_blocks.cloud.utils import bigquery as bigquery_utils from uti...
packages/propensity/08.audience_generation.ipynb
google/compass
apache-2.0
Set parameters
configs = helpers.get_configs('config.yaml') dest_configs, run_id_configs = configs.destination, configs.run_id # GCP project ID PROJECT_ID = dest_configs.project_id # Name of BigQuery dataset, # destination for created tables for modelling and activation. DATASET_NAME = dest_configs.dataset_name # To distinguish the...
packages/propensity/08.audience_generation.ipynb
google/compass
apache-2.0
Read the prediction dataset In this step, we assume the prediction dataset is available as a BigQuery table.
# SQL for extracting prediction dataset when using BQML. sql = f""" SELECT user_id, snapshot_ts, days_since_latest_activity, days_since_first_activity, probs.label AS predicted_score_label, probs.prob AS score FROM `{PROJECT_ID}.{DATASET_NAME}.{PREDICTIONS_TABLE}` AS predictions, UNN...
packages/propensity/08.audience_generation.ipynb
google/compass
apache-2.0
If required, the users can be filtered by using days_since_latest_activity (tenure) and days_since_first_activity (recency) columns before creating the audience groups. Create audience groups
# Separate the users into <AUDIENCE_GROUPS> number of audience groups df_prediction = df_prediction.sort_values(by='score', ascending=False).reset_index() # To avoid duplicate edges of bins we use the index # as rank in the qcut function below df_prediction['audience_group'] = ...
packages/propensity/08.audience_generation.ipynb
google/compass
apache-2.0
Write the audience data to a BigQuery table
# Inspect table before uploading to BigQuery cols_to_load = ['user_id', 'snapshot_ts', 'days_since_latest_activity', 'days_since_first_activity', 'predicted_score_label', 'score', 'audience_group', 'test_cont...
packages/propensity/08.audience_generation.ipynb
google/compass
apache-2.0
Check final audience uploaded to a BigQuery table
sql = f""" SELECT snapshot_ts, audience_group, test_control, COUNT(*) as count FROM `{PROJECT_ID}.{destination_table}` GROUP BY 1,2,3 ORDER BY 1,2,3; """ print (sql) df_check = bq_utils.run_query(sql).to_dataframe() df_check
packages/propensity/08.audience_generation.ipynb
google/compass
apache-2.0
Import relevant stingray libraries.
from stingray.simulator.transfer import TransferFunction from stingray.simulator.transfer import simple_ir, relativistic_ir
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
Creating TransferFunction A transfer function can be initialized by passing a 2-d array containing time across the first dimension and energy across the second. For example, if the 2-d array is defined by arr, then arr[1][5] defines a time of 5 units and energy of 1 unit. For the purpose of this tutorial, we have store...
response = np.loadtxt('intensity.txt')
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
Initialize transfer function by passing the array defined above.
transfer = TransferFunction(response) transfer.data.shape
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
By default, time and energy spacing across both axes are set to 1. However, they can be changed by supplying additional parameters dt and de. Obtaining Time-Resolved Response The 2-d transfer function can be converted into a time-resolved/energy-averaged response.
transfer.time_response()
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
This sets time parameter which can be accessed by transfer.time
transfer.time[1:10]
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
Additionally, energy interval over which to average, can be specified by specifying e0 and e1 parameters. Obtaining Energy-Resolved Response Energy-resolved/time-averaged response can be also be formed from 2-d transfer function.
transfer.energy_response()
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
This sets energy parameter which can be accessed by transfer.energy
transfer.energy[1:10]
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
Plotting Responses TransferFunction() creates plots of time-resolved, energy-resolved and 2-d responses. These plots can be saved by setting save parameter.
transfer.plot(response='2d') transfer.plot(response='time') transfer.plot(response='energy')
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
By enabling save=True parameter, the plots can be also saved. IO TransferFunction can be saved in pickle format and retrieved later.
transfer.write('transfer.pickle')
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
Saved files can be read using static read() method.
transfer_new = TransferFunction.read('transfer.pickle') transfer_new.time[1:10]
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
Artificial Responses For quick testing, two helper impulse response models are provided. 1- Simple IR simple_ir() allows to define an impulse response of constant height. It takes in time resolution starting time, width and intensity as arguments.
s_ir = simple_ir(dt=0.125, start=10, width=5, intensity=0.1) plt.plot(s_ir)
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
2- Relativistic IR A more realistic impulse response mimicking black hole dynamics can be created using relativistic_ir(). Its arguments are: time_resolution, primary peak time, secondary peak time, end time, primary peak value, secondary peak value, rise slope and decay slope. These paramaters are set to appropriate v...
r_ir = relativistic_ir(dt=0.125) plt.plot(r_ir)
Transfer Functions/TransferFunction Tutorial.ipynb
StingraySoftware/notebooks
mit
Next get the login credentials All requests to the SQE API require valid credentials. You can get them like this:
r = requests.post(api, json={"transaction": "validateSession", "PASSWORD":"asdf", "USER_NAME":"test"}) session = r.json()['SESSION_ID']
Text_Extraction/SQE-API-Demo.ipynb
Scripta-Qumranica-Electronica/Data-Processing
mit
Making requests All calls to the SQE API will use a transaction in the post request payload data. This should be accompanied by the necessary data to perform that transaction. Finding all available scrolls Try, for instance, downloading a list of scrolls with the transaction getCombs. You can also use the little pytho...
r = requests.post(api, json={"transaction": "getCombs", "SESSION_ID":session}) scrolls = r.json()['results'] def scrollIdByName(name): sid = None for scroll in scrolls: if name == scroll['name']: sid = scroll['scroll_version_id'] break return sid selectedScroll = scrollIdBy...
Text_Extraction/SQE-API-Demo.ipynb
Scripta-Qumranica-Electronica/Data-Processing
mit
Finding available cols/frags The API transaction getColOfComb will send you all columns and fragments of a scroll in their canonical order—you must supply the desired scroll_version_id.
r = requests.post(api, json={"transaction": "getColOfComb", "scroll_version_id": selectedScroll, "SESSION_ID":session}) cols = r.json()['results'] print(json.dumps(cols, indent=2, sort_keys=True)) col2 = cols[1]
Text_Extraction/SQE-API-Demo.ipynb
Scripta-Qumranica-Electronica/Data-Processing
mit
transcriptions There are several different ways to work with transcribed text. After downloading it with the transaction getSignStreamOfFrag, you will want to serialize it into something more human freindly. The transcriptions in the database are a DAG, but these initial API calls serialize it into an ordered array f...
r = requests.post(api, json={"transaction": "getSignStreamOfFrag", "scroll_version_id": selectedScroll, "col_id": col2['col_id'], "SESSION_ID":session}) text = r.json()['text'] builder = SchemaBuilder() builder.add_object(text) print(json.dumps(builder.to_schema(), indent=2, sort_keys=False))
Text_Extraction/SQE-API-Demo.ipynb
Scripta-Qumranica-Electronica/Data-Processing
mit
The actual data looks like this:
print(json.dumps(r.json(), indent=2, sort_keys=False))
Text_Extraction/SQE-API-Demo.ipynb
Scripta-Qumranica-Electronica/Data-Processing
mit
Since the data already comes in order, you could simply iterate over the lists to quickly see the text (note the helper functions at the beginning of the cell):
#The following helpers serialize each element to a list, since they could be either a scalar or list def serializeChars(sign): if isinstance(sign['chars'], list): return sign['chars'] else: return [sign['chars']] def serializeCharLetters(char): if isinstance(char['sign_char'], list): ...
Text_Extraction/SQE-API-Demo.ipynb
Scripta-Qumranica-Electronica/Data-Processing
mit
The previous method does not do any advanced checking to see if signs are damaged or reconstructed. It just prints the entirety of the transcribed text. We could do a minimal output that only prints those transcribed characters which are fully visible (this information is transmitted in the attribute_id and attribute_...
def outputMinimalText(): #Begin printing the output print(r.json()['text'][0]['scroll_name']) # Cycle through the cols/fragments for fragment in r.json()['text'][0]['fragments']: print(fragment['fragment_name'], end='') #Cycle through the lines for line in fragment['lines']: ...
Text_Extraction/SQE-API-Demo.ipynb
Scripta-Qumranica-Electronica/Data-Processing
mit
You could also serialize this to HTML by reading the all of the attribute tags more closely and adding some nice CSS.
def outputHTMLText(): print('<!DOCTYPE html>') print('<html>') print('<head>') print('\t<meta charset="UTF-8">') print('\t<title>SQE Transcription Output</title>') print(""" <style> span.non-rcnst + span.reconstructed:before { content: '['; } ...
Text_Extraction/SQE-API-Demo.ipynb
Scripta-Qumranica-Electronica/Data-Processing
mit
TESS End-to-End 6 Simulated Light Curve Time Series<br> Source: https://archive.stsci.edu/tess/ete-6.html
from skdaccess.astro.tess.simulated.cache import DataFetcher as TESS_DF from skdaccess.framework.param_class import * import numpy as np tess_fetcher = TESS_DF([AutoList([376664523])]) tess_dw = tess_fetcher.output() label, data = next(tess_dw.getIterator())
skdaccess/examples/Demo_TESS_Simulated_Data.ipynb
skdaccess/skdaccess
mit
Plot Relative PDCSAP Flux vs time
plt.gcf().set_size_inches(6,2); plt.scatter(data.loc[valid_index, 'TIME'], data.loc[valid_index, 'RELATIVE_PDCSAP_FLUX'], s=2, edgecolor='none'); plt.xlabel('Time'); plt.ylabel('Relative PDCSAP Flux'); plt.title('Simulated Data TID: ' + str(int(label)));
skdaccess/examples/Demo_TESS_Simulated_Data.ipynb
skdaccess/skdaccess
mit
Vertex client library: Hyperparameter tuning image classification model <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb"> <img src="https://...
import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG
notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Tutorial Now you are ready to start creating your own hyperparameter tuning and training of a custom image classification. Set up clients The Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex server....
# client options same for all services client_options = {"api_endpoint": API_ENDPOINT} def create_job_client(): client = aip.JobServiceClient(client_options=client_options) return client def create_model_client(): client = aip.ModelServiceClient(client_options=client_options) return client clients...
notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Define the worker pool specification Next, you define the worker pool specification for your custom hyperparameter tuning job. The worker pool specification will consist of the following: replica_count: The number of instances to provision of this machine type. machine_spec: The hardware specification. disk_spec : (o...
JOB_NAME = "custom_job_" + TIMESTAMP MODEL_DIR = "{}/{}".format(BUCKET_NAME, JOB_NAME) if not TRAIN_NGPU or TRAIN_NGPU < 2: TRAIN_STRATEGY = "single" else: TRAIN_STRATEGY = "mirror" EPOCHS = 20 STEPS = 100 DIRECT = True if DIRECT: CMDARGS = [ "--model-dir=" + MODEL_DIR, "--epochs=" + str(...
notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Examine the hyperparameter tuning package Package layout Before you start the hyperparameter tuning, you will look at how a Python package is assembled for a custom hyperparameter tuning job. When unarchived, the package contains the following directory/file layout. PKG-INFO README.md setup.cfg setup.py trainer __init...
# Make folder for Python hyperparameter tuning script ! rm -rf custom ! mkdir custom # Add package information ! touch custom/README.md setup_cfg = "[egg_info]\n\ntag_build =\n\ntag_date = 0" ! echo "$setup_cfg" > custom/setup.cfg setup_py = "import setuptools\n\nsetuptools.setup(\n\n install_requires=[\n\n ...
notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Store hyperparameter tuning script on your Cloud Storage bucket Next, you package the hyperparameter tuning folder into a compressed tar ball, and then store it in your Cloud Storage bucket.
! rm -f custom.tar custom.tar.gz ! tar cvf custom.tar custom ! gzip custom.tar ! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_cifar10.tar.gz
notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Reporting back the result of the trial using hypertune For each trial, your Python script needs to report back to the hyperparameter tuning service the objective metric for which you specified as the criteria for evaluating the trial. For this example, you will specify in the study specification that the objective metr...
def create_hyperparameter_tuning_job(hpt_job): response = clients["job"].create_hyperparameter_tuning_job( parent=PARENT, hyperparameter_tuning_job=hpt_job ) print("name:", response.name) print("display_name:", response.display_name) print("state:", response.state) print("create_time:", ...
notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Tuning a model - CIFAR10 Now that you have seen the overall steps for hyperparameter tuning a custom training job using a Python package that mimics training a model, you will do a new hyperparameter tuning job for a custom training job for a CIFAR10 model. For this example, you will change two parts: Specify the CIFA...
study_spec = { "metrics": [ { "metric_id": "val_accuracy", "goal": aip.StudySpec.MetricSpec.GoalType.MAXIMIZE, } ], "parameters": [ { "parameter_id": "lr", "discrete_value_spec": {"values": [0.001, 0.01, 0.1]}, "scale_type":...
notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Task.py contents In the next cell, you write the contents of the hyperparameter tuning script task.py. I won't go into detail, it's just there for you to browse. In summary: Parse the command line arguments for the hyperparameter settings for the current trial. Get the directory where to save the model artifacts from ...
%%writefile custom/trainer/task.py # Custom Job for CIFAR10 import tensorflow_datasets as tfds import tensorflow as tf from hypertune import HyperTune import argparse import os import sys # Command Line arguments parser = argparse.ArgumentParser() parser.add_argument('--model-dir', dest='model_dir', ...
notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
The first thing to understand when working with pandas dataframes in HoloViews is how data is indexed. Pandas dataframes are structured as tables with any number of columns and indexes. HoloViews, on the other hand, deals with Dimensions. HoloViews container objects such as HoloMap, NdLayout, GridSpace and NdOverlay ha...
df = pd.DataFrame({'a':[1,2,3,4], 'b':[4,5,6,7], 'c':[8, 9, 10, 11]}) HTML(df.to_html())
doc/Tutorials/Pandas_Conversion.ipynb
vascotenner/holoviews
bsd-3-clause
Now that we have a basic dataframe, we can wrap it in the HoloViews Table Element:
example = hv.Table(df)
doc/Tutorials/Pandas_Conversion.ipynb
vascotenner/holoviews
bsd-3-clause
The data on the Table Element is accessible via the .data attribute like on all other Elements.
list(example.data.columns)
doc/Tutorials/Pandas_Conversion.ipynb
vascotenner/holoviews
bsd-3-clause
As you can see, we now have a Table, which has a and b as its kdims and c as its value_dimension. Because it is not needed by HoloViews, the index of the original dataframe was dropped, but if the indexes are meaningful you make that column available using the .reset_index method on the pandas dataframe:
HTML(df.reset_index().to_html())
doc/Tutorials/Pandas_Conversion.ipynb
vascotenner/holoviews
bsd-3-clause
Now we can employ the HoloViews slicing semantics to select the desired subset of the data and use the usual compositing + operator to lay the data out side by side:
example[:, 4:8:2] + example[2:5:2, :]
doc/Tutorials/Pandas_Conversion.ipynb
vascotenner/holoviews
bsd-3-clause
Dropping and reducing columns The above was the simple case: we converted all the dataframe columns to a Table object. Where pandas excels, however, is making a large set of data available in a form that makes selection easy. This time, let's only select a subset of the Dimensions.
example.to.scatter('a', 'b', [])
doc/Tutorials/Pandas_Conversion.ipynb
vascotenner/holoviews
bsd-3-clause
As you can see, HoloViews simply ignored the remaining Dimension. By default, the conversion functions ignore any numeric unselected Dimensions. All non-numeric Dimensions are converted to Dimensions on the returned HoloMap, however. Both of these behaviors can be overridden by supplying explicit map dimensions and/or ...
%%opts Curve [xticks=3 yticks=3] example.to.curve('a', 'b', []) + example
doc/Tutorials/Pandas_Conversion.ipynb
vascotenner/holoviews
bsd-3-clause
Finally, we can convert all homogenous HoloViews types (i.e. anything except Layout and Overlay) back to a pandas dataframe using the dframe method.
HTML(example.dframe().to_html())
doc/Tutorials/Pandas_Conversion.ipynb
vascotenner/holoviews
bsd-3-clause
As the name suggests boundary_conditions.py contains the information about the boundary conditions for the setup considered. While the current problem in consideration is for periodic boundary conditions, $\texttt{Bolt}$ also supports Dirichlet, mirror, and shearing box boundary conditions. The setups for these boundar...
!cat domain.py
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
domain.py contains data about the phase space domain and resolution that has been considered. Note that we've taken the number of grid points along q2 as 3 although it's a 1D problem. It must be ensured that the number of grid zones in q1 and q2 are greater than or equal to the the number of ghost zones that are taken ...
!cat params.py
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
Let's go over each of the attributes mentioned above to understand their usage. While some of these attributes are flags and options that need to be mentioned for every system being solved, there are a few attributes which are specific to the non-relativistic Boltzmann system being solved. The params module can be used...
!cat initialize.py
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
As you can see the initialize module contains the function initialize_f which initializes the distribution function using the parameters that were declared. Now that we've setup the parameters for the specific test problem that we want to solve, we'll proceed to describe how we input the desired equation of our model i...
import bolt.src.nonrelativistic_boltzmann.advection_terms as advection_terms import bolt.src.nonrelativistic_boltzmann.collision_operator as collision_operator import bolt.src.nonrelativistic_boltzmann.moments as moments
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
Let's start of by seeing how we've introduced the advection terms specific to the non-relativistic Boltzmann equation into the framework of $\texttt{Bolt}$. Advection terms are introduced into $\texttt{Bolt}$ through the advection_terms which has the functions A_q, C_q, C_p, C_p. It is expected that A_q and C_q take t...
!cat $BOLT_HOME/bolt/src/nonrelativistic_boltzmann/advection_terms.py
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
We hope the model described is quite clear from the docstrings. Note that we describe the model in terms of variables in velocities v and not the canonical variables p to avoid confusion with momentum. Next, we proceed to see how moments we define moments for our system of interest.
!cat $BOLT_HOME/bolt/src/nonrelativistic_boltzmann/moments.py
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
As you can see all the moment quantities take (f, v1, v2, v3, integral_measure) as arguments interms of which we define the moments for the system. By default, integral_measure is taken to be dv1 dv2 dv3. These definitions are referred to by the solver routine compute_moments, which calls the appropriate moment routine...
!cat $BOLT_HOME/bolt/src/nonrelativistic_boltzmann/collision_operator.py
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
Here the BGK function is our source term, and takes the arguments (f, t, q1, q2, v1, v2, v3, moments, params, flag). Note that moments is the solver routine of compute_moments which is used to compute the moments at the current instance of computing the collison operator. In parameters, we had defined an attribute inst...
# Importing dependencies: import arrayfire as af import numpy as np import pylab as pl %matplotlib inline # Importing the classes which are used to declare the physical_system and solver objects from bolt.lib.physical_system import physical_system from bolt.lib.nonlinear.nonlinear_solver import nonlinear_solver from b...
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
We define the system we want to solve through the physical_system class. This class takes it's arguments as (domain, boundary_conditions, params, initialize, advection_terms, source_function, moments) which we had explored above. The declared object is then passed to the linear and nonlinear solver objects to provide i...
# Defining the physical system to be solved: system = physical_system(domain, boundary_conditions, params, initialize, advection_terms, collision_operator.BGK, moments ...
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
The default data format in $\texttt{Bolt}$ is (Np, Ns, N_q1, N_q2), where Np is the number of zones in p-space, Ns is the number of species and N_q1 and N_q2 are the number of gridzones along q1 and q2 respectively. Below since we want to obtain the amplitude for the density in the physical domain non-inclusive of the ...
# Storing data at time t = 0: n_nls = nls.compute_moments('density') # Check for the data non inclusive of the ghost zones: rho_data_nls[0] = af.max(n_nls[:, :, N_g_q:-N_g_q, N_g_q:-N_g_q]) n_ls = ls.compute_moments('density') rho_data_ls[0] = af.max(n_ls) for time_index, t0 in enumerate(time_arr...
example_problems/nonrelativistic_boltzmann/quick_start/tutorial.ipynb
ShyamSS-95/Bolt
gpl-3.0
We have developed the theory for the linear Kalman filter. Then, in the last two chapters we broached the topic of using Kalman filters for nonlinear problems. In this chapter we will learn the Extended Kalman filter (EKF). The EKF handles nonlinearity by linearizing the system at the point of the current estimate, and...
import kf_book.ekf_internal as ekf_internal ekf_internal.show_linearization()
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
If the curve above is the process model, then the dotted lines shows the linearization of that curve for the estimate $x=1.5$. We linearize systems by taking the derivative, which finds the slope of a curve: $$\begin{aligned} f(x) &= x^2 -2x \ \frac{df}{dx} &= 2x - 2 \end{aligned}$$ and then evaluating it at $x$: $$\be...
ekf_internal.show_radar_chart()
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
This gives us the equalities: $$\begin{aligned} \epsilon &= \tan^{-1} \frac y x\ r^2 &= x^2 + y^2 \end{aligned}$$ Design the State Variables We want to track the position of an aircraft assuming a constant velocity and altitude, and measurements of the slant distance to the aircraft. That means we need 3 state variabl...
from math import sqrt def HJacobian_at(x): """ compute Jacobian of H matrix at x """ horiz_dist = x[0] altitude = x[2] denom = sqrt(horiz_dist**2 + altitude**2) return array ([[horiz_dist/denom, 0., altitude/denom]])
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
Finally, let's provide the code for $h(\bar{\mathbf x})$:
def hx(x): """ compute measurement for slant range that would correspond to state x. """ return (x[0]**2 + x[2]**2) ** 0.5
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
Now let's write a simulation for our radar.
from numpy.random import randn import math class RadarSim(object): """ Simulates the radar signal returns from an object flying at a constant altityude and velocity in 1D. """ def __init__(self, dt, pos, vel, alt): self.pos = pos self.vel = vel self.alt = alt self....
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
Design Process and Measurement Noise The radar measures the range to a target. We will use $\sigma_{range}= 5$ meters for the noise. This gives us $$\mathbf R = \begin{bmatrix}\sigma_{range}^2\end{bmatrix} = \begin{bmatrix}25\end{bmatrix}$$ The design of $\mathbf Q$ requires some discussion. The state $\mathbf x= \begi...
from filterpy.common import Q_discrete_white_noise from filterpy.kalman import ExtendedKalmanFilter from numpy import eye, array, asarray import numpy as np dt = 0.05 rk = ExtendedKalmanFilter(dim_x=3, dim_z=1) radar = RadarSim(dt, pos=0., vel=100., alt=1000.) # make an imperfect starting guess rk.x = array([radar.po...
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
Using SymPy to compute Jacobians Depending on your experience with derivatives you may have found the computation of the Jacobian difficult. Even if you found it easy, a slightly more difficult problem easily leads to very difficult computations. As explained in Appendix A, we can use the SymPy package to compute the J...
import sympy sympy.init_printing(use_latex=True) x, x_vel, y = sympy.symbols('x, x_vel y') H = sympy.Matrix([sympy.sqrt(x**2 + y**2)]) state = sympy.Matrix([x, x_vel, y]) H.jacobian(state)
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
This result is the same as the result we computed above, and with much less effort on our part! Robot Localization It's time to try a real problem. I warn you that this section is difficult. However, most books choose simple, textbook problems with simple answers, and you are left wondering how to solve a real world pr...
ekf_internal.plot_bicycle()
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
In the Unscented Kalman Filter chapter we derived these equations: $$\begin{aligned} \beta &= \frac d w \tan(\alpha) \ x &= x - R\sin(\theta) + R\sin(\theta + \beta) \ y &= y + R\cos(\theta) - R\cos(\theta + \beta) \ \theta &= \theta + \beta \end{aligned} $$ where $\theta$ is the robot's heading. You do not need to un...
import sympy from sympy.abc import alpha, x, y, v, w, R, theta from sympy import symbols, Matrix sympy.init_printing(use_latex="mathjax", fontsize='16pt') time = symbols('t') d = v*time beta = (d/w)*sympy.tan(alpha) r = w/sympy.tan(alpha) fxu = Matrix([[x-r*sympy.sin(theta) + r*sympy.sin(theta+beta)], [y...
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
That looks a bit complicated. We can use SymPy to substitute terms:
# reduce common expressions B, R = symbols('beta, R') F = F.subs((d/w)*sympy.tan(alpha), B) F.subs(w/sympy.tan(alpha), R)
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
This form verifies that the computation of the Jacobian is correct. Now we can turn our attention to the noise. Here, the noise is in our control input, so it is in control space. In other words, we command a specific velocity and steering angle, but we need to convert that into errors in $x, y, \theta$. In a real sys...
V = fxu.jacobian(Matrix([v, alpha])) V = V.subs(sympy.tan(alpha)/w, 1/R) V = V.subs(time*v/R, B) V = V.subs(time*v, 'd') V
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
This should give you an appreciation of how quickly the EKF become mathematically intractable. This gives us the final form of our prediction equations: $$\begin{aligned} \mathbf{\bar x} &= \mathbf x + \begin{bmatrix}- R\sin(\theta) + R\sin(\theta + \beta) \ R\cos(\theta) - R\cos(\theta + \beta) \ \beta\end{bmatrix}\...
px, py = symbols('p_x, p_y') z = Matrix([[sympy.sqrt((px-x)**2 + (py-y)**2)], [sympy.atan2(py-y, px-x) - theta]]) z.jacobian(Matrix([x, y, theta]))
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
Now we need to write that as a Python function. For example we might write:
from math import sqrt def H_of(x, landmark_pos): """ compute Jacobian of H matrix where h(x) computes the range and bearing to a landmark for state x """ px = landmark_pos[0] py = landmark_pos[1] hyp = (px - x[0, 0])**2 + (py - x[1, 0])**2 dist = sqrt(hyp) H = array( [[-(px - x[0...
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
We also need to define a function that converts the system state into a measurement.
from math import atan2 def Hx(x, landmark_pos): """ takes a state variable and returns the measurement that would correspond to that state. """ px = landmark_pos[0] py = landmark_pos[1] dist = sqrt((px - x[0, 0])**2 + (py - x[1, 0])**2) Hx = array([[dist], [atan2(py - x[1, ...
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
Design Measurement Noise It is reasonable to assume that the noise of the range and bearing measurements are independent, hence $$\mathbf R=\begin{bmatrix}\sigma_{range}^2 & 0 \ 0 & \sigma_{bearing}^2\end{bmatrix}$$ Implementation We will use FilterPy's ExtendedKalmanFilter class to implement the filter. Its predict() ...
from filterpy.kalman import ExtendedKalmanFilter as EKF from numpy import dot, array, sqrt class RobotEKF(EKF): def __init__(self, dt, wheelbase, std_vel, std_steer): EKF.__init__(self, 3, 2, 2) self.dt = dt self.wheelbase = wheelbase self.std_vel = std_vel self.std_steer = s...
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
Now we have another issue to handle. The residual is notionally computed as $y = z - h(x)$ but this will not work because our measurement contains an angle in it. Suppose z has a bearing of $1^\circ$ and $h(x)$ has a bearing of $359^\circ$. Naively subtracting them would yield a angular difference of $-358^\circ$, wher...
def residual(a, b): """ compute residual (a-b) between measurements containing [range, bearing]. Bearing is normalized to [-pi, pi)""" y = a - b y[1] = y[1] % (2 * np.pi) # force in range [0, 2 pi) if y[1] > np.pi: # move to [-pi, pi) y[1] -= 2 * np.pi return y
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
The rest of the code runs the simulation and plots the results, and shouldn't need too much comment by now. I create a variable landmarks that contains the landmark coordinates. I update the simulated robot position 10 times a second, but run the EKF only once per second. This is for two reasons. First, we are not usin...
from filterpy.stats import plot_covariance_ellipse from math import sqrt, tan, cos, sin, atan2 import matplotlib.pyplot as plt dt = 1.0 def z_landmark(lmark, sim_pos, std_rng, std_brg): x, y = sim_pos[0, 0], sim_pos[1, 0] d = np.sqrt((lmark[0] - x)**2 + (lmark[1] - y)**2) a = atan2(lmark[1] - y, lmark[0...
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
I have plotted the landmarks as solid squares. The path of the robot is drawn with a black line. The covariance ellipses for the predict step are light gray, and the covariances of the update are shown in green. To make them visible at this scale I have set the ellipse boundary at 6$\sigma$. We can see that there is a ...
landmarks = array([[5, 10], [10, 5], [15, 15], [20, 5]]) ekf = run_localization( landmarks, std_vel=0.1, std_steer=np.radians(1), std_range=0.3, std_bearing=0.1) plt.show() print('Final P:', ekf.P.diagonal())
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
The uncertainly in the estimates near the end of the track are smaller. We can see the effect that multiple landmarks have on our uncertainty by only using the first two landmarks.
ekf = run_localization( landmarks[0:2], std_vel=1.e-10, std_steer=1.e-10, std_range=1.4, std_bearing=.05) print('Final P:', ekf.P.diagonal())
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
The estimate quickly diverges from the robot's path after passing the landmarks. The covariance also grows quickly. Let's see what happens with only one landmark:
ekf = run_localization( landmarks[0:1], std_vel=1.e-10, std_steer=1.e-10, std_range=1.4, std_bearing=.05) print('Final P:', ekf.P.diagonal())
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
As you probably suspected, one landmark produces a very bad result. Conversely, a large number of landmarks allows us to make very accurate estimates.
landmarks = array([[5, 10], [10, 5], [15, 15], [20, 5], [15, 10], [10,14], [23, 14], [25, 20], [10, 20]]) ekf = run_localization( landmarks, std_vel=0.1, std_steer=np.radians(1), std_range=0.3, std_bearing=0.1, ylim=(0, 21)) print('Final P:', ekf.P.diagonal())
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
Discussion I said that this was a real problem, and in some ways it is. I've seen alternative presentations that used robot motion models that led to simpler Jacobians. On the other hand, my model of the movement is also simplistic in several ways. First, it uses a bicycle model. A real car has two sets of tires, and e...
import kf_book.nonlinear_plots as nonlinear_plots nonlinear_plots.plot_ekf_vs_mc()
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
The EKF computation is rather inaccurate. In contrast, here is the performance of the UKF:
nonlinear_plots.plot_ukf_vs_mc(alpha=0.001, beta=3., kappa=1.)
self_driving/deps/Kalman_and_Bayesian_Filters_in_Python_master/11-Extended-Kalman-Filters.ipynb
zaqwes8811/micro-apps
mit
Changing value changes the function behavior as well
value = "ABCD" print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'), funcs['a']('D'))
misc/function_map.ipynb
juditacs/snippets
lgpl-3.0
Solution 2 - function factory using closure
d = {'a': 'AB', 'b': 'C'} def foo(value): def bar(v): return v in value return bar funcs = {} for key, value in d.items(): funcs[key] = foo(value) # True, True, False ? print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C')) # False, True ? d = {'a': 'AB', 'b': 'C'} def foo(value): de...
misc/function_map.ipynb
juditacs/snippets
lgpl-3.0
Changing value doesn't affect the functions
value = "ABCD" print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'), funcs['a']('D'))
misc/function_map.ipynb
juditacs/snippets
lgpl-3.0
Solution 3 - partial
from functools import partial d = {'a': 'AB', 'b': 'C'} funcs = {} for key, value in d.items(): funcs[key] = partial(lambda v, value: v in value, value=value) # True, True, False ? print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C')) # False, True ? print(funcs['b']('AB'), funcs['b']('C'))
misc/function_map.ipynb
juditacs/snippets
lgpl-3.0
Changing value
value = "ABCD" print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'), funcs['a']('D'))
misc/function_map.ipynb
juditacs/snippets
lgpl-3.0
When the document is ready (loaded and the DOM constrcuted), jQuery will register the click callback on the elements with the #flip id.
%%writefile jquery_slide_toggle.html -a <style> #panel, #flip { padding: 5px; text-align: center; background-color: #e5eecc; border: solid 1px #c3c3c3; } #panel { padding: 50px; display: none; } </style> %%writefile jquery_slide_toggle.html -a <div id="flip">Click to slide the panel down or...
web/jquery_slide.ipynb
satishgoda/learning
mit
Note I was first typing the entire html code in one cell and executing it. But later I need to make notes, so I came up with the %%writefile cell magic way to organize the html code.
%%html <script> $(document).ready(function(){ $("#flip0").click(function(){ $("#panel0").slideToggle("fast"); }); }); </script> <style> #panel0, #flip0 { padding: 5px; text-align: center; background-color: #e5eecc; border: solid 1px #c3c3c3; } #panel0 { padding: 50px; displa...
web/jquery_slide.ipynb
satishgoda/learning
mit
Reformat into a shape that's more adapted to the models we're going to train: - data as a flat matrix, - labels as float 1-hot encodings.
tdr=train_dataset.reshape((-1, 28*28)).astype(np.float32) print(train_dataset.shape) print (tdr.shape) print(train_labels) print (type(train_labels)) print((train_labels[:,None])) (np.arange(10) == train_labels[:,None]).astype(np.float32) #np.arange(10) image_size = 28 num_labels = 10 def reformat(dataset, labels): ...
random/catfish/2_fullyconnected.ipynb
emsi/ml-toolbox
agpl-3.0
(Only if you are using a colab notebook) We need to authenticate to Google Cloud and create the service client. After running the cell below, a link will appear which you need to click on and follow the instructions.
# ONLY RUN IF YOU ARE IN A COLAB NOTEBOOK. from google.colab import auth auth.authenticate_user()
examples/cloudml-bank-marketing/bank_marketing_classification_model.ipynb
GoogleCloudPlatform/professional-services
apache-2.0
Next, we need to set our project. Replace 'PROJECT_ID' with your GCP project ID.
%env GOOGLE_CLOUD_PROJECT=PROJECT_ID !gcloud config set project $GOOGLE_CLOUD_PROJECT
examples/cloudml-bank-marketing/bank_marketing_classification_model.ipynb
GoogleCloudPlatform/professional-services
apache-2.0
Third, you need to activate some of the GCP services that we will be using. Run the following cell if you need to activate API's. Which can also be done via the GUI via APIs and Services -> Enable APIS and Services.
!gcloud services enable ml.googleapis.com !gcloud services enable bigquery-json.googleapis.com
examples/cloudml-bank-marketing/bank_marketing_classification_model.ipynb
GoogleCloudPlatform/professional-services
apache-2.0