markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
**Conclusion:**- Classification accuracy is the **easiest classification metric to understand**- But, it does not tell you the **underlying distribution** of response values- And, it does not tell you what **"types" of errors** your classifier is making 5. Confusion matrixTable that describes the performance of a clas... | # IMPORTANT: first argument is true values, second argument is predicted values
print(metrics.confusion_matrix(y_test, y_pred_class)) | [[114 16]
[ 46 16]]
| BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
 - Every observation in the testing set is represented in **exactly one box**- It's a 2x2 matrix because there are **2 response classes**- The format shown here is **not** universal **Basic terminology**- **True Positives (TP):** we *correctly* predicted that they *do... | # print the first 25 true and predicted responses
print('True:', y_test.values[0:25])
print('Pred:', y_pred_class[0:25])
# save confusion matrix and slice into four pieces
confusion = metrics.confusion_matrix(y_test, y_pred_class)
TP = confusion[1, 1]
TN = confusion[0, 0]
FP = confusion[0, 1]
FN = confusion[1, 0] | _____no_output_____ | BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
 Metrics computed from a confusion matrix **Classification Accuracy:** Overall, how often is the classifier correct? | print((TP + TN) / float(TP + TN + FP + FN))
print(metrics.accuracy_score(y_test, y_pred_class)) | 0.6770833333333334
0.6770833333333334
| BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
**Classification Error:** Overall, how often is the classifier incorrect?- Also known as "Misclassification Rate" | print((FP + FN) / float(TP + TN + FP + FN))
print(1 - metrics.accuracy_score(y_test, y_pred_class)) | 0.3229166666666667
0.32291666666666663
| BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
**Sensitivity:** When the actual value is positive, how often is the prediction correct?- How "sensitive" is the classifier to detecting positive instances?- Also known as "True Positive Rate" or "Recall" | print(TP / float(TP + FN))
print(metrics.recall_score(y_test, y_pred_class)) | 0.25806451612903225
0.25806451612903225
| BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
**Specificity:** When the actual value is negative, how often is the prediction correct?- How "specific" (or "selective") is the classifier in predicting positive instances? | print(TN / float(TN + FP)) | 0.8769230769230769
| BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
**False Positive Rate:** When the actual value is negative, how often is the prediction incorrect? | print(FP / float(TN + FP)) | 0.12307692307692308
| BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
**Precision:** When a positive value is predicted, how often is the prediction correct?- How "precise" is the classifier when predicting positive instances? | print(TP / float(TP + FP))
print(metrics.precision_score(y_test, y_pred_class)) | 0.5
0.5
| BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
Many other metrics can be computed: F1 score, Matthews correlation coefficient, etc. **Conclusion:**- Confusion matrix gives you a **more complete picture** of how your classifier is performing- Also allows you to compute various **classification metrics**, and these metrics can guide your model selection**Which metric... | # print the first 10 predicted responses
logreg.predict(X_test)[0:10]
# print the first 10 predicted probabilities of class membership
logreg.predict_proba(X_test)[0:10, :]
# print the first 10 predicted probabilities for class 1
logreg.predict_proba(X_test)[0:10, 1]
# store the predicted probabilities for class 1
y_pr... | _____no_output_____ | BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
**Decrease the threshold** for predicting diabetes in order to **increase the sensitivity** of the classifier | # predict diabetes if the predicted probability is greater than 0.3
from sklearn.preprocessing import binarize
y_pred_class = binarize([y_pred_prob], 0.3)[0]
# print the first 10 predicted probabilities
y_pred_prob[0:10]
# print the first 10 predicted classes with the lower threshold
y_pred_class[0:10]
# previous confu... | 0.6153846153846154
| BSD-3-Clause | Day04/1-classification/classificationV2.ipynb | kxu08/Bootcamp2019 |
Tutorial: Creating Tasks Pre-requisiteBefore we start, we need to install EvoJAX and import some libraries. **Note** In our [paper](https://arxiv.org/abs/2202.05008), we ran the experiments on NVIDIA V100 GPU(s). Your results can be different from ours. | from IPython.display import clear_output, Image
!pip install evojax
!pip install torchvision # We use torchvision.datasets.MNIST in this tutorial.
clear_output()
import os
import numpy as np
import jax
import jax.numpy as jnp
from evojax.task.cartpole import CartPoleSwingUp
from evojax.policy.mlp import MLPPolicy
f... | EvoJAX: 2022-02-12 05:53:28,121 [INFO] Welcome to the tutorial on Task creation!
absl: 2022-02-12 05:53:28,133 [INFO] Starting the local TPU driver.
absl: 2022-02-12 05:53:28,135 [INFO] Unable to initialize backend 'tpu_driver': Not found: Unable to find driver in registry given worker: local://
absl: 2022-02-12 05:53:... | Apache-2.0 | examples/notebooks/TutorialTaskImplementation.ipynb | jamesbut/evojax |
Introduction EvoJAX has three major components: the *task*, the *policy network* and the *neuroevolution algorithm*. Once these components are implemented and instantiated, we can use a trainer to start the training process. The following code snippet provides an example of how we use EvoJAX. | seed = 42 # Wish me luck!
# We use the classic cart-pole swing up as our tasks, see
# https://github.com/google/evojax/tree/main/evojax/task for more example tasks.
# The test flag provides the opportunity for a user to
# 1. Return different signals as rewards. For example, in our MNIST example,
# we use negative ... | reward=[934.1182]
| Apache-2.0 | examples/notebooks/TutorialTaskImplementation.ipynb | jamesbut/evojax |
Including the three major components, EvoJAX implements the entire training pipeline in JAX. In the first release, we have created several [demo tasks](https://github.com/google/evojax/tree/main/evojax/task) to showcase EvoJAX's capacity. And we encourage the users to bring their own tasks. To this end, we will walk yo... | from torchvision import datasets
from flax.struct import dataclass
from evojax.task.base import TaskState
from evojax.task.base import VectorizedTask
# This state contains the information we wish to carry over to the next step.
# The state will be used in `VectorizedTask.step` method.
# In supervised learning tasks, ... | EvoJAX: 2022-02-12 05:54:41,285 [INFO] ConvNetPolicy.num_params = 11274
EvoJAX: 2022-02-12 05:54:41,435 [INFO] Start to train for 5000 iterations.
EvoJAX: 2022-02-12 05:54:52,635 [INFO] Iter=100, size=64, max=-0.8691, avg=-1.0259, min=-1.4128, std=0.1188
EvoJAX: 2022-02-12 05:54:56,730 [INFO] Iter=200, size=64, max=-0.... | Apache-2.0 | examples/notebooks/TutorialTaskImplementation.ipynb | jamesbut/evojax |
Okay! Our implementation of the classification task is successful and EvoJAX achieved $>98\%$ test accuracy within 5 min on a V100 GPU.As mentioned before, MNIST is a simple one-step task, we want to get you familiar with the interfaces. Next, we will build the classic cart-pole task from scratch. Cart-pole swing up ... | from evojax.task.base import TaskState
from evojax.task.base import VectorizedTask
import PIL
# Define some physics metrics.
GRAVITY = 9.82
CART_MASS = 0.5
POLE_MASS = 0.5
POLE_LEN = 0.6
FRICTION = 0.1
FORCE_SCALING = 10.0
DELTA_T = 0.01
CART_X_LIMIT = 2.4
# Define some constants for visualization.
SCREEN_W = 600
SC... | reward=[4.687451], steps=221
| Apache-2.0 | examples/notebooks/TutorialTaskImplementation.ipynb | jamesbut/evojax |
The random policy does not solve the cart-pole task, but our implementation seems to be correct. Let's now plug in this task to EvoJAX. | train_task = CartPole(test=False)
test_task = CartPole(test=True)
# We use the same policy and solver to solve this "new" task.
policy = MLPPolicy(
input_dim=train_task.obs_shape[0],
hidden_dims=[64, 64],
output_dim=train_task.act_shape[0],
logger=logger,
)
solver = PGPE(
pop_size=64,
param_siz... | reward=[923.1105]
| Apache-2.0 | examples/notebooks/TutorialTaskImplementation.ipynb | jamesbut/evojax |
Nice! EvoJAX is able to solve the new cart-pole task within a minute.In this tutorial, we walked you through the process of creating tasks from scratch. The two examples we used are simple and are supposed to help you understand the interfaces. If you are interested in learning more, please check out our GitHub [repo](... | _____no_output_____ | Apache-2.0 | examples/notebooks/TutorialTaskImplementation.ipynb | jamesbut/evojax | |
Provider Table MappingThis is an attempt at mapping FHIR to OMOP using the following guide: https://build.fhir.org/ig/HL7/cdmh/profiles.htmlomop-to-fhir-mappingsIn this notebook we are mapping FHIR to the OMOP Provider Table Load Data Frame from Parquet Catalog File | from pyspark.sql import SparkSession
from pyspark.sql.functions import dayofmonth,month,year,to_date,trunc,split,explode,array
# Create a local Spark session
spark = SparkSession.builder.appName('etl').getOrCreate()
# Reads file
df = spark.read.parquet('data/catalog.parquet') | _____no_output_____ | MIT | notebooks/Provider.ipynb | spe-uob/HealthcareLakeETL |
Data Frame schema | #df.printSchema() | _____no_output_____ | MIT | notebooks/Provider.ipynb | spe-uob/HealthcareLakeETL |
Practitioner Mapping Filter By Practitioner Resource type | filtered = df.filter(df['resourceType'] == 'Practitioner')
#filtered.printSchema() | _____no_output_____ | MIT | notebooks/Provider.ipynb | spe-uob/HealthcareLakeETL |
Categorical encodersExamples of how to use the different categorical encoders using the Titanic dataset. | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from feature_engine import categorical_encoders as ce
from feature_engine.missing_data_imputers import CategoricalVariableImputer
pd.set_option('display.max_columns', None)
# Load titanic datas... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
CountFrequencyCategoricalEncoderThe CountFrequencyCategoricalEncoder, replaces the categories by the count or frequency of the observations in the train set for that category. If we select "count" in the encoding_method, then for the variable colour, if there are 10 observations in the train set that show colour blue,... | count_enc = ce.CountFrequencyCategoricalEncoder(
encoding_method='frequency', variables=['cabin', 'pclass', 'embarked'])
count_enc.fit(X_train)
# we can explore the encoder_dict_ to find out the category replacements.
count_enc.encoder_dict_
# transform the data: see the change in the head view
train_t = count_e... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
CountLabels are replaced by the number of the observations that show that label in the train set. | # this time we encode only 1 variable
count_enc = ce.CountFrequencyCategoricalEncoder(encoding_method='count',
variables='cabin')
count_enc.fit(X_train)
# we can find the mappings in the encoder_dict_ attribute.
count_enc.encoder_dict_
# transform the data: see the cha... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Select categorical variables automaticallyIf we don't indicate which variables we want to encode, the encoder will find all categorical variables | # this time we ommit the argument for variable
count_enc = ce.CountFrequencyCategoricalEncoder(encoding_method = 'count')
count_enc.fit(X_train)
# we can see that the encoder selected automatically all the categorical variables
count_enc.variables
# transform the data: see the change in the head view
train_t = count... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Note that if there are labels in the test set that were not present in the train set, the transformer will introduce NaN, and raise a warning. MeanCategoricalEncoderThe MeanCategoricalEncoder replaces the labels of the variables by the mean value of the target for that label. For example, in the variable colour, if th... | # we will transform 3 variables
mean_enc = ce.MeanCategoricalEncoder(variables=['cabin', 'pclass', 'embarked'])
# Note: the MeanCategoricalEncoder needs the target to fit
mean_enc.fit(X_train, y_train)
# see the dictionary with the mappings per variable
mean_enc.encoder_dict_
mean_enc.variables
# we can see the trans... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Automatically select the variablesThis encoder will select all categorical variables to encode, when no variables are specified when calling the encoder | mean_enc = ce.MeanCategoricalEncoder()
mean_enc.fit(X_train, y_train)
mean_enc.variables
# we can see the transformed variables in the head view
train_t = count_enc.transform(X_train)
test_t = count_enc.transform(X_test)
test_t.head() | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
WoERatioCategoricalEncoderThis encoder replaces the labels by the weight of evidence or the ratio of probabilities. It only works for binary classification. The weight of evidence is given by: np.log( p(1) / p(0) ) The target probability ratio is given by: p(1) / p(0) Weight of evidence | ## Rare value encoder first to reduce the cardinality
# see below for more details on this encoder
rare_encoder = ce.RareLabelCategoricalEncoder(
tol=0.03, n_categories=2, variables=['cabin', 'pclass', 'embarked'])
rare_encoder.fit(X_train)
# transform
train_t = rare_encoder.transform(X_train)
test_t = rare_enco... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
RatioSimilarly, it is recommended to remove rare labels and high cardinality before using this encoder. | # rare label encoder first: transform
train_t = rare_encoder.transform(X_train)
test_t = rare_encoder.transform(X_test)
ratio_enc = ce.WoERatioCategoricalEncoder(
encoding_method='ratio', variables=['cabin', 'pclass', 'embarked'])
# to fit we need to pass the target y
ratio_enc.fit(train_t, y_train)
ratio_enc.enc... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
OrdinalCategoricalEncoderThe OrdinalCategoricalEncoder will replace the variable labels by digits, from 1 to the number of different labels. If we select "arbitrary", then the encoder will assign numbers as the labels appear in the variable (first come first served). If we select "ordered", the encoder will assign num... | # we will encode 3 variables:
ordinal_enc = ce.OrdinalCategoricalEncoder(
encoding_method='ordered', variables=['pclass', 'cabin', 'embarked'])
# for this encoder, we need to pass the target as argument
# if encoding_method='ordered'
ordinal_enc.fit(X_train, y_train)
# here we can see the mappings
ordinal_enc.enc... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Arbitrary | ordinal_enc = ce.OrdinalCategoricalEncoder(encoding_method='arbitrary',
variables='cabin')
# for this encoder we don't need to add the target. You can leave it or remove it.
ordinal_enc.fit(X_train, y_train)
ordinal_enc.encoder_dict_ | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Note that the ordering of the different labels is not the same when we select "arbitrary" or "ordered" | # transform: see the numerical values in the former categorical variables
train_t = ordinal_enc.transform(X_train)
test_t = ordinal_enc.transform(X_test)
test_t.head() | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Automatically select categorical variablesThese encoder as well selects all the categorical variables, if None is passed to the variable argument when calling the enconder. | ordinal_enc = ce.OrdinalCategoricalEncoder(encoding_method = 'arbitrary')
# for this encoder we don't need to add the target. You can leave it or remove it.
ordinal_enc.fit(X_train)
ordinal_enc.variables
# transform: see the numerical values in the former categorical variables
train_t = ordinal_enc.transform(X_train)... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
OneHotCategoricalEncoderPerforms One Hot Encoding. The encoder can select how many different labels per variable to encode into binaries. When top_categories is set to None, all the categories will be transformed in binary variables. However, when top_categories is set to an integer, for example 10, then only the 10 m... | ohe_enc = ce.OneHotCategoricalEncoder(
top_categories=None,
variables=['pclass', 'cabin', 'embarked'],
drop_last=False)
ohe_enc.fit(X_train)
ohe_enc.drop_last
ohe_enc.encoder_dict_
train_t = ohe_enc.transform(X_train)
test_t = ohe_enc.transform(X_train)
test_t.head() | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Dropping the last category for linear models | ohe_enc = ce.OneHotCategoricalEncoder(
top_categories=None,
variables=['pclass', 'cabin', 'embarked'],
drop_last=True)
ohe_enc.fit(X_train)
ohe_enc.encoder_dict_
train_t = ohe_enc.transform(X_train)
test_t = ohe_enc.transform(X_train)
test_t.head() | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Selecting top_categories to encode | ohe_enc = ce.OneHotCategoricalEncoder(
top_categories=2,
variables=['pclass', 'cabin', 'embarked'],
drop_last=False)
ohe_enc.fit(X_train)
ohe_enc.encoder_dict_
train_t = ohe_enc.transform(X_train)
test_t = ohe_enc.transform(X_train)
test_t.head() | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
RareLabelCategoricalEncoderThe RareLabelCategoricalEncoder groups labels that show a small number of observations in the dataset into a new category called 'Rare'. This helps to avoid overfitting.The argument tol indicates the percentage of observations that the label needs to have in order not to be re-grouped into t... | ## Rare value encoder
rare_encoder = ce.RareLabelCategoricalEncoder(
tol=0.03, n_categories=5, variables=['cabin', 'pclass', 'embarked'])
rare_encoder.fit(X_train)
# the encoder_dict_ contains a dictionary of the {variable: frequent labels} pair
rare_encoder.encoder_dict_
train_t = rare_encoder.transform(X_trai... | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Automatically select all categorical variablesIf no variable list is passed as argument, it selects all the categorical variables. | ## Rare value encoder
rare_encoder = ce.RareLabelCategoricalEncoder(tol = 0.03, n_categories=5)
rare_encoder.fit(X_train)
rare_encoder.encoder_dict_
train_t = rare_encoder.transform(X_train)
test_t = rare_encoder.transform(X_train)
test_t.head() | _____no_output_____ | BSD-3-Clause | examples/categorical-encoders.ipynb | iahsanujunda/feature_engine |
Simple Linear Regression Importing all libraries required | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
%matplotlib inline
# Reading data from remote link
url = "http... | _____no_output_____ | MIT | Task 1-Prediction using Supervised ML/Prediction using Supervised ML.ipynb | Divyakathirvel26/GRIP-Internship-Tasks |
Data Visualization | # Plotting the distribution of scores
data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show() | _____no_output_____ | MIT | Task 1-Prediction using Supervised ML/Prediction using Supervised ML.ipynb | Divyakathirvel26/GRIP-Internship-Tasks |
Linear Regression Model | X = data.iloc[:, :-1].values
y = data.iloc[:, 1].values
X_train, X_test, y_train, y_test = train_test_split(X, y,train_size=0.80,test_size=0.20,random_state=42) | _____no_output_____ | MIT | Task 1-Prediction using Supervised ML/Prediction using Supervised ML.ipynb | Divyakathirvel26/GRIP-Internship-Tasks |
Training the model | from sklearn.linear_model import LinearRegression
linearRegressor= LinearRegression()
linearRegressor.fit(X_train, y_train)
y_predict= linearRegressor.predict(X_train) | _____no_output_____ | MIT | Task 1-Prediction using Supervised ML/Prediction using Supervised ML.ipynb | Divyakathirvel26/GRIP-Internship-Tasks |
Training the Algorithm | regressor = LinearRegression()
regressor.fit(X_train, y_train)
print("Training complete.")
# Plotting the regression line
line = regressor.coef_*X+regressor.intercept_
# Plotting for the test data
plt.scatter(X, y)
plt.plot(X, line);
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Perc... | _____no_output_____ | MIT | Task 1-Prediction using Supervised ML/Prediction using Supervised ML.ipynb | Divyakathirvel26/GRIP-Internship-Tasks |
Checking the accuracy scores for training and test set | print('Test Score')
print(regressor.score(X_test, y_test))
print('Training Score')
print(regressor.score(X_train, y_train))
y_test
y_predict
y_predict[:5]
data= pd.DataFrame({'Actual': y_test,'Predicted': y_predict[:5]})
data
#Let's predict the score for 9.25 hpurs
print('Score of student who studied for 9.25 hours a ... | Score of student who studied for 9.25 hours a dat [92.38611528]
| MIT | Task 1-Prediction using Supervised ML/Prediction using Supervised ML.ipynb | Divyakathirvel26/GRIP-Internship-Tasks |
Model Evaluation Metrics | #Checking the efficiency of model
mean_squ_error = mean_squared_error(y_test, y_predict[:5])
mean_abs_error = mean_absolute_error(y_test, y_predict[:5])
print("Mean Squred Error:",mean_squ_error)
print("Mean absolute Error:",mean_abs_error) | Mean Squred Error: 1404.2200673968694
Mean absolute Error: 33.80918778157651
| MIT | Task 1-Prediction using Supervised ML/Prediction using Supervised ML.ipynb | Divyakathirvel26/GRIP-Internship-Tasks |
How to use the Data Lab *Store Client* ServiceThis notebook documents how to use the Data Lab virtual storage system via the store client service. This can be done either from a Python script (e.g. within this notebook) or from the command line using the datalab command. The storage manager service interfaceThe store ... | # Standard notebook imports
from getpass import getpass
from dl import authClient, storeClient | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Comment out and run the cell below if you need to login to Data Lab: | ## Get the authentication token for the user
#token = authClient.login(input("Enter user name: (+ENTER) "),getpass("Enter password: (+ENTER) "))
#if not authClient.isValidToken(token):
# raise Exception('Token is not valid. Please check your usename/password and execute this cell again.') | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Listing a file/directoryWe can see all the files that are in a specific directory or get a full listing for a specific file. In this case, we'll list the default virtual storage directory to use as a basis for changes we'll make below. | listing = storeClient.ls (name = 'vos://')
print (listing) | cutout.fits,public,results,tmp
| BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
The *public* directory shown here is visible to all Data Lab users and provides a means of sharing data without having to setup special access. Similarly, the *tmp* directory is read-protected and provides a convenient temporary directory to be used in a workflow. File Existence and InfoAside from simply listing file... | # A simple file existence test:
if storeClient.access ('vos://public'):
print ('User "public" directory exists')
if storeClient.access ('vos://public', mode='w'):
print ('User "public" directory is group/world writable')
else:
print ('User "public" directory is not group/world writable')
if storeClient... | User "public" directory exists
User "public" directory is not group/world writable
User "tmp" directory exists
User "tmp" directory is not group/world writable
| BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Uploading a fileNow we want to upload a new data file from our local disk to the virtual storage: | storeClient.put (to = 'vos://newmags.csv', fr = './newmags.csv')
print(storeClient.ls (name='vos://')) | (1 / 1) ./newmags.csv -> vos://newmags.csv
cutout.fits,newmags.csv,public,results,tmp
| BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Downloading a fileLet's say we want to download a file from our virtual storage space, in this case a query result that we saved to it in the "How to use the Data Lab query manager service" notebook: | storeClient.get (fr = 'vos://newmags.csv', to = './mymags.csv') | (1/1) [====================] [ 142B] newmags.csv
| BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
It is also possible to get the contents of a remote file directly into your notebook by specifying the location as an empty string: | data = storeClient.get (fr = 'vos://newmags.csv', to = '')
print (data) | id,g,r,i
001,22.3,12.4,21.5
002,22.3,12.4,21.5
003,22.3,12.4,21.5
004,22.3,12.4,21.5
005,22.3,12.4,21.5
006,22.3,12.4,21.5
007,22.3,12.4,21.5
| BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Loading a file from a remote URLIt is possible to load a file directly to virtual storage from a remote URL )e.g. an "accessURL" for an image cutout, a remote data file, etc) using the "storeClient.load()" method: | url = "http://datalab.noirlab.edu/svc/cutout?col=&siaRef=c4d_161005_022804_ooi_g_v1.fits.fz&extn=31&POS=335.0,0.0&SIZE=0.1"
storeClient.load('vos://cutout.fits',url) | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Creating a directoryWe can create a directory on the remote storage to be used for saving data later: | storeClient.mkdir ('vos://results') | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Copying a file/directoryWe want to put a copy of the file in a remote work directory: | storeClient.mkdir ('vos://temp')
print ("Before: " + storeClient.ls (name='vos://temp/'))
storeClient.cp (fr = 'vos://newmags.csv', to = 'vos://temp/newmags.csv',verbose=True)
print ("After: " + storeClient.ls (name='vos://temp/'))
print(storeClient.ls('vos://',format='long')) | -rw-rw-r-x demo01 2963520 22 Nov 2021 14:22 cutout.fits
-rw-rw-r-x demo01 142 30 Nov 2021 14:58 newmags.csv
drwxrwxr-x demo01 0 14 Jul 2020 10:01 public/
drwxrwxr-x demo01 0 22 Nov 2021 14:22 results/
drwxrwxr-x demo01 0 30 Nov 2021 14:58 temp/
drwxrwx--- demo01 0 14 Jul 20... | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Notice that in the *ls()* call we append the directory name with a trailing '/' to list the contents of the directory rather than the directory itself. Linking to a file/directory**WARNING**: Linking is currently **not** working in the Data Lab storage manager. This notebook will be updated when the problem has been r... | storeClient.ln ('vos://mags.csv', 'vos://temp/newmags.csv')
print ("Root dir: " + storeClient.ls (name='vos://'))
print ("Temp dir: " + storeClient.ls (name='vos://temp/')) | Root dir: cutout.fits,newmags.csv,public,results,temp,tmp
Temp dir: newmags.csv
| BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Moving/renaming a file/directoryWe can move a file or directory: | storeClient.mv(fr = 'vos://temp/newmags.csv', to = 'vos://results')
print ("Results dir: " + storeClient.ls (name='vos://results/')) | Results dir: newmags.csv
| BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Deleting a fileWe can delete a file: | print ("Before: " + storeClient.ls (name='vos://'))
storeClient.rm (name = 'vos://mags.csv')
print ("After: " + storeClient.ls (name='vos://')) | Before: cutout.fits,newmags.csv,public,results,temp,tmp
After: cutout.fits,newmags.csv,public,results,temp,tmp
| BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Deleting a directoryWe can also delete a directory, doing so also deletes the contents of that directory: | storeClient.rmdir(name = 'vos://temp') | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Tagging a file/directory**Warning**: Tagging is currently **not** working in the Data Lab storage manager. This notebook will be updated when the problem has been resolved.We can tag any file or directory with arbitrary metadata: | storeClient.tag('vos://results', 'The results from my analysis') | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Cleanup the demo directory of remaining files | storeClient.rm (name = 'vos://newmags.csv')
storeClient.rm (name = 'vos://results')
storeClient.ls (name = 'vos://') | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Using the datalab commandThe datalab command provides an alternate command line way to work with the query manager through the query subcommands, which is especially useful if you want to interact with the query manager from your local computer. Please have the `datalab` command line utility installed first (for insta... | #!datalab login | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
and enter the credentials as prompted. Downloading a fileLet's say we want to download a file from our virtual storage space: | #!datalab get fr="vos://mags.csv" to="./mags.csv" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Uploading a fileNow we want to upload a new data file from our local disk: | #!datalab put fr="./newmags.csv" to="vos://newmags.csv" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Copying a file/directoryWe want to put a copy of the file in a remote work directory: | #!datalab cp fr="vos://newmags.csv" to="vos://temp/newmags.csv" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Linking to a file/directorySometimes we want to create a link to a file or directory: | #!datalab ln fr="vos://temp/mags.csv" to="vos://mags.csv" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Listing a file/directoryWe can see all the files that are in a specific directory or get a full listing for a specific file: | #!datalab ls name="vos://temp" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Creating a directoryWe can create a directory: | #!datalab mkdir name="vos://results" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Moving/renaming a file/directoryWe can move a file or directory: | #!datalab mv fr="vos://temp/newmags.csv" to="vos://results" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Deleting a fileWe can delete a file: | #!datalab rm name="vos://temp/mags.csv" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Deleting a directoryWe can also delete a directory: | #!datalab rmdir name="vos://temp" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
Tagging a file/directoryWe can tag any file or directory with arbitrary metadata: | #!datalab tag name="vos://results" tag="The results from my analysis" | _____no_output_____ | BSD-3-Clause | 04_HowTos/StoreClient/How_to_use_the_Data_Lab_StoreClient.ipynb | noaodatalab/notebooks_default |
*Bosonic statistics and the Bose-Einstein condensation* `Doruk Efe Gökmen -- 30/08/2018 -- Ankara` Non-interacting ideal bosonsNon-interacting bosons is the only system in physics that can undergo a phase transition without mutual interactions between its components.Let us enumerate the energy eigenstates of a single... | Emax = 30
States = []
for E_x in range(Emax):
for E_y in range(Emax):
for E_z in range(Emax):
States.append(((E_x + E_y + E_z), (E_x, E_y, E_z)))
States.sort()
for k in range(Emax):
print '%3d' % k, States[k][0], States[k][1] | 0 0 (0, 0, 0)
1 1 (0, 0, 1)
2 1 (0, 1, 0)
3 1 (1, 0, 0)
4 2 (0, 0, 2)
5 2 (0, 1, 1)
6 2 (0, 2, 0)
7 2 (1, 0, 1)
8 2 (1, 1, 0)
9 2 (2, 0, 0)
10 3 (0, 0, 3)
11 3 (0, 1, 2)
12 3 (0, 2, 1)
13 3 (0, 3, 0)
14 3 (1, 0, 2)
15 3 (1, 1, 1)
16 3 (1, 2, 0)
17 3 (2, 0, 1)
18 3 (2, 1, 0)
19 3 (3, 0, 0)
... | MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
Here it can be perceived that the degeneracy at an energy level $E_n$, which we denote by $\mathcal{N}(E_n)$, is $\frac{(n+1)(n+2)}{2}$. Alternatively, we may use a more systematic approach. We can calculate the number of states at the $n$th energy level as $\mathcal{N}(E_n)=\sum_{E_x=0}^{E_n}\sum_{E_y=0}^{E_n}\sum_{E_... | %pylab inline
import math, numpy as np, pylab as plt
#calculate the partition function for 5 bosons by stacking the bosons in one of the N_states
#number of possible states and counting only a specific order of them (they are indistinguishable)
def bosons_bounded_harmonic(beta, N):
Energy = [] #initialise the vec... | Populating the interactive namespace from numpy and matplotlib
Temperature: 1.0 Total number of possible states: 575757 | Partition function: 17.3732972183 | Average energy per particle: 1.03133265311 | Condensate fraction (ground state occupation per particle): 0.446969501933
| MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
Here we see that all particles are in the ground states at very low temperatures this is a simple consequence of Boltzmann statistics. At zero temperature all the particles populate the ground state. Bose-Einstein condensation is something else, it means that a finite fraction of the system is in the ground-state for t... | import random
N = 3 #length of the list
statistics = {}
L = range(N) #initialise the list
nsteps = 10
for step in range(nsteps):
i = random.randint(0, N - 1) #pick two random indices i and j from the list L
j = random.randint(0, N - 1)
L[i], L[j] = L[j], L[i] #exchange the i'th and j'th elements
if tup... | _____no_output_____ | MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
Let us look at the permutation cycles and their frequency of occurrence: | import random
N = 20 #length of the list
stats = [0] * (N + 1) #initialise the "stats" vector
L = range(N) #initialise the list
nsteps = 1000000 #number of steps
for step in range(nsteps):
i = random.randint(0, N - 1) #pick two random indices i and j from the list L
j = random.randint(0, N - 1)
L[i], L[j] ... | 1 10130
2 5008
3 3395
4 2438
5 1969
6 1659
7 1403
8 1260
9 1118
10 949
11 943
12 833
13 778
14 745
15 642
16 618
17 610
18 553
19 530
20 492
| MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
The partition function of permutations $\mathcal{P}$ on a list of lentgth $N$ is $Y_N=\sum_\mathcal{P}\text{weight}(\mathcal{P})$. Let $z_n$ be the weight of a permutation cycle of length $n$. Then, the permutation $[0,1,2,3]\rightarrow[0,1,2,3]$, which can be represented as $(0)(1)(2)(3)$, has the weight $z_1^4$; simi... | import random, math, pylab, mpl_toolkits.mplot3d
#3 dimensional Levy algorithm, used for resampling the positions of entire permutation cycles of bosons
#to sample positions
def levy_harmonic_path(k, beta):
#direct sample (rejection-free) three coordinate values, use diagonal density matrix
#k corresponds to ... | _____no_output_____ | MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
 But we do know that for the harmonic trap, the single 3-dimensional particle partition function is given by $z(\beta)=\left(\frac{1}{1-e^{-\beta}}\right)^3$. The permutation cycle of length $k$ corresponds to $z_k=z(k\beta)=\left(\frac{1}{1-e^{-k\beta}}\right)^3$. Hence, using (9) and (10), we have ... | import math, pylab
def z(k, beta):
return 1.0 / (1.0 - math.exp(- k * beta)) ** 3 #partition function of a single particle in a harmonic trap
def canonic_recursion(N, beta): #Landsberg recursion relations for the partition function of N bosons
Z = [1.0] #Z_0 = 1
for M in range(1, N + 1):
Z.append(... | _____no_output_____ | MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
Since we have an analytical solution to the problem, we can now implement a rejection-free direct sampling algorithm for the permutations. | import math, random
def z(k, beta): #partition function of a single particle in a harmonic trap
return (1.0 - math.exp(- k * beta)) ** (-3)
def canonic_recursion(N, beta): #Landsberg recursion relation for the partition function of N bosons in a harmonic trap
Z = [1.0]
for M in range(1, N + 1):
Z.... | _____no_output_____ | MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
Physical properties of the 1-dimensional classical and bosonic systems* Consider 2 non-interacting **distinguishable particles** in a 1-dimensional harmonic trap: | import random, math, pylab
#There are only two possible cases: For k=1, we sample a single position (cycle of length 1),
#for k=2, we sample two positions (a cycle of length two).
def levy_harmonic_path(k):
x = [random.gauss(0.0, 1.0 / math.sqrt(2.0 * math.tanh(k * beta / 2.0)))] #direct-sample the first position... | _____no_output_____ | MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
* Consider two non-interacting **indistinguishable bosonic** quantum particles in a one-dimensional harmonic trap: | import math, random, pylab, numpy as np
def z(beta):
return 1.0 / (1.0 - math.exp(- beta))
def pi_two_bosons(x, beta): #exact two boson position distribution
pi_x_1 = math.sqrt(math.tanh(beta / 2.0)) / math.sqrt(math.pi) * math.exp(-x ** 2 * math.tanh(beta / 2.0))
pi_x_2 = math.sqrt(math.tanh(beta)) / mat... | _____no_output_____ | MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
We can use dictionaries instead of lists. The implementation is in the following program. Here we also calculate the correlation between the two particles, i.e. sample of the absolute distance $r$ between the two bosons. The comparison between the resulting distribution and the distribution for the distinguishable case... | import math, random, pylab
def prob_r_distinguishable(r, beta): #the exact correlation function for two particles
sigma = math.sqrt(2.0) / math.sqrt(2.0 * math.tanh(beta / 2.0))
prob = (math.sqrt(2.0 / math.pi) / sigma) * math.exp(- r ** 2 / 2.0 / sigma ** 2)
return prob
def levy_harmonic_path(k):
x =... | _____no_output_____ | MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
3-dimensional bosons Isotropic trap | import random, math, numpy, sys, os
import matplotlib.pyplot as plt
def harmonic_ground_state(x):
return math.exp(-x ** 2)/math.sqrt(math.pi)
def levy_harmonic_path_3d(k):
x0 = tuple([random.gauss(0.0, 1.0 / math.sqrt(2.0 *
math.tanh(k * beta / 2.0))) for d in range(3)])
x = [x0]
for j... | starting from file data_boson_configuration_N512_T0.8.txt
| MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
Anisotropic trapWe can imitate the experiments that imitate 1-d bosons in *cigar shaped* anisotropic harmonic traps, and 2-d bosons in *pancake shaped* anisotropic harmonic traps. | %pylab inline
import random, math, numpy, os, sys
def levy_harmonic_path_3d_anisotropic(k, omega):
sigma = [1.0 / math.sqrt(2.0 * omega[d] *
math.tanh(0.5 * k * beta * omega[d])) for d in xrange(3)]
xk = tuple([random.gauss(0.0, sigma[d]) for d in xrange(3)])
x = [xk]
for j in range(1, k):... | Populating the interactive namespace from numpy and matplotlib
omega: [4. 4. 1.]
starting from file data_boson_configuration_anisotropic_N512_T0.5_cigar.txt
| MIT | 8. Bose-Einstein condensation.ipynb | cphysics/simulation |
Working with 3D city models in Python**Balázs Dukai** [*@BalazsDukai*](https://twitter.com/balazsdukai), **FOSS4G 2019**Tweet CityJSON[3D geoinformation research group, TU Delft, Netherlands](https://3d.bk.tudelft.nl/)Repo of this talk: [https://github.com/balazsdukai/foss4g2019](https://github.c... | import json
import os
path = os.path.join('data', 'rotterdam_subset.json')
with open(path) as fin:
cm = json.loads(fin.read())
print(f"There are {len(cm['CityObjects'])} CityObjects")
# list all IDs
for id in cm['CityObjects']:
print(id, "\t") | There are 16 CityObjects
{C9D4A5CF-094A-47DA-97E4-4A3BFD75D3AE}
{71B60053-BC28-404D-BAB9-8A642AAC0CF4}
{6271F75F-E8D8-4EE4-AC46-9DB02771A031}
{DE77E78F-B110-43D2-A55C-8B61911192DE}
{19935DFC-F7B3-4D6E-92DD-C48EE1D1519A}
{953BC999-2F92-4B38-95CF-218F7E05AFA9}
{8D716FDE-18DD-4FB5-AB06-9D207377240E}
{C6AAF95... | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
+ Working with a CityJSON file is straightforward. One can open it with the standard library and get going.+ But you need to know the schema well.+ And you need to write everything from scratch. That is why we are developing **cjio**. **cjio** is how *we eat what we cook*Aims to help to actually work with and analyse 3... | ! cjio --help
! cjio data/rotterdam_subset.json info
! cjio data/rotterdam_subset.json validate
! cjio data/rotterdam_subset.json \
subset --exclude --id "{CD98680D-A8DD-4106-A18E-15EE2A908D75}" \
merge data/rotterdam_one.json \
reproject 2056 \
save data/test_rotterdam.json | [30m[46mParsing data/rotterdam_subset.json[0m
[30m[46mSubset of CityJSON[0m
[30m[46mMerging files[0m
[30m[46mReproject to EPSG:2056[0m
[?25l [####################################] 100% [?25h
[30m[46mSaving CityJSON to a file /home/balazs/Reports/talk_cjio_foss4g_2019/data/test_rotterdam.json... | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
+ The CLI was first, no plans for API+ **Works with whole city model only**+ Functions for the CLI work with the JSON directly, passing it along+ Simple and effective architecture `cjio`'s APIAllow *read* --> *explore* --> *modify* --> *write* iterationWork with CityObjects and their partsFunctions for common op... | import os
from copy import deepcopy
from cjio import cityjson
from shapely.geometry import Polygon
import matplotlib.pyplot as plt
plt.close('all')
from sklearn.preprocessing import FunctionTransformer
from sklearn import cluster
import numpy as np | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
In the following we work with a subset of the 3D city model of Rotterdam Load a CityJSON The `load()` method loads a CityJSON file into a CityJSON object. | path = os.path.join('data', 'rotterdam_subset.json')
cm = cityjson.load(path)
print(type(cm)) | <class 'cjio.cityjson.CityJSON'>
| CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Using the CLI commands in the APIYou can use any of the CLI commands on a CityJSON object *However,* not all CLI commands are mapped 1-to-1 to `CityJSON` methodsAnd we haven't harmonized the CLI and the API yet. | cm.validate() | -- Validating the syntax of the file
(using the schemas 1.0.0)
-- Validating the internal consistency of the file (see docs for list)
--Vertex indices coherent
--Specific for CityGroups
--Semantic arrays coherent with geometry
--Root properties
--Empty geometries
--Duplicate vertices
--Orphan vertices
--CityGM... | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Explore the city modelPrint the basic information about the city model. Note that `print()` returns the same information as the `info` command in the CLI. | print(cm) | {
"cityjson_version": "1.0",
"epsg": 7415,
"bbox": [
90454.18900000001,
435614.88,
0.0,
91002.41900000001,
436048.217,
18.29
],
"transform/compressed": true,
"cityobjects_total": 16,
"cityobjects_present": [
"Building"
],
"materials": false,
"textures": true
}
| CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Getting objects from the modelGet CityObjects by their *type*, or a list of types. Also by their IDs. Note that `get_cityobjects()` == `cm.cityobjects` | buildings = cm.get_cityobjects(type='building')
# both Building and BuildingPart objects
buildings_parts = cm.get_cityobjects(type=['building', 'buildingpart'])
r_ids = ['{C9D4A5CF-094A-47DA-97E4-4A3BFD75D3AE}',
'{6271F75F-E8D8-4EE4-AC46-9DB02771A031}']
buildings_ids = cm.get_cityobjects(id=r_ids) | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Properties and geometry of objects | b01 = buildings_ids['{C9D4A5CF-094A-47DA-97E4-4A3BFD75D3AE}']
print(b01)
b01.attributes | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
CityObjects can have *children* and *parents* | b01.children is None and b01.parents is None | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
CityObject geometry is a list of `Geometry` objects. That is because a CityObject can have multiple geometry representations in different levels of detail, eg. a geometry in LoD1 and a second geometry in LoD2. | b01.geometry
geom = b01.geometry[0]
print("{}, lod {}".format(geom.type, geom.lod)) | MultiSurface, lod 2
| CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Geometry boundaries and Semantic SurfacesOn the contrary to a CityJSON file, the geometry boundaries are dereferenced when working with the API. This means that the vertex coordinates are included in the boundary definition, not only the vertex indices.`cjio` doesn't provide specific geometry classes (yet), eg. MultiS... | transformation_object = cm.transform
geom_transformed = geom.transform(transformation_object)
geom_transformed.boundaries[0][0] | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
But it might be easier to transform (decompress) the whole model on load. | cm_transformed = cityjson.load(path, transform=True)
print(cm_transformed) | {
"cityjson_version": "1.0",
"epsg": 7415,
"bbox": [
90454.18900000001,
435614.88,
0.0,
91002.41900000001,
436048.217,
18.29
],
"transform/compressed": false,
"cityobjects_total": 16,
"cityobjects_present": [
"Building"
],
"materials": false,
"textures": true
}
| CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Semantic Surfaces are stored in a similar fashion as in a CityJSON file, in the `surfaces` attribute of a Geometry object. | geom.surfaces | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
`surfaces` does not store geometry boundaries, just references (`surface_idx`). Use the `get_surface_boundaries()` method to obtain the boundary-parts connected to the semantic surface. | roofs = geom.get_surfaces(type='roofsurface')
roofs
roof_boundaries = []
for r in roofs.values():
roof_boundaries.append(geom.get_surface_boundaries(r))
roof_boundaries | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Assigning attributes to Semantic Surfaces1. extract the surfaces,2. make the changes on the surface,3. overwrite the CityObjects with the changes. | cm_copy = deepcopy(cm)
new_cos = {}
for co_id, co in cm.cityobjects.items():
new_geoms = []
for geom in co.geometry:
# Only LoD >= 2 models have semantic surfaces
if geom.lod >= 2.0:
# Extract the surfaces
roofsurfaces = geom.get_surfaces('roofsurface')
for i,... | {
"id": "{C9D4A5CF-094A-47DA-97E4-4A3BFD75D3AE}",
"type": "Building",
"attributes": {
"TerrainHeight": 3.03,
"bron_tex": "UltraCAM-X 10cm juni 2008",
"voll_tex": "complete",
"bron_geo": "Lidar 15-30 punten - nov. 2008",
"status": "1"
},
"children": null,
"parents": null,
"geometry_type... | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Create new Semantic SurfacesThe process is similar as previously. However, in this example we create new SemanticSurfaces that hold the values which we compute from the geometry. The input city model has a single semantic "WallSurface", without attributes, for all the walls of a building. The snippet below illustrates... | new_cos = {}
for co_id, co in cm_copy.cityobjects.items():
new_geoms = []
for geom in co.geometry:
if geom.lod >= 2.0:
max_id = max(geom.surfaces.keys())
old_ids = []
for w_i, wsrf in geom.get_surfaces('wallsurface').items():
old_ids... | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Analysing CityModels In the following I show how to compute some attributes from CityObject geometry and use these attributes as input for machine learning. For this we use the LoD2 model of Zürich.Download the Zürich data set from https://3d.bk.tudelft.nl/opendata/cityjson/1.0/Zurich_Building_L... | path = os.path.join('data', 'zurich.json')
zurich = cityjson.load(path, transform=True) | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
A simple geometry function Here is a simple geometry function that computes the area of the groundsurface (footprint) of buildings in the model. It also show how to cast surfaces, in this case the ground surface, to Shapely Polygons. | def compute_footprint_area(co):
"""Compute the area of the footprint"""
footprint_area = 0
for geom in co.geometry:
# only LoD2 (or higher) objects have semantic surfaces
if geom.lod >= 2.0:
footprints = geom.get_surfaces(type='groundsurface')
# ... | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.