markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
REGION - Used for operations
throughout the rest of this notebook. Make sure to choose a region where Cloud
Vertex AI services are
available. You may
not use a Multi-Regional Storage bucket for training with Vertex AI.
MODEL_ARTIFACT_DIR - Folder directory path to your model artifacts within a Cloud Storage bucket, for... | BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"} | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Write your pre-processor
Scaling training data so each numerical feature column has a mean of 0 and a standard deviation of 1 can improve your model.
Create preprocess.py, which contains a class to do this scaling: | %mkdir app
%%writefile app/preprocess.py
import numpy as np
class MySimpleScaler(object):
def __init__(self):
self._means = None
self._stds = None
def preprocess(self, data):
if self._means is None: # during training only
self._means = np.mean(data, axis=0)
if se... | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Train and store model with pre-processor
Next, use preprocess.MySimpleScaler to preprocess the iris data, then train a model using scikit-learn.
At the end, export your trained model as a joblib (.joblib) file and export your MySimpleScaler instance as a pickle (.pkl) file: | %cd app/
import pickle
import joblib
from preprocess import MySimpleScaler
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
iris = load_iris()
scaler = MySimpleScaler()
X = scaler.preprocess(iris.data)
y = iris.target
model = RandomForestClassifier()
model.fit(X, y)
jobli... | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Upload model artifacts and custom code to Cloud Storage
Before you can deploy your model for serving, Vertex AI needs access to the following files in Cloud Storage:
model.joblib (model artifact)
preprocessor.pkl (model artifact)
Run the following commands to upload your files: | !gsutil cp model.joblib preprocessor.pkl {BUCKET_NAME}/{MODEL_ARTIFACT_DIR}/
%cd .. | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Build a FastAPI server | %%writefile app/main.py
from fastapi import FastAPI, Request
import joblib
import json
import numpy as np
import pickle
import os
from google.cloud import storage
from preprocess import MySimpleScaler
from sklearn.datasets import load_iris
app = FastAPI()
gcs_client = storage.Client()
with open("preprocessor.pkl",... | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Add pre-start script
FastAPI will execute this script before starting up the server. The PORT environment variable is set to equal AIP_HTTP_PORT in order to run FastAPI on same the port expected by Vertex AI. | %%writefile app/prestart.sh
#!/bin/bash
export PORT=$AIP_HTTP_PORT | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Store test instances to use later
To learn more about formatting input instances in JSON, read the documentation. | %%writefile instances.json
{
"instances": [
[6.7, 3.1, 4.7, 1.5],
[4.6, 3.1, 1.5, 0.2]
]
} | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Build and push container to Artifact Registry
Build your container
Optionally copy in your credentials to run the container locally. | # NOTE: Copy in credentials to run locally, this step can be skipped for deployment
%cp $GOOGLE_APPLICATION_CREDENTIALS app/credentials.json | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Write the Dockerfile, using tiangolo/uvicorn-gunicorn-fastapi as a base image. This will automatically run FastAPI for you using Gunicorn and Uvicorn. Visit the FastAPI docs to read more about deploying FastAPI with Docker. | %%writefile Dockerfile
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
COPY ./app /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Build the image and tag the Artifact Registry path that you will push to. | !docker build \
--tag={REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE} \
. | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Run and test the container locally (optional)
Run the container locally in detached mode and provide the environment variables that the container requires. These env vars will be provided to the container by Vertex Prediction once deployed. Test the /health and /predict routes, then stop the running image. | !docker rm local-iris
!docker run -d -p 80:8080 \
--name=local-iris \
-e AIP_HTTP_PORT=8080 \
-e AIP_HEALTH_ROUTE=/health \
-e AIP_PREDICT_ROUTE=/predict \
-e AIP_STORAGE_URI={BUCKET_NAME}/{MODEL_ARTIFACT_DIR} \
-e GOOGLE_APPLICATION_CREDENTIALS=credentials.json \
{REGION}-docker.pkg.dev/{PR... | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Push the container to artifact registry
Configure Docker to access Artifact Registry. Then push your container image to your Artifact Registry repository. | !gcloud beta artifacts repositories create {REPOSITORY} \
--repository-format=docker \
--location=$REGION
!gcloud auth configure-docker {REGION}-docker.pkg.dev
!docker push {REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE} | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Deploy to Vertex AI
Use the Python SDK to upload and deploy your model.
Upload the custom container model | from google.cloud import aiplatform
aiplatform.init(project=PROJECT, location=REGION)
model = aiplatform.Model.upload(
display_name=MODEL_DISPLAY_NAME,
artifact_uri=f"{BUCKET_NAME}/{MODEL_ARTIFACT_DIR}",
serving_container_image_uri=f"{REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}",
) | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Deploy the model on Vertex AI
After this step completes, the model is deployed and ready for online prediction. | endpoint = model.deploy(machine_type="n1-standard-4") | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Send predictions
Using Python SDK | endpoint.predict(instances=[[6.7, 3.1, 4.7, 1.5], [4.6, 3.1, 1.5, 0.2]]) | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Using REST | ENDPOINT_ID = endpoint.name
! curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d @instances.json \
https://{REGION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{REGION}/endpoints/{ENDPOINT_ID}:predict | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Using gcloud CLI | !gcloud beta ai endpoints predict $ENDPOINT_ID \
--region=$REGION \
--json-request=instances.json | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Cleaning up
To clean up all Google Cloud resources used in this project, you can delete the Google Cloud
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial: | # Undeploy model and delete endpoint
endpoint.delete(force=True)
# Delete the model resource
model.delete()
# Delete the container image from Artifact Registry
!gcloud artifacts docker images delete \
--quiet \
--delete-tags \
{REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE} | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Solution : Numpy
Numric Python or simply "numpy".
An alternative to python list: Numpy Array.
calculation is performed over entire arrays( element wise )
Easy and Fast.
Importing Numpy
Syntax: import numpy | import numpy as np # selective import
# Convet the followoing list to numpy arrays
height = [1.75, 1.65, 1.71, 1.89, 1.79]
weight = [65.4, 59.2, 63.6, 88.4, 68.7]
np_height = np.array( height )
np_weight = np.array( weight )
# Let's confirm this as numpy arrray
type(np_height)
type(np_weight)
bmi = np_weight / np_... | Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb | dataDogma/Computer-Science | gpl-3.0 |
Note:
Numpy assumes that your array contain elements of same type.
If the arary contains elements of differnet types, then resulitng numpy array will converted to type string.
Numpy array should'nt be missclassified as an array, technically it a "new data type", just like int, string, float or boolean, and:
Co... | # A numpy arary with different types
np.array( [1, 2.5, "are different", True ] ) | Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb | dataDogma/Computer-Science | gpl-3.0 |
Numpy : remarks | # a simple python list
py_list = [ 1, 2, 3 ]
# a numpy array
numpy_array = np.array([1, 2, 3])
"""
remarks:
+ If we add py_list with itself, it will generate a list of
new length.
+ Whereas, if we add the numpy_array, it would perform,
"element wise addition"
Warning:
Again be careful while using differ... | Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb | dataDogma/Computer-Science | gpl-3.0 |
Numpy Subsetting
All the subsetting operation on a list, also get's performed on
Numpy arrays, except for a few minor change, we look them now. | bmi
# get the fourth elemnt from the numpy array "bmi"
print("The bmi of the fourth element is: " + str( bmi[3] ) )
# slice and dice
print("\nThe bmi's from 2nd to 3rd element is: " + str( bmi[2 : 4] ) )
"""
Specifically for Numpy, there's another way to do list
subsetting via "booleans", here's how.
"""
... | Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb | dataDogma/Computer-Science | gpl-3.0 |
Exercise :
RQ1: Which Numpy function do you use to create an array?
Ans: array()
RQ2: Which two statements describe the advantage of Numpy Package over regular Python Lists?
Ans:
The Numpy Package provides the array, a data type that can be used to do element-wise calculations.
Because Numpy arrays can only hol... | """
Instructions:
+ Import the "numpy" package as "np", so that you can refer to "numpy" with "np".
+ Use "np.array()" to create a Numpy array from "baseball". Name this array "np_baseball".
+ Print out the "type of np_baseball" to check that you got it right.
"""
# Create list baseball
baseba... | Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb | dataDogma/Computer-Science | gpl-3.0 |
2. Baseball player's height
Preface:
You are a huge baseball fan. You decide to call the MLB (Major League Baseball) and ask around for some more statistics on the height of the main players. They pass along data on more than a thousand players, which is stored as a regular Python list: height. The height is expressed... | """
Instructions:
+ Create a Numpy array from height. Name this new array np_height.
+ Print "np_height".
+ Multiply "np_height" with 0.0254 to convert all height measurements from inches to meters.
- Store the new values in a new array, "np_height_m".
+ Print out np_height... | Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb | dataDogma/Computer-Science | gpl-3.0 |
3. Baseball player's BMI:
Preface:
The MLB also offers to let you analyze their weight data. Again, both are available as regular Python lists: height and weight. height is in inches and weight is in pounds.
It's now possible to calculate the BMI of each baseball player. Python code to convert height to a Numpy array... | """
Instructions:
+ Create a Numpy array from the weight list with the correct units.
- Multiply by 0.453592 to go from pounds to kilograms.
- Store the resulting Numpy array as np_weight_kg.
+ Use np_height_m and np_weight_kg to calculate the BMI of each player.
... | Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb | dataDogma/Computer-Science | gpl-3.0 |
4. Leightweight baseball players:
To subset both regular Python lists and Numpy arrays, you can use square brackets:
x = [4 , 9 , 6, 3, 1]
x[1]
import numpy as np
y = np.array(x)
y[1]
For Numpy specifically, you can also use boolean Numpy arrays:
high = y > 5
y[high] | """
Instructions:
+ Create a boolean Numpy array:
- the element of the array should be "True",
- If the corresponding baseball player's BMI is below 21.
- You can use the "<" operator for this
- Name the array "light", Print the array "light".
... | Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb | dataDogma/Computer-Science | gpl-3.0 |
5. Numpy Side Effect:
Preface:
Numpy arrays cannot contain elements with different types.
If you try to build such a list, some of the elments' types are changed to end up with a homogenous list.
This is known as type coercion.
Second, the typical arithmetic operators,
such as +, -, * and / have a differe... | """
Instructions:
+ Subset np_weight: print out the element at index 50.
+ Print out a sub-array of np_height: It contains the elements at index 100 up to and including index 110
"""
# height and weight are available as a regular lists
# Import numpy
import numpy as np
# Store weight and height lists a... | Courses/DAT-208x/DAT208X - Week 4 - Section 1 - Numpy.ipynb | dataDogma/Computer-Science | gpl-3.0 |
Run photon packets in parallel plane (film) medium
This is an example code to run a Monte Carlo calculation for photon packets travelling in a scattering medium.
Set random number seed. This is so that the code produces the same trajectories each time (for testing purposes). Comment this out or set the seed to None f... | seed = 1
# Properties of system
ntrajectories = 100 # number of trajectories
nevents = 100 # number of scattering events in each trajectory
wavelen = sc.Quantity('600 nm') # wavelength for scattering calculations
radius = sc.Quantity('0.125 um') # particle r... | montecarlo_tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Plot trajectories | trajectories.plot_coord(ntrajectories, three_dim=True) | montecarlo_tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Calculate the fraction of trajectories that are reflected and transmitted | thickness = sc.Quantity('50 um') # thickness of the sample film
reflectance, transmittance = det.calc_refl_trans(trajectories, thickness, n_medium, n_sample, boundary)
print('Reflectance = '+ str(reflectance))
print('Transmittance = '+ str(transmittance))
print('Absorption coefficient = ' + str(mu_abs)) | montecarlo_tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Add absorption to the system (in the particle and/or in the matrix)
Having absorption the particle or in the matrix implies that their refractive indices are complex (have a non-zero imaginary component). To include the effect of this absorption into the calculations, we just need to specify the complex refractive inde... | # Properties of system
n_particle = sc.Quantity(1.54 + 0.001j, '')
n_matrix = ri.n('vacuum', wavelen) + 0.0001j
n_sample = ri.n_eff(n_particle, n_matrix, volume_fraction)
# Calculate the phase function and scattering and absorption coefficients from the single scattering model
p, mu_scat, mu_abs = mc.calc_... | montecarlo_tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
As expected, the reflected fraction decreases if the system is absorbing.
Calculate the reflectance for a system of core-shell particles
When the system is made of core-shell particles, we must specify the refractive index, radius, and volume fraction of each layer, from innermost to outermost.
The reflectance is no... | # Properties of system
ntrajectories = 100 # number of trajectories
nevents = 100 # number of scattering events in each trajectory
wavelen = sc.Quantity('600 nm')
radius = sc.Quantity(np.array([0.125, 0.13]), 'um') # specify the radii from innermost to outermost layer
n_pa... | montecarlo_tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Calculate the reflectance for a polydisperse system
We can calculate the reflectance of a polydisperse system with either one or two species of particles, meaning that there are one or two mean radii, and each species has its own size distribution. We then need to specify the mean radius, the polydispersity index (pdi)... | # Properties of system
n_particle = sc.Quantity(1.54, '')
n_matrix = ri.n('vacuum', wavelen)
n_sample = ri.n_eff(n_particle, n_matrix, volume_fraction)
# define the parameters for polydispersity
radius = sc.Quantity('125 nm')
radius2 = sc.Quantity('150 nm')
concentration = sc.Quantity(np.array([0.9,0.1]), '')... | montecarlo_tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Calculate the reflectance for a sample with surface roughness
Two classes of surface roughnesses are implemented in the model:
1) When the surface roughness is high compared to the wavelength of light, we assume that light “sees” a nanoparticle before “seeing” the sample as an effective medium. The photons take a step ... | # Properties of system
ntrajectories = 100 # number of trajectories
nevents = 100 # number of scattering events in each trajectory
wavelen = sc.Quantity('600 nm')
radius = sc.Quantity('0.125 um')
volume_fraction = sc.Quantity(0.5, '')
n_particle = sc.Quantity(1.54, '') ... | montecarlo_tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Run photon packets in a medium with a spherical boundary
Example code to run a Monte Carlo calculation for photon packets travelling in a sample with a spherical boundary
There are only a few subtle differences between running the basic Monte Carlo calculation for a sphere and a film:
1. Set boundary='sphere' instead o... | # Properties of system
ntrajectories = 100 # number of trajectories
nevents = 100 # number of scattering events in each trajectory
wavelen = sc.Quantity('600 nm') # wavelength for scattering calculations
radius = sc.Quantity('0.125 um') # particle radius
asse... | montecarlo_tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
For spherical boundaries, there tends to be more light reflected back into the film upon an attempted exit, due to Fresnel reflection (this includes both total internal reflection and partial reflections). We've addressed this problem by including the option to re-run these Fresnel reflected trajectories as new Monte C... | # Calculate reflectance and transmittance
# The default value of plot_exits is False, so you need not set it to avoid plotting trajectories.
# The default value of run_tir is True, so you need not set it to include fresnel reflected trajectories.
reflectance, transmittance = det.calc_refl_trans(trajectories, assembly_d... | montecarlo_tutorial.ipynb | manoharan-lab/structural-color | gpl-3.0 |
Installing development tools
Let's start by installing Java. We'll use the default-jdk, which uses OpenJDK. This will take a while, so feel free to go for a walk or do some stretching.
Note: Alternatively, you could install the propietary Oracle JDK instead. | # Update and upgrade the system before installing anything else.
run('apt-get update > /dev/null')
run('apt-get upgrade > /dev/null')
# Install the Java JDK.
run('apt-get install default-jdk > /dev/null')
# Check the Java version to see if everything is working well.
run('javac -version') | examples/notebooks/get-started/try-apache-beam-java.ipynb | iemejia/incubator-beam | apache-2.0 |
Now, let's install Gradle, which we'll need to automate the build and running processes for our application.
Note: Alternatively, you could install and configure Maven instead. | import os
# Download the gradle source.
gradle_version = 'gradle-5.0'
gradle_path = f"/opt/{gradle_version}"
if not os.path.exists(gradle_path):
run(f"wget -q -nc -O gradle.zip https://services.gradle.org/distributions/{gradle_version}-bin.zip")
run('unzip -q -d /opt gradle.zip')
run('rm -f gradle.zip')
# We're... | examples/notebooks/get-started/try-apache-beam-java.ipynb | iemejia/incubator-beam | apache-2.0 |
build.gradle
We'll also need a build.gradle file which will allow us to invoke some useful commands. | %%writefile build.gradle
plugins {
// id 'idea' // Uncomment for IntelliJ IDE
// id 'eclipse' // Uncomment for Eclipse IDE
// Apply java plugin and make it a runnable application.
id 'java'
id 'application'
// 'shadow' allows us to embed all the dependencies into a fat jar.
id 'com.github.johnreng... | examples/notebooks/get-started/try-apache-beam-java.ipynb | iemejia/incubator-beam | apache-2.0 |
Creating the directory structure
Java and Gradle expect a specific directory structure. This helps organize large projects into a standard structure.
For now, we only need a place where our quickstart code will reside. That has to go within ./src/main/java/. | run('mkdir -p src/main/java/samples/quickstart') | examples/notebooks/get-started/try-apache-beam-java.ipynb | iemejia/incubator-beam | apache-2.0 |
Minimal word count
The following example is the "Hello, World!" of data processing, a basic implementation of word count. We're creating a simple data processing pipeline that reads a text file and counts the number of occurrences of every word.
There are many scenarios where all the data does not fit in memory. Notice... | %%writefile src/main/java/samples/quickstart/WordCount.java
package samples.quickstart;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Count;... | examples/notebooks/get-started/try-apache-beam-java.ipynb | iemejia/incubator-beam | apache-2.0 |
Build and run
Let's first check how the final file system structure looks like. These are all the files required to build and run our application.
build.gradle - build configuration for Gradle
src/main/java/samples/quickstart/WordCount.java - application source code
data/kinglear.txt - input data, this could be any fi... | # Build the project.
gradle('build')
# Check the generated build files.
run('ls -lh build/libs/') | examples/notebooks/get-started/try-apache-beam-java.ipynb | iemejia/incubator-beam | apache-2.0 |
There are two files generated:
* The content.jar file, the application generated from the regular build command. It's only a few kilobytes in size.
* The WordCount.jar file, with the baseName we specified in the shadowJar section of the gradle.build file. It's a several megabytes in size, with all the required librarie... | # Run the shadow (fat jar) build.
gradle('runShadow')
# Sample the first 20 results, remember there are no ordering guarantees.
run('head -n 20 outputs/part-00000-of-*') | examples/notebooks/get-started/try-apache-beam-java.ipynb | iemejia/incubator-beam | apache-2.0 |
Distributing your application
We can run our fat JAR file as long as we have a Java Runtime Environment installed.
To distribute, we copy the fat JAR file and run it with java -jar. | # You can now distribute and run your Java application as a standalone jar file.
run('cp build/libs/WordCount.jar .')
run('java -jar WordCount.jar')
# Sample the first 20 results, remember there are no ordering guarantees.
run('head -n 20 outputs/part-00000-of-*') | examples/notebooks/get-started/try-apache-beam-java.ipynb | iemejia/incubator-beam | apache-2.0 |
Word count with comments
Below is mostly the same code as above, but with comments explaining every line in more detail. | %%writefile src/main/java/samples/quickstart/WordCount.java
package samples.quickstart;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Count;... | examples/notebooks/get-started/try-apache-beam-java.ipynb | iemejia/incubator-beam | apache-2.0 |
Setup Google Cloud project | PROJECT = '[your-project-id]' # Change to your project id.
REGION = 'us-central1' # Change to your region.
if PROJECT == "" or PROJECT is None or PROJECT == "[your-project-id]":
# Get your GCP project id from gcloud
shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT = she... | 06-model-deployment.ipynb | GoogleCloudPlatform/mlops-with-vertex-ai | apache-2.0 |
Set configurations | VERSION = 'v01'
DATASET_DISPLAY_NAME = 'chicago-taxi-tips'
MODEL_DISPLAY_NAME = f'{DATASET_DISPLAY_NAME}-classifier-{VERSION}'
ENDPOINT_DISPLAY_NAME = f'{DATASET_DISPLAY_NAME}-classifier'
CICD_IMAGE_NAME = 'cicd:latest'
CICD_IMAGE_URI = f"gcr.io/{PROJECT}/{CICD_IMAGE_NAME}" | 06-model-deployment.ipynb | GoogleCloudPlatform/mlops-with-vertex-ai | apache-2.0 |
1. Run CI/CD steps locally | os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
os.environ['MODEL_DISPLAY_NAME'] = MODEL_DISPLAY_NAME
os.environ['ENDPOINT_DISPLAY_NAME'] = ENDPOINT_DISPLAY_NAME | 06-model-deployment.ipynb | GoogleCloudPlatform/mlops-with-vertex-ai | apache-2.0 |
Run the model artifact testing | !py.test src/tests/model_deployment_tests.py::test_model_artifact -s | 06-model-deployment.ipynb | GoogleCloudPlatform/mlops-with-vertex-ai | apache-2.0 |
Run create endpoint | !python build/utils.py \
--mode=create-endpoint\
--project={PROJECT}\
--region={REGION}\
--endpoint-display-name={ENDPOINT_DISPLAY_NAME} | 06-model-deployment.ipynb | GoogleCloudPlatform/mlops-with-vertex-ai | apache-2.0 |
Run deploy model | !python build/utils.py \
--mode=deploy-model\
--project={PROJECT}\
--region={REGION}\
--endpoint-display-name={ENDPOINT_DISPLAY_NAME}\
--model-display-name={MODEL_DISPLAY_NAME} | 06-model-deployment.ipynb | GoogleCloudPlatform/mlops-with-vertex-ai | apache-2.0 |
Test deployed model endpoint | !py.test src/tests/model_deployment_tests.py::test_model_endpoint | 06-model-deployment.ipynb | GoogleCloudPlatform/mlops-with-vertex-ai | apache-2.0 |
2. Execute the Model Deployment CI/CD routine in Cloud Build
The CI/CD routine is defined in the model-deployment.yaml file, and consists of the following steps:
1. Load and test the the trained model interface.
2. Create and endpoint in Vertex AI if it doesn't exists.
3. Deploy the model to the endpoint.
4. Test the e... | !echo $CICD_IMAGE_URI
!gcloud builds submit --tag $CICD_IMAGE_URI build/. --timeout=15m | 06-model-deployment.ipynb | GoogleCloudPlatform/mlops-with-vertex-ai | apache-2.0 |
Run CI/CD from model deployment using Cloud Build | REPO_URL = "https://github.com/GoogleCloudPlatform/mlops-with-vertex-ai.git" # Change to your github repo.
BRANCH = "main"
SUBSTITUTIONS=f"""\
_REPO_URL='{REPO_URL}',\
_BRANCH={BRANCH},\
_CICD_IMAGE_URI={CICD_IMAGE_URI},\
_PROJECT={PROJECT},\
_REGION={REGION},\
_MODEL_DISPLAY_NAME={MODEL_DISPLAY_NAME},\
_ENDPOINT_DIS... | 06-model-deployment.ipynb | GoogleCloudPlatform/mlops-with-vertex-ai | apache-2.0 |
RequestsでWebページを取得 | # Requestsでgihyo.jpのページのデータを取得
import requests
r = requests.get('http://gihyo.jp/lifestyle/clip/01/everyday-cat')
r.status_code # ステータスコードを取得
r.text[:50] # 先頭50文字を取得 | 4_scraping/4_2_scraping.ipynb | takanory/pymook-samplecode | mit |
Requestsを使いこなす
connpass APIリファレンス https://connpass.com/about/api/ | # JSON形式のAPIレスポンスを取得
r = requests.get('https://connpass.com/api/v1/event/?keyword=python')
data = r.json() # JSONをデコードしたデータを取得
for event in data['events']:
print(event['title'])
# 各種HTTPメソッドに対応
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post('http://httpbin.org/post', data=payload)
r = requests.pu... | 4_scraping/4_2_scraping.ipynb | takanory/pymook-samplecode | mit |
httpbin(1): HTTP Client Testing Service https://httpbin.org/
Beautiful Soup 4でWebページを解析 | # Beautiful Soup 4で「技評ねこ部通信」を取得
import requests
from bs4 import BeautifulSoup
r = requests.get('http://gihyo.jp/lifestyle/clip/01/everyday-cat')
soup = BeautifulSoup(r.content, 'html.parser')
title = soup.title # titleタグの情報を取得
type(title) # オブジェクトの型は Tag 型
print(title) # タイトルの中身を確認
print(title.text) # タイトルの中のテキストを取得
... | 4_scraping/4_2_scraping.ipynb | takanory/pymook-samplecode | mit |
Beautiful Soup 4を使いこなす | # タグの情報を取得する
div = soup.find('div', class_='readingContent01')
type(div) # データの型はTag型
div.name
div['class']
div.attrs # 全属性を取得
# さまざまな検索方法
a_tags = soup.find_all('a') # タグ名を指定
len(a_tags)
import re
for tag in soup.find_all(re.compile('^b')): # 正規表現で指定
print(tag.name)
for tag in soup.find_all(['html', 'title']... | 4_scraping/4_2_scraping.ipynb | takanory/pymook-samplecode | mit |
Contents
I. The crystal structure
A. Download and visualize
B. Try assigning a forcefield
II. Parameterizing a small molecule
A. Isolate the ligand
B. Assign bond orders and hydrogens
C. Generate forcefield parameters
III. Prepping the protein
A. Strip waters
B. Histidine
IV. Prep for dynamics
A. Assign the for... | protease = mdt.from_pdb('3AID')
protease
protease.draw() | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
B. Try assigning a forcefield
This structure is not ready for MD - this command will raise a ParameterizationError Exception. After running this calculation, click on the Errors/Warnings tab to see why. | amber_ff = mdt.forcefields.DefaultAmber()
newmol = amber_ff.create_prepped_molecule(protease) | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
You should see 3 errors:
1. The residue name ARQ not recognized
1. Atom HD1 in residue HIS69, chain A was not recognized
1. Atom HD1 in residue HIS69, chain B was not recognized
(There's also a warning about bond distances, but these can be generally be fixed with an energy minimization before running dynamics)
We'... | sel = mdt.widgets.ResidueSelector(protease)
sel
drugres = mdt.Molecule(sel.selected_residues[0])
drugres.draw2d(width=700, show_hydrogens=True) | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
B. Assign bond orders and hydrogens
A PDB file provides only limited information; they often don't provide indicate bond orders, hydrogen locations, or formal charges. These can be added, however, with the add_missing_pdb_data tool: | drugmol = mdt.tools.set_hybridization_and_saturate(drugres)
drugmol.draw(width=500)
drugmol.draw2d(width=700, show_hydrogens=True) | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
C. Generate forcefield parameters
We'll next generate forcefield parameters using this ready-to-simulate structure.
NOTE: for computational speed, we use the gasteiger charge model. This is not advisable for production work! am1-bcc or esp are far likelier to produce sensible results. | drug_parameters = mdt.create_ff_parameters(drugmol, charges='gasteiger') | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
III. Prepping the protein
Section II. dealt with getting forcefield parameters for an unknown small molecule. Next, we'll prep the other part of the structure.
A. Strip waters
Waters in crystal structures are usually stripped from a simulation as artifacts of the crystallization process. Here, we'll remove the waters f... | dehydrated = mdt.Molecule([atom for atom in protease.atoms if atom.residue.type != 'water']) | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
B. Histidine
Histidine is notoriously tricky, because it exists in no less than three different protonation states at biological pH (7.4) - the "delta-protonated" form, referred to with residue name HID; the "epsilon-protonated" form aka HIE; and the doubly-protonated form HIP, which has a +1 charge. Unfortunately, cry... | mdt.guess_histidine_states(dehydrated) | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
IV. Prep for dynamics
With these problems fixed, we can succesfully assigne a forcefield and set up the simulation.
A. Assign the forcefield
Now that we have parameters for the drug and have dealt with histidine, the forcefield assignment will succeed: | amber_ff = mdt.forcefields.DefaultAmber()
amber_ff.add_ff(drug_parameters)
sim_mol = amber_ff.create_prepped_molecule(dehydrated) | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
B. Attach and configure simulation methods
Armed with the forcefield parameters, we can connect an energy model to compute energies and forces, and an integrator to create trajectories: | sim_mol.set_energy_model(mdt.models.OpenMMPotential, implicit_solvent='obc', cutoff=8.0*u.angstrom)
sim_mol.set_integrator(mdt.integrators.OpenMMLangevin, timestep=2.0*u.fs)
sim_mol.configure_methods() | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
C. Equilibrate the protein
The next series of cells first minimize the crystal structure to remove clashes, then heats the system to 300K. | mintraj = sim_mol.minimize()
mintraj.draw()
traj = sim_mol.run(20*u.ps)
viewer = traj.draw(display=True)
viewer.autostyle() | moldesign/_notebooks/Example 4. HIV Protease bound to an inhibitor.ipynb | Autodesk/molecular-design-toolkit | apache-2.0 |
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... | docs/source/examples/Natural and artificial perturbations.ipynb | newlawrence/poliastro | mit |
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]) # km
v0 = np.array([-7.36138, -2.98997, 1.64354]) # km/s
k = Earth.k.to(u.km**3 / u.s**2).value
orbit = Orbit.from_vectors(Earth, r0 * u.km, v0 * u.km / u.s)
tof = (48.0 * u.h).to(u.s).value
rr, vv = cowell(orbit, np.linspace(0, tof, 2000), ad=J2_perturbation, J2=Earth.J2... | docs/source/examples/Natural and artificial perturbations.ipynb | newlawrence/poliastro | mit |
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... | docs/source/examples/Natural and artificial perturbations.ipynb | newlawrence/poliastro | mit |
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... | docs/source/examples/Natural and artificial perturbations.ipynb | newlawrence/poliastro | mit |
Units support all functionality that is supported by floats. Unit combinations are automatically taken care of. | dist = mg.Length(65, "mile")
time = mg.Time(30, "min")
speed = dist / time
print "The speed is {}".format(speed)
#Let's do a more sensible unit.
print "The speed is {}".format(speed.to("mile h^-1")) | notebooks/2013-01-01-Units.ipynb | materialsvirtuallab/matgenb | bsd-3-clause |
Note that complex units are specified as space-separated powers of units. Powers are specified using "^". E.g., "kg m s^-1". Only integer powers are supported.
Now, let's do some basic science. | g = mg.FloatWithUnit(9.81, "m s^-2") #Acceleration due to gravity
m = mg.Mass(2, "kg")
h = mg.Length(10, "m")
print "The force is {}".format(m * g)
print "The potential energy is force is {}".format((m * g * h).to("J")) | notebooks/2013-01-01-Units.ipynb | materialsvirtuallab/matgenb | bsd-3-clause |
Some highly complex conversions are possible with this system. Let's do some made up units. We will also demonstrate pymatgen's internal unit consistency checks. | made_up = mg.FloatWithUnit(100, "Ha^3 bohr^-2")
print made_up.to("J^3 ang^-2")
try:
made_up.to("J^2")
except mg.UnitError as ex:
print ex | notebooks/2013-01-01-Units.ipynb | materialsvirtuallab/matgenb | bsd-3-clause |
For arrays, we have the equivalent EnergyArray, ... and ArrayWithUnit classes. All other functionality remain the same. | dists = mg.LengthArray([1, 2, 3], "mile")
times = mg.TimeArray([0.11, 0.12, 0.23], "h")
print "Speeds are {}".format(dists / times) | notebooks/2013-01-01-Units.ipynb | materialsvirtuallab/matgenb | bsd-3-clause |
Merge CSV databases | from tools import get_psycinfo_database
words_df = get_psycinfo_database()
words_df.head()
#words_df.to_csv("data/PsycInfo/processed/psychinfo_combined.csv.bz2", encoding='utf-8',compression='bz2') | Word_Tracker/3rd_Yr_Paper/PsychoInfo.ipynb | aboSamoor/compsocial | gpl-3.0 |
Load PsychINFO unified database | #psychinfo = pd.read_csv("data/PsycInfo/processed/psychinfo_combined.csv.bz2", encoding='utf-8', compression='bz2')
psychinfo = words_df | Word_Tracker/3rd_Yr_Paper/PsychoInfo.ipynb | aboSamoor/compsocial | gpl-3.0 |
Term appearance in abstract and title | abstract_occurrence = []
for x,y in psychinfo[["Term", "Abstract"]].fillna("").values:
if x.lower() in y.lower():
abstract_occurrence.append(1)
else:
abstract_occurrence.append(0)
psychinfo["term_in_abstract"] = abstract_occurrence
title_occurrence = []
for x,y in psychinfo[["Term", "Title"]].fillna("").va... | Word_Tracker/3rd_Yr_Paper/PsychoInfo.ipynb | aboSamoor/compsocial | gpl-3.0 |
PsycINFO Tasks
Keep the current spreadsheet and add the following:
1. ~~Add Term in Abstract to spreadsheet~~ (word co-occurrence and control for the length of the abstract--lambda(len(abstract)) )do this for NSF/NIH data as well
1. ~~Add Term in Title to spreadsheet~~
1. ~~Copy the word data into a new column (title ... | len(psychinfo_search["Population Group"].value_counts()) | Word_Tracker/3rd_Yr_Paper/PsychoInfo.ipynb | aboSamoor/compsocial | gpl-3.0 |
Creazione della mappa
invece che uno scatterplot con dei raggi, la libreria ci consente solo di fare una heatmap (eventualmente pesata) | roma = pandas.read_csv("../data/Roma_towers.csv")
coordinate = roma[['lat', 'lon']].values
heatmap = gmaps.heatmap(coordinate)
gmaps.display(heatmap)
# TODO scrivere che dietro queste due semplici linee ci sta un pomeriggio intero di smadonnamenti
colosseo = (41.890183, 12.492369)
import gmplot
from gmplot import G... | src/heatmap_and_range.ipynb | FedericoMuciaccia/SistemiComplessi | mit |
NOTE guardando la mappa
Sembrano esserci dei problemi con la posizione delle antenne: ci sono antenne sul tevere, su ponte Sisto, dentro il parchetto di Castel Sant'Angelo, in mezzo al pratone della Sapienza, in cima al dipartimento di Fisica...
Inoltre sembra esserci una strana clusterizzazione lungo le vie di traffic... |
# condizioni di filtro
raggioMin = 1
# raggioMax = 1000
raggiPositivi = roma.range >= raggioMin
# raggiCorti = roma.range < raggioMax
# query con le condizioni
#romaFiltrato = roma[raggiPositivi & raggiCorti]
romaFiltrato = roma[raggiPositivi]
raggi = romaFiltrato.range
print max(raggi)
# logaritmic (base 2) binn... | src/heatmap_and_range.ipynb | FedericoMuciaccia/SistemiComplessi | mit |
Frequency-rank | # istogramma sugli interi
unique, counts = numpy.unique(raggi.values, return_counts=True)
# print numpy.asarray((unique, counts)).T
rank = numpy.arange(1,len(unique)+1)
frequency = numpy.array(sorted(counts, reverse=True))
pyplot.figure(figsize=(20,10))
pyplot.title('Distribuzione del raggio di copertura')
pyplot.ylab... | src/heatmap_and_range.ipynb | FedericoMuciaccia/SistemiComplessi | mit |
Cumulative histogram
the cumulative distribution function cdf(x) is the probability that a real-valued random variable X will take a value less than or equal to x | conteggi, binEdges = numpy.histogram(raggi.values,
bins=max(raggi)-min(raggi))
conteggiCumulativi = numpy.cumsum(conteggi)
valoriRaggi = numpy.delete(binEdges, -1)
N = len(raggi.values)
pyplot.figure(figsize=(12,10))
pyplot.title('Raggio di copertura')
pyplot.ylabel("Numero di antenne"... | src/heatmap_and_range.ipynb | FedericoMuciaccia/SistemiComplessi | mit |
<a id='step1a'></a>
A. Baseline Case: No Torque Tube
When torquetube is False, zgap is the distance from axis of torque tube to module surface, but since we are rotating from the module's axis, this Zgap doesn't matter for this baseline case. | #CASE 0 No torque tube
# When torquetube is False, zgap is the distance from axis of torque tube to module surface, but since we are rotating from the module's axis, this Zgap doesn't matter.
# zgap = 0.1 + diameter/2.0
torquetube = False
customname = '_NoTT'
module_NoTT = demo.makeModule(name=customname,x=x,y=y, nu... | docs/tutorials/9 - Advanced topics - 1 axis torque tube Shading for 1 day (Research documentation).ipynb | NREL/bifacial_radiance | bsd-3-clause |
<a id='step1b'></a>
B. ZGAP = 0.1 | #ZGAP 0.1
zgap = 0.1
customname = '_zgap0.1'
tubeParams = {'tubetype':tubetype,
'diameter':diameter,
'material':material,
'axisofrotation':False,
'visible':True} # either pass this into makeModule, or separately into module.addTorquetube()
module_zgap01 = demo.ma... | docs/tutorials/9 - Advanced topics - 1 axis torque tube Shading for 1 day (Research documentation).ipynb | NREL/bifacial_radiance | bsd-3-clause |
<a id='step1c'></a>
C. ZGAP = 0.2 | #ZGAP 0.2
zgap = 0.2
customname = '_zgap0.2'
tubeParams = {'tubetype':tubetype,
'diameter':diameter,
'material':material,
'axisofrotation':False,
'visible':True} # either pass this into makeModule, or separately into module.addTorquetube()
module_zgap02 = demo.mak... | docs/tutorials/9 - Advanced topics - 1 axis torque tube Shading for 1 day (Research documentation).ipynb | NREL/bifacial_radiance | bsd-3-clause |
<a id='step1d'></a>
D. ZGAP = 0.3 | #ZGAP 0.3
zgap = 0.3
customname = '_zgap0.3'
tubeParams = {'tubetype':tubetype,
'diameter':diameter,
'material':material,
'axisofrotation':False,
'visible':True} # either pass this into makeModule, or separately into module.addTorquetube()
module_zgap03 = demo.mak... | docs/tutorials/9 - Advanced topics - 1 axis torque tube Shading for 1 day (Research documentation).ipynb | NREL/bifacial_radiance | bsd-3-clause |
<a id='step2'></a>
2. Read-back the values and tabulate average values for unshaded, 10cm gap and 30cm gap | import glob
import pandas as pd
resultsfolder = os.path.join(testfolder, 'results')
print (resultsfolder)
filenames = glob.glob(os.path.join(resultsfolder,'*.csv'))
noTTlist = [k for k in filenames if 'NoTT' in k]
zgap10cmlist = [k for k in filenames if 'zgap0.1' in k]
zgap20cmlist = [k for k in filenames if 'zgap0.2'... | docs/tutorials/9 - Advanced topics - 1 axis torque tube Shading for 1 day (Research documentation).ipynb | NREL/bifacial_radiance | bsd-3-clause |
<a id='step3'></a>
3. plot spatial loss values for 10cm and 30cm data | import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Helvetica']
plt.rcParams['axes.linewidth'] = 0.2 #set the value globally
fig = plt.figure()
fig.set_size_inches(4, 2.5)
ax = fig.add_axes((0.15,0.15,0.78,0.75))
#plt.rc('font', family='sans-serif')
plt.rc('xt... | docs/tutorials/9 - Advanced topics - 1 axis torque tube Shading for 1 day (Research documentation).ipynb | NREL/bifacial_radiance | bsd-3-clause |
<a id='step4'></a>
4. Overall Shading Loss Factor
To calculate shading loss factor, we can use the following equation:
<img src="../images_wiki/AdvancedJournals/Equation_ShadingFactor.PNG"> | ShadingFactor = (1 - cm30_back.sum() / unsh_back.sum())*100 | docs/tutorials/9 - Advanced topics - 1 axis torque tube Shading for 1 day (Research documentation).ipynb | NREL/bifacial_radiance | bsd-3-clause |
Reading an NCEP BUFR data set
NCEP BUFR (Binary Universal Form for the Representation of meteorological data) can be read two ways:
Fortran code with BUFRLIB
py-ncepbufr, which is basically Python wrappers around BUFRLIB
In this example we'll use py-ncepbufr to read a snapshot of the Argo data tank from WCOSS, sh... | import matplotlib.pyplot as plt # graphics library
import numpy as np
import ncepbufr # python wrappers around BUFRLIB | test/Python_tutorial_bufr.ipynb | jswhit/py-ncepbufr | isc |
For the purposes of this demo I've made a local copy of the Argo data tank on WCOSS
located at
/dcom/us007003/201808/b031/xx005
Begin by opening the file | bufr = ncepbufr.open('data/xx005') | test/Python_tutorial_bufr.ipynb | jswhit/py-ncepbufr | isc |
Movement and data access within the BUFR file is through these methods:
bufr.advance()
bufr.load_subset()
bufr.read_subset()
bufr.rewind()
bufr.close()
There is a lot more functionality to ncepbufr, such as searching on multiple mnenomics, printing or saving the BUFR table included in the file, printing or saving the ... | # move down to first message - a return code of 0 indicates success
bufr.advance()
# load the message subset -- a return code of 0 indicates success
bufr.load_subset() | test/Python_tutorial_bufr.ipynb | jswhit/py-ncepbufr | isc |
You can print the subset and determine the parameter names. BUFR dumps can be very verbose, so I'll just copy in the header and the first subset replication from a bufr.dump_subset() command.
I've highlighted in red the parameters I want to plot.
<pre style="font-size: x-small">
MESSAGE TYPE NC031005
004001 YE... | temp = bufr.read_subset('SSTH').squeeze()-273.15 # convert from Kelvin to Celsius
sal = bufr.read_subset('SALNH').squeeze()
depth = bufr.read_subset('WPRES').squeeze()/10000. # convert from Pa to depth in meters
# observation location, date, and receipt time
lon = bufr.read_subset('CLONH')[0][0]
lat = bufr.read_subset... | test/Python_tutorial_bufr.ipynb | jswhit/py-ncepbufr | isc |
Set up the plotting figure. But this time, just for fun, let's put both the temperature and salinity profiles on the same axes. This trick uses both the top and bottom axis for different parameters.
As these are depth profiles, we need twin x-axes and a shared y-axis for the depth. | fig = plt.figure(figsize = (5,4))
ax1 = plt.axes()
ax1.plot(temp, depth,'r-')
ax1.grid(axis = 'y')
ax1.invert_yaxis() # flip the y-axis for ocean depths
ax2 = ax1.twiny() # here's the second x-axis definition
ax2.plot(np.nan, 'r-', label = 'Temperature')
ax2.plot(sal, depth, 'b-', label = 'Salinity')
ax2... | test/Python_tutorial_bufr.ipynb | jswhit/py-ncepbufr | isc |
Update time series for the symbols below.
Time series will be fetched for any symbols not already cached. | pf.update_cache_symbols(symbols=['msft', 'orcl', 'tsla']) | examples/A00.update-cache-symbols/update-cache-symbols.ipynb | fja05680/pinkfish | mit |
Remove the time series for TSLA | pf.remove_cache_symbols(symbols=['tsla']) | examples/A00.update-cache-symbols/update-cache-symbols.ipynb | fja05680/pinkfish | mit |
Update time series for all symbols in the cache directory | pf.update_cache_symbols() | examples/A00.update-cache-symbols/update-cache-symbols.ipynb | fja05680/pinkfish | mit |
Remove time series for all symbols in the cache directory | # WARNING!!! - if you uncomment the line below, you'll wipe out
# all the symbols in your cache directory
#pf.remove_cache_symbols() | examples/A00.update-cache-symbols/update-cache-symbols.ipynb | fja05680/pinkfish | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.