branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>coryell1287/atom<file_sep>/js/menuAnimations.js (function() { 'use strict'; var menuBtn = document.getElementsByClassName('menu')[0]; var sideNav = document.getElementsByClassName('side-nav-bar')[0]; var topNav = document.getElementsByClassName('top-nav-bar')[0]; var mobBtn = document.getElementsByClassName('mobile-menu')[0]; var scrollTimer = -1; eUtl.addEvent(menuBtn, 'click', openMenu); eUtl.addEvent(window, 'scroll', closeMenu); eUtl.addEvent(mobBtn, 'click', mobileMenu); function openMenu() { menuBtn.classList.toggle('open-menu'); sideNav.classList.toggle('open-menu'); } function closeMenu() { menuBtn.classList.remove('open-menu'); sideNav.classList.remove('open-menu'); topNav.classList.add('open-menu'); if (window.scrollY === 0) { topNav.classList.remove('open-menu'); } if (scrollTimer != -1) { clearTimeout(scrollTimer); } scrollTimer = setTimeout(function() { topNav.classList.remove('open-menu'); }, 3000); } function mobileMenu() { mobBtn.classList.toggle('mobile-close'); var navbar = document.querySelector('.mobile-navbar'); navbar.classList.toggle('open-mobile-bar'); } })(); <file_sep>/js/pageAnimation.js /****************************/ /* Smoothe Scroll Animation */ /****************************/ $(document).ready(function() { $('a[href^="#"]').on('click', function(e) { eUtl.preventDefault(e); var target = this.hash; var $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top - 100 }, 900); window.location.hash = target; }); }); /****************************/ /* Image Scroll Animation */ /****************************/ eUtl.addEvent(window, 'scroll', function() { var imageScroll = window.scrollY; var fixedImage = document.querySelector('.fixed-image'); fixedImage.style.backgroundPosition = 'left' + imageScroll + 'px'; }, false); /*********************************/ /* Page Animation each section */ /*********************************/ var techList = document.querySelector('.tech-list'); eUtl.addEvent(window, 'scroll', aboutAnimation); eUtl.addEvent(window, 'scroll', skillAnimation); eUtl.addEvent(window, 'scroll', contactAnimation); function skillAnimation() { var techKnow = document.querySelector('.tech-know'); var aniTech = techKnow.offsetTop - 600; if (aniTech < window.scrollY) { techKnow.classList.add('scale'); techList.classList.add('scale'); } else { techKnow.classList.remove('scale'); techList.classList.remove('scale'); } } function aboutAnimation() { var conn = document.querySelector('.connect-contain'); var aniCon = conn.offsetTop - 580; if (aniCon < window.scrollY) { conn.classList.add('up'); } else { conn.classList.remove('up'); } } function contactAnimation() { var contact = document.getElementById('contact'); var formBlurb = document.querySelector('.get-in-touch'); var formWrapper = document.querySelector('.form-wrapper'); var contAnim = contact.offsetTop - 500; if (contAnim < window.scrollY) { formBlurb.classList.add('move-right'); formWrapper.classList.add('move-left'); } else { formBlurb.classList.remove('move-right'); formWrapper.classList.remove('move-left'); } if (screen.width == 800) { contAnim = contact.offsetTop - 1000; if (contAnim < window.scrollY) { formBlurb.classList.add('move-right'); formWrapper.classList.add('move-left'); } else { formBlurb.classList.remove('move-right'); formWrapper.classList.remove('move-left'); } } } /*********************************/ /* Show examples of Portfolio */ /*********************************/ var examples = document.getElementById('examples-wrapper'); var portBtn = document.querySelector('.portfolio-link'); var overlay = document.querySelector('.ex-overlay'); var closeOver = document.getElementById('close-overlay'); eUtl.addEvent(portBtn, 'click', showPortfolio); eUtl.addEvent(closeOver, 'click', closeExamples); function showPortfolio() { examples.classList.add('show'); overlay.classList.add('show'); } function closeExamples() { examples.classList.remove('show'); } <file_sep>/js/sendMail.js var mailapplication = mailapplication || {}; mailapplication.usermodule = (function() { var XMLHttp = function() { var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { xhr = new ActiveXObject('Msxml2.XMLHttp'); } catch (e) { xhr = new ActiveXObject('Microsoft.XMLHttp'); } } return xhr; }; return { sendMail: function() { var promise = new Promise(function(resolve, reject) { var xhr = new XMLHttp(); var form = document.getElementById('contactForm'); var method = form.method; var url = form.action; var input = document.querySelectorAll('[required]'); var params = ''; var payload = []; for (var i = 0; i < input.length; i++) { payload.push(encodeURIComponent(input[i].name) + '=' + encodeURIComponent(input[i].value)); } params = payload.join('&'); console.log(params); xhr.open(method, url, true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send(params); xhr.onreadystatechange = function() { if (xhr.status == 200 && xhr.readyState == 'OK') { var success = resolve(xhr.response); return success; } else { var good = reject(xhr.responseText); console.log(good); } }; xhr.onerror = function() { reject(xhr.responseText); } return promise; }); } }; })(); <file_sep>/js/formValidation.js (function() { document.forms[0].noValidate = true; var form = document.forms[0]; var input = document.querySelectorAll('[required]'); for (var i = 0; i < input.length; i++) { input[i].value = ''; } eUtl.addEvent(form, 'submit', function(e) { eUtl.preventDefault(e); var elements = input; var valid = {}; var isValid; var isFormValid; for (var i = 0; i < elements.length; i++) { isValid = validateInput(elements[i]); if (!isValid) { displayErrorMessage(elements[i]); } else { removeErrorMessage(elements[i]); } valid[elements[i].id] = isValid; } for (var field in valid) { if (!valid[field]) { isFormValid = false; break; } isFormValid = true; } if (isFormValid) { mailapplication.usermodule.sendMail(); } }, false); function validateInput(el) { if (requiredField(el)) { var valid = !emptyField(el); if (!valid) { setErrorMessage(el, ' is required'); } return valid; } return true; } function requiredField(el) { return ((typeof el.required === 'boolean' && el.required)) || (typeof el.required === 'string'); } function emptyField(el) { return !el.value || el.value === el.placeholder; } function setErrorMessage(el, message) { var elId = el.getAttribute('id'); el.dataset.msg = '&times; ' + elId + message; } function displayErrorMessage(el) { el.classList.add('required'); var elemId = el.id; var spanMsg = document.querySelector('span.' + elemId); spanMsg.classList.add('error'); spanMsg.innerHTML = el.dataset.msg; } function removeErrorMessage(el) { el.classList.remove('required'); var elemId = el.id; var spanMsg = document.querySelector('span.' + elemId); spanMsg.classList.remove('error'); } })(); <file_sep>/js/what.php <?php echo "You see me.";
d4b93d2a45eac7b6ba49a78ebf8b3c778c8b5835
[ "JavaScript", "PHP" ]
5
JavaScript
coryell1287/atom
935c7732b2ecd85e0cf59ed69db1e307030989ec
bd182700893ca462ecdf5185291d3a60c048287d
refs/heads/master
<repo_name>Censseo/nextdom-devenv<file_sep>/.devcontainer/entrypoint.sh #!/bin/bash echo 'Start mysql' service mysql start if [ -f /usr/share/nextdom/core/config/common.config.php ]; then echo 'Nextdom is already install' else echo 'Start Nexdom installation' rm -r /usr/share/nextdom git clone -b develop https://github.com/NextDom/nextdom-core.git /usr/share/nextdom chmod +x /usr/share/nextdom/install/postinst ./usr/share/nextdom/install/postinst echo 'Granting priviledge to mysql for remote connection' mysql --execute="GRANT ALL PRIVILEGES ON *.* TO 'nextdom'@'127.0.0.1' IDENTIFIED BY 'nextdom' WITH GRANT OPTION;" fi echo 'All init complete' echo 'Start apache2' service apache2 restart echo 'Start mysql' service mysql restart<file_sep>/README.md # nextdom-devenv <file_sep>/.devcontainer/Dockerfile # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.140.1/containers/debian/.devcontainer/base.Dockerfile # [Choice] Debian version: buster, stretch ARG VARIANT="buster" FROM mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT} ENV ROOT_PASSWORD <PASSWORD> ENV APACHE_PORT 8080 ENV SSH_PORT 8022 ENV MODE_HOST 0 ENV VERSION docker ENV BRANCH develop ENV locale-gen fr_FR.UTF-8 ENV DEBIAN_FRONTEND noninteractive ENV APT_KEY_DONT_WARN_ON_DANGEROUS_USAGE DontWarn RUN mkdir /usr/share/nextdom RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ && apt-get -y install --no-install-recommends git software-properties-common gnupg wget ca-certificates RUN add-apt-repository non-free RUN wget -qO - http://debian.nextdom.org/debian/nextdom.gpg.key | apt-key add - RUN echo "deb http://debian.nextdom.org/debian nextdom main" >/etc/apt/sources.list.d/nextdom.list RUN apt update RUN apt -y install nextdom-mysql nextdom-common RUN apt-get install php-xdebug --yes \ && echo "xdebug.remote_enable=on" >> /etc/php/7.3/mods-available/xdebug.ini \ && echo "xdebug.remote_autostart=on" >> /etc/php/7.3/mods-available/xdebug.ini \ && echo "xdebug.remote_port=9900" >> /etc/php/7.3/mods-available/xdebug.ini COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"]
c4ce2cea7c95764ee08f55b19c231397fa63a874
[ "Markdown", "Dockerfile", "Shell" ]
3
Shell
Censseo/nextdom-devenv
89a74a76761ed0ee93454de2ace227bfa4aeb41a
70185cc08fc3649bdaebf9483db803c244e78e42
refs/heads/master
<repo_name>chris-stellato/capstone1<file_sep>/src/data_wrangling.py from pyspark.sql.functions import * import pyspark as ps import pandas as pd import re import matplotlib.pyplot as plt import seaborn as sn from scipy import stats import numpy as np import os import json import glob spark = ps.sql.SparkSession.builder \ .master("local[4]") \ .appName("df capstone") \ .getOrCreate() path_to_json = "./data/" json_pattern = os.path.join(path_to_json,'*.json') file_list = glob.glob(json_pattern) first_frame = spark.read.json(file_list[0], multiLine=True) playlist = first_frame.head()[1] single_playlist = playlist[0] column_names = single_playlist.__fields__ list_of_frames = [] ##modify for desired # of json files to read in for file in file_list[:20]: current_df = spark.read.json(file, multiLine=True) current_playlist = current_df.head()[1] current_pframe = pd.DataFrame(current_playlist, columns=column_names) list_of_frames.append(current_pframe) df = pd.concat(list_of_frames) def make_new_feature(df, numerator, denominator, new_feat_name): df[new_feat_name] = df[numerator] / df[denominator] return df.head() def save_to_csv(file_path) df.to_csv(file_path) pass <file_sep>/README.md # <NAME> - Capstone 1 project #### Spotify Million Playlist Dataset ### Presentation The final project presentation includes visual aids, results of hypothesis testing, and a summary of insights and takeaways. View the final project presentation: https://github.com/chris-stellato/capstone_1/blob/master/capstone_1_presentation.pdf # # #### Original Proposal: Spotify Million Playlist Dataset https://www.aicrowd.com/challenges/spotify-million-playlist-dataset-challenge ##### Dataset This dataset contains records of 1M spotify playlists, allowing Data Scientists to draw connections between songs within playlists and make helpful recommendations to users. Some interesting fields include: * playlist identifier * playlist tracklist and track ids * timestamp last edit * count of number of edits to the playlist * playlist length #### Possible Visualizations * distribution of playlist length (maybe asking what is the "perfect length mixtape"?) * histogram of genres most added to playlists * scatterplot mapping genre spread in playlists (asking how diverse is each playlist?) #### Possible Hypotheses to test: * "95% of playlists have between X and Y tracks in them" * "Playlists usually stick to one genre and rarely deviate" ## Daily project updates: #### Monday update: - Dowloaded data - launched spark docker instance, created jupyter notebook - read in json file and explored data - worked to move nested data into workable dataframes - still in data wrangling mode. #### Tuesday update: - continued EDA - cleaned dataframes & added diversity_ratio column - started seeing if columns of interest were normally distributed - started thinking about possible hypothesis and how to test them - mucked around with unsuccessful distributions, sampling, graphs that didn't bear fruit #### Wednesday update: - combined multiple JSON files into a single dataframe with 20k playlist records - checked again that diversity_ratio and num_followers are NOT normally distributed - set up bootstrapping to generate list of sample sets and the means of each sample set - plotted those bootstrapped distributions to find normal distributions - defined confidence intervals and ran hypothesis test, rejected null hypothesis - discussed maybe bootstrap isn't the best approach, should look at beta distributions and bayes #### Thursday update: - adjusted bootstrappping method - clarified hypothesis test - cleaned up visuals - began creating presentation ### Friday update: - finishing presentation - review with instructors and make adjustments - add py files with helper functions to repo - add presentation to repo - clean up repo and prepare for presentation <file_sep>/src/eda_and_hypothesis_testing.py import pandas as pd import matplotlib.pyplot as plt import seaborn as sn from scipy import stats import numpy as np import statsmodels.api as sm import pylab import statsmodels.stats.weightstats as ws #read in csv and return pandas dataframe def csv_to_pdframe(file_path): return pd.read_csv(file_path) #test chosen pandas series for normal distribution #saves two figures (box plot and histogram) to PWD and returns Shapiro Wilk test result def test_for_normal(pandas_dframe, feature_name): #box plot fig, ax = plt.subplots(figsize=(5,3)) pandas_dframe.feature_name.plot(kind='box') ax.set_title('diversity ratio', fontsize=14) fig.savefig('box_plot.png', dpi=300) #histogram fig, ax = plt.subplots(figsize=(5,3)) pandas_dframe.feature_name.hist() ax.set_xlabel('diversity ratio', fontsize=14) fig.savefig('histogram.png', dpi=300) #Shapiro Wilk test return stats.shapiro(pandas_dframe.feature_name.sample(500)) #save a heatmap figure and return a correlation dataframe def correlation_eda(pandas_dframe): #saving heatmap fig, ax = plt.subplots(figsize=(10,6)) sn.set(font_scale=1) sn.heatmap(pandas_dframe.corr(), annot=True) fig.savefig('heatmap.png', dpi=300) #returning correlation matrix return pandas_dframe.corr() #dividing chosen feature into two dataframes, storing them in two variables and printing out some key stats #feature_value is the value point at which the feature data will be divided. def divide_data(df, groupby_feature, measure_feature, grouping_value): less_than = df[df['groupby_feature'] < grouping_value] greater_equal = df[df['groupby_feature'] >= grouping_value] print (f'{groupby_feature} less than {grouping_value}, {measure_feature}: \n mean {less_than.measure_feature.mean()} \n std {less_than.measure_feature.std()} \n \n') print (f'{groupby_feature} greater or equal to {grouping_value}, {measure_feature}: \n mean {greater_equal.measure_feature.mean()} \n std {greater_equal.measure_feature.std()} \n \n') pass #bootstrapping helper functions def bootstrap(data, num_samps=1000): return [data.sample(len(data), replace=True) for i in range(num_samps)] def bootstrap_ci(boot_samp_list, ci=95): boot_strap_means = [] for samp in boot_samp_list: boot_strap_means.append(np.mean(samp)) left_endpoint = np.percentile(boot_strap_means, (100-ci)/2) right_endpoint = np.percentile(boot_strap_means, 100-((100-ci)/2)) return left_endpoint, right_endpoint def bootstrap_list_of_means(df, measure_feature): df_sample_list = np.array(bootstrap(df.measure_feature, 1000)) return df_sample_list.mean(axis=1) #returns the left and right endpoints for confidence interval for a bootstrapped sample set def confidence_interval(df, measure_feature) print ('left, right \n') return bootstrap_ci(bootstrap(df.measure_feature))
109488ab622bc00805417a49a57c71bdd5906ae5
[ "Markdown", "Python" ]
3
Python
chris-stellato/capstone1
613bab0df290aff4e88292df3e69bf7afe1a8756
557f81567060ad5913a8881c57f7a0b3806013a1
refs/heads/master
<file_sep>var avow = require('avow'); var output; function FizzBuzz(n) { // output is empty string output = ''; // Loops 'n' times for (var i = 1; i <= n; i++) { if (i % 5 !== 0 && i % 3 !== 0) { // i is divisible by neither 3 nor 5 output += '.'; } else if (i % 3 === 0 && i % 5 !== 0) { // i is divisible by 3 but not 5 output += 'Fizz'; } else if (i % 3 !== 0 && i % 5 === 0) { // i is divisible by 5 but not 3 output += 'Buzz'; } else if (i % 3 === 0 && i % 5 === 0) { // i is divisible by both 3 and 5 output += 'FizzBuzz'; } } // Checks to see if input is a string if (typeof n === "string") { output = 'You must enter a number'; } return output; } avow('FizzBuzz 1 should be .', '.' === FizzBuzz(1), '.', FizzBuzz(1)); avow('FizzBuzz 2 should be ..', '..' === FizzBuzz(2), '..', FizzBuzz(2)); avow('FizzBuzz 3 should be ..Fizz', '..Fizz' === FizzBuzz(3), '..Fizz', FizzBuzz(3)); avow('FizzBuzz 5 should be ..Fizz.Buzz', '..Fizz.Buzz' === FizzBuzz(5), '..Fizz.Buzz', FizzBuzz(5)); avow('FizzBuzz 10 should be ..Fizz.BuzzFizz..FizzBuzz', '..Fizz.BuzzFizz..FizzBuzz' === FizzBuzz(10), '..Fizz.BuzzFizz..FizzBuzz', FizzBuzz(10)); avow('FizzBuzz 15 should be ..Fizz.BuzzFizz..FizzBuzz.Fizz..FizzBuzz', '..Fizz.BuzzFizz..FizzBuzz.Fizz..FizzBuzz' === FizzBuzz(15), '..Fizz.BuzzFizz..FizzBuzz.Fizz..FizzBuzz', FizzBuzz(15));
8df1181f2b03e26cfcfc61db7e31df13bf114def
[ "JavaScript" ]
1
JavaScript
doctorj89/w3d2-fizzbuzz
ec9dda1c82e41c97f4afd7c0050396a48f268ef6
98c7e3e75c043367679900a303295f3885a210e0
refs/heads/master
<repo_name>CADSalud/indiceENSANUT<file_sep>/src/01_carga.R setwd("~/Documents/cad/ensanut2012/salud/") library(foreign) adultos <- read.spss('Adultos.sav') etiquetas <- attributes(adultos)$variable.labels adultos.df <- as.data.frame(adultos) names(adultos.df)
0cb4d63419d6e4696490e3bd63ad5329b883c5df
[ "R" ]
1
R
CADSalud/indiceENSANUT
31c4fb82c6fe5aad429486b49cbbcdf24b8d0a43
02286aebe5a28f2893f4f26b1122e43d219b5fa3
refs/heads/main
<file_sep>package main import ( "fmt" "github.com/DABronskikh/bgo-3_08.1/pkg/transactions" "io" "log" "os" ) func main() { const filenameCSV = "demoFile.csv" const filenameJSON = "demoFile.json" svc := transactions.NewService() for i := 0; i < 20; i++ { _, err := svc.Register("001", "002", 1000_00) if err != nil { log.Print(err) return } } // CSV if err := demoExportCSV(svc, filenameCSV); err != nil { log.Fatal(err) } demoImportCSV := transactions.NewService() if err := demoImportCSV.ImportCSV(filenameCSV); err != nil { log.Fatal(err) } fmt.Println("demoImportCSV = ", demoImportCSV) //JSON if err := svc.ExportJSON(filenameJSON); err != nil { log.Fatal(err) } demoImportJSON := transactions.NewService() if err := demoImportJSON.ImportJSON(filenameJSON); err != nil { log.Fatal(err) } fmt.Println("demoImportJSON = ", demoImportJSON) } func demoExportCSV(svc *transactions.Service, filename string) (err error) { file, err := os.Create(filename) if err != nil { log.Print(err) return } defer func(c io.Closer) { if err := c.Close(); err != nil { log.Print(err) } }(file) err = svc.ExportCSV(file) if err != nil { log.Print(err) return } return nil } <file_sep>module github.com/DABronskikh/bgo-3_08.1 go 1.14
99ba0ee65afab7ea6a329c8bdc7f7082843405c2
[ "Go Module", "Go" ]
2
Go
DABronskikh/bgo-3_08.1
434aaa3d89b6783a1e30720606ad72812b9a79ea
a40e2d6a961d8f51ac561783aca219449f1a5904
refs/heads/main
<file_sep><?php namespace ZT\BlogThemePuremedia\Setup\Patch\Data; use Magento\Framework\Setup\Patch\DataPatchInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; class AddPuremediaThemeSetting implements DataPatchInterface { const THEME_NAME = 'Puremedia Theme'; /** * @var ModuleDataSetupInterface */ private $moduleDataSetup; public function __construct( ModuleDataSetupInterface $moduleDataSetup ) { $this->moduleDataSetup = $moduleDataSetup; } public function apply() { $data = [ 'name' => self::THEME_NAME, 'identifier' => 'puremedia' ] ; $this->moduleDataSetup->getConnection()->insertForce( $this->moduleDataSetup->getTable( 'ztpwa_blog_theme_settings' ), $data ); } public function getAliases() { return []; } public static function getDependencies() { return []; } /** * {@inheritdoc} */ public static function getVersion() { return '1.0.0'; } } <file_sep><?php namespace ZT\BlogThemePuremedia\Controller\Adminhtml\Setting; use ZT\BlogTheme\Controller\Adminhtml\Setting\Edit as ThemeEdit; /** * Edit PWA Blog Theme action. */ class Edit extends ThemeEdit { } <file_sep># magento2-blog-theme-puremedia
9b6c9393b9ffa910967c28b5b8d012e2d8e937f8
[ "Markdown", "PHP" ]
3
PHP
zorto-pwa-group/magento2-blog-theme-puremedia
98e8dc41c87f7818f881ff43bf57ef5c055b002c
e325c266edb151326793fee912730e06366f9892
refs/heads/master
<file_sep><?php abstract class BaseComponent { protected function redirect(Request $request, $component){ $response = new Response(); if(isset($component) && method_exists($component, $request->getAction())){ $action = $request->getAction(); $response = $component->$action($request); if(method_exists($component, 'commit')){ $component->commit(); } } else{ $response->setResponseContent('INVALID_REQUEST'); } return $response; } protected function getComponent($name, $type){ $class_name = $name . $type; $type = strtolower($type); require_once __DIR__ . "/../../$type/$class_name.php"; return new $class_name($name); } }<file_sep><?php require_once __DIR__ . "/../modules/base/BaseModel.php"; class ProdutoModel extends BaseModel { public function insert(Request $request){ $statement = " insert into item (nome, preco, quantidade, idcategoria) values (:nome, :preco, :quantidade, :idcategoria) "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function delete(Request $request){ $statement = " delete from item where iditem = :iditem "; $response = $this->databaseHandler->executeQuery($statement, $request->getData()); if(!$response->isSuccess()){ return $response; } return $this->list($request); } public function list(Request $request){ $statement = " select iditem, nome, quantidade, preco from item "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function view(Request $request){ $statement = " select iditem, nome, quantidade, preco, idcategoria from item where iditem = :iditem "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function edit(Request $request){ $response = $this->view($request); if(!$response->isSuccess()){ return $response; } $quantidade = $response->getData('quantidade'); $modificador = $request->getData('modificador'); if($quantidade + $modificador < 0){ $response->setResponseContent('INVALID_REQUEST_DATA', ['modificador']); return $response; } $statement = " update item set nome = :nome, preco = :preco, quantidade = quantidade + :modificador, idcategoria = :idcategoria where iditem = :iditem; "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } }<file_sep><!-- Header section --> <header class="header-section"> <div class="header-background"> <div class="header-top"> <div class="container"> <div class="row"> <div class="col-lg-2"> <a href="/public/main.php" class="site-logo"> <img src="/public/assets/img/keyarlogo.png" class="site-logo" alt="logo"> </a> </div> <div class="col-xl-6 col-lg-5"> </div> <div class="col-xl-4 col-lg-5"> <div class="user-panel painel-usuario"> <div class="up-item"> <div class="dropdown"> <i class="flaticon-profile"></i> <a class="dropdown-toggle" id="menu-perfil" href="#" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Perfil</a> <div class="dropdown-menu" aria-labelledby="menu-perfil"> <?php // se for cliente if($_SESSION["idperfil"] == 1){ echo '<a class="dropdown-item" href="/public/cliente/gerenciar_perfil.php">Gerenciar Perfil</a><br>'; echo '<a class="dropdown-item" href="/public/pedido/gerenciar_pedidos.php">Gerenciar Pedidos</a><br>'; } // se for balconista if($_SESSION["idperfil"] == 2){ echo '<a class="dropdown-item" href="/public/pedido/confirmar_retirada.php">Confirmar Retirada de Pedido<br></a>'; echo '<a class="dropdown-item" href="/public/produto/gerenciar_itens.php">Gerenciar Produtos</a><br>'; } ?> <a class="dropdown-item" href="/public/index.php?name=usuario&action=logout">Sair</a> </div> </div> </div> <?php // se for cliente if($_SESSION["idperfil"] == 1){ echo '<div class="up-item"> <div class="shopping-card"> <i class="flaticon-bag"></i> </div> <a href="/public/pedido/visualizar_pedido.php?name=pedido&action=list_cart">Meu Pedido</a>'; } ?> </div> </div> </div> </div> </div> </div> </header><file_sep><?php require_once __DIR__ . "/../backend/Api.php"; $request = new Request('sync', true); $response = $api->process($request); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="description" content=" Divisima | eCommerce Template"> <meta name="keywords" content="divisima, eCommerce, creative, html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Stylesheets --> <?php require_once __DIR__ . "/assets/layout/main_css.php"; ?> </head> <body> <!-- Header --> <header class="header-section"> <?php require_once __DIR__ . "/assets/layout/header.php"; ?> </header> <div class="square" style="width: 30%"> <img src="/public/assets/img/mobile.png" class="imgresp" height="170" width="500" alt=""> <div class="sq-content">Controle os seus gastos.</div> </div> <div class="square" style="width: 30%"> <img src="/public/assets/img/stoque.png" class="imgresp" height="170" width="500" alt=""> <div class="sq-content">Compre o quanto quiser.</div> </div> <div class="square" style="width: 30%"> <img src="/public/assets/img/relatorio.jpg" class="imgresp" height="170" width="500" alt=""> <div class="sq-content center">Gerencie na ponta do lápis.</div> </div> <hr> <div class="square" style="width: 30%"> <img src="/public/assets/img/app.jpg" class="imgresp" height="170" width="500" alt=""> <div class="sq-content">App amigável e descomplicado.</div> </div> <div class="square" style="width: 30%"> <img src="/public/assets/img/card.jpg" class="imgresp" height="170" width="500" alt=""> <div class="sq-content">Pague e receba com segurança.</div> </div> <div class="square" style="width: 30%"> <img src="/public/assets/img/venda.jpg" class="imgresp" height="170" width="500" alt=""> <div class="sq-content">faça um bom negócio!</div> </div> <hr> <!-- Arquivos JS --> <?php require_once __DIR__ . "/assets/layout/main_scripts.php"; ?> <script src="/public/assets/vendor/datatables/datatables.minMain.js"></script> </body> </html><file_sep><?php trait RequestDataValidation { protected function isValidAdditional($field, $rules){ return $this->isValidRequired($field, $rules) && $this->isValidMin($field, $rules) && $this->isValidMax($field, $rules); } private function isValidRequired($field, $rules){ $isRequired = isset($rules['required']); $isEmpty = preg_match('/^$/', $this->data[$field]); return !$isRequired || $isRequired && !$isEmpty; } private function isValidMin($field, $rules){ $hasMin = isset($rules["min"]); if($hasMin){ $validMin = null; $type = gettype($this->data[$field]); if($type == 'string'){ $validMin = strlen($this->data[$field]) >= intval($rules["min"]); } else { $validMin = $this->data[$field] >= intval($rules["min"]); } } return !$hasMin || $hasMin && $validMin; } private function isValidMax($field, $rules){ $hasMax = isset($rules["max"]); if($hasMax) { $validMax = null; $type = gettype($this->data[$field]); if ($type == 'string') { $validMax = strlen($this->data[$field]) <= intval($rules["max"]); } else { $validMax = $this->data[$field] <= intval($rules["max"]); } } return !$hasMax || $hasMax && $validMax; } }<file_sep><?php trait ResponseFormat { public function toJson() { return json_encode($this->toArray(), JSON_FORCE_OBJECT); } public function __toString() { return json_encode($this->toArray(), JSON_FORCE_OBJECT); } public function toArray() { return [ "code" => $this->code, "message" => $this->message, "invalid_fields" => $this->invalidFields, "data" => $this->data ]; } }<file_sep><?php class ResponseErrors { private $errorsList = [ "SUCCESS" => [0, "Action executed successful."], "INVALID_REQUEST" => [1, "Required request parameters 'Table', 'Action' or 'Data' is invalid or missing."], "INVALID_REQUEST_DATA" => [2, "Required 'Data' request parameters is invalid or missing."], "SERVER_READY" => [3, "Server ready to receive requests."], "INVALID_LOGIN" => [4, "Invalid login. Please verify and try again."], "INVALID_PASSWORD" => [5, "Invalid password. Please verify and try again."], "NOT_AUTHENTICATED" => [6, "Not authenticated. Please authenticate using your login and password."], ]; public function getResponseError($name){ if(isset($name) && array_key_exists($name, $this->errorsList)){ return [ 'code' => $this->errorsList[$name][0], 'message' => $this->errorsList[$name][1], ]; } elseif(!isset($name) && $name == ''){ return [ 'code' => null, 'message' => null, ]; } else{ return [ 'code' => $this->errorsList['SUCCESS'][0], 'message' => $this->errorsList['SUCCESS'][1], ]; } } }<file_sep><?php $_GET = [ "name" => "pedido", "action" => "list_itens_pedido", ]; $_POST = [ "idpedido" => 1, ]; require_once __DIR__ . "/../backend/Api.php"; $request = new Request('sync'); $response = $api->process($request);<file_sep><?php $_GET = [ "name" => "produto", "action" => "edit", ]; $_POST = [ "iditem" => 1, "nome" => "Coxinha", "preco" => "4.00", "modificador" => "20", "idcategoria" => "1", ]; require_once __DIR__ . "/../backend/Api.php"; $request = new Request('sync'); $response = $api->process($request);<file_sep><?php require_once "traits/ResponseValidation.php"; require_once "traits/ResponseFormat.php"; require_once "traits/ResponseInitialization.php"; require_once "traits/ResponseTypesValidation.php"; require_once "traits/ResponseErrors.php"; class Response extends RuntimeException { use ResponseInitialization; use ResponseTypesValidation; use ResponseValidation; use ResponseFormat; protected $code; protected $message; private $data; private $invalidFields; public function __construct() { parent::__construct("", 0); $this->data = []; $this->invalidFields = []; } public function getInvalidFields() { return $this->invalidFields; } public function getData($field = '', $toArray = false) { if(isset($field)){ $index = array_key_first($this->data); if(isset($this->data[$index][$field])){ return $this->data[$index][$field]; } elseif(isset($this->data[$field])){ return $this->data[$field]; } else{ return ''; } } elseif($this->isUniqueElementArray() && !$toArray) { return $this->data[0]; } else{ return $this->data; } } }<file_sep><?php require_once __DIR__ . "/../../backend/Api.php"; $request = new Request('sync', true, 1); $response = $api->process($request); $_GET = [ "name" => "pedido", "action" => "list"]; $request2 = new Request('sync', true, 1); $response2 = $api->process($request2); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="description" content=" Divisima | eCommerce Template"> <meta name="keywords" content="divisima, eCommerce, creative, html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Stylesheets --> <?php require_once __DIR__ . "/../assets/layout/main_css.php"; ?> </head> <body> <!-- Page Preloder --> <div id="preloder"> <div class="loader"></div> </div> <!-- Header --> <header class="header-section"> <?php require_once __DIR__ . "/../assets/layout/header.php"; ?> </header> <!-- checkout section --> <section class="checkout-section"> <div class="container"> <div class="spad"> <div class="cart-table"> <h4>Gerenciamento De Pedidos</h4> <div class="cart-table-warp"> <table id="lista_produtos" class="display"> <thead> <tr> <th>NUMERO DO PEDIDO</th> <th>VALOR TOTAL</th> <th>STATUS</th> </tr> </thead> <tbody> <?php // Listando foreach ($response2->getData(null, true) as $registry){ echo '<form method="post">'; echo '<tr>'; echo "<td>" . $registry['idpedido'] . "</td>"; echo "<td> R$ " . number_format($registry['valor_total'], 2) . "</td>"; echo "<td>" . $registry['status_pedido'] . "</td>"; echo '</tr>'; echo '</form>'; } ?> </tbody> </table> <a href="/public/pedido/gerenciar_itens_pedido.php?name=produto&action=list" class="site-btn">NOVO PEDIDO</a> <a href="/public/main.php" class="site-btn sb-dark">VOLTAR</a> </div> </div> </div> </div> </section> <!-- Scripts --> <?php require_once __DIR__ . "/../assets/layout/main_scripts.php"; ?> <script src="/public/assets/js/scripts.js"></script> <script src="/public/assets/vendor/datatables/datatables.minPagamento.js"> </script> </body> </html><file_sep><?php $_GET = [ "name" => "usuario", "action" => "edit", ]; $_POST = [ "senha" => "", "telefone" => "1111", "email" => "1111", "cep" => "1111", "logradouro" => "1111", "numero" => "1111", "complemento" => "1111", ]; require_once __DIR__ . "/../backend/Api.php"; $request = new Request('sync'); $response = $api->process($request);<file_sep><?php require_once __DIR__ . "/../../backend/Api.php"; $request = new Request('sync', true, 2); $response = $api->process($request); $_GET = [ "name" => "produto", "action" => "list"]; $request2 = new Request('sync', true, 2); $response2 = $api->process($request2); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="description" content=" Divisima | eCommerce Template"> <meta name="keywords" content="divisima, eCommerce, creative, html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Stylesheets --> <?php require_once __DIR__ . "/../assets/layout/main_css.php"; ?> </head> <body> <!-- Header --> <header class="header-section"> <?php require_once __DIR__ . "/../assets/layout/header.php"; ?> </header> <!-- Conteúdo da Página --> <section class="product-filter-section"> <div class="container"> <div class="spad"> <div class="cart-table"> <form> <table id="lista_produtos" class="display"> <thead> <tr> <th>PRODUTO</th> <th>QUANTIDADE<br>ESTOQUE</th> <th>PREÇO</th> <th>EDITAR</th> <th>EXCLUIR</th> </tr> </thead> <tbody> <?php // Listando foreach ($response2->getData(null, true) as $registry){ echo '<form method="post">'; echo '<tr>'; echo "<td>" . $registry['nome'] . "</td>"; echo "<td>" . $registry['quantidade'] . "</td>"; echo "<td> R$ " . number_format($registry['preco'], 2) . "</td>"; echo '<td class="total-col">'; echo "<button type='submit' formmethod='post' formaction='editar_item.php'>"; echo '<img width="24px" src="/public/assets/vendor/css-datatables/images/editar.png">'; echo "</button> "; echo '</td>'; echo '<td class="total-col">'; echo "<button type='submit' formmethod='post' formaction='?name=produto&action=delete'>"; echo '<img width="24px" src="/public/assets/vendor/css-datatables/images/delete1.png">'; echo "</button>"; echo '<td>'; echo "<input type='hidden' name='iditem' value='{$registry['iditem']}'>"; echo '</td>'; echo '</form>'; } ?> </tbody> </table> <br> <a href="/public/produto/cadastro_item.php" class="site-btn submit-order-btn">NOVO PRODUTO</a> <a href="/public/main.php" class="site-btn sb-dark">VOLTAR</a> </form> </div> </div> </div> </section> <!-- Arquivos JS --> <?php require_once __DIR__ . "/../assets/layout/main_scripts.php"; ?> <script src="/public/assets/js/scripts.js"></script> <script src="/public/assets/vendor/datatables/datatables.minMain.js"> </script> </body> </html><file_sep><?php require_once __DIR__ . "/../modules/base/BaseController.php"; class UsuarioController extends BaseController { public function login(Request $request){ $fieldRules = [ "login" => ["required", "max:45", "type:text"], "senha" => ["required", "max:255", "type:text"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $response = $this->redirect($request, $this->model); $response = $this->auth->login($request, $response, 'senha'); if($response->isSuccess()){ header('Location: /public/main.php'); exit; } } return $response; } public function verify_auth(Request $request){ $response = new Response(); if(!$request->isValidAuth() || !$request->isValidProfile()){ header('Location: /public/index.php'); exit; } else { $response->setResponseContent('SUCCESS'); } return $response; } public function logout(Request $request){ $response = $this->auth->logout(); if($response->isSuccess()){ header('Location: /public/index.php'); exit; } } public function insert(Request $request){ $fieldRules = [ "login" => ["required", "max:45", "type:text"], "senha" => ["required", "max:255", "type:text"], "nome" => ["required", "max:45", "type:text"], "sobrenome" => ["required", "max:45", "type:text"], "cpf" => ["required", "type:integer"], "telefone" => ["required", "max:90", "type:text"], "email" => ["required", "max:90", "type:text"], "cep" => ["required", "max:45", "type:text"], "logradouro" => ["required", "max:45", "type:text"], "numero" => ["required", "type:integer"], "complemento" => ["required", "max:45", "type:text"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $senha = $request->toHash('data', 'senha'); $request->setData('senha', $senha); $response = $this->redirect($request, $this->model); } else{ $response->setResponseContent(null, null, $request->getData()); } return $response; } public function delete(Request $request){ $request->setData('idcliente', $_SESSION['idcliente']); $response = $this->redirect($request, $this->model); if($response->isSuccess()){ $this->logout($request); header('Location: /public/index.php'); exit; } return $response; } public function view(Request $request){ $request->setData('idcliente', $_SESSION['idcliente']); $response = $this->redirect($request, $this->model); return $response; } public function edit(Request $request){ $fieldRules = [ "senha" => ["max:255", "type:text"], "telefone" => ["required", "max:90", "type:text"], "email" => ["required", "max:90", "type:text"], "cep" => ["required", "max:45", "type:text"], "logradouro" => ["required", "max:45", "type:text"], "numero" => ["required", "type:integer"], "complemento" => ["required", "max:45", "type:text"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ if(!empty($request->getData('senha'))){ $senha = $request->toHash('data', 'senha'); $request->setData('senha', $senha); } $request->setData('idcliente', $_SESSION['idcliente']); $request->setData('idusuario', $_SESSION['idusuario']); $response = $this->redirect($request, $this->model); } else{ $response->setResponseContent(null, null, $request->getData()); } return $response; } }<file_sep>-- MySQL Script generated by MySQL Workbench -- Wed Jun 3 23:14:13 2020 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema SistemaControlePedidos -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema SistemaControlePedidos -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `SistemaControlePedidos` DEFAULT CHARACTER SET utf8 ; USE `SistemaControlePedidos` ; -- ----------------------------------------------------- -- Table `SistemaControlePedidos`.`Perfil` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `SistemaControlePedidos`.`Perfil` ( `idPerfil` INT NOT NULL AUTO_INCREMENT, `nome` VARCHAR(45) NOT NULL, PRIMARY KEY (`idPerfil`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `SistemaControlePedidos`.`Usuario` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `SistemaControlePedidos`.`Usuario` ( `idUsuario` INT NOT NULL AUTO_INCREMENT, `login` VARCHAR(45) NOT NULL, `senha` VARCHAR(255) NOT NULL, `idPerfil` INT NOT NULL, PRIMARY KEY (`idUsuario`), INDEX `fk_PerfilCliente_Perfil1_idx` (`idPerfil` ASC) , UNIQUE INDEX `login_UNIQUE` (`login` ASC) , UNIQUE INDEX `idUsuario_UNIQUE` (`idUsuario` ASC) , CONSTRAINT `fk_PerfilCliente_Perfil1` FOREIGN KEY (`idPerfil`) REFERENCES `SistemaControlePedidos`.`Perfil` (`idPerfil`) ON DELETE CASCADE ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `SistemaControlePedidos`.`Cliente` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `SistemaControlePedidos`.`Cliente` ( `idCliente` INT NOT NULL AUTO_INCREMENT, `cpf` BIGINT UNSIGNED NOT NULL UNIQUE, `nome` VARCHAR(45) NOT NULL, `sobrenome` VARCHAR(45) NOT NULL, `email` VARCHAR(90) NOT NULL, `telefone` VARCHAR(90) NOT NULL, `cep` VARCHAR(45) NOT NULL, `logradouro` VARCHAR(45) NOT NULL, `numero` INT NOT NULL, `complemento` VARCHAR(45) NOT NULL, `idUsuario` INT NOT NULL, PRIMARY KEY (`idCliente`), UNIQUE INDEX `idCliente_UNIQUE` (`idCliente` ASC) , INDEX `fk_Cliente_Usuario1_idx` (`idUsuario` ASC) , CONSTRAINT `fk_Cliente_Usuario1` FOREIGN KEY (`idUsuario`) REFERENCES `SistemaControlePedidos`.`Usuario` (`idUsuario`) ON DELETE CASCADE ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `SistemaControlePedidos`.`StatusPedido` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `SistemaControlePedidos`.`StatusPedido` ( `idStatusPedido` INT NOT NULL AUTO_INCREMENT, `nome` VARCHAR(90) NULL, PRIMARY KEY (`idStatusPedido`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `SistemaControlePedidos`.`Pedido` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `SistemaControlePedidos`.`Pedido` ( `idPedido` INT NOT NULL AUTO_INCREMENT, `idStatusPedido` INT NOT NULL, `idFormaPagamento` INT NOT NULL, `idCliente` INT NOT NULL, PRIMARY KEY (`idPedido`), INDEX `fk_Pedido_statusPedido1_idx` (`idStatusPedido` ASC) , INDEX `fk_Pedido_Cliente1_idx` (`idCliente` ASC) , CONSTRAINT `fk_Pedido_statusPedido1` FOREIGN KEY (`idStatusPedido`) REFERENCES `SistemaControlePedidos`.`StatusPedido` (`idStatusPedido`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_Pedido_Cliente1` FOREIGN KEY (`idCliente`) REFERENCES `SistemaControlePedidos`.`Cliente` (`idCliente`) ON DELETE CASCADE ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `SistemaControlePedidos`.`Categoria` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `SistemaControlePedidos`.`Categoria` ( `idCategoria` INT NOT NULL AUTO_INCREMENT, `nome` VARCHAR(90) NULL, PRIMARY KEY (`idCategoria`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `SistemaControlePedidos`.`Item` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `SistemaControlePedidos`.`Item` ( `idItem` INT NOT NULL AUTO_INCREMENT, `nome` VARCHAR(45) NULL, `preco` DECIMAL(10, 2) NULL, `quantidade` INT NULL, `idCategoria` INT NOT NULL, PRIMARY KEY (`idItem`), INDEX `fk_ItemPedido_Categoria1_idx` (`idCategoria` ASC) , CONSTRAINT `fk_ItemPedido_Categoria1` FOREIGN KEY (`idCategoria`) REFERENCES `SistemaControlePedidos`.`Categoria` (`idCategoria`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `SistemaControlePedidos`.`ItemPedido` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `SistemaControlePedidos`.`ItemPedido` ( `idItemPedido` INT NOT NULL AUTO_INCREMENT, `idPedido` INT NOT NULL, `idItem` INT NOT NULL, `quantidade` INT NOT NULL, INDEX `fk_Pedido_has_ItemPedido_ItemPedido1_idx` (`idItem` ASC) , INDEX `fk_Pedido_has_ItemPedido_Pedido1_idx` (`idPedido` ASC) , PRIMARY KEY (`idItemPedido`), CONSTRAINT `fk_Pedido_has_ItemPedido_Pedido1` FOREIGN KEY (`idPedido`) REFERENCES `SistemaControlePedidos`.`Pedido` (`idPedido`) ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT `fk_Pedido_has_ItemPedido_ItemPedido1` FOREIGN KEY (`idItem`) REFERENCES `SistemaControlePedidos`.`Item` (`idItem`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; <file_sep><?php trait ResponseTypesValidation { protected function isDatabaseException($exception){ return preg_match('/SQLSTATE\[/', $exception->getMessage()); } protected function isExecutionDatabaseException($exception){ return isset($exception->errorInfo[2]); } }<file_sep><?php trait ResponseInitialization { public function setException($exception){ if($this->isDatabaseException($exception)) { $this->setDatabaseExceptionContent($exception); } elseif($this->isExecutionDatabaseException($exception)){ $this->setExecutionDatabaseExceptionContent($exception); } else{ $this->setExceptionContent($exception); } } private function setDatabaseExceptionContent($exception){ preg_match('/SQLSTATE\[(\w+)]:{0,1} (?:\[(\w+)] ){0,1}(.*)/', $exception->getMessage(), $matches); $this->code = $matches[1] == 'HT000' ? $matches[2] : $matches[1]; $this->message = $matches[3]; } private function setExecutionDatabaseExceptionContent($exception){ $this->message = $exception->errorInfo[2]; $this->code = $exception->getCode(); } private function setExceptionContent($exception){ $this->message = $exception->getMessage(); $this->code = $exception->getCode(); } public function setResponseContent($name = '', $invalidFields = [], $data = []){ $responseErrors = new ResponseErrors(); $content = $responseErrors->getResponseError($name); $this->code = isset($content['code']) ? $content['code'] : $this->code; $this->message = isset($content['message']) ? $content['message'] : $this->message; $this->invalidFields = isset($invalidFields) ? $invalidFields : $this->invalidFields; $this->data = isset($data) ? $data : $this->data; } }<file_sep><?php require_once __DIR__ . "/../modules/api/request/Request.php"; require_once __DIR__ . "/../modules/api/response/Response.php"; require_once __DIR__ . "/../modules/base/BaseComponent.php"; class Api extends BaseComponent { private $controller; public function __construct() { if(session_status() === PHP_SESSION_NONE){ session_start(); } } public function process(Request $request){ $response = new Response(); try{ if($request->emptyRequest()){ $response->setResponseContent('NOT_AUTHENTICATED'); } elseif($request->validRequest()){ $this->controller = $this->getComponent($request->toPascalCase('name'), "Controller"); $response = $this->redirect($request, $this->controller); } else{ $response->setResponseContent('INVALID_REQUEST'); } } catch (Exception $exception){ $response->setException($exception); } return $response; } }<file_sep><?php class Cart { private function createCart(){ if(!isset($_SESSION['cart'])){ $_SESSION['cart'] = []; } } public function edit(Request $request, Response $response, $productIdField, $quantityField){ if($response->isSuccess()){ $this->createCart(); $productId = $response->getData($productIdField); $quantity = $request->getData($quantityField); $quantityAvailable = $response->getData($quantityField); if($quantityAvailable - $quantity < 0){ $response->setResponseContent('INVALID_REQUEST_DATA', [$quantityField]); return $response; } $data = $response->getData(null); $data[$quantityField] = $quantity; $_SESSION['cart'][$productId] = $data; $response->setResponseContent('SUCCESS', null, $_SESSION['cart']); } return $response; } public function delete(Request $request, $productIdField){ $productId = $request->getData($productIdField); $this->createCart(); if(isset($_SESSION['cart'][$productId])){ unset($_SESSION['cart'][$productId]); } $response = new Response(); $response->setResponseContent('', null, $_SESSION['cart']); return $response; } private function join(Request $request, Response $response){ } public function list(){ $this->createCart(); $response = new Response(); $response->setResponseContent('', null, $_SESSION['cart']); return $response; } }<file_sep><?php require_once __DIR__ . "/../../backend/Api.php"; $request = new Request('sync'); $response = $api->process($request); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Stylesheets --> <?php require_once __DIR__ . "/../assets/layout/index_css.php"; ?> <link rel='stylesheet' href='/public/assets/css/styles_novousuario2.css'> </head> <body> <div class="container-login100"> <div class="wrap-login100 p-l-55 p-r-55 p-t-30 p-b-30 container-custom" id=formulario-cliente> <form class="login100-form validate-form" action="../index.php?name=usuario&action=insert" method="post"> <span class="login100-form-title p-b-37"> NOVO CLIENTE </span> <?php if($response->getCode() != 6){ echo '<div class="alert alert-warning" role="alert">'; echo $response->getMessage(); if($response->getCode() == 2){ echo " Invalid Fields: " . implode(", ", $response->getInvalidFields()); } echo '</div>'; } ?> <div class="wrap-input100 validate-input m-b-20" data-validate="nomeusuario"> <input class="input100" type="text" name="login" placeholder="Login" value="<?php echo $response->getData('login') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-20" data-validate="senha"> <input class="input100" type="text" name="senha" placeholder="Senha" value="<?php echo $response->getData('senha') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-20" data-validate="nome"> <input class="input100" type="text" name="nome" placeholder="Nome" value="<?php echo $response->getData('nome') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-20" data-validate="sobrenome"> <input class="input100" type="text" name="sobrenome" placeholder="Sobrenome" value="<?php echo $response->getData('sobrenome') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-25" data-validate="cpf"> <input class="input100" type="text" name="cpf" placeholder="CPF" value="<?php echo $response->getData('cpf') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-20" data-validate="telefone"> <input class="input100" type="text" name="telefone" placeholder="Telefone" value="<?php echo $response->getData('telefone') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-20" data-validate="e-mail"> <input class="input100" type="text" name="email" placeholder="E-mail" value="<?php echo $response->getData('email') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-20" data-validate="cep"> <input class="input100" type="text" name="cep" placeholder="CEP" value="<?php echo $response->getData('cep') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-20" data-validate="logradouro"> <input class="input100" type="text" name="logradouro" placeholder="Logradouro" value="<?php echo $response->getData('logradouro') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-25" data-validate="numero"> <input class="input100" type="text" name="numero" placeholder="Número" value="<?php echo $response->getData('numero') ?>"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-20" data-validate="complemento"> <input class="input100" type="text" name="complemento" placeholder="Complemento" value="<?php echo $response->getData('complemento') ?>"> <span class="focus-input100"></span> </div> <div class="container-login100-form-btn"> <div class="text-center"> <button type="submit"> CRIAR CADASTRO </button> </div> </div> </form> </div> </div> <!-- Scripts --> <?php require_once __DIR__ . "/../assets/layout/index_scripts.php"; ?> </body> </html><file_sep><?php require_once __DIR__ . "/../../backend/Api.php"; $request = new Request('sync', true, 1); $response = $api->process($request); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="description" content=" Divisima | eCommerce Template"> <meta name="keywords" content="divisima, eCommerce, creative, html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Stylesheets --> <?php require_once __DIR__ . "/../assets/layout/main_css.php"; ?> </head> <body> <!-- Page Preloder --> <div id="preloder"> <div class="loader"></div> </div> <!-- Header --> <header class="header-section"> <?php require_once __DIR__ . "/../assets/layout/header.php"; ?> </header> <section class="checkout-section"> <div class="container"> <div class="tamanho"> <div class="spad"> <div class="cart-table"> <h2 class="mb-3">Finalizar Compra</h2> <hr> <form name="formPagamento" action="" id="formPagamento"> <h4 class="mb-3">Dados do Comprador</h4> <hr> <div class="row"> <div class="col-md-6 mb-3"> <label>Nome</label> <input type="text" name="senderName" id="senderName" placeholder="Nome completo" value="<NAME>" class="form-control" required> </div> <div class="col-md-6 mb-3"> <label>CPF</label> <input type="number" name="senderCPF" id="senderCPF" placeholder="CPF sem traço" value="22111944785" class="form-control" required> </div> </div> <div class="row"> <div class="col-md-2 mb-3"> <label>DDD</label> <input type="number" name="senderAreaCode" id="senderAreaCode" placeholder="DDD" value="41" class="form-control" required> </div> <div class="col-md-4 mb-3"> <label>Telefone</label> <input type="number" name="senderPhone" id="senderPhone" placeholder="Somente número" value="56273440" class="form-control" required> </div> <div class="col-md-6 mb-3"> <label>E-mail</label> <input type="email" name="senderEmail" id="senderEmail" placeholder="E-mail do comprador" value="<EMAIL>" class="form-control" required> </div> </div> <hr> <h4 class="mb-3">Endereço de Entrega</h4> <hr> <input type="hidden" name="shippingAddressRequired" id="shippingAddressRequired" value="true"> <div> <div class="col-md-13 mb-3"> <label>Logradouro</label> <input type="text" name="shippingAddressStreet" class="form-control" id="shippingAddressStreet" placeholder="Av.Rua." value="R. <NAME>" required> </div> <div class="row"> <div class="col-md-3 mb-3"> <label>Número</label> <input type="number" name="shippingAddressNumber" class="form-control" id="shippingAddressNumber" placeholder="Número" value="1384" required> </div> <div class="col-md-5 mb-3"> <label>Complemento</label> <input type="text" name="shippingAddressComplement" class="form-control" id="shippingAddressComplement" placeholder="Complemento" value="2o andar"> </div> <div class="col-md-4 mb-3"> <label>CEP</label> <input type="number" name="shippingAddressPostalCode" class="form-control" id="shippingAddressPostalCode" placeholder="CEP sem traço" value="01452002" required> </div> </div> <div class="row"> <div class="col-md-5 mb-3"> <label>Bairro</label> <input type="text" name="shippingAddressDistrict" class="form-control" id="shippingAddressDistrict" placeholder="Bairro" value="Centro" required> </div> <div class="col-md-5 mb-3"> <label>Cidade</label> <input type="text" name="shippingAddressCity" class="form-control" id="shippingAddressCity" placeholder="Cidade" value="Curitiba" required> </div> <div class="col-md-2 mb-3"> <label>Estado</label> <select name="shippingAddressState" class="custom-select d-block w-100" id="shippingAddressState" required> <option value="">Selecione</option> <option value="AC">AC</option> <option value="AL">AL</option> <option value="AP">AP</option> <option value="AM">AM</option> <option value="BA">BA</option> <option value="CE">CE</option> <option value="DF">DF</option> <option value="ES">ES</option> <option value="GO">GO</option> <option value="MA">MA</option> <option value="MT">MT</option> <option value="MS">MS</option> <option value="MG">MG</option> <option value="PA">PA</option> <option value="PB">PB</option> <option value="PR" selected>PR</option> <option value="PE">PE</option> <option value="PI">PI</option> <option value="RJ">RJ</option> <option value="RN">RN</option> <option value="RS">RS</option> <option value="RO">RO</option> <option value="RR">RR</option> <option value="SC">SC</option> <option value="SP">SP</option> <option value="SE">SE</option> <option value="TO">TO</option> </select> </div> </div> <!-- Moeda utilizada para pagamento --> <input type="hidden" name="shippingAddressCountry" id="shippingAddressCountry" value="BRL"> <!-- 1 - PAC / 2 - SEDEX / 3 - Sem frete --> <input type="hidden" name="shippingType" value="3"> <!-- Valor do frete --> <input type="hidden" name="shippingCost" value="0.00"> <!-- Pagamento com cartão de crédito --> <input type="hidden" name="bandeiraCartao" id="bandeiraCartao"> <input type="hidden" name="valorParcelas" id="valorParcelas"> <input type="hidden" name="tokenCartao" id="tokenCartao"> <input type="hidden" name="hashCartao" id="hashCartao"> <hr> <h4 class="mb-3">Dados do Cartão </h4> <hr> <div class="mb-3"> <label >Nome do titular</label> <input type="text" name="creditCardHolderName" class="form-control" id="creditCardHolderName" placeholder="Nome igual ao escrito no cartão" value="<NAME>"> <small id="creditCardHolderName" class="form-text text-muted"> Como está gravado no cartão </small> </div> <div class="row"> <div class="col-md-4 mb-3"> <label>CPF do titular</label> <input type="number" name="creditCardHolderCPF" id="creditCardHolderCPF" placeholder="CPF sem traço" value="22111944785" class="form-control"> </div> <div class="col-md-4 mb-3"> <label>Nascimento</label> <input type="text" name="creditCardHolderBirthDate" id="creditCardHolderBirthDate" placeholder="Data de Nascimento." value="27/10/1987" class="form-control"> </div> </div> <div class="row"> <div class="col-md-6"> <label>Parcelas</label> <select name="qntParcelas" id="qntParcelas" class="form-control select-qnt-parcelas"> </select> </div> <div class="col-md-5 mb-3"> <label>Número do cartão</label> <div class="input-group"> <input type="number" name="numCartao" maxlength="16" class="form-control" id="numCartao" value="41111"> <div class="input-group-prepend"> <span class="input-group-text bandeira-cartao"> </span> </div> </div> <small id="numCartao" class="form-text text-muted"> Preencha para ver o parcelamento </small> </div> </div> <div class="row"> <div class="col-md-4 mb-3"> <label>Mês de Validade</label> <input type="number" name="mesValidade" id="mesValidade" maxlength="2" value="12" class="form-control"> </div> <div class="col-md-4 mb-3"> <label>Ano de Validade</label> <input type="number" name="anoValidade" id="anoValidade" maxlength="4" value="2030" class="form-control"> </div> <div class="col-md-3 mb-3 creditCard"> <label>CVV</label> <input type="number" name="numCartao" class="form-control" id="cvvCartao" maxlength="3" value="123"> <small id="cvvCartao" class="form-text text-muted"> 3 digitos no verso do cartão. </small> </div> </div> </div> <hr> <h4 class="col-md-13 mb-3">Endereço do titular do cartão</h4> <hr> <div class="row"> <div class="col-md-12 mb-3"> <label>Logradouro</label> <input type="text" name="billingAddressStreet" id="billingAddressStreet" placeholder="Av. Rua" value="<NAME>" class="form-control"> </div> </div> <div class="row"> <div class="col-md-3 mb-3"> <label>Número</label> <input type="number" name="billingAddressNumber" id="billingAddressNumber" placeholder="Número" value="1384" class="form-control"> </div> <div class="col-md-5 mb-3"> <label>Complemento</label> <input type="text" name="billingAddressComplement" id="billingAddressComplement" placeholder="Complemento" value="5o andar" class=" form-control"> </div> <div class="col-md-4 mb-3"> <label>CEP</label> <input type="number" name="billingAddressPostalCode" class="form-control" id="billingAddressPostalCode" placeholder="CEP sem traço" value="01452002"> </div> </div> <div class="row"> <div class="col-md-5 mb-3"> <label>Bairro</label> <input type="text" name="billingAddressDistrict" id="billingAddressDistrict" placeholder="Bairro" value="Santa Cândida" class="form-control"> </div> <div class="col-md-5 mb-3"> <label>Cidade</label> <input type="text" name="billingAddressCity" id="billingAddressCity" placeholder="Cidade" value="Curitiba" class="form-control"> </div> <div class="col-md-2 mb-3"> <label>Estado</label> <select name="billingAddressState" class="custom-select d-block w-100" id="billingAddressState"> <option value="">Selecione</option> <option value="AC">AC</option> <option value="AL">AL</option> <option value="AP">AP</option> <option value="AM">AM</option> <option value="BA">BA</option> <option value="CE">CE</option> <option value="DF">DF</option> <option value="ES">ES</option> <option value="GO">GO</option> <option value="MA">MA</option> <option value="MT">MT</option> <option value="MS">MS</option> <option value="MG">MG</option> <option value="PA">PA</option> <option value="PB">PB</option> <option value="PR" selected>PR</option> <option value="PE">PE</option> <option value="PI">PI</option> <option value="RJ">RJ</option> <option value="RN">RN</option> <option value="RS">RS</option> <option value="RO">RO</option> <option value="RR">RR</option> <option value="SC">SC</option> <option value="SP">SP</option> <option value="SE">SE</option> <option value="TO">TO</option> </select> </div> </div> <input type="hidden" name="paymentMethod" id="creditCard" value="creditCard"> <input type="hidden" name="billingAddressCountry" id="billingAddressCountry" value="BRL"> <input type="hidden" name="itemId1" id="itemId1" value="itemId1"> <input type="hidden" name="itemDescription1" id="itemDescription1" value="itemDescription1"> <input type="hidden" name="paymentMethod" id="paymentMethod" value="creditCard"> <input type="hidden" name="itemQuantity1" id="itemQuantity1" value="itemQuantity1"> <input type="hidden" name="Quantity" id="Quantity" value="Quantity"> <input type="hidden" name="itemAmount1" id="itemAmount1" value="itemAmount1"> <input type="hidden" name="reference" id="reference" value="1001"> <input type="hidden" name="installmentValue" id="installmentValue" value="2"> <input type="hidden" name="noIntInstalQuantity" id="noIntInstalQuantity" value="2"> <input type="hidden" name="currency" id="currency" value="BRL"> <br> <span id="msg"></span> <br> <hr> <button type="submit" name="btnComprar" id="btnComprar" class="site-btn">FINALIZAR</button> <a href="/public/pedido/visualizar_pedido.php" class="site-btn sb-dark">VOLTAR</a> </form> </div> </div> </div> </div> <!-- Scripts --> <?php require_once __DIR__ . "/../assets/layout/main_scripts.php"; ?> <script type="text/javascript" src="<?php echo SCRIPT_PAGSEGURO; ?>"></script> <script src="/src/pagamento/controller/CPagamento.js"> </script> </body> </html> <file_sep><?php require_once __DIR__ . "/../../backend/Api.php"; $request = new Request('sync', true); $response = $api->process($request); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="description" content=" Divisima | eCommerce Template"> <meta name="keywords" content="divisima, eCommerce, creative, html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Favicon --> <link href="/public/assets/img/favicon.ico" rel="shortcut icon"/> <!-- Google Font --> <link href="https://fonts.googleapis.com/css?family=Josefin+Sans:300,300i,400,400i,700,700i" rel="stylesheet"> <!-- Stylesheets --> <?php require_once __DIR__ . "/../assets/layout/main_css.php"; ?> </head> <body> <!-- Page Preloder --> <div id="preloder"> <div class="loader"></div> </div> <!-- Header --> <header class="header-section"> <?php require_once __DIR__ . "/../assets/layout/header.php"; ?> </header> <!-- checkout section --> <section class="checkout-section"> <div class="container"> <div class="spad"> <div class="col-md-10"> <div class="cart-table"> <form class="checkout-form" method="post" action="?name=produto&action=insert"> <h3>Cadastro de Item</h3> <?php if($response->getCode() != 6){ echo '<div class="alert alert-warning" role="alert">'; echo $response->getMessage(); if($response->getCode() == 2){ echo " Invalid Fields: " . implode(", ", $response->getInvalidFields()); } echo '</div>'; } ?> <div class="row address-inputs"> <div class="col-md-12"> <input type="text" placeholder="Nome" name="nome" id="nome" value='<?php ?>'> </div> <div class="col-md-6"> <input type="text" placeholder="Preço" name="preco" id="preco" value='<?php ?>'> </div> <div class="col-md-6"> <input style='width:120px' type='number' name='quantidade' placeholder='Quantidade'> <div class="col-md-12"> <select name="idcategoria"> <option value="1">Salgados</option> <option value="2">Doces</option> <option value="3">Bebidas</option> </select> </div> </div> <hr> </div> <button class="site-btn submit-order-btn">CADASTRAR</button> <a href="/public/produto/gerenciar_itens.php?name=produto&action=list" class="site-btn sb-dark">VOLTAR</a> </form> </div> </div> </div> </div> </section> <!-- checkout section end --> <!-- Scripts --> <?php require_once __DIR__ . "/../assets/layout/main_scripts.php"; ?> <script src="/public/assets/js/scripts.js"></script> <script> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); } } </script> </body> </html><file_sep><?php trait RequestDataTypeValidation { protected function isValidType($field, $rules){ $response = null; switch ($rules['type']){ case 'custom': $response = $this->isCustom($field, $rules); break; case 'alphanumerictext': $response = $this->isAlphaNumericText($field); break; case 'alphatext': $response = $this->isAlphaText($field); break; case 'text': $response = $this->isText($field); break; case 'date': $response = $this->isDate($field); break; case 'time': $response = $this->isTime($field); break; case 'datetime': $response = $this->isDateTime($field); break; case 'decimal': $response = $this->isDecimal($field); break; case 'money': $response = $this->isMoney($field); break; default: $response = $this->isInteger($field); } return $response; } private function isCustom($field, $rules) { return isset($rules["regex"]) && preg_match($rules["regex"], $this->data[$field]); } private function isAlphaNumericText($field) { return preg_match('/^[A-Za-zÁÉÍÓÚáéíóúÂÊÎÔÛÃÕÀÈÌÒÙÇâêîôûãõàèìòùç _0-9]{0,}$/', $this->data[$field]); } private function isAlphaText($field) { return preg_match('/^[A-Za-zÁÉÍÓÚáéíóúÂÊÎÔÛÃÕÀÈÌÒÙÇâêîôûãõàèìòùç _]{0,}$/', $this->data[$field]); } private function isText($field) { return preg_match('/^[\w\s\p{L}\p{M}\p{Z}\p{N}\p{P}\p{S}\p{C}]{0,}$/u', $this->data[$field]); } private function isDate($field) { return preg_match('/^\d{4}-\d{2}-\d{2}$/', $this->data[$field]); } private function isTime($field) { return preg_match('/^\d{2}[:]\d{2}$/', $this->data[$field]); } private function isDateTime($field) { return preg_match('/^\d{4}-\d{2}-\d{2} \d{2}[:]\d{2}$/', $this->data[$field]); } private function isInteger($field) { return preg_match('/^[+-]{0,1}\d{0,}$/', $this->data[$field]); } private function isDecimal($field) { return preg_match('/^[+-]{0,1}\d+(?:[.]\d+){0,1}$/', $this->data[$field]); } private function isMoney($field) { return preg_match('/^[+-]{0,1}\d+(?:[.]\d{2,2}){0,1}$/', $this->data[$field]); } }<file_sep><?php require_once __DIR__ . "/../modules/base/BaseModel.php"; class PedidoModel extends BaseModel { public function insert(Request $request){ $statement = " insert into pedido (idcliente, idstatuspedido, idformapagamento) values (:idcliente, :idstatuspedido, :idformapagamento) "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function list(Request $request){ $statement = " select idcliente, idpedido, idstatuspedido, idformapagamento, ifnull(sum(valor_total_produto), 0) as valor_total, status_pedido from (select idcliente, idpedido, idstatuspedido, idformapagamento, quantidade * preco as valor_total_produto, status_pedido from (select pedido.idcliente, pedido.idpedido, pedido.idstatuspedido, pedido.idformapagamento, itempedido.quantidade, item.preco, statuspedido.nome as status_pedido from pedido inner join statuspedido on pedido.idstatuspedido = statuspedido.idstatuspedido left join itempedido on pedido.idpedido = itempedido.idpedido left join item on itempedido.iditem = item.iditem) as r) as s where idcliente = :idcliente group by idpedido "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function list_by_status(Request $request){ $statement = " select idpedido, cpf from pedido left join cliente on pedido.idcliente = cliente.idcliente where idstatuspedido = :idstatuspedido; "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function list_itens_pedido(Request $request){ $statement = " select itempedido.iditem, nome, itempedido.quantidade from pedido right join itempedido on pedido.idpedido = itempedido.idpedido right join item on itempedido.iditem = item.iditem where pedido.idpedido = :idpedido; "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function view(Request $request){ $statement = " select idpedido, cpf from pedido left join cliente on pedido.idcliente = cliente.idcliente where idpedido = :idpedido; "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function view_item(Request $request){ $statement = " select iditem, nome, preco, quantidade from item where iditem = :iditem; "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function edit(Request $request){ $response = $this->view_item($request); if(!$response->isSuccess()){ return $response; } $quantidade = $response->getData('quantidade'); $modificador = $request->getData('modificador'); if($quantidade + $modificador < 0){ $response->setResponseContent('INVALID_REQUEST_DATA', ['modificador']); return $response; } $statement = " update item set nome = :nome, quantidade = quantidade - :modificador, idcategoria = :idcategoria where iditem = :iditem; "; $response = $this->databaseHandler->executeQuery($statement, $request->getData()); if($response->isSuccess()){ $response = $this->view_item($request); } return $response; } public function edit_cart(Request $request){ return $this->view_item($request); } public function edit_status(Request $request){ $statement = " update pedido set idstatuspedido = :idstatuspedido where idpedido = :idpedido "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } }<file_sep><?php class Auth { public function login(Request $request, Response $response, $passwordField){ $newResponse = new Response(); $passwordFromForm = $request->getData($passwordField); $passwordFromDatabase = $response->getData($passwordField); if($response->isEmpty()){ $newResponse->setResponseContent('INVALID_LOGIN'); } elseif(password_verify($passwordFromForm, $passwordFromDatabase)){ $_SESSION["logged"] = true; $_SESSION = array_merge($_SESSION, $response->getData(null)); unset($_SESSION[$passwordField]); $newResponse->setResponseContent('SUCCESS'); } else{ $newResponse->setResponseContent('INVALID_PASSWORD'); } return $newResponse; } public function logout(){ $response = new Response(); $_SESSION["logged"] = false; $_SESSION['cart'] = []; $response->setResponseContent('SUCCESS'); return $response; } }<file_sep><?php require_once __DIR__ . "/../modules/base/BaseController.php"; class PedidoController extends BaseController { public function insert(Request $request){ $fieldRules = [ "idcliente" => ["required", "type:integer", "min:0"], "idstatuspedido" => ["required", "type:integer", "min:0"], "idformapagamento" => ["required", "type:integer", "min:0"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $request->setData('idstatuspedido', 2); $response = $this->redirect($request, $this->model); } return $response; } public function delete(Request $request){ $fieldRules = [ "idpedido" => ["required", "type:integer", "min:0"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $request->setData('idstatuspedido', 6); $response = $this->redirect($request, $this->model); } return $response; } public function delete_from_cart(Request $request){ $fieldRules = [ "iditem" => ["required", "type:integer", "min:0"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $response = $this->cart->delete($request, 'iditem'); } return $response; } public function list(Request $request){ $request->setData('idcliente', $_SESSION['idcliente']); return $this->redirect($request, $this->model); } public function list_by_status(Request $request){ $request->setData('idstatuspedido', 4); return $this->redirect($request, $this->model); } public function list_cart(Request $request){ return $this->cart->list(); } public function list_itens_pedido(Request $request){ return $this->redirect($request, $this->model); } public function view(Request $request){ return $this->redirect($request, $this->model); } public function edit_status(Request $request){ $fieldRules = [ "idpedido" => ["required", "type:integer", "min:0"], "cpf" => ["required", "type:integer"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $_GET['action'] = 'view'; $request2 = new Request("sync"); $response = $this->view($request2); $cpf_inserido = $request->getData('cpf'); $cpf_cadastro = $response->getData('cpf'); if($cpf_inserido == $cpf_cadastro){ $request->setData('idstatuspedido', 5); $response = $this->redirect($request, $this->model); if(!$response->isSuccess()){ header('Location: confirmar_retirada.php'); } } else{ $response->setResponseContent('INVALID_REQUEST_DATA', ['cpf'], []); header('Location: confirmar_retirada.php'); } } return $response; } public function edit_cart(Request $request){ $fieldRules = [ "iditem" => ["required", "type:integer", "min:0"], "quantidade" => ["required", "type:integer", "min:0"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $response = $this->redirect($request, $this->model); $response = $this->cart->edit($request, $response, 'iditem', 'quantidade'); } return $response; } }<file_sep><?php require_once __DIR__ . "/../modules/base/BaseModel.php"; class UsuarioModel extends BaseModel { public function login(Request $request){ $statement = " select usuario.idusuario, idperfil, idcliente, senha from usuario left join cliente on usuario.idusuario = cliente.idusuario where login = :login "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function insert(Request $request){ $statement = " insert into usuario (idperfil, login, senha) values (1, :login, :senha) "; $response = $this->databaseHandler->executeQuery($statement, $request->getData()); if(!$response->isSuccess()){ return $response; } $idusuario = $this->databaseHandler->getLastInsertedKey(); $statement = " insert into cliente (idusuario, cpf, nome, sobrenome, email, telefone, cep, logradouro, numero, complemento) values ($idusuario, :cpf, :nome, :sobrenome, :email, :telefone, :cep, :logradouro, :numero, :complemento) "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function delete(Request $request){ $statement = " delete from usuario where idusuario = :idusuario "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function view(Request $request){ $statement = " select email, telefone, cep, logradouro, numero, complemento from cliente where idcliente = :idcliente "; return $this->databaseHandler->executeQuery($statement, $request->getData()); } public function edit(Request $request){ $statement = " update cliente set email = :email, telefone = :telefone, cep = :cep, logradouro = :logradouro, numero = :numero, complemento = :complemento where idcliente = :idcliente "; $response = $this->databaseHandler->executeQuery($statement, $request->getData()); if(!$response->isSuccess()){ return $response; } $statement = " update usuario set senha = case when :senha = '' then senha else :senha end where idusuario = :idusuario "; $response = $this->databaseHandler->executeQuery($statement, $request->getData()); if(!$response->isSuccess()){ return $response; } return $this->view($request); } }<file_sep><?php $_GET = [ "name" => "usuario", "action" => "login", ]; $_POST = [ "login" => "admin", "senha" => "<PASSWORD>", ]; require_once __DIR__ . "/../backend/Api.php"; $request = new Request('sync'); $response = $api->process($request);<file_sep>rootProject.name='Keyar' include ':app' <file_sep><?php require_once __DIR__ . "/../../backend/Api.php"; $request = new Request('sync', true, 1); $response = $api->process($request); $_GET = [ "name" => "pedido", "action" => "list_itens_pedido"]; $request2 = new Request('sync', true, 1); $response2 = $api->process($request2); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="description" content=" Divisima | eCommerce Template"> <meta name="keywords" content="divisima, eCommerce, creative, html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Stylesheets --> <?php require_once __DIR__ . "/../assets/layout/main_css.php"; ?> </head> <body> <!-- Header --> <header class="header-section"> <?php require_once __DIR__ . "/../assets/layout/header.php"; ?> </header> <!-- Conteúdo da Página --> <section class="product-filter-section"> <div class="container"> <div class="spad"> <div class="cart-table"> <h4>Lista de Itens do Pedido</h4> <div class="cart-table-warp"> <table id="lista_produtos" class="display"> <thead> <tr> <th>CÓDIGO<br>PRODUTO</th> <th>PRODUTO</th> <th>QUANTIDADE</th> </tr> </thead> <tbody> <?php // Listando foreach ($response2->getData(null, true) as $registry){ echo '<tr>'; echo "<td>" . $registry['iditem'] . "</td>"; echo "<td>" . $registry['nome'] . "</td>"; echo "<td>" . $registry['quantidade'] . "</td>"; echo '</tr>'; } ?> </tbody> </table> <br> <a href="/public/pedido/confirmar_retirada.php" class="site-btn sb">VOLTAR</a> </div> </div> </div> </div> </section> <!-- Arquivos JS --> <?php require_once __DIR__ . "/../assets/layout/main_scripts.php"; ?> <script src="/public/assets/js/scripts.js"></script> <script src="/public/assets/vendor/datatables/datatables.minMain.js"> </script> </body> </html> <file_sep><?php require_once __DIR__ . "/api/Api.php"; $api = new Api(); <file_sep><?php trait RequestValidation { public function validRequest(){ $regex = '/^[a-zA-Z_]+$/'; return preg_match($regex, $this->name) && preg_match($regex, $this->action); } public function emptyRequest(){ return $this->name === "" || $this->action === ""; } public function isValidAuth(){ return !$this->requireAuth || ($this->requireAuth && isset($_SESSION["logged"]) && $_SESSION["logged"]); } public function isValidProfile() { return !isset($this->profile) || isset($_SESSION["idperfil"]) && $_SESSION["idperfil"] == $this->profile; } private function breakRules($rules){ $newRules = []; foreach ($rules as $rule){ $regex = '/^(?<rule>[A-Za-z0-9_]+)(?::(?<value>\N+)){0,1}/'; preg_match($regex, $rule, $matches); $newRules[$matches['rule']] = isset($matches['value']) ? $matches['value'] : true; } return $newRules; } private function removeFieldsWithoutRules($fieldRules){ foreach($this->data as $field => $value){ if(!array_key_exists($field, $fieldRules)){ unset($this->data[$field]); } } } private function isRuleWithoutField($field){ return !isset($this->data[$field]) || !array_key_exists($field, $this->data); } public function validateRequestData($fieldRules){ $invalidFields = []; $response = new Response(); $this->removeFieldsWithoutRules($fieldRules); foreach($fieldRules as $field => $rules){ if($this->isRuleWithoutField($field)){ $invalidFields[] = $field; } else{ $rules = $this->breakRules($rules); $validField = $this->validateField($field, $rules); if(!$validField){ $invalidFields[] = $field; $response->setResponseContent('INVALID_REQUEST_DATA'); } } } if(!empty($invalidFields)){ $response->setResponseContent('INVALID_REQUEST_DATA', $invalidFields); } else{ $response->setResponseContent(''); } return $response; } public function validateField($field, $rules){ return $this->isValidType($field, $rules) && $this->isValidAdditional($field, $rules); } }<file_sep><?php require_once __DIR__ . "/../../backend/Api.php"; $_GET = [ "name" => "pedido", "action" => "list_cart"]; $request = new Request('sync', true, 1); $response = $api->process($request); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="description" content=" Divisima | eCommerce Template"> <meta name="keywords" content="divisima, eCommerce, creative, html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Stylesheets --> <?php require_once __DIR__ . "/../assets/layout/main_css.php"; ?> </head> <body> <!-- Page Preloder --> <div id="preloder"> <div class="loader"></div> </div> <!-- Header --> <header class="header-section"> <?php require_once __DIR__ . "/../assets/layout/header.php"; ?> </header> <!-- cart section end --> <section class="cart-section spad"> <div class="container"> <div class="row"> <div class="col-lg-7"> <div class="cart-table"> <h4>Seu Pedido</h4> <hr> <div class="cart-table-warp"> <table> <tbody> <?php $valor_total = 0; $data = $response->getData(null, true); if(!empty($data)){ foreach ($data as $registry){ $valor_total += (float) $registry['preco'] * $registry['quantidade']; echo '<tr>'; echo '<td class= "qtde-data"><data type = "text" id = "qtde" name = "qtde" maxlength = "3" size = "2" >' . 'Quantidade ' . $registry['quantidade'] . '</data ></td >'; echo '<td class="product-col" >'; echo '<div class="pc-title">'; echo '<span><u>Preço unitário: </u></span>'; echo '<span> R$' . number_format((float) $registry['preco'], 2, ',', '') . '</span>'; echo '<p>' . $registry['nome'] . '</p></td>'; echo '</td>'; echo '<td class="product-col" >'; echo '<div class="pc-title">'; echo '<h4>R$' . number_format((float) $registry['preco'] * $registry['quantidade'], 2, ',', '') . '</h4></td>'; echo '</tr>'; } } else{ echo '<h5>Seu pedido está vazio ou ainda não foi criado.</h5><br>Crie e gerencie os seus pedidos através do menu superior direito "Perfil", e clicando na opção "Gerenciar Pedidos".'; } ?> </tbody> </table> </div> <div class="total-cost"> <?php if (!empty($data)){ echo '<h6>Valor Total: R$ ' . number_format((float) $valor_total, 2, ',', '') . '</h6>'; } ?> </div> </div> </div> <div class="col-lg-5 card-right"> <?php // Se existir idpedido , exibe o botão de ir para pagamento if ($valor_total > 0) { echo '<a href="/public/pagamento/selecao_forma_pagamento.php" class="site-btn">CONTINUAR PARA PAGAMENTO</a>'; } ?> <a href="/public/pedido/gerenciar_itens_pedido.php" class="site-btn sb-dark">ADICIONAR MAIS</a> </div> </div> </div> </section> <!-- cart section end --> <!-- Scripts --> <?php require_once __DIR__ . "/../assets/layout/main_scripts.php"; ?> </body> </html><file_sep>use sistemacontrolepedidos; # Perfis de Usuario insert into perfil values (1, "Cliente"); insert into perfil values (2, "Balconista"); # Status de Pedido insert into statuspedido values (1, "Em Aberto"); insert into statuspedido values (2, "Aguardando Pagamento"); insert into statuspedido values (3, "Pagamento Confirmado"); insert into statuspedido values (4, "Pronto para Retirada"); insert into statuspedido values (5, "Retirado"); insert into statuspedido values (6, "Cancelado"); # Categorias insert into categoria values (1, "Salgados"); insert into categoria values (2, "Doces"); insert into categoria values (3, "Bebidas"); # Usuarios do Perfil Balconista insert into usuario values (1, "admin", "$2y$04$jcWOI/JnrtKE1uLsl0HjzO4YG0gFcuFVOxBdLkSR/nGYZo2raHnbC", 2); # Usuarios do Perfil Cliente insert into usuario values (2, "jgabardo", "$2y$04$LeD9YApp6zyuc4wksLTeeOdLqKlvLlE9zaiXbt.Tm4sVjFgkU5/mW", 1); insert into usuario values (3, "asantos", "$2y$04$2yLvggfdpMgFRJLnw55GH.2jElhG/JbuiSS70tKsHHJAvgMD4Yrt.", 1); insert into usuario values (4, "gdouglas", "$2y$04$tamTVg7rSWWLyRMfYu.ll.OEjMc8kkgOb2PHNpMhxgPnc1ullWvue", 1); # Clientes INSERT INTO `sistemacontrolepedidos`.`cliente` (`idCliente`, `cpf`, `nome`, `sobrenome`, `email`, `telefone`, `cep`, `logradouro`, `numero`, `complemento`, `idUsuario`) VALUES ('1', '123456789-01', '<NAME>', '<NAME>', '<EMAIL>', '4133333333', '12345678', 'Rua Iapo', '111', 'Casa', '3'); INSERT INTO `sistemacontrolepedidos`.`cliente` (`idCliente`, `cpf`, `nome`, `sobrenome`, `email`, `telefone`, `cep`, `logradouro`, `numero`, `complemento`, `idUsuario`) VALUES ('2', '234567890-12', 'Guilherme', '<NAME>', '<EMAIL>', '4133333333', '12345678', 'Rua Iapo', '111', 'Casa', '4'); INSERT INTO `sistemacontrolepedidos`.`cliente` (`idCliente`, `cpf`, `nome`, `sobrenome`, `email`, `telefone`, `cep`, `logradouro`, `numero`, `complemento`, `idUsuario`) VALUES ('3', '345678901-23', 'João', 'Gabardo', '<EMAIL>', '4133333333', '12345678', 'Rua Iapo', '111', 'Casa', '2');<file_sep># Order Control System TECPUC course completion work. ## Authors - <NAME> - <NAME> - <NAME> ## Description This repository has: - The source code of the developed system, using the following technologies: HTML5, CSS3, JavaScript and PHP. - SQL scripts for MySQL database creation, used by the developed system. - The source code of the mobile application, which has a WebView for accessing the responsive website. <file_sep><?php require_once __DIR__ . "/../modules/base/BaseController.php"; class ProdutoController extends BaseController { public function insert(Request $request){ $fieldRules = [ "nome" => ["required", "max:45", "type:text"], "preco" => ["required", "type:money"], "quantidade" => ["required", "type:integer", "min:0"], "idcategoria" => ["required", "type:integer"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $response = $this->redirect($request, $this->model); } return $response; } public function delete(Request $request){ $fieldRules = [ "iditem" => ["required", "type:integer", "min:0"] ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $response = $this->redirect($request, $this->model); } return $response; } public function list(Request $request){ $response = $this->redirect($request, $this->model); return $response; } public function view(Request $request){ $fieldRules = [ "iditem" => ["required", "type:integer", "min:0"] ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $response = $this->redirect($request, $this->model); } return $response; } public function edit(Request $request){ $fieldRules = [ "nome" => ["required", "max:45", "type:text"], "preco" => ["required", "type:money"], "modificador" => ["required", "type:integer"], "idcategoria" => ["required", "type:text"], "iditem" => ["required", "type:integer", "min:0"], ]; $response = $request->validateRequestData($fieldRules); if($response->isSuccess()){ $response = $this->redirect($request, $this->model); } return $response; } }<file_sep><?php require_once __DIR__ . "/../api/response/Response.php"; class DatabaseHandler { // TODO: configure according to the project private $database = 'mysql'; private $databaseName = 'sistemacontrolepedidos'; private $host = 'localhost'; private $user = 'root'; private $password = ''; private static $connection; public function __construct() { try { self::$connection = new PDO( $this->database . ":host={$this->host};dbname=" . $this->databaseName, $this->user, $this->password ); self::$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $exception){ $response = new Response(); $response->setException($exception); throw $response; } } public function beginTransaction(){ if(!self::$connection->inTransaction()){ self::$connection->beginTransaction(); } } public function commit(){ if(self::$connection->inTransaction()){ self::$connection->commit(); } } public function rollback(){ if(self::$connection->inTransaction()){ self::$connection->rollBack(); } } private function getQueryParameters($statement, $parameters){ preg_match_all('/:[A-Za-z0-9_]+/', $statement, $matches); foreach ($parameters as $index => $value){ if(in_array(":$index", $matches[0])) { $parameters[":$index"] = $value; } unset($parameters[$index]); } return $parameters; } public function executeQuery($statement, $parameters = []){ try { $query = self::$connection->prepare($statement); $parameters = $this->getQueryParameters($statement, $parameters); $query->execute($parameters); $data = $query->fetchAll(PDO::FETCH_ASSOC); $response = new Response(); $response->setResponseContent('SUCCESS', null, $data); return $response; } catch(PDOException $exception){ $this->rollback(); $response = new Response(); $response->setException($exception); return $response; } } public function getLastInsertedKey(){ return self::$connection->lastInsertId(); } }<file_sep><?php trait RequestFormat { public function toPascalCase($field, $subfield = null){ $string = ""; if(property_exists($this, $field)){ if(isset($subfield) && isset($this->$field[$subfield])){ $string = str_replace("_", " ", $this->$field[$subfield]); } else{ $string = str_replace("_", " ", $this->$field); } $string = ucwords($string); $string = str_replace(" ", "", $string); } return $string; } public function toLowerCase($field, $subfield = null){ $string = ""; if(property_exists($this, $field)){ if(isset($this->$field[$subfield])){ $string = strtolower($this->$field[$subfield]); } else{ $string = strtolower($this->$field); } } return $string; } public function toHash($field, $subfield = null){ $string = ""; if(property_exists($this, $field)){ if(isset($this->$field[$subfield]) && array_key_exists($subfield, $this->$field)){ $string = password_hash($this->$field[$subfield], PASSWORD_DEFAULT); } else{ $string = password_hash($this->$field, PASSWORD_DEFAULT); } } return $string; } }<file_sep><?php require_once __DIR__ . "/../../backend/Api.php"; $request = new Request('sync', true, 2); $response = $api->process($request); $_GET = [ "name" => "pedido", "action" => "list_by_status"]; $request2 = new Request('sync', true, 2); $response2 = $api->process($request2); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="description" content=" Divisima | eCommerce Template"> <meta name="keywords" content="divisima, eCommerce, creative, html"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Stylesheets --> <?php require_once __DIR__ . "/../assets/layout/main_css.php"; ?> </head> <body> <!-- Page Preloder --> <div id="preloder"> <div class="loader"></div> </div> <!-- Header --> <header class="header-section"> <?php require_once __DIR__ . "/../assets/layout/header.php"; ?> </header> <!-- checkout section --> <section class="checkout-section"> <div class="container"> <div class="spad"> <div class="cart-table"> <h3>Confirmar Retirada de Pedidos</h3> <div class="cart-table-warp"> <table id="lista_produtos" class="display"> <thead> <tr> <th>NÚMERO DO PEDIDO</th> <th>CPF DO CLIENTE</th> <th>AÇÃO</th> </tr> </thead> <tbody> <?php // Listando foreach ($response2->getData(null, true) as $registry){ echo '<tr>'; echo '<form method="post" action="gerenciar_itens_pedido_retirada.php?name=pedido&action=edit_status">'; echo '<td>' . $registry['idpedido'] . '</td>'; echo '<td><input style="width:130px" type="text" name="cpf"></td>'; echo '<td class="total-col"><button type="submit">Confirmar Retirada</button></td>'; echo "<input type='hidden' name='idpedido' value='{$registry['idpedido']}'>"; echo '</form>'; echo '</tr>'; } ?> </tbody> </table> <br> <a href="/public/main.php" class="site-btn">VOLTAR</a> </div> </div> </div> </div> </section> <!-- Scripts --> <?php require_once __DIR__ . "/../assets/layout/main_scripts.php"; ?> <script src="/public/assets/js/scripts.js"></script> <script src="/public/assets/vendor/datatables/datatables.minMain.js"> </script> </body> </html> <file_sep><?php $_GET = [ "name" => "pedido", "action" => "edit_cart", ]; $_POST = [ "iditem" => 1, "quantidade" => 1, ]; require_once __DIR__ . "/../backend/Api.php"; $request = new Request('sync'); $response = $api->process($request);<file_sep><?php require_once __DIR__ . "/../backend/Api.php"; $request = new Request('sync'); $response = $api->process($request); $_GET = [ "name" => "usuario", "action" => "verify_auth"]; $request2 = new Request('sync'); $response2 = $api->process($request2); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>KeyAr</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Arquivos CSS --> <?php require_once __DIR__ . "/assets/layout/index_css.php"; ?> </head> <body> <div class="container-login100"> <div class="wrap-login100 p-l-55 p-r-55 p-t-50 p-b-30"> <form class="login100-form validate-form" method="post" action="?name=usuario&action=login"> <span class="login100-form-title p-b-37"> LOGIN </span> <?php if($response2->getCode() != 6 && $response2->getCode() != 6){ echo '<div class="alert alert-warning" role="alert">'; echo $response2->getMessage(); if($response2->getCode() == 2){ echo " Invalid Fields: " . implode(", ", $response2->getInvalidFields()); } echo '</div>'; } ?> <div class="wrap-input100 validate-input m-b-20" data-validate="login"> <input class="input100" type="text" name="login" placeholder="Login"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-25" data-validate="senha"> <input class="input100" type="password" name="senha" placeholder="Senha"> <span class="focus-input100"></span> </div> <br> <br> <br> <div class="container-login100-form-btn"> <button type="submit" class="login100-form-btn"> LOGIN </button> </div> <div class="text-center p-t-57 p-b-20"> <div class="text-center"> <a href="/public/cliente/novo_cliente.php">Novo Usuário? Cadastre-se! </a> </div> </div> </form> </div> </div> <!-- Scripts --> <?php require_once __DIR__ . "/assets/layout/index_scripts.php"; ?> </body> </html><file_sep><?php require_once __DIR__ . "/../database/DatabaseHandler.php"; require_once __DIR__ . "/../base/BaseComponent.php"; abstract class BaseModel extends BaseComponent { protected $databaseHandler; public function __construct() { $this->databaseHandler = new DatabaseHandler(); $this->databaseHandler->beginTransaction(); } public function do_commit() { $this->databaseHandler->commit(); } }<file_sep><?php require_once __DIR__ . "/api/Api.php"; header('Content-Type: application/json; charset=utf-8'); $api = new Api(); $request = new Request('async'); $response = $api->process($request);<file_sep><?php require_once "BaseComponent.php"; require_once __DIR__ . '/../controller/modules/Auth.php'; require_once __DIR__ . '/../controller/modules/Cart.php'; abstract class BaseController extends BaseComponent { protected $model; protected $auth; protected $cart; public function __construct($name) { $this->model = $this->getComponent($name, "Model"); $this->auth = new Auth(); $this->cart = new Cart(); } public function commit(){ $this->model->do_commit(); } }<file_sep><?php trait ResponseValidation { private function isUniqueElementArray(){ return count($this->data) == 1 && isset($this->data[0]); } public function isSuccess(){ return $this->code === 0; } public function isEmpty(){ return empty($this->data); } }<file_sep><?php require_once "traits/RequestValidation.php"; require_once "traits/RequestFormat.php"; require_once "traits/RequestDataValidation.php"; require_once "traits/RequestDataTypeValidation.php"; class Request { use RequestValidation; use RequestFormat; use RequestDataValidation; use RequestDataTypeValidation; protected $name; protected $action; protected $requireAuth; protected $profile; protected $data; public function __construct($requestType, $requireAuth = false, $profile = null) { if($requestType == "async"){ $this->getAsyncRequest(); } else{ $this->getSyncRequest(); } $this->requireAuth = $requireAuth; $this->profile = $profile; } private function getSyncRequest(){ $this->name = isset($_GET["name"]) ? $_GET["name"] : ""; $this->action = isset($_GET["action"]) ? $_GET["action"] : ""; $this->data = isset($_POST) ? $_POST : []; } private function getAsyncRequest(){ $request = json_decode(file_get_contents('php://input'), true); $this->name = isset($request["name"]) ? $request["name"] : ""; $this->action = isset($request["action"]) ? $request["action"] : ""; $this->data = isset($request["data"]) ? $request["data"] : []; } public function getName() { return $this->name; } public function getAction() { return $this->action; } public function getData($field = null) { $output = null; if(isset($this->data[$field])){ $output = $this->data[$field]; } else{ $output = $this->data; } return $output; } public function setData($field, $data) { $this->data[$field] = $data; } }
d8ff654afa22119ef53fbef80d9dd32c1c2080a6
[ "Markdown", "SQL", "PHP", "Gradle" ]
46
PHP
liipeandre/sistema-controle-pedidos
f4e8a1ca0605045b57d02b1eacd4369579a4e9af
873ff3e308a44f408b6ba618997b6dca1f1fc276
refs/heads/master
<repo_name>aravind123cs/DJ-Mobile<file_sep>/src/screens/videoBackground.js import React, { Component } from 'react'; import { Dimensions, StyleSheet, View, Image } from 'react-native'; import { Screen } from '@shoutem/ui'; import Video from 'react-native-video'; import BaseScreen from './base'; const window = Dimensions.get('window'); export default class VideoBackgroundScreen extends BaseScreen { static navigationOptions = { ...BaseScreen.navigationOptions, headerStyle: { backgroundColor: 'transparent' } }; render() { const { navigate } = this.props.navigation; return ( <Screen> <Video source={require('../../assets/background.mp4')} // Can be a URL or a local file. rate={0.8} // 0 is paused, 1 is normal. muted={true} // Mutes the audio entirely. //paused={!this.props.isActive} // Pauses playback entirely. resizeMode="cover" // Fill the whole screen at aspect ratio. repeat={true} // Repeat forever. playInBackground={false} // Audio continues to play when app entering background. playWhenInactive={false} // [iOS] Video continues to play when control or notification center are shown. progressUpdateInterval={250.0} // [iOS] Interval to fire onProgress (default to ~250ms) style={styles.backgroundVideo} /> <Image source={require('../../assets/video-noise.png')} style={{...styles.backgroundImage, resizeMode:'stretch', width:window.width, height:window.height+64 }}/> {this.renderContents()} </Screen> ) } } const styles = { backgroundVideo: { position: 'absolute', top: -64, left: 0, bottom: 0, right: 0, }, backgroundImage: { position: 'absolute', top: -64, left: 0, bottom: 0, right: 0, } }<file_sep>/src/screens/stillBackground.js import React, { Component } from 'react'; import { Dimensions, StyleSheet, View, Image } from 'react-native'; import { Screen } from '@shoutem/ui'; import Video from 'react-native-video'; import {ImageBackground, ScrollView} from 'react-native'; const window = Dimensions.get('window'); export default class StillBackgroundScreen extends Component { render() { // const { navigate } = this.props.navigation; console.log('this.props') console.log(this.props) return ( <View style={{ flex: 1 }}> <ImageBackground resizeMode={'stretch'} style={{ flex: 1 }} source={require('../../assets/stillBackground.png')} > {this.props.children} </ImageBackground> </View> ) } } const styles = { backgroundVideo: { position: 'absolute', top: 0, left: 0, bottom: 0, right: 0, } }<file_sep>/src/screens/home/landing.js import React, { Component } from "react"; import { ImageBackground, View, StatusBar, Image, Dimensions } from "react-native"; import { Container, Button, H3, Text, Footer, FooterTab, Icon, Content } from "native-base"; import styles from "./styles"; import StillBackground from "../stillBackground"; const deviceWidth = Dimensions.get("window").width; const deviceHeight = Dimensions.get("window").height; const launchscreenLogo = { uri: "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" }; class Landing extends Component { static navigationOptions = { title: null, headerLeft: null, header: null }; constructor(props){ super(props) this.state = { } } handleSignUp() { const { navigate } = this.props.navigation; navigate("Tcs"); } render() { return ( <Container> <Image source={require('../../../assets/stillBackground.png')} style={{position: "absolute", zIndex:0,flex: 1 , width: deviceWidth, height: deviceHeight }} /> <StatusBar barStyle="light-content" /> {/* <StillBackground> */} <View style={styles.logoContainer}> <Image source={launchscreenLogo} style={styles.logo} /> </View> <View style={{ alignItems: "center", marginBottom: 50, backgroundColor: "transparent" }} > <H3 style={styles.text}>App to showcase</H3> <View style={{ marginTop: 8 }} /> <H3 style={styles.text}>NativeBase components</H3> <View style={{ marginTop: 8 }} /> </View> <Content padder> <Button onPress={() => this.handleSignUp()} rounded block light bordered style={styles.mb15} > <Text>Sign up</Text> </Button> <Button rounded block light style={styles.mb15}> <Text>login</Text> </Button> </Content> {/* </StillBackground> */} </Container> ); } } export default Landing; <file_sep>/src/screens/sign-up/pin-entry.js import React, { Component } from "react"; import { Container, Header, Title, Content, View, Text, Button, Icon, Footer, FooterTab, Left, Right, Body } from "native-base"; import SecureInput from "../../components/secureInput"; import DigitPad from "../../components/digitPad"; import styles from "./styles"; class PinEntry extends Component { static navigationOptions = { title: "Pin entry" // headerLeft:null, // header: null }; constructor(props) { super(props); this.state = { value: "", valueAgain: "", repeating: false, error: false }; } onPadPress(value) { if (value == "Reset") { this.setState({ value: "", valueAgain: "", repeating: false, error: false }); return; } let newValue; if (!this.state.repeating) { if (value == "Del") { newValue = this.state.value.substring(0, this.state.value.length - 1); } else newValue = this.state.value + value; if (newValue.length == 6) { this.setState({ value: newValue, repeating: true, error: false }); } else this.setState({ value: newValue, error: false }); } else { if (value == "Del") { newValue = this.state.valueAgain.substring( 0, this.state.valueAgain.length - 1 ); } else newValue = this.state.valueAgain + value; if (newValue.length > 6) return; this.setState({ valueAgain: newValue, error: false }); // compare two values and show error if needed if (newValue.length == 6) { if (this.state.value !== newValue) { this.setState({ error: true, value: "", valueAgain: "", repeating: false }); } else { this.setState({ error: false }); const { navigate } = this.props.navigation; navigate("Home"); } } } } render() { console.log(this.state); return ( <Container style={styles.container}> <Content padder> {!this.state.repeating ? <View> <View style={{ marginVertical: 20, justifyContent: "center", alignItems: "center" }} > <Text>Enter security pin</Text> </View> <SecureInput length={6} value={this.state.value} /> </View> : <View> <View style={{ marginVertical: 20, justifyContent: "center", alignItems: "center" }} > <Text>Confirm security pin</Text> </View> <SecureInput length={6} value={this.state.valueAgain} /> </View>} <View style={{ marginVertical: 20, justifyContent: "center", alignItems: "center" }} > {this.state.error ? <Text>PINS Do Not Match Try Again</Text> : null} </View> </Content> <Footer style={{ backgroundColor: "transparent", height: 220, marginBottom: 10 }} > <FooterTab style={{ backgroundColor: "transparent" }}> <DigitPad onPress={this.onPadPress.bind(this)} /> </FooterTab> </Footer> </Container> ); } } export default PinEntry; <file_sep>/src/screens/base.js import React from 'react'; // import { themeVariables } from '~/src/ui/styles'; import { Screen } from '@shoutem/ui'; import { Dimensions, StyleSheet, View, Image } from 'react-native'; export default class BaseScreen extends React.PureComponent { static navigationOptions = { headerStyle: { // backgroundColor: themeVariables.navBarBackground, }, title: <Image source={require('../../assets/logo.png')} resizeMode="cover" style={{ width:30, height:26 }} /> }; render() { console.log('098909890989098909') console.log(this) return ( <Screen> {this.renderContents()} </Screen> ) } render(){ return null; } }<file_sep>/src/components/secureInput/index.js import React, { Component } from "react"; import PropTypes from "prop-types"; import { Text, Button, View } from "native-base"; const BULLET = "•"; const REVEAL_TIMEOUT = 1000; export default class SecureInput extends Component { static propTypes = { setData: PropTypes.func, length: PropTypes.number.isRequired, value: PropTypes.string.isRequired }; constructor(props) { super(props); let digits = []; for (let digit = 0; digit < this.props.length; digit++) { digits.push(null); } this.state = { digits, caret: 0, value: null }; } componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.value) { if (this.revealer) { clearTimeout(this.revealer); this.revealer = null; } let reveal = null; if (nextProps.value) { if (nextProps.value.length < this.props.value.length) { reveal = false; } } if (nextProps.value.length <= this.props.length) this.setData(nextProps.value, reveal); } } setData(value, autoReveal = null) { let digits = []; if (value == null) { for (let digit = 0; digit < this.props.length; digit++) { digits.push(null); } this.setState({ digits, caret: 0, value: null }); return; } const caretPos = value.length - 1; if ( autoReveal !== false && (caretPos == 0 || caretPos == this.state.caret + 1) ) { autoReveal = true; } digits = this.state.digits.splice(); for (let digit = 0; digit < this.props.length; digit++) { if ( (!autoReveal && digit < value.length) || (autoReveal && digit < caretPos) ) digits[digit] = BULLET; else digits[digit] = null; } if (autoReveal) { const char = value.substr(caretPos); digits[caretPos] = char; const that = this; this.revealer = setTimeout(function() { digits[caretPos] = BULLET; that.setState({ digits }); }, REVEAL_TIMEOUT); } this.setState({ digits, caret: caretPos, value }); } render() { return ( <View> <View style={{ flex: 1, flexDirection: "row" }}> {this.state.digits.map((digit, index) => <View key={index} style={{ flex: 1, flexDirection: "row", borderRadius: 6, borderWidth: 1, backgroundColor: "white", borderColor: "#C3C3C3", marginLeft: 6, marginRight: 6, height: 50, alignItems: "center", justifyContent:"center" }} > <Text style={{ fontSize: 18, textAlign: "center" }} > {digit} </Text> </View> )} </View> </View> ); } } <file_sep>/src/screens/sign-up/index.js import React, { Component } from "react"; import { ImageBackground, View, StatusBar } from "react-native"; import { Container, Button, H3, Text, Footer, FooterTab, Icon } from "native-base"; import styles from "./styles"; import StillBackground from '../stillBackground' // const launchscreenBg = url("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"); const launchscreenLogo = {uri: 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'} class Home extends Component { static navigationOptions = { title:null, headerLeft:null, header: null }; render() { return ( <Container> <StatusBar barStyle="light-content" /> <StillBackground> <View style={styles.logoContainer}> <ImageBackground source={launchscreenLogo} style={styles.logo} /> </View> <View style={{ alignItems: "center", marginBottom: 50, backgroundColor: "transparent" }} > <H3 style={styles.text}>App to showcase</H3> <View style={{ marginTop: 8 }} /> <H3 style={styles.text}>NativeBase components</H3> <View style={{ marginTop: 8 }} /> </View> <Footer> <FooterTab> <Button active={this.state.tab1} onPress={() => this.toggleTab1()}> <Icon active={this.state.tab1} name="apps" /> <Text>Apps</Text> </Button> <Button active={this.state.tab2} onPress={() => this.toggleTab2()}> <Icon active={this.state.tab2} name="camera" /> <Text>Camera</Text> </Button> <Button active={this.state.tab3} onPress={() => this.toggleTab3()}> <Icon active={this.state.tab3} name="compass" /> <Text>Compass</Text> </Button> <Button active={this.state.tab4} onPress={() => this.toggleTab4()}> <Icon active={this.state.tab4} name="contact" /> <Text>Contact</Text> </Button> </FooterTab> </Footer> </StillBackground> </Container> ); } } export default Home; <file_sep>/src/screens/sign-up/personal-details.js import React, { Component } from "react"; import { ImageBackground, View, StatusBar, Keyboard } from "react-native"; import { Container, Button, H3, Text, Footer, FooterTab, Icon, Content, Form, Item, Label, Input } from "native-base"; import styles from "./styles"; class PersonalDetails extends Component { static navigationOptions = { title: "Personal details" // headerLeft:null, // header: null }; handleContinue() { Keyboard.dismiss() const { navigate } = this.props.navigation; navigate("Selfie"); } render() { return ( <Container style={styles.container}> <Content padder> <Form> <Item floatingLabel> <Label>Email</Label> <Input /> </Item> <Item floatingLabel> <Label>Phone number</Label> <Input /> </Item> </Form> </Content> <Footer> <FooterTab style={{ backgroundColor: "#FFF" }}> <Button iconLeft transparent onPress={() => { this.handleContinue(); }} // style={styles.mb15} > <Text style={{fontSize: 14}}>Continue</Text> </Button> </FooterTab> </Footer> </Container> ); } } export default PersonalDetails; <file_sep>/src/screens/home/index.js import React, { Component } from "react"; import { ImageBackground, View, StatusBar, Image, Dimensions } from "react-native"; import { Container, Button, H3, Text, Footer, FooterTab, Icon, Content } from "native-base"; import Video from "react-native-video"; import styles from "./styles"; import StillBackground from "../stillBackground"; const deviceWidth = Dimensions.get("window").width; const deviceHeight = Dimensions.get("window").height; // const launchscreenBg = url("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"); const launchscreenLogo = { uri: "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" }; class Home extends Component { static navigationOptions = ({ navigation }) => { const { params = {} } = navigation.state; return { title: null, headerLeft: <Icon name="menu" onPress={() => params.handleOpen()} /> }; }; constructor(props) { super(props); this.state = {}; } componentDidMount() { this.props.navigation.setParams({ handleOpen: this.handleOpenDrawer }); } handleOpenDrawer = () => { this.props.navigation.navigate("DrawerOpen"); }; render() { return ( <Container> <Video source={require("../../../assets/background.mp4")} // Can be a URL or a local file. rate={1} // 0 is paused, 1 is normal. muted={true} // Mutes the audio entirely. paused={false} // Pauses playback entirely. resizeMode="cover" // Fill the whole screen at aspect ratio. repeat={true} // Repeat forever. playInBackground={true} // Audio continues to play when app entering background. playWhenInactive={true} // [iOS] Video continues to play when control or notification center are shown. progressUpdateInterval={250.0} // [iOS] Interval to fire onProgress (default to ~250ms) style={{ position: "absolute", zIndex: 0, flex: 1, width: deviceWidth, height: deviceHeight }} /> <StatusBar barStyle="light-content" /> {/* <StillBackground> */} <View style={styles.logoContainer}> <Image source={launchscreenLogo} style={styles.logo} /> </View> <View style={{ alignItems: "center", marginBottom: 50, backgroundColor: "transparent" }} > <H3 style={styles.text}>App to showcase</H3> <View style={{ marginTop: 8 }} /> <H3 style={styles.text}>NativeBase components</H3> <View style={{ marginTop: 8 }} /> </View> {/* </StillBackground> */} </Container> ); } } export default Home; <file_sep>/src/screens/sign-up/tcs.js import React, { Component } from "react"; import { ImageBackground, View, ScrollView, Image, Alert } from "react-native"; import { Container, Button, H3, Text, Footer, FooterTab, // Icon, Content } from "native-base"; import Icon from "react-native-vector-icons/FontAwesome"; import AwesomeAlert from "react-native-awesome-alerts"; import styles from "./styles"; import StillBackground from "../stillBackground"; const launchscreenLogo = { uri: "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" }; class TermsAndCondition extends Component { static navigationOptions = { title: "Terms and condition" // headerLeft:null, // header: null }; constructor(props) { super(props); this.state = { showAlert: false }; } handleReject() { this.setState({showAlert: true}) // const { navigate } = this.props.navigation; // navigate("Landing"); // Alert.alert( // 'Alert Title', // 'My Alert Msg', // [ // {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')}, // {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, // {text: 'OK', onPress: () => navigate("Landing")}, // ], // { cancelable: false } // ) } handleAccept() { const { navigate } = this.props.navigation; navigate("PersonalDetails"); } handleConfirmReject() { const { navigate } = this.props.navigation; navigate("Landing") // Alert.alert( // "Alert Title", // "My Alert Msg", // [ // { // text: "Ask me later", // onPress: () => console.log("Ask me later pressed") // }, // { // text: "Cancel", // onPress: () => console.log("Cancel Pressed"), // style: "cancel" // }, // { text: "OK", onPress: () => navigate("Landing") } // ], // { cancelable: false } // ); } handleCancelReject() { // Alert.alert( // "Alert Title", // "My Alert Msg", // [ // { // text: "Ask me later", // onPress: () => console.log("Ask me later pressed") // }, // { // text: "Cancel", // onPress: () => console.log("Cancel Pressed"), // style: "cancel" // }, // { text: "OK", onPress: () => console.log("OK Pressed") } // ], // { cancelable: false } // ); this.setState({showAlert: false}) } render() { const { showAlert } = this.state; return ( <Container style={styles.container}> <Content padder> <Text style={{ paddingHorizontal: 10, paddingVertical: 15 }}> What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. <NAME>, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc. </Text> </Content> <Footer> <FooterTab style={{ backgroundColor: "#FFF" }}> <Button iconLeft transparent onPress={() => { this.handleReject(); }} style={styles.mb15} > <Icon name="thumbs-down" size={26} /> <Text>Reject</Text> </Button> <Button iconLeft transparent onPress={() => { this.handleAccept(); }} style={styles.mb15} > <Icon name="thumbs-up" size={26} /> <Text>Accept</Text> </Button> </FooterTab> </Footer> <AwesomeAlert alertContainerStyle={{ position: "absolute", top: 0, bottom: 0, zIndex: 1000000 }} show={showAlert} showProgress={false} title="Warning" message="Are you sure want to reject terms and conditions" closeOnTouchOutside={true} closeOnHardwareBackPress={false} showCancelButton={true} showConfirmButton={true} cancelText="No, cancel" confirmText="Yes, reject" confirmButtonColor="#DD6B55" onCancelPressed={() => { this.handleCancelReject(); }} onConfirmPressed={() => { this.handleConfirmReject(); }} /> </Container> ); } } export default TermsAndCondition; <file_sep>/src/screens/sign-up/selfie.js import React, { Component } from "react"; import { ImageBackground, View, StatusBar, TouchableOpacity, Image } from "react-native"; import { Container, Button, H3, Text, Footer, FooterTab, Content, Form, Item, Label, Input } from "native-base"; import { RNCamera } from "react-native-camera"; import Icon from "react-native-vector-icons/FontAwesome"; import styles from "./styles"; class Selfie extends Component { static navigationOptions = { title: "Take selfie" // headerLeft:null, // header: null }; constructor(props) { super(props); this.state = { faceArray: {}, image: "" }; } takePicture = async function() { if (this.camera) { const options = { quality: 0.5, base64: true }; const data = await this.camera.takePictureAsync(options); this.setState({ image: data.base64 }); console.log(data); } }; handleFaceDetected(faceArray) { console.log("faceArray"); console.log(faceArray); this.setState({ faceArray: faceArray.faces[0].bounds.origin }); } handleRetake(){ this.setState({image: ""}) } handleContinue(){ const { navigate } = this.props.navigation; navigate("PinEntry"); } render() { const { image, faceArray } = this.state; return ( <Container style={styles.container}> {/* <Content padder> */} {image == "" ? <RNCamera ref={ref => { this.camera = ref; }} style={styles.preview} autoFocus={RNCamera.Constants.AutoFocus.on} autoFocusPointOfInterest={faceArray} type={RNCamera.Constants.Type.front} onFacesDetected={this.handleFaceDetected.bind(this)} faceDetectionMode={RNCamera.Constants.FaceDetection.Mode.fast} flashMode={RNCamera.Constants.FlashMode.off} permissionDialogTitle={"Permission to use camera"} permissionDialogMessage={ "We need your permission to use your camera phone" } onGoogleVisionBarcodesDetected={({ barcodes }) => { console.log(barcodes); }} /> : <Image style={styles.imagePreview} source={{ uri: "data:image/png;base64," + image }} />} {/* </Content> */} {image == "" ? <Footer > <FooterTab style={{ backgroundColor: "#FFF" }}> <Button onPress={this.takePicture.bind(this)} dark transparent> <Icon name="camera" size={36} /> </Button> </FooterTab> </Footer> : <Footer> <FooterTab style={{ backgroundColor: "#FFF" }}> <Button iconLeft transparent onPress={() => { this.handleRetake(); }} style={styles.mb15} > {/* <Icon name="thumbs-up" size={26} /> */} <Text style={{ fontSize: 16 }}>Retake</Text> </Button> <Button iconLeft transparent onPress={() => { this.handleContinue(); }} style={styles.mb15} > {/* <Icon name="thumbs-up" size={26} /> */} <Text style={{ fontSize: 16 }}>Continue</Text> </Button> </FooterTab> </Footer>} </Container> ); } } export default Selfie;
cbb2356617b5210f148a66e2e085431a5cadb5f3
[ "JavaScript" ]
11
JavaScript
aravind123cs/DJ-Mobile
e628dd37d6f36c0503b2d828a6a93aae86b124d8
6495194ebaec94b23cdb7f17a11e5b09497894d6
refs/heads/master
<file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # link load with extra tweaks for wmutils # with thanks to z3bra for the idea URL="$1" rawp() { case "$URL" in *paste.lisp.org/*) URL="$(echo $URL)/raw" ;; *pastebin.com/*) URL="http://pastebin.com/raw/$(echo $URL | cut -d/ -f 4)" ;; *pbin.in/*) URL="http://pbin.in/raw/$(echo $URL | cut -d/ -f 4)" ;; *paste.list.org/*) URL="http://paste.lisp.org/display/$(echo $URL | cut -d/ -f 4)/raw" ;; esac } openBrowser() { test ! -z $(wid.sh 'chrome') && { google-chrome-stable --new-tab "$URL" 2> /dev/null } || { windows.sh -s 2 google-chrome-stable --new-tab "$URL" 2> /dev/null } focus.sh "$(wid.sh 'chrome')" } # sync clipboards printf '%s\n' "$URL" | xsel -pi printf '%s\n' "$URL" | xsel -si printf '%s\n' "$URL" | xsel -bi case "$URL" in *.gifv|*.webm) exec mpv "$URL" --really-quiet --loop-file & ;; *.jp*g|*.png|*.webm|*.gif|*gfycat.com/*) mediad "$URL" ;; *imgur.com/a/?????*) openBrowser ;; *imgur.com/???????*) URL=$(printf '%s\n' "${URL}.png") mediad "$URL" ;; *.mkv|*.mp4|*.ogv|*youtube.com/watch*|*youtu.be/*|*.googlevideo.com/videoplayback*) exec mpv "$URL" --really-quiet & ;; *twitch.tv/*) livestreamer "$URL" source -Q ;; gopher://*) urxvt -e cgo "$URL" ;; *paste.lisp.org/*|*pastebin.com/raw*|*pbin.in/*) rawp urxvt -name "paste" -e zsh -i -c "curl -s '$URL' | $EDITOR -" ;; *.txt|*ix.io/*|*p.iotek.org/*|*sprunge.us/*|*bpaste.net/*|*pastebin.com*|*pbin.in/raw*) urxvt -name "paste" -e zsh -i -c "curl -s '$URL' | $EDITOR -" ;; *) openBrowser ;; esac <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # wrapper script around xscreenshot and ff2png fnmatch() { case "$2" in $1) return 0 ;; *) printf '%s\n' "Please enter a valid window id."; exit 1 ;; esac } img=${img:-./shot} test ! -z $1 && { fnmatch '0x*' "$1" && { xscreenshot "$1" | ff2png > "${img}.png" } } || { xscreenshot | ff2png > "${img}.png" } <file_sep>#!/bin/sh # # File : /home/wildefyr/v # Maintainer : Wildefyr | http://wildefyr.net # TODO: finish find upgrade if [ -z $1 ]; then exit fi find /media/storage/videos -type f -name "$1*" for i in $(seq $(cat $videolist | wc -l)); do video=$(cat $videolist | head -n $i | tail -1) if [[ $video == *"$2"* ]]; then echo $video > $tmpvideolist fi done if [ $(cat $tmpvideolist | wc -l) -eq 1 ]; then mpv "$(cat $tmpvideolist)" > /dev/null > /dev/null &! fi <file_sep>#!/bin/sh xset +fp ~/.fonts xset fp rehash fc-cache fc-cache -fv <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # dirty oneliner for uploading stuff to wildefyr.net FILES="$@" rsync -avr ${FILES} wildefyr.net:/builds/wildefyr.net/media -h --progress <file_sep>#!/bin/sh # # wildefyr - 2015 (c) wtfpl # launch dmenu filled with program suggestions and geometry set . fyrerc.sh cachedir=${XDG_CACHE_HOME:-"$HOME/.cache"} cache=$cachedir/dmenu_run rm $cache range=$(echo $PATH | grep : -o | wc -l) for i in $(seq $range); do ls -lL $(echo $PATH | cut -d: -f $i) | awk '{print $NF}' >> $cache done cat $HOME/.zsh/aliases.zsh | cut -d= -f1 | sed 's/alias //g' | \ sed '/#/d' | sort | uniq -u >> $cache barx=$((0)) bary=$((0)) barw=$((SW)) barh=$((25 - BW)) bar_font=$(awk '/.font/ {print $3}' < ~/.Xresources) cat $cache | dmenu -x $barx -y $bary -w $barw -h $barh -l 0 -fn $bar_font \ -nf '#D7D7D7' -sf '#B23450' -nb '#03070B' -sb '#03070B' "$@" | \ sed 's#$#\&#' | ${SHELL:-"/bin/zsh"} <file_sep>#!/bin/sh xcapectrl() { pgrep xcape 2>&1 > /dev/null && pkill xcape 2>&1 > /dev/null || \ xcape -e 'Control_L=Escape' -t 500 } case $1 in poker) xmodmap ~/wildconfig/bindings/poker xcapectrl ;; quickfire) xmodmap ~/wildconfig/bindings/quickfire xcapectrl ;; chrbook) xmodmap ~/wildconfig/bindings/chrbook xcapectrl ;; *) xmodmap ~/wildconfig/bindings/poker xcapectrl ;; esac <file_sep>#!/bin/sh # Script by Ypnose - http://ypnose.org # Query PKGBUILD online # TODO: REWORK DAT UGLY CRAP! usage() { printf "%s\n" "Usage: ${0##*/} [-a]" printf "%s\n" " OPTARG:" printf "%s\n" " -a Search package on AUR." printf "%s\n\n" "If OPTARG is empty, pkgcat will query package on [core], [extra] and then [community] repos." } if [ -z "$1" ] || [ "$1" = -h ]; then usage exit 1 fi LET="$(echo $2 | awk '{print substr ($0, 0, 2)}')" AUR="https://aur.archlinux.org/packages/$LET/$2/PKGBUILD" URLP="https://projects.archlinux.org/svntogit/packages.git/plain/trunk/PKGBUILD?h=packages/$1" URLC="https://projects.archlinux.org/svntogit/community.git/plain/trunk/PKGBUILD?h=packages/$1" if [ "$1" = "-a" ] && [ "$#" -eq 2 ]; then printf "\033[1;32m%s\033[0m\n" "Searching on AUR..." if [ -z "$(curl -s $AUR | awk '/404/')" ]; then printf "\n%s\n" "$(curl -s $AUR)" exit 0 else printf "\033[1;31m%s\033[0m\n" "Package not found!" exit 1 fi fi printf "\033[1;32m%s\033[0m\n" "Trying core / extra repo..." if [ "$(curl -s $URLP | awk 'NR == 1 {print $1}')" != "<!DOCTYPE" ]; then printf "\n%s\n" "$(curl -s $URLP)" exit 0 else printf "\033[1;31m%s\033[0m\n" "Package not found in core / extra" printf "\033[1;32m%s\033[0m\n" "Trying community repo..." if [ "$(curl -s $URLC | awk 'NR == 1 {print $1}')" != "<!DOCTYPE" ]; then printf "\n%s\n" "$(curl -s $URLC)" exit 0 else printf "\033[1;31m%s\033[0m\n" "Package not found!" exit 1 fi fi exit 0 <file_sep>#!/bin/sh clear FILE=$HOME/.notes test -f $FILE && rm -f $NOTES while true; do read -r line echo $line >> $FILE done <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # a fairly nice info script f0=''; f1=''; f2=''; f3='' f4=''; f5=''; f6=''; f7='' b0=''; b1=''; b2=''; b4='' b4=''; b5=''; b6=''; b7='' B=''; R=''; I='' USER="$USER" HOST="$(hostname)" test "$HOST" = "wildefyr-crux" && { SYS="$(crux)" PACK="$(pkginfo -i | wc -l)" } || { SYS="DEBIAN version $(cat /etc/debian_version)" PACK=$(dpkg-query -f '${binary:Package}\n' -W | wc -l) } KERN="$(uname -sr)" TIME="$(uptime -p | sed s:"up "::)" ps ux | grep -v grep | grep "mpv" -q && { M="$(mpvc -f '%artist% - %title%')" } clear=$(tput sgr0) clear cat << EOF $(wild) $R $f7$B$I$b6█$I$b0 $USER@$HOST $I$b7 $R $f7$B$I$b6█$I$b0 $KERN - $TIME $R $f7$B$I$b6█$I$b0 $SYS - $PACK Packages $R EOF test ! -z "$M" && { cat << MUSIC $f7$B$I$b6█$I$b0 $M $R MUSIC } printf '\n' <file_sep>#!/bin/sh # # wildefyr - 2015 (c) wtfpl # get nvidia gpu information # relies on nvidia-smi ARGS="$@" usage () { cat <<EOF usage: $(basename $0) [] l: List gpu(s). t: Print tempreture of gpu. h: Show this help. EOF test -z $1 || exit $1 } listgpu() { nvidia-smi -L | cut -d\ -f 3-5 } gputemp() { nvidia-smi -q -d TEMPERATURE | awk '/Current/ {print $5}' } main() { type nvidia-smi 2>&1 > /dev/null || { printf '%s\n' "nvidia-smi is not installed on your $$PATH." exit 1 } case $1 in l) listgpu ;; t) gputemp ;; *) usage 0 ;; esac } main $ARGS <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # colour output script for irc usage mainly ARGS="$@" usage() { cat << EOF Usage: $(basename $0) [color] [back] [message] EOF test $# -eq 0 || exit $1 } main() { case $1 in h|help|-h|--help) usage 0 ;; esac f0=''; f1=''; f2=''; f3='' f4=''; f5=''; f6=''; f7='' b0=''; b1=''; b2=''; b4='' b4=''; b5=''; b6=''; b7='' B=''; R=''; I='' case $1 in b) CLR="$f0" ;; r) CLR="$f1" ;; g) CLR="$f2" ;; m) CLR="$f3" ;; d) CLR="$f4" ;; p) CLR="$f5" ;; c) CLR="$f6" ;; w) CLR="$f7" ;; *) usage 1 ;; esac case $2 in b) BACK="$b0" ;; r) BACK="$b1" ;; g) BACK="$b2" ;; m) BACK="$b3" ;; d) BACK="$b4" ;; p) BACK="$b5" ;; c) BACK="$b6" ;; w) BACK="$b7" ;; esac test -z "$BACK" && { MESSAGE=$(echo "$@" | cut -d\ -f 2-) } || { MESSAGE=$(echo "$@" | cut -d\ -f 3-) } cat << EOF $CLR$B$BACK$MESSAGE$R EOF } main $ARGS <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # perform a trace of a shell script and log the results test -z "$1" && { printf '%s\n' "No script given." exit 1 } sh -x "$@" 2> /tmp/shtrace $EDITOR /tmp/shtrace <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # quick n' dirty script to transfer folder from flac to mp3 for file in *.flac; do ffmpeg -i "$file" -qscale:a 0 $(printf '%s\n' "$file" | sed 's/.flac/.mp3/') done <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # produce my bar information ACTIVE="%{F#D7D7D7}" INACTIVE="%{F#737373}" whiteSpace=$(printf '%s' " ") string="$whiteSpace%{l}$(taskbar.sh)" string="${string}%{r}${ACTIVE}" mpvcinfo=$(mpvc -f "%status% | %title% | #%position%/%playlistlength% | %volume%%" 2> /dev/null) string="${string}\ %{A1:mpvc toggle:}\ %{A3:mpvc next:}\ %{A4:mpvc volume +5:}\ %{A5:mpvc volume -5:}\ ${mpvcinfo}\ %{A}%{A}%{A}%{A}" string="${string} " volume=$(amixer get Master | sed -n 's/^.*\[\([0-9]\+\)%.*$/\1/p') dateFormat=$(date '+%d %b %T') cputemp=$(cpu t) string="${string}${ACTIVE}\ %{A4:amixer -c 0 set Master 2db+ unmute -q:}\ %{A5:amixer -c 0 set Master 2db- unmute -q:}\ ${cputemp}C | ${volume}% | ${dateFormat}${whiteSpace}${whiteSpace}\ %{A}%{A}" printf '%s\n' "${string}" <file_sep>#!/bin/bash # # z3bra -- 2014-01-21 test -z "$1" && exit || FILENAME=$1 clear W3MIMGDISPLAY="/usr/lib/w3m/w3mimgdisplay" FONTH=10 # size of one terminal row FONTW=10 # size of one terminal column COLUMNS=`tput cols` LINES=`tput lines` width=$(identify "$FILENAME" | cut -d. -f 2 | cut -d\ -f 3 | cut -d'x' -f 1) height=$(identify "$FILENAME" | cut -d. -f 2 | cut -d\ -f 3 | cut -d'x' -f 2 | cut -d'+' -f 1) max_width=$(($FONTW * $COLUMNS)) max_height=$(($FONTH * $(($LINES - 2)))) # substract one line for prompt test $width -gt $max_width && { height=$(($height * $max_width / $width)) width=$max_width } test $height -gt $max_height && { width=$(($width * $max_height / $height)) height=$max_height } w3m_command="0;1;0;0;$width;$height;;;;;$FILENAME\n4;\n3;" tput cup $(($height/$FONTH)) 0 echo -e $w3m_command | $W3MIMGDISPLAY echo $width $max_width $height $max_height <file_sep>#!/bin/sh # # wildefyr - 2015 (c) wtfpl # sick console menu while :; do $HOME/bin/sysinfo printf '%s'"\033[0;36m>> \033[0;37m"; read -r action clear case "$action" in e|exit) exit ;; x|xinit) xinit ;; z|zsh) zsh ;; s|ssh) con ;; r|reboot) power.sh -r ;; p|poweroff) power.sh -p ;; d|dtach) dtach -A /tmp/irc -z weechat ;; m|muxserv) tmux attach || tmux new ;; esac done <file_sep>#!/bin/sh # # wildefyr & z3bra - (c) wtfpl 2015 # print cpu info ARGS="$@" usage () { cat <<EOF usage: $(basename $0) [hptn] p: Percentage of cpu used. t: Print tempreture of cpu. n: Number of running processes. h: Show this help. EOF test -z $1 || exit $1 } cpuperc () { LINE=`ps -eo pcpu |grep -vE '^\s*(0.0|%CPU)' |tr '\n' '+'|sed 's/+$//'` echo "`echo $LINE | bc`" } cpunumb() { ls /proc | grep -oE '^[0-9]*$' | wc -w } cputemp() { sensors | cut -d: -f 2 | sed '3!d;s/+//;s/\..*//;s/\ //g' } main() { case $1 in p) cpuperc ;; n) cpunumb ;; t) cputemp ;; *) usage 0 ;; esac } main $ARGS <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # wrapper for viewing media from the web ARGS="$@" usage() { printf '%s\n' "Usage: $(basename $0) <urls>" test -z $1 || exit $1 } main() { MEDIADIR=${IMAGEDIR:-/tmp/media} FILES="$@" test ! -d $MEDIADIR && mkdir -p $MEDIADIR for file in $FILES; do case $1 in *pub.iotek.org/*) fileLocation=$MEDIADIR/$(printf '%s' $file | cut -d/ -f 5) ;; *i.imgur.com*) fileLocation=$MEDIADIR/$(printf '%s' $file | cut -d/ -f 4) ;; *) fileLocation=$MEDIADIR/latest ;; esac wget "$file" -O "$fileLocation" -q mpv --really-quiet --loop-file "$fileLocation" done } main $ARGS <file_sep>#!/bin/sh file="$1" test ! -f "$file" && { printf '%s\n' "File doesn't exist!" exit 1 } ioup "$file" | xsel -i xsel -o | xsel -bi <file_sep>#!/bin/sh # # wildefyr - 2015 (c) wtfpl # wrapper for twitch.tv usage() { printf '%s\n' "usage: $(basename $0) <channelname> (quality)" exit 1 } test -z $1 && usage || channelName=$1 test -z $2 && quality="source" || quality=$2 livestreamer http://twitch.tv/"$channelName" $quality -Q & <file_sep>#!/bin/sh # # wildefyr && z3bra - (c) wtfpl 2016 # display relevant memory statistics usage () { cat <<EOF usage: $(basename $0) [-hptu] h : print help p : percentage of memory used (default) t : total available memory u : memory used EOF } # display the total of available memory in human readable format memtotal () { t=$(grep MemTotal /proc/meminfo | awk '{print $2}') memTotal=$(echo "$t / 1024" | bc) printf '%s\n' "${memTotal}M" } # display the memory used memused () { t=$(grep MemTotal /proc/meminfo | awk '{print $2}') f=$(grep MemFree /proc/meminfo | awk '{print $2}') b=$(grep ^Buffers /proc/meminfo | awk '{print $2}') c=$(grep ^Cached /proc/meminfo | awk '{print $2}') memUsed=$(echo "($t - $f - $c - $b) / 1024" | bc) printf '%s\n' "${memUsed}M" } # display the memory used in percentage memperc () { t=$(grep MemTotal /proc/meminfo | awk '{print $2}') f=$(grep MemFree /proc/meminfo | awk '{print $2}') b=$(grep ^Buffers /proc/meminfo | awk '{print $2}') c=$(grep ^Cached /proc/meminfo | awk '{print $2}') mem=`echo "100 * ($t - $f - $c - $b) / $t" | bc` printf '%s\n' "${mem}%" } case $1 in t) memtotal ;; u) memused ;; p) memperc ;; *) usage ;; esac <file_sep>#!/bin/sh # # onodera - onodera at openmailbox dot org # refactored by arianon - arianon at openmailbox dot org # further refactoring by wildefyr - wildefur at gmail dot com # creates a port template ARGS="$@" DEFAULT="wild-crux-ports" PACKAGER="wildefyr, me at wildefyr dot net" PORTSDIR=${PORTSDIR:-/usr/ports} usage() { cat << USAGE Usage: $(basename $0) [name] [directory] USAGE test -z $1 || exit $1 } color() { f0=''; f1=''; f2=''; f3='' f4=''; f5=''; f6=''; f7='' b0=''; b1=''; b2=''; b4='' b4=''; b5=''; b6=''; b7='' B=''; R=''; I='' cat << COLOR $f0$B$I$b6>$I$b7 $@ $I$b7$R COLOR } createPort() { test -d $PORTSDIR/$directory && { cd $PORTSDIR/$directory test -d $name && { test -f $name/Pkgfile && { # test for vimcat for colour output type vimcat 2>&1 > /dev/null && { vimcat $PORTSDIR/$directory/$name/Pkgfile } || { cat $PORTSDIR/$directory/$name/Pkgfile } printf '%s' "Edit Pkgfile? [Y/n]: "; read -r edit test "$edit" = "n" && { printf '%s' "Delete Port? [N/y]: "; read -r delete test "$delete" = "y" && { sudo rm -r $PORTSDIR/$directory/$name } || { printf '%s\n' "Exiting..." } exit } || { prt-get edit $name buildVerify exit } } } || { rm -rf $name mkdir $name } cd $name } || { printf '%s\n' "Not a valid directory." exit 1 } } getPortInfo() { color "Enter 'git' to add a git source." printf '%s' "Version: "; while read -r version; do test -z "$version" && { color "Version cannot be empty." printf '%s' "Version: " continue } break done test "$version" = "git" && { printf '%s' "Git Source: "; while read -r gitsource; do test -z "$gitsource" && { color "Git Source cannot be empty." printf '%s' "Git Source: " continue } test "$(echo "$gitsource" | grep -E '(https?|git)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]')" || { color "Git Source does not have a valid URL." printf '%s' "Git Source: " continue } break done color "Leave blank for 'master' branch." printf '%s' "Branch: "; while read -r branch; do test -z "$branch" && { branch="master" } break done } || { printf '%s' "Source: "; while read -r source; do test -z "$source" && { color "Source cannot be empty." printf '%s' "Source: " continue } break done } printf '%s' "Description: "; while read -r description; do test -z "$description" && { color "Description cannot be empty." printf '%s' "Description: " continue } test -z "$(echo "$description" | grep -o "^[A-Z]")" && { color "Descriptions should start with a capital letter." printf '%s' "Description: " continue } test -z "$(echo "$description" | grep -o "\.$")" && { color "Descriptions should end with a period." printf '%s' "Description: " continue } break done test "$version" = "git" && description="$description (git checkout)" printf '%s' "URL: "; while read -r url; do test -z "$url" && { color "URL cannot be empty." printf '%s' "URL: " continue } test "$(echo "$url" | grep -E '(https?|git|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]')" || { color "URL is not valid." printf '%s' "URL: " continue } break done printf '%s' "Depends on: "; while read -r deps; do test -n "$(echo "$deps" | grep -o ",")" && { color "Dependencies should only be separated by a space." printf '%s' "Dependencies: " continue } break done test "$version" = "git" && deps=" git $deps" || deps=" $deps" printf '%s' "Include 6c37 header? [Y/n]: "; read -r sixcthreeseven test "$sixcthreeseven" != "n" && { maintainer="yes" } } maintainerHeader() { test "$maintainer" = "yes" && { test "$version" = "git" && { printf '%s' "# Maintainer: 6c37 Team, https://github.com/6c37/crux-ports-git/issues" } || { printf '%s' "# Maintainer: 6c37 Team, https://github.com/6c37/crux-ports/issues" } } } cdpkg() { TAB="$(printf '\t')" test "$version" = "git" && { cat << GIT ${TAB}cd \$PKGMK_SOURCE_DIR ${TAB}if cd \$name; then ${TAB}${TAB}git fetch -q; git reset --hard origin/\$branch ${TAB}else ${TAB}${TAB}git clone $gitsource -b \$branch \$name ${TAB}${TAB}cd \$name ${TAB}fi GIT } || { cat << TARBALL ${TAB}cd \$name-\$version TARBALL } } createPkgfile() { cat > "Pkgfile" << EOTEMPLATE # Description: $description # URL: $url # Packager: $PACKAGER $(maintainerHeader) # Depends on:$deps name=$name version=$version release=1 source=($source) $(test "$version" = "git" && printf '%s' "branch=$branch") build() { $(cdpkg) } EOTEMPLATE } buildVerify() { printf '%s' "Build package now? [Y/n]: "; read -r confirm test "$confirm" != "n" && { test "$(prt-get listinst | grep $name)" = "$name" && { sudo prt-get update $name -fr } || { sudo prt-get depinst $name } prtverify $PORTSDIR/$directory/$name } } main() { # take first arg as name case $1 in h|-h|help|--help) usage 0 ;; *) test ! -z $1 && { name=$1 } || { printf '%s' "Name: "; read -r name } esac # take second arg as port repo test ! -z $2 && { directory=$2 } || { test ! -z $DEFAULT && { directory=$DEFAULT } || { find $PORTSDIR -maxdepth 1 -type d | cut -d/ -f 4 | sort printf '\n%s' "Directory: "; read -r directory } } createPort getPortInfo createPkgfile prt-get cache prt-get edit $name buildVerify } main $ARGS <file_sep>#!/bin/sh test -z $1 && { printf '%s\n' "Directory given cannot be empty." exit 1 } || { DIR=$1 } urxvt -cd $DIR & <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # I'm lazy okay? ip="192.168.1.221" mac="50:e5:49:3e:19:67" test "$(hostname)" = "wildefyr-chromebook" && { cmd="wakeonlan" } || { cmd="wol" } ${cmd} -i ${ip} ${mac} <file_sep>#!/bin/bash # # wildefyr - 2016 (c) wtfpl # simple notify script that uses fyre # depends on: lemonbar txtw && a sane unix environment # inspired by: http://blog.z3bra.org/2014/04/pop-it-up.html ARGS="$@" usage() { cat << EOF Usage: $(basename $0) [-d seconds] [-D] [-m message] -d : Duration of notification in seconds. -D : Disable notifiction sound. -m : Message to display. -h : Print this help. Exit codes: 0 : Progran ran succesfully. 1 : Argument Error 2 : Dependacy Error EOF test -z $1 && exit 0 || exit $1 } createDialog() { . fyrerc.sh # kill notify on new run POPNAME='pop' pidof -s $POPNAME 2>&1 > /dev/null && kill -9 $(pidof -s $POPNAME) POPUPFILE=${POPUPFILE:-/tmp/.popup} txtw -s 12 "$@" > $POPUPFILE barw=$(cat /tmp/.popup | awk '{for (i=1;i<=NF;++i) total += $i; print total}') test -f $POPUPFILE && rm $POPUPFILE bary=$((TGAP - 40 + BW)) barw=$((barw + 20 - 2*BW)) barh=$((XGAP - 2*BW)) barx=$((SW - XGAP - barw - 500 - BW)) bar_bg='#03070B' bar_fg='#D7D7D7' bar_font=$(awk '/.font/ {print $3}' < ~/.Xresources) test $SOUNDENABLED = "true" && playNotificationSound test $SOUNDENABLED = "true" && { DURATION=$(soxi $NOTIFICATION | \ awk '/Duration/ {printf "%s", $3}' | sed 's/00//g; s/://g') } || { DURATION=3 } (echo "%{c}$@"; sleep $DURATION) | { exec -a $POPNAME lemonbar -d -g ${barw}x${barh}+${barx}+${bary} -B${bar_bg} -F${bar_fg} -f ${bar_font} } killall backbar -q } playNotificationSound() { pkill "notification" -f play -q $NOTIFICATION 2>&1 > /dev/null & } validateDeps() { type txtw 2>&1 > /dev/null || { printf '%s\n' "txtw has not been found on your \$PATH." exit 2 } } main() { # has the user inputed *anything* test $# -eq 0 && usage 1 validateDeps NOTIFICATION=${NOTIFICATION:-~/files/sounds/notification.mp3} SOUNDENABLED=true for arg in "$@"; do case $arg in -d) DURATION=$arg DURATIONFLAG=false test "$MESSAGEFLAG" = "true" && MESSAGEFLAG=false ;; -D) SOUNDENABLED=false test "$MESSAGEFLAG" = "true" && MESSAGEFLAG=false ;; -?) test "$MESSAGEFLAG" = "true" && MESSAGEFLAG=false ;; -h) usage 0 ;; esac test "$MESSAGEFLAG" = "true" && \ ARGSTRING="$ARGSTRING $arg" case $arg in -m) MESSAGEFLAG=true ;; -d) DURATIONFLAG=true ;; esac done test -z "$ARGSTRING" && { printf '%s\n' "No message to print." } || { createDialog $ARGSTRING } } main $ARGS <file_sep>#!/bin/sh # # http://blog.robertelder.org/bash-one-liner-compose-music/ hexdump -v -e '/1 "%u\n"' < /dev/urandom | \ awk '{ split("0,2,3,5,7,8,10,12",a,","); \ for (i = 0; i < 1; i+= 0.0001) \ printf("%08X\n", 100*sin(1382*exp((a[$1 % 8]/12)*log(2))*i)) }' | \ xxd -r -p | aplay -c 4 -f S32_LE -r 4000 <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # dirty script to get hosts server=$(cat ~/.ssh/known_hosts | cut -f1 -d' ' | cut -d, -f1 | fzf --reverse) mosh $server 2> /dev/null <file_sep>#!/bin/sh # # wildefyr - 2015 (c) wtfpl # syslink files from dotfiledir to system options='-s -f -v -n' dotfiledir=${dotfiledir:-$HOME/wildconfig} usage() { cat << EOF Usage $(basename $0) <core|opt|xorg> EOF test -z $1 || exit $1 } core() { test -d ~/.vim/undo && mkdir -p -v ~/.vim/undo test -d ~/.vim/backup && mkdir -p -v ~/.vim/backup ln $options $dotfiledir/vim/vimrc ~/.vimrc ln $options $dotfiledir/vim/colors ~/.vim/colors ln $options $dotfiledir/vim/vimpagerrc ~/.vim/vimpagerrc ln $options $dotfiledir/zsh ~/.zsh ln $options $dotfiledir/zsh/zprofile ~/.zprofile ln $options $dotfiledir/tmuxinator ~/.tmuxinator ln $options $dotfiledir/tmuxinator/tmux.conf ~/.tmux.conf ln $options $dotfiledir/git/gitconfig ~/.gitconfig } opt() { test -d ~/.config/nvim && mkdir -v ~/.config/nvim ln $options $dotfiledir/vim/vimrc ~/.config/nvim/init.vim ln $options $dotfiledir/vim/colors ~/.config/nvim/colors } xorg() { ln $options $dotfiledir/fonts ~/.fonts ln $options $dotfiledir/visuals/xinitrc ~/.xinitrc ln $options $dotfiledir/visuals/Xresources ~/.Xresources ln $options $dotfiledir/mpv ~/.config/mpv ln $options $dotfiledir/youtube-dl ~/.config/youtube-dl ln $options $dotfiledir/sxiv ~/.config/sxiv } case $1 in c|core) core ;; o|opt) opt ;; x|xorg) xorg ;; *) usage 0 ;; esac <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # search for zsh aliases test -z $1 && exit cat ~/.zsh/aliases.zsh | grep $1 | sed s/'alias '// <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # mass process video urls for youtube-dl ARGS="$@" URLS="" usage() { cat << EOF usage $(basename $0) [directory] EOF test -z $1 || exit $1 } main() { test -z $1 && { directory="./" } || { directory=$1 } for i in $URLS; do youtube-dl $i --no-playlist -o "$directory /%(title)s" done } main $ARGS <file_sep>#!/bin/sh # # wildefyr - 2015 (c) wtfpl # lazy fzf function to kill processes KILL=$(ps ax | sed '1d' | fzf -m -x --tac | awk '{print $1}') kill -9 $KILL <file_sep>#!/bin/sh case $1 in net) cat ~/bin/.wildefyr3 | toilet -f term -w 200 -t --gay ;; 3d) cat ~/bin/.wildefyr2 | toilet -f term -w 200 -t --gay ;; *) cat ~/bin/.wildefyr | toilet -f term -w 200 -t --gay ;; esac <file_sep>#!/bin/sh # # wildefyr - 2016 (c) MIT # prepare hooks directory to be backed up git rev-parse --is-inside-git-dir 2>&1 > /dev/null && { TOPDIR="$(git rev-parse --show-toplevel)/.hooks" GITDIR="$(git rev-parse --git-dir)/hooks" test ! -d "$TOPDIR" && { rm -rf "$GITDIR/*.samples" cp -rf "$GITDIR" "$TOPDIR" rm -rf "$GITDIR" ln -sv "$TOPDIR" "$GITDIR" git add "$TOPDIR" git commit -m 'Add: custom git hooks' } || { printf '%s\n' "Custom hooks directory already exists!" exit 2 } } || { printf '%s\n' "You're not inside a git directory!" exit 1 } <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # create a new script in pwd test ! -z $1 && { filename=$1 } || { printf '%s' "Please enter filename: "; while read -r filename; do test -z $filename && { printf '%s' "Please enter filename: " continue } break done } printf "#!/bin/sh\n#\n" > $filename chmod +x $filename $EDITOR $filename <file_sep>#!/bin/sh # # wildefyr - 2016 (c) wtfpl # my bar backbar() { barx=$1 bary=$2 barw=$3 barh=$4 bar_bg=$5 while :; do printf '\n' sleep 100d done | lemonbar -d -g ${barw}x${barh}+${barx}+${bary} -B${bar_bg} -n "backbar" } runTaskbar() { while true; do barinfo sleep 0.1 done } . fyrerc.sh # set bar variables and launch backbar barx=$((0)) bary=$((0)) barw=$((SW)) barh=$((25)) bar_bg='#66D7D7D7' backbar $barx $bary $barw $barh $bar_bg & barh=$((barh - BW)) bar_bg='#03070B' bar_fg='#D7D7D7' bar_font=$(awk '/.font/ {print $3}' < ~/.Xresources) runTaskbar | lemonbar -d -g ${barw}x${barh}+${barx}+${bary} -B${bar_bg} \ -F${bar_fg} -f${bar_font} -n "mainbar" -a 100 | /bin/sh & <file_sep>#!/bin/sh # # strip color codes from output sed 's/\x1B\[[0-9;]*[JKmsu]//g'
5bce6c1f12948cbaa2625c0fe15aad663cb45cfa
[ "Shell" ]
37
Shell
Wildefyr/scripts
618063536bb709f042aa5f4fe55b8bb4e1d042bf
02ffe4a378bf043063eab05b6dadef28b6897f22
refs/heads/master
<repo_name>array-of-sunshine/algos<file_sep>/euler6.rb # very first thing you should do # make sure you understand the question/problem, solve it by hand # sum of the squares # (1 * 1) + (2 * 2) + (3 * 3) + (4 * 4) ... (10 * 10) # start with the number 1 -- DONE # increase that number by 1, some amount of times (probably a loop) -- DONE # figure out how to square a number -- DONE # add the numbers together (SUM) # sum = 0 # index = 1 # 100.times do # sum += index * index # index += 1 # end # sum_of_the_squares = sum # # square of the sum # # (1 + 2 + 3 + 4) ** 2 # # subtract the two numbers # # start off with number 1 -- DONE # # make a loop -- DONE # # add the numbers together # # square the end result # sum = 0 # index = 1 # 100.times do # sum += index # index += 1 # end # square_of_the_sums = sum * sum # p (square_of_the_sums - sum_of_the_squares) # The sum of the squares of the first ten natural numbers is, # 12 + 22 + ... + 102 = 385 # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. # REFACTORING # sum_of_the_squares = 0 # index = 1 # square_of_the_sums = 0 # 100.times do # sum_of_the_squares += index * index # square_of_the_sums += index # index += 1 # end # square_of_the_sums = square_of_the_sums * square_of_the_sums # p (square_of_the_sums - sum_of_the_squares) # apples = [12,5,2,1,5,3] # index = 0 # sum = 0 # apples.length.times do # sum += apples[index] # index += 1 # end # p sum # p apples.reduce(:+)
a35d2f71bb59ed69b95987c1a0efd9c6d59e362a
[ "Ruby" ]
1
Ruby
array-of-sunshine/algos
318d5141a47b471d5f5f12c7a70163c3b1fdc512
fd7b382d51cafb2c6137f4c543b3b08672ba60fe
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ListApp { public partial class NumberEntryUI : Form { List<double> numbers = new List<double>(); public NumberEntryUI() { InitializeComponent(); } private void addButton_Click(object sender, EventArgs e) { double number = Convert.ToDouble(numberTextBox.Text); numbers.Add(number); countTextBox.Text = numbers.Count.ToString(); } private void showAllButton_Click(object sender, EventArgs e) { double sum = 0; numberListBox.Items.Clear(); foreach (double aNumber in numbers) { numberListBox.Items.Add(aNumber); sum += aNumber; } sumTextBox.Text = sum.ToString(); } } } <file_sep>ListApp =======
5aa536160b3e8bbbd685f3382ef15fea2ce35ebf
[ "Markdown", "C#" ]
2
C#
taukir4u/ListApp
26ef7fb3285297277568c855c302449cc4069079
07dac98d8c63642b6cd62c58dc90825881fbbc3e
refs/heads/master
<file_sep># pluralsight_javascript Used to practice courses * Uso el paquete localtunnel(globally) to share my Work in Progress (WIP): lt --port 3000 --subdomain eltonina * We can use the snpm start -s to have a silence mode * The security check has been integrated in the nom command * Dependence of babel(transpiler), webpack(bundle) * To use Sourcemap to debug the app: debugger * Using ESLint as Linter * Testing - Framework: (Mocha), Jasmine, Tape, QUnit, Ava, Jest - Assertion: (Chai), Expect, Should - Helper Library: (JSDOM), Cheerio - Where test: (Node) + Browser: Karma, Testem + Headless Browser: PhantomJS + In-memory DOM (Node-JSDOM) - Where to place Test: Alongside (.spec or .test) - When test should run (When Saving) * Continuos Integration - Using Travis CI (Linux) -> SignUp with the GitHub account - Using AppVeyor CI(Windows) -> SignUp with the GitHub account * Fetch to call APIs * Mocking HTTP - JSON Schema faker (json-shema.org) - Generate Random Data + faker.js + chance.js + randexp.js - Serve Data via API + JSON Server<file_sep>/* This file contains reference to the vendor libraries we're using in this project. This is used by webpack in the production build only*. A separete bundle ffor vendor code is useful since it's unlikely to change as often as the application's code. So all the libraries we reference here will be written to vendorJs so they can be cached until one of them change. So basically, this avoids customers having to download a huge JS file anytime a line of code changes. They only have to download vendorJS when a vendor library changes which should be less frecuent. Any files that aren't referenced here will be bundle into mainJS for the production build. */ /* eslint-disable no-unused-vars */ import fetch from 'whatwg-fetch';
41895507cc77a2dfde57d24ca8eab32ac1ea4fb1
[ "Markdown", "JavaScript" ]
2
Markdown
eltonina/pluralsight_javascript
1081469fb1fda18934615cb17e9f4b2aa5a19930
2006d32eb026dcb6908a014a13cef3adf4f8c036
refs/heads/master
<file_sep>//business Logic //busines logic for LocationLog function LocationLog() { this.location = []; this.currentId = 0; } LocationLog.prototype.addLocation = function(location) { location.id = this.assignId(); this.location.push(location) } LocationLog.prototype.assignId = function() { this.currentId += 1; return this.currentId; } // business logic for Locations function Location(location, date, landmarks, notes) { this.location = location; this.date = date; this.landmarks = landmarks; this.notes = notes; } Location.prototype.details = function() { return "<div class='well'><p class = 'col-3-md location'>" + this.location + "</p><p class = 'col-9-md details'>" + this.date + "<br>" + this.landmarks + "<br>" + this.notes + "</p></div>" } //User Interface $(document).ready(function() { $("#inputForm").submit(function(){ event.preventDefault() let locationInput = new Location($("#location").val(), $("#date").val(), $("#landmarks").val(), $("#notes").val()) $("#outputRecord").append(locationInput.details()) //populate values }) $(document).on('click', 'div.well', function() { $(this).children("p.details").toggle(); }); }); <file_sep># _Places You've Been_ #### _Page to track places you have visited with information about the location and visit_ ##### __Created:__ 6/15/2020 ##### __Last Updated:__ 6/15/2020 ##### By _**<NAME> & <NAME>**_ ## Description _{detailed desc}_ ## Behaviors | Spec| Example input | Example Output | ----------- | ----------- | ----------- | | User enters a locatoin they have visited, displays in the output | "Kansas" | "Kansas" | | Addition details about the location/visit are saved when the form is submitted | "4/15/205">"Rose Garden, Timber's Stadium, Pioneer Square">"It rained the whole time but the food was great" | n/a | | When the location is clicked from the output, previously user entered details about the visit will display | click: "Portland" | "4/15/205">"Rose Garden, Timber's Stadium, Pioneer Square">"It rained the whole time but the food was great" | ## Setup/Installation Requirements ##### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Open by downloading: 1. Internet Browser 2. Code editor like VScode to view the codebase ##### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Open by downloading: 1. Download this repository onto your computer 2. Double click index.html to open it in your web browser ##### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Open via Bash/GitBash: 1. Clone this repository onto your computer: "git clone https://github.com/Lackeyt/places-you-have-been" 2. Navigate into the "places-you-have-been" directory in Visual Studio Code or preferred text editor: 3. Open the project "code ." 3. Open index.html in your browser: "open index.html" ##### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;View Directly in your Browser: * Navigate to {GH Pages URL} in your web browser. ## Known Bugs * n/a ## Support and contact details * Discord: TysonL#4409 * Email: <EMAIL> ## Technologies Used * Visual Studio Code * HTML * CSS * Bootstrap * Javascript * JQuery ## Resources: * ### License Copyright (c) 2020 **_<NAME>_** This software is licensed under the MIT license.
03954da9af997cf05e9bd845b68281eafe016b97
[ "JavaScript", "Markdown" ]
2
JavaScript
Lackeyt/places-you-have-been
96bde88c470fa92a77edcec8ad0e0a3e6a6f1156
6cb14f1ecbbe1808530d6c1a78bea8c8cfdf3cab
refs/heads/master
<file_sep># Import libraries import numpy as np import pandas as pd from time import time from sklearn.metrics import f1_score # Read student data student_data = pd.read_csv("student-data.csv") print("Student data read successfully!") #student_data.info() from IPython.display import display display(student_data.head(n=5)) # TODO: Calculate number of students n_students = len(student_data) # TODO: Calculate number of features n_features = student_data.shape[1]-1 # TODO: Calculate passing students n_passed = student_data[student_data['passed'] == 'yes'].shape[0] # TODO: Calculate failing students n_failed = student_data[student_data['passed'] == 'no'].shape[0] # TODO: Calculate graduation rate grad_rate = float(n_passed/n_students)*100 # Print the results print("Total number of students: {}".format(n_students)) print("Number of features: {}".format(n_features)) print("Number of students who passed: {}".format(n_passed)) print("Number of students who failed: {}".format(n_failed)) print("Graduation rate of the class: {:.2f}%".format(grad_rate)) # Extract feature columns feature_cols = list(student_data.columns[:-1]) # Extract target column 'passed' target_col = student_data.columns[-1] # Show the list of columns print ("Feature columns:\n{}".format(feature_cols)) print("\nTarget column: {}".format(target_col)) # Separate the data into feature data and target data (X_all and y_all, respectively) X_all = student_data[feature_cols] y_all = student_data[target_col] # Show the feature information by printing the first five rows print ("\nFeature values:") print( X_all.head()) def preprocess_features(X): ''' Preprocesses the student data and converts non-numeric binary variables into binary (0/1) variables. Converts categorical variables into dummy variables. ''' # Initialize new output DataFrame output = pd.DataFrame(index = X.index) # Investigate each feature column for the data for col, col_data in X.iteritems(): # If data type is non-numeric, replace all yes/no values with 1/0 if col_data.dtype == object: col_data = col_data.replace(['yes', 'no'], [1, 0]) # If data type is categorical, convert to dummy variables if col_data.dtype == object: # Example: 'school' => 'school_GP' and 'school_MS' col_data = pd.get_dummies(col_data, prefix = col) # Collect the revised columns output = output.join(col_data) return output X_all = preprocess_features(X_all) print( "Processed feature columns ({} total features):\n{}".format(len(X_all.columns), list(X_all.columns))) # TODO: Import any additional functionality you may need here from sklearn.model_selection import train_test_split # TODO: Set the number of training points num_train = 300 # Set the number of testing points num_test = X_all.shape[0] - num_train # TODO: Shuffle and split the dataset into the number of training and testing points above X_train , X_test , y_train , y_test = train_test_split(X_all,y_all,test_size=0.25,random_state=1) # Show the results of the split print("Training set has {} samples.".format(X_train.shape[0])) print("Testing set has {} samples.".format(X_test.shape[0])) def train_classifier(clf, X_train, y_train): ''' Fits a classifier to the training data. ''' # Start the clock, train the classifier, then stop the clock start = time() clf.fit(X_train, y_train) end = time() # Print the results print( "Trained model in {:.4f} seconds".format(end - start)) def predict_labels(clf, features, target): ''' Makes predictions using a fit classifier based on F1 score. ''' # Start the clock, make predictions, then stop the clock start = time() y_pred = clf.predict(features) end = time() # Print and return results print( "Made predictions in {:.4f} seconds.".format(end - start)) return f1_score(target.values, y_pred, pos_label='yes') def train_predict(clf, X_train, y_train, X_test, y_test): ''' Train and predict using a classifer based on F1 score. ''' # Indicate the classifier and the training set size print("Training a {} using a training set size of {}. . .".format(clf.__class__.__name__, len(X_train))) # Train the classifier train_classifier(clf, X_train, y_train) # Print the results of prediction for both training and testing print( "F1 score for training set: {:.4f}.".format(predict_labels(clf, X_train, y_train))) print("F1 score for test set: {:.4f}.".format(predict_labels(clf, X_test, y_test))) # TODO: Import the three supervised learning models from sklearn # from sklearn import model_A from sklearn.naive_bayes import GaussianNB # from sklearn import model_B from sklearn.tree import DecisionTreeClassifier # from sklearn import model_C from sklearn.svm import SVC # TODO: Initialize the three models clf_A = GaussianNB() clf_B = DecisionTreeClassifier() clf_C = SVC() # TODO: Set up the training set sizes X_train_100 = X_train.iloc[:100, :] y_train_100 = y_train.iloc[:100] X_train_200 = X_train.iloc[:200, :] y_train_200 = y_train.iloc[:200] X_train_300 = X_train.iloc[:300, :] y_train_300 = y_train.iloc[:300] # TODO: Execute the 'train_predict' function for each classifier and each training set size # train_predict(clf, X_train, y_train, X_test, y_test) for clf in [clf_A,clf_B,clf_C]: print("\n {} :\n".format(clf.__class__.__name__)) for i in [100,200,300]: train_predict(clf, X_train[:i], y_train[:i], X_test, y_test) # TODO: Import 'GridSearchCV' and 'make_scorer' from sklearn.grid_search import GridSearchCV from sklearn.metrics import make_scorer # TODO: Create the parameters list you wish to tune parameters = {'max_depth': np.arange(1, 10)} # TODO: Initialize the classifier clf = DecisionTreeClassifier() # TODO: Make an f1 scoring function using 'make_scorer' f1_scorer = make_scorer(f1_score,pos_label='yes') # TODO: Perform grid search on the classifier using the f1_scorer as the scoring method grid_obj = GridSearchCV(clf,parameters,f1_scorer) # TODO: Fit the grid search object to the training data and find the optimal parameters grid_obj = grid_obj.fit(X_train,y_train) # Get the estimator clf = grid_obj.best_estimator_ # Report the final F1 score for training and testing after parameter tuning print("\n Tuned model has a training F1 score of {:.4f}.\n".format(predict_labels(clf, X_train, y_train))) print("\n Tuned model has a testing F1 score of {:.4f}.\n".format(predict_labels(clf, X_test, y_test)))
cca7ff43515fd5643d4b024a988842f01495b0c3
[ "Python" ]
1
Python
kpatel4241/student_intervention
fcf378e7d29074078c2b0afa566bcbd3eb8d2646
9879ac09b4203dc5b0a9d90e4fd9b097b439cf44
refs/heads/master
<file_sep># ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** """ | :class:`pandas.Series` functions and operators implementations in SDC | Also, it contains Numba internal operators which are required for Series type handling """ import numba import numpy import operator import pandas import math import sys from numba.errors import TypingError from numba.typing import signature from numba.extending import intrinsic from numba import (types, numpy_support, cgutils) from numba.typed import Dict from numba import prange import sdc import sdc.datatypes.common_functions as common_functions from sdc.datatypes.common_functions import (TypeChecker, check_index_is_numeric, find_common_dtype_from_numpy_dtypes, sdc_join_series_indexes, sdc_arrays_argsort) from sdc.datatypes.hpat_pandas_rolling_types import ( gen_sdc_pandas_rolling_overload_body, sdc_pandas_rolling_docstring_tmpl) from sdc.datatypes.hpat_pandas_series_rolling_types import _hpat_pandas_series_rolling_init from sdc.datatypes.hpat_pandas_stringmethods_types import StringMethodsType from sdc.datatypes.hpat_pandas_getitem_types import SeriesGetitemAccessorType from sdc.hiframes.pd_series_type import SeriesType from sdc.str_arr_ext import (StringArrayType, string_array_type, str_arr_is_na, str_arr_set_na, num_total_chars, pre_alloc_string_array, cp_str_list_to_array, make_str_arr_from_list, str_arr_set_na_by_mask) from sdc.utils import to_array, sdc_overload, sdc_overload_method, sdc_overload_attribute from sdc.datatypes import hpat_pandas_series_autogenerated from .pandas_series_functions import apply @sdc_overload(operator.getitem) def hpat_pandas_series_accessor_getitem(self, idx): """ Pandas Series operator :attr:`pandas.Series.get` implementation **Algorithm**: result = series[idx] **Test**: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_static_getitem_series1 Parameters ---------- series: :obj:`pandas.Series` input series idx: :obj:`int`, :obj:`slice` or :obj:`pandas.Series` input index Returns ------- :class:`pandas.Series` or an element of the underneath type object of :class:`pandas.Series` """ _func_name = 'Operator getitem().' if not isinstance(self, SeriesGetitemAccessorType): return None accessor = self.accessor.literal_value if accessor == 'iloc': if isinstance(idx, (types.List, types.Array, types.SliceType)): def hpat_pandas_series_iloc_list_slice_impl(self, idx): result_data = self._series._data[idx] result_index = self._series.index[idx] return pandas.Series(result_data, result_index, self._series._name) return hpat_pandas_series_iloc_list_slice_impl if isinstance(idx, (int, types.Integer)): def hpat_pandas_series_iloc_impl(self, idx): return self._series._data[idx] return hpat_pandas_series_iloc_impl def hpat_pandas_series_iloc_callable_impl(self, idx): index = numpy.asarray(list(map(idx, self._series._data))) return pandas.Series(self._series._data[index], self._series.index[index], self._series._name) return hpat_pandas_series_iloc_callable_impl raise TypingError('{} The index must be an Integer, Slice or List of Integer or a callable.\ Given: {}'.format(_func_name, idx)) if accessor == 'iat': if isinstance(idx, (int, types.Integer)): def hpat_pandas_series_iat_impl(self, idx): return self._series._data[idx] return hpat_pandas_series_iat_impl raise TypingError('{} The index must be a Integer. Given: {}'.format(_func_name, idx)) if accessor == 'loc': # Note: Loc return Series # Note: Loc slice and callable with String is not implemented # Note: Loc slice without start is not supported min_int64 = numpy.iinfo('int64').min max_int64 = numpy.iinfo('int64').max index_is_none = (self.series.index is None or isinstance(self.series.index, numba.types.misc.NoneType)) if isinstance(idx, types.SliceType) and not index_is_none: def hpat_pandas_series_loc_slice_impl(self, idx): series = self._series index = series.index start_position = len(index) stop_position = 0 max_diff = 0 min_diff = 0 start_position_inc = len(index) start_position_dec = len(index) stop_position_inc = 0 stop_position_dec = 0 idx_start = idx.start idx_stop = idx.stop for i in numba.prange(len(index)): if index[i] >= idx_start: start_position_inc = min(start_position_inc, i) if index[i] <= idx_start: start_position_dec = min(start_position_dec, i) if index[i] <= idx_stop: stop_position_inc = max(stop_position_inc, i) if index[i] >= idx_stop: stop_position_dec = max(stop_position_dec, i) if i > 0: max_diff = max(max_diff, index[i] - index[i - 1]) min_diff = min(min_diff, index[i] - index[i - 1]) if max_diff*min_diff < 0: raise ValueError("Index must be monotonic increasing or decreasing") if max_diff > 0: start_position = start_position_inc stop_position = stop_position_inc if idx_stop < index[0]: return pandas.Series(data=series._data[:0], index=series._index[:0], name=series._name) else: start_position = start_position_dec stop_position = stop_position_dec if idx.stop != max_int64 else len(index) if idx_stop > index[0] and idx_stop != max_int64: return pandas.Series(data=series._data[:0], index=series._index[:0], name=series._name) stop_position = min(stop_position + 1, len(index)) if ( start_position >= len(index) or stop_position <= 0 or stop_position <= start_position ): return pandas.Series(data=series._data[:0], index=series._index[:0], name=series._name) return pandas.Series(data=series._data[start_position:stop_position], index=index[start_position:stop_position], name=series._name) return hpat_pandas_series_loc_slice_impl if isinstance(idx, types.SliceType) and index_is_none: def hpat_pandas_series_loc_slice_noidx_impl(self, idx): max_slice = sys.maxsize start = idx.start stop = idx.stop if idx.stop == max_slice: stop = max_slice - 1 result_data = self._series._data[start:stop+1] result_index = numpy.arange(start, stop + 1) return pandas.Series(result_data, result_index, self._series._name) return hpat_pandas_series_loc_slice_noidx_impl if isinstance(idx, (int, types.Integer, types.UnicodeType, types.StringLiteral)): def hpat_pandas_series_loc_impl(self, idx): index = self._series.index mask = numpy.empty(len(self._series._data), numpy.bool_) for i in numba.prange(len(index)): mask[i] = index[i] == idx return pandas.Series(self._series._data[mask], index[mask], self._series._name) return hpat_pandas_series_loc_impl raise TypingError('{} The index must be an Number, Slice, String, List, Array or a callable.\ Given: {}'.format(_func_name, idx)) if accessor == 'at': if isinstance(idx, (int, types.Integer, types.UnicodeType, types.StringLiteral)): def hpat_pandas_series_at_impl(self, idx): index = self._series.index mask = numpy.empty(len(self._series._data), numpy.bool_) for i in numba.prange(len(index)): mask[i] = index[i] == idx return self._series._data[mask] return hpat_pandas_series_at_impl raise TypingError('{} The index must be a Number or String. Given: {}'.format(_func_name, idx)) raise TypingError('{} Unknown accessor. Only "loc", "iloc", "at", "iat" are supported.\ Given: {}'.format(_func_name, accessor)) @sdc_overload(operator.getitem) def hpat_pandas_series_getitem(self, idx): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.get Limitations ----------- Supported ``key`` can be one of the following: - Integer scalar, e.g. :obj:`series[0]` - A slice, e.g. :obj:`series[2:5]` - Another series Examples -------- .. literalinclude:: ../../../examples/series_getitem.py :language: python :lines: 27- :caption: Getting Pandas Series elements :name: ex_series_getitem .. command-output:: python ./series_getitem.py :cwd: ../../../examples .. todo:: Fix SDC behavior and add the expected output of the > python ./series_getitem.py to the docstring Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series operator :attr:`pandas.Series.get` implementation **Algorithm**: result = series[idx] **Test**: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_static_getitem_series1 Parameters ---------- series: :obj:`pandas.Series` input series idx: :obj:`int`, :obj:`slice` or :obj:`pandas.Series` input index Returns ------- :class:`pandas.Series` or an element of the underneath type object of :class:`pandas.Series` """ _func_name = 'Operator getitem().' if not isinstance(self, SeriesType): return None # Note: Getitem return Series index_is_none = isinstance(self.index, numba.types.misc.NoneType) index_is_none_or_numeric = index_is_none or (self.index and isinstance(self.index.dtype, types.Number)) index_is_string = not index_is_none and isinstance(self.index.dtype, (types.UnicodeType, types.StringLiteral)) if ( isinstance(idx, types.Number) and index_is_none_or_numeric or (isinstance(idx, (types.UnicodeType, types.StringLiteral)) and index_is_string) ): def hpat_pandas_series_getitem_index_impl(self, idx): index = self.index mask = numpy.empty(len(self._data), numpy.bool_) for i in numba.prange(len(index)): mask[i] = index[i] == idx return pandas.Series(self._data[mask], index[mask], self._name) return hpat_pandas_series_getitem_index_impl if (isinstance(idx, types.Integer) and index_is_string): def hpat_pandas_series_idx_impl(self, idx): return self._data[idx] return hpat_pandas_series_idx_impl if isinstance(idx, types.SliceType): # Return slice for str values not implement def hpat_pandas_series_getitem_idx_slice_impl(self, idx): return pandas.Series(self._data[idx], self.index[idx], self._name) return hpat_pandas_series_getitem_idx_slice_impl if ( isinstance(idx, (types.List, types.Array)) and isinstance(idx.dtype, (types.Boolean, bool)) ): def hpat_pandas_series_getitem_idx_list_impl(self, idx): return pandas.Series(self._data[idx], self.index[idx], self._name) return hpat_pandas_series_getitem_idx_list_impl if (index_is_none and isinstance(idx, SeriesType)): if isinstance(idx.data.dtype, (types.Boolean, bool)): def hpat_pandas_series_getitem_idx_list_impl(self, idx): index = numpy.arange(len(self._data)) if (index != idx.index).sum() == 0: return pandas.Series(self._data[idx._data], index[idx._data], self._name) return hpat_pandas_series_getitem_idx_list_impl def hpat_pandas_series_getitem_idx_list_impl(self, idx): res = numpy.copy(self._data[:len(idx._data)]) index = numpy.arange(len(self._data)) for i in numba.prange(len(res)): for j in numba.prange(len(index)): if j == idx._data[i]: res[i] = self._data[j] return pandas.Series(res, index[idx._data], self._name) return hpat_pandas_series_getitem_idx_list_impl if (isinstance(idx, SeriesType) and not isinstance(self.index, types.NoneType)): if isinstance(idx.data.dtype, (types.Boolean, bool)): # Series with str index not implement def hpat_pandas_series_getitem_idx_series_impl(self, idx): if (self._index != idx._index).sum() == 0: return pandas.Series(self._data[idx._data], self._index[idx._data], self._name) return hpat_pandas_series_getitem_idx_series_impl def hpat_pandas_series_getitem_idx_series_impl(self, idx): index = self.index data = self._data size = len(index) data_res = [] index_res = [] for value in idx._data: mask = numpy.zeros(shape=size, dtype=numpy.bool_) for i in numba.prange(size): mask[i] = index[i] == value data_res.extend(data[mask]) index_res.extend(index[mask]) return pandas.Series(data=data_res, index=index_res, name=self._name) return hpat_pandas_series_getitem_idx_series_impl raise TypingError('{} The index must be an Number, Slice, String, Boolean Array or a Series.\ Given: {}'.format(_func_name, idx)) @sdc_overload(operator.setitem) def hpat_pandas_series_setitem(self, idx, value): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.__setitem__ Examples -------- .. literalinclude:: ../../../examples/series_setitem_int.py :language: python :lines: 27- :caption: Setting Pandas Series elements :name: ex_series_setitem .. code-block:: console > python ./series_setitem_int.py 0 0 1 4 2 3 3 2 4 1 dtype: int64 > python ./series_setitem_slice.py 0 5 1 4 2 0 3 0 4 0 dtype: int64 > python ./series_setitem_series.py 0 5 1 0 2 3 3 0 4 1 dtype: int64 Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series operator :attr:`pandas.Series.set` implementation Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_setitem* Parameters ---------- series: :obj:`pandas.Series` input series idx: :obj:`int`, :obj:`slice` or :obj:`pandas.Series` input index value: :object input value Returns ------- :class:`pandas.Series` or an element of the underneath type object of :class:`pandas.Series` """ ty_checker = TypeChecker('Operator setitem.') ty_checker.check(self, SeriesType) if not (isinstance(idx, (types.Integer, types.SliceType, SeriesType))): ty_checker.raise_exc(idx, 'int, Slice, Series', 'idx') if not((isinstance(value, SeriesType) and isinstance(value.dtype, self.dtype)) or \ isinstance(value, type(self.dtype))): ty_checker.raise_exc(value, self.dtype, 'value') if isinstance(idx, types.Integer) or isinstance(idx, types.SliceType): def hpat_pandas_series_setitem_idx_integer_impl(self, idx, value): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_setitem_for_value Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_setitem_for_slice """ self._data[idx] = value return self return hpat_pandas_series_setitem_idx_integer_impl if isinstance(idx, SeriesType): def hpat_pandas_series_setitem_idx_series_impl(self, idx, value): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_setitem_for_series """ super_index = idx._data self._data[super_index] = value return self return hpat_pandas_series_setitem_idx_series_impl @sdc_overload_attribute(SeriesType, 'iloc') def hpat_pandas_series_iloc(self): """ Pandas Series method :meth:`pandas.Series.iloc` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_iloc* Parameters ---------- self: :obj:`pandas.Series` input series Returns ------- :obj:`series` returns an object of :obj:`series` """ _func_name = 'Attribute iloc().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_iloc_impl(self): return sdc.datatypes.hpat_pandas_getitem_types.series_getitem_accessor_init(self, 'iloc') return hpat_pandas_series_iloc_impl @sdc_overload_attribute(SeriesType, 'loc') def hpat_pandas_series_loc(self): """ Pandas Series method :meth:`pandas.Series.loc` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_loc* Parameters ---------- self: :obj:`pandas.Series` input series Returns ------- :obj:`series` returns an object of :obj:`series` """ _func_name = 'Attribute loc().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_loc_impl(self): return sdc.datatypes.hpat_pandas_getitem_types.series_getitem_accessor_init(self, 'loc') return hpat_pandas_series_loc_impl @sdc_overload_attribute(SeriesType, 'iat') def hpat_pandas_series_iat(self): """ Pandas Series method :meth:`pandas.Series.iat` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_iat* Parameters ---------- self: :obj:`pandas.Series` input series Returns ------- :obj:`series` returns an object of :obj:`series` """ _func_name = 'Attribute iat().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_iat_impl(self): return sdc.datatypes.hpat_pandas_getitem_types.series_getitem_accessor_init(self, 'iat') return hpat_pandas_series_iat_impl @sdc_overload_attribute(SeriesType, 'at') def hpat_pandas_series_at(self): """ Pandas Series method :meth:`pandas.Series.at` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_at* Parameters ---------- self: :obj:`pandas.Series` input series Returns ------- :obj:`series` returns an object of :obj:`series` """ _func_name = 'Attribute at().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_at_impl(self): return sdc.datatypes.hpat_pandas_getitem_types.series_getitem_accessor_init(self, 'at') return hpat_pandas_series_at_impl @sdc_overload_method(SeriesType, 'nsmallest') def hpat_pandas_series_nsmallest(self, n=5, keep='first'): """ Pandas Series method :meth:`pandas.Series.nsmallest` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_nsmallest* Parameters ---------- self: :obj:`pandas.Series` input series n: :obj:`int`, default 5 Return this many ascending sorted values. keep: :obj:`str`, default 'first' When there are duplicate values that cannot all fit in a Series of n elements: first : return the first n occurrences in order of appearance. last : return the last n occurrences in reverse order of appearance. all : keep all occurrences. This can result in a Series of size larger than n. *unsupported* Returns ------- :obj:`series` returns :obj:`series` """ _func_name = 'Method nsmallest().' if not isinstance(self, SeriesType): raise TypingError('{} The object\n given: {}\n expected: {}'.format(_func_name, self, 'series')) if not isinstance(n, (types.Omitted, int, types.Integer)): raise TypingError('{} The object n\n given: {}\n expected: {}'.format(_func_name, n, 'int')) if not isinstance(keep, (types.Omitted, str, types.UnicodeType, types.StringLiteral)): raise TypingError('{} The object keep\n given: {}\n expected: {}'.format(_func_name, keep, 'str')) def hpat_pandas_series_nsmallest_impl(self, n=5, keep='first'): if keep != 'first': raise ValueError("Method nsmallest(). Unsupported parameter. Given 'keep' != 'first'") # mergesort is used for stable sorting of repeated values indices = self._data.argsort(kind='mergesort')[:max(n, 0)] return self.take(indices) return hpat_pandas_series_nsmallest_impl @sdc_overload_method(SeriesType, 'nlargest') def hpat_pandas_series_nlargest(self, n=5, keep='first'): """ Pandas Series method :meth:`pandas.Series.nlargest` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_nlargest* Parameters ---------- self: :obj:`pandas.Series` input series n: :obj:`int`, default 5 Return this many ascending sorted values. keep: :obj:`str`, default 'first' When there are duplicate values that cannot all fit in a Series of n elements: first : return the first n occurrences in order of appearance. last : return the last n occurrences in reverse order of appearance. all : keep all occurrences. This can result in a Series of size larger than n. *unsupported* Returns ------- :obj:`series` returns :obj:`series` """ _func_name = 'Method nlargest().' if not isinstance(self, SeriesType): raise TypingError('{} The object\n given: {}\n expected: {}'.format(_func_name, self, 'series')) if not isinstance(n, (types.Omitted, int, types.Integer)): raise TypingError('{} The object n\n given: {}\n expected: {}'.format(_func_name, n, 'int')) if not isinstance(keep, (types.Omitted, str, types.UnicodeType, types.StringLiteral)): raise TypingError('{} The object keep\n given: {}\n expected: {}'.format(_func_name, keep, 'str')) def hpat_pandas_series_nlargest_impl(self, n=5, keep='first'): if keep != 'first': raise ValueError("Method nlargest(). Unsupported parameter. Given 'keep' != 'first'") # data: [0, 1, -1, 1, 0] -> [1, 1, 0, 0, -1] # index: [0, 1, 2, 3, 4] -> [1, 3, 0, 4, 2] (not [3, 1, 4, 0, 2]) # subtract 1 to ensure reverse ordering at boundaries indices = (-self._data - 1).argsort(kind='mergesort')[:max(n, 0)] return self.take(indices) return hpat_pandas_series_nlargest_impl @sdc_overload_attribute(SeriesType, 'shape') def hpat_pandas_series_shape(self): """ Pandas Series attribute :attr:`pandas.Series.shape` implementation **Algorithm**: result = series.shape **Test**: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_shape1 Parameters ---------- series: :obj:`pandas.Series` input series Returns ------- :obj:`tuple` a tuple of the shape of the underlying data """ _func_name = 'Attribute shape.' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_shape_impl(self): return self._data.shape return hpat_pandas_series_shape_impl @sdc_overload_method(SeriesType, 'std') def hpat_pandas_series_std(self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None): """ Pandas Series method :meth:`pandas.Series.std` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_std Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_std_unboxing Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_std_str Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_std_unsupported_params Parameters ---------- self: :obj:`pandas.Series` input series axis: :obj:`int`, :obj:`str` Axis along which the operation acts 0/None/'index' - row-wise operation 1/'columns' - column-wise operation *unsupported* skipna: :obj:`bool` exclude NA/null values level: :obj:`int`, :obj:`str` If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar *unsupported* ddof: :obj:`int` Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. numeric_only: :obj:`bool` Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. *unsupported* Returns ------- :obj:`scalar` returns :obj:`scalar` """ _func_name = 'Method std().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not isinstance(self.data.dtype, types.Number): msg = '{} The object must be a number. Given self.data.dtype: {}' raise TypingError(msg.format(_func_name, self.data.dtype)) if not isinstance(skipna, (types.Omitted, types.Boolean, types.NoneType)) and skipna is not None: raise TypingError('{} The object must be a boolean. Given skipna: {}'.format(_func_name, skipna)) if not isinstance(ddof, (types.Omitted, int, types.Integer)): raise TypingError('{} The object must be an integer. Given ddof: {}'.format(_func_name, ddof)) for name, arg in [('axis', axis), ('level', level), ('numeric_only', numeric_only)]: if not isinstance(arg, (types.Omitted, types.NoneType)) and arg is not None: raise TypingError('{} Unsupported parameters. Given {}: {}'.format(_func_name, name, arg)) def hpat_pandas_series_std_impl(self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None): var = self.var(axis=axis, skipna=skipna, level=level, ddof=ddof, numeric_only=numeric_only) return var ** 0.5 return hpat_pandas_series_std_impl @sdc_overload_attribute(SeriesType, 'values') def hpat_pandas_series_values(self): """ Pandas Series attribute 'values' implementation. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.values.html#pandas.Series.values Algorithm: result = series.values Where: series: pandas.series result: pandas.series as ndarray Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_values """ _func_name = 'Attribute values.' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_values_impl(self): return self._data return hpat_pandas_series_values_impl @sdc_overload_method(SeriesType, 'value_counts') def hpat_pandas_series_value_counts(self, normalize=False, sort=True, ascending=False, bins=None, dropna=True): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.value_counts Examples -------- .. literalinclude:: ../../../examples/series/series_value_counts.py :language: python :lines: 27- :caption: Getting the number of values excluding NaNs :name: ex_series_value_counts .. command-output:: python ./series/series_value_counts.py :cwd: ../../../examples .. note:: Parameter bins and dropna for Strings are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.count <pandas.Series.count>` Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.value_counts` implementation. Note: Elements with the same count might appear in result in a different order than in Pandas .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_value_counts* Parameters ----------- self: :obj:`pandas.Series` input series normalize: :obj:`boolean`, default False If True then the object returned will contain the relative frequencies of the unique values sort: :obj: `boolean`, default True Sort by frequencies ascending: :obj:`boolean`, default False Sort in ascending order bins: :obj:`integer`, default None *unsupported* dropna: :obj:`boolean`, default True Skip counts of NaN Returns ------- :returns :obj:`pandas.Series` """ _func_name = 'Method value_counts().' ty_checker = TypeChecker('Method value_counts().') ty_checker.check(self, SeriesType) if not isinstance(normalize, (types.Omitted, types.Boolean, bool)) and normalize is True: ty_checker.raise_exc(normalize, 'boolean', 'normalize') if not isinstance(sort, (types.Omitted, types.Boolean, bool)): ty_checker.raise_exc(sort, 'boolean', 'sort') if not isinstance(ascending, (types.Omitted, types.Boolean, bool)): ty_checker.raise_exc(ascending, 'boolean', 'ascending') if not isinstance(bins, (types.Omitted, types.NoneType)) and bins is not None: ty_checker.raise_exc(bins, 'boolean', 'bins') if not isinstance(dropna, (types.Omitted, types.Boolean, bool)): ty_checker.raise_exc(dropna, 'boolean', 'dropna') if isinstance(self.data, StringArrayType): def hpat_pandas_series_value_counts_str_impl( self, normalize=False, sort=True, ascending=False, bins=None, dropna=True): value_counts_dict = Dict.empty( key_type=types.unicode_type, value_type=types.intp ) nan_counts = 0 for i, value in enumerate(self._data): if str_arr_is_na(self._data, i): if not dropna: nan_counts += 1 continue value_counts_dict[value] = value_counts_dict.get(value, 0) + 1 need_add_nan_count = not dropna and nan_counts values = [key for key in value_counts_dict] counts_as_list = [value_counts_dict[key] for key in value_counts_dict.keys()] values_len = len(values) if need_add_nan_count: # append a separate empty string for NaN elements values_len += 1 values.append('') counts_as_list.append(nan_counts) counts = numpy.asarray(counts_as_list, dtype=numpy.intp) indexes_order = numpy.arange(values_len) if sort: indexes_order = counts.argsort() if not ascending: indexes_order = indexes_order[::-1] counts_sorted = numpy.take(counts, indexes_order) values_sorted_by_count = [values[i] for i in indexes_order] # allocate the result index as a StringArray and copy values to it result_index = make_str_arr_from_list(values_sorted_by_count) if need_add_nan_count: # set null bit for StringArray element corresponding to NaN element (was added as last in values) index_previous_nan_pos = values_len - 1 for i in numpy.arange(values_len): if indexes_order[i] == index_previous_nan_pos: str_arr_set_na(result_index, i) break return pandas.Series(counts_sorted, index=result_index, name=self._name) return hpat_pandas_series_value_counts_str_impl elif isinstance(self.dtype, types.Number): series_dtype = self.dtype def hpat_pandas_series_value_counts_number_impl( self, normalize=False, sort=True, ascending=False, bins=None, dropna=True): value_counts_dict = Dict.empty( key_type=series_dtype, value_type=types.intp ) zero_counts = 0 is_zero_found = False for value in self._data: if (dropna and numpy.isnan(value)): continue # Pandas hash-based value_count_float64 function doesn't distinguish between # positive and negative zeros, hence we count zero values separately and store # as a key the first zero value found in the Series if not value: zero_counts += 1 if not is_zero_found: zero_value = value is_zero_found = True continue value_counts_dict[value] = value_counts_dict.get(value, 0) + 1 if zero_counts: value_counts_dict[zero_value] = zero_counts unique_values = numpy.asarray( list(value_counts_dict), dtype=self._data.dtype ) value_counts = numpy.asarray( [value_counts_dict[key] for key in value_counts_dict], dtype=numpy.intp ) indexes_order = numpy.arange(len(value_counts)) if sort: indexes_order = value_counts.argsort() if not ascending: indexes_order = indexes_order[::-1] sorted_unique_values = numpy.take(unique_values, indexes_order) sorted_value_counts = numpy.take(value_counts, indexes_order) return pandas.Series(sorted_value_counts, index=sorted_unique_values, name=self._name) return hpat_pandas_series_value_counts_number_impl return None @sdc_overload_method(SeriesType, 'var') def hpat_pandas_series_var(self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None): """ Pandas Series method :meth:`pandas.Series.var` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_var Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_var_unboxing Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_var_str Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_var_unsupported_params Parameters ---------- self: :obj:`pandas.Series` input series axis: :obj:`int`, :obj:`str` Axis along which the operation acts 0/None/'index' - row-wise operation 1/'columns' - column-wise operation *unsupported* skipna: :obj:`bool` exclude NA/null values level: :obj:`int`, :obj:`str` If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar *unsupported* ddof: :obj:`int` Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. numeric_only: :obj:`bool` Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. *unsupported* Returns ------- :obj:`scalar` returns :obj:`scalar` """ _func_name = 'Method var().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not isinstance(self.data.dtype, types.Number): msg = '{} The object must be a number. Given self.data.dtype: {}' raise TypingError(msg.format(_func_name, self.data.dtype)) if not isinstance(skipna, (types.Omitted, types.Boolean, types.NoneType)) and skipna is not None: raise TypingError('{} The object must be a boolean. Given skipna: {}'.format(_func_name, skipna)) if not isinstance(ddof, (types.Omitted, int, types.Integer)): raise TypingError('{} The object must be an integer. Given ddof: {}'.format(_func_name, ddof)) for name, arg in [('axis', axis), ('level', level), ('numeric_only', numeric_only)]: if not isinstance(arg, (types.Omitted, types.NoneType)) and arg is not None: raise TypingError('{} Unsupported parameters. Given {}: {}'.format(_func_name, name, arg)) def hpat_pandas_series_var_impl(self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None): if skipna is None: skipna = True if skipna: valuable_length = len(self._data) - numpy.sum(numpy.isnan(self._data)) if valuable_length <= ddof: return numpy.nan return numpy.nanvar(self._data) * valuable_length / (valuable_length - ddof) if len(self._data) <= ddof: return numpy.nan return self._data.var() * len(self._data) / (len(self._data) - ddof) return hpat_pandas_series_var_impl @sdc_overload_attribute(SeriesType, 'index') def hpat_pandas_series_index(self): """ Pandas Series attribute :attr:`pandas.Series.index` implementation **Algorithm**: result = series.index **Test**: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_index1 python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_index2 Parameters ---------- series: :obj:`pandas.Series` input series Returns ------- :class:`pandas.Series` the index of the Series """ _func_name = 'Attribute index.' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if isinstance(self.index, types.NoneType) or self.index is None: def hpat_pandas_series_index_none_impl(self): return numpy.arange(len(self._data)) return hpat_pandas_series_index_none_impl else: def hpat_pandas_series_index_impl(self): return self._index return hpat_pandas_series_index_impl hpat_pandas_series_rolling = sdc_overload_method(SeriesType, 'rolling')( gen_sdc_pandas_rolling_overload_body(_hpat_pandas_series_rolling_init, SeriesType)) hpat_pandas_series_rolling.__doc__ = sdc_pandas_rolling_docstring_tmpl.format( ty='Series', ty_lower='series') @sdc_overload_attribute(SeriesType, 'size') def hpat_pandas_series_size(self): """ Pandas Series attribute :attr:`pandas.Series.size` implementation .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_size Parameters ---------- series: :obj:`pandas.Series` input series Returns ------- :class:`pandas.Series` Return the number of elements in the underlying data. """ _func_name = 'Attribute size.' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_size_impl(self): return len(self._data) return hpat_pandas_series_size_impl @sdc_overload_attribute(SeriesType, 'str') def hpat_pandas_series_str(self): """ Pandas Series attribute :attr:`pandas.Series.str` implementation .. only:: developer Test: python -m sdc.runtests sdc.tests.test_hiframes.TestHiFrames.test_str_get Parameters ---------- series: :obj:`pandas.Series` input series Returns ------- :class:`pandas.core.strings.StringMethods` Output class to manipulate with input data. """ _func_name = 'Attribute str.' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not isinstance(self.data.dtype, (types.List, types.UnicodeType)): msg = '{} Can only use .str accessor with string values. Given: {}' raise TypingError(msg.format(_func_name, self.data.dtype)) def hpat_pandas_series_str_impl(self): return pandas.core.strings.StringMethods(self) return hpat_pandas_series_str_impl @sdc_overload_attribute(SeriesType, 'ndim') def hpat_pandas_series_ndim(self): """ Pandas Series attribute :attr:`pandas.Series.ndim` implementation .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_getattr_ndim Parameters ---------- self: :obj:`pandas.Series` input series Returns ------- :obj:`int` Number of dimensions of the underlying data, by definition 1 """ _func_name = 'Attribute ndim.' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_ndim_impl(self): return 1 return hpat_pandas_series_ndim_impl @sdc_overload_attribute(SeriesType, 'T') def hpat_pandas_series_T(self): """ Pandas Series attribute :attr:`pandas.Series.T` implementation .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_getattr_T Parameters ---------- self: :obj:`pandas.Series` input series Returns ------- :obj:`numpy.ndarray` An array representing the underlying data """ _func_name = 'Attribute T.' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_T_impl(self): return self._data return hpat_pandas_series_T_impl @sdc_overload(len) def hpat_pandas_series_len(self): """ Pandas Series operator :func:`len` implementation .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_len Parameters ---------- series: :class:`pandas.Series` Returns ------- :obj:`int` number of items in the object """ _func_name = 'Operator len().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) def hpat_pandas_series_len_impl(self): return len(self._data) return hpat_pandas_series_len_impl @sdc_overload_method(SeriesType, 'astype') def hpat_pandas_series_astype(self, dtype, copy=True, errors='raise'): """ Pandas Series method :meth:`pandas.Series.astype` implementation. Cast a pandas object to a specified dtype dtype .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_astype* Parameters ----------- dtype : :obj:`numpy.dtype` or :obj:`dict` Use a numpy.dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, …}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types. copy : :obj:`bool`, default :obj:`True` Return a copy when True Currently copy=False is not supported errors : :obj:`str`, default :obj:`'raise'` Control raising of exceptions on invalid data for provided dtype. * raise : allow exceptions to be raised * ignore : suppress exceptions. On error return original object Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` Cast a :obj:`pandas.Series` to a specified dtype dtype """ _func_name = 'Method astype().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given self: {}'.format(_func_name, self)) if not isinstance(copy, (types.Omitted, bool, types.Boolean)): raise TypingError('{} The object must be a boolean. Given copy: {}'.format(_func_name, copy)) if (not isinstance(errors, (types.Omitted, str, types.UnicodeType, types.StringLiteral)) and errors in ('raise', 'ignore')): raise TypingError('{} The object must be a string literal. Given errors: {}'.format(_func_name, errors)) # Return StringArray for astype(str) or astype('str') def hpat_pandas_series_astype_to_str_impl(self, dtype, copy=True, errors='raise'): num_chars = 0 arr_len = len(self._data) # Get total chars for new array for i in prange(arr_len): item = self._data[i] num_chars += len(str(item)) # TODO: check NA data = pre_alloc_string_array(arr_len, num_chars) for i in prange(arr_len): item = self._data[i] data[i] = str(item) # TODO: check NA return pandas.Series(data, self._index, self._name) # Return npytypes.Array from npytypes.Array for astype(types.functions.NumberClass), example - astype(np.int64) def hpat_pandas_series_astype_numba_impl(self, dtype, copy=True, errors='raise'): return pandas.Series(self._data.astype(dtype), self._index, self._name) # Return npytypes.Array from npytypes.Array for astype(types.StringLiteral), example - astype('int64') def hpat_pandas_series_astype_literal_type_numba_impl(self, dtype, copy=True, errors='raise'): return pandas.Series(self._data.astype(numpy.dtype(dtype)), self._index, self._name) # Return self def hpat_pandas_series_astype_no_modify_impl(self, dtype, copy=True, errors='raise'): return pandas.Series(self._data, self._index, self._name) if ((isinstance(dtype, types.Function) and dtype.typing_key == str) or (isinstance(dtype, types.StringLiteral) and dtype.literal_value == 'str')): return hpat_pandas_series_astype_to_str_impl # Needs Numba astype impl support converting unicode_type to NumberClass and other types if isinstance(self.data, StringArrayType): if isinstance(dtype, types.functions.NumberClass) and errors == 'raise': raise TypingError(f'Needs Numba astype impl support converting unicode_type to {dtype}') if isinstance(dtype, types.StringLiteral) and errors == 'raise': try: literal_value = numpy.dtype(dtype.literal_value) except: pass # Will raise the exception later else: raise TypingError(f'Needs Numba astype impl support converting unicode_type to {dtype.literal_value}') if isinstance(self.data, types.npytypes.Array) and isinstance(dtype, types.functions.NumberClass): return hpat_pandas_series_astype_numba_impl if isinstance(self.data, types.npytypes.Array) and isinstance(dtype, types.StringLiteral): try: literal_value = numpy.dtype(dtype.literal_value) except: pass # Will raise the exception later else: return hpat_pandas_series_astype_literal_type_numba_impl # Raise error if dtype is not supported if errors == 'raise': raise TypingError(f'{_func_name} The object must be a supported type. Given dtype: {dtype}') else: return hpat_pandas_series_astype_no_modify_impl @sdc_overload_method(SeriesType, 'shift') def hpat_pandas_series_shift(self, periods=1, freq=None, axis=0, fill_value=None): """ Pandas Series method :meth:`pandas.Series.shift` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_shift Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_shift_unboxing Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_shift_full Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_shift_str Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_shift_fill_str Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_shift_unsupported_params Parameters ---------- self: :obj:`pandas.Series` input series periods: :obj:`int` Number of periods to shift. Can be positive or negative. freq: :obj:`DateOffset`, :obj:`tseries.offsets`, :obj:`timedelta`, :obj:`str` Offset to use from the tseries module or time rule (e.g. ‘EOM’). *unsupported* axis: :obj:`int`, :obj:`str` Axis along which the operation acts 0/None/'index' - row-wise operation 1/'columns' - column-wise operation *unsupported* fill_value : :obj:`int`, :obj:`float` The scalar value to use for newly introduced missing values. Returns ------- :obj:`scalar` returns :obj:`series` object """ _func_name = 'Method shift().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not isinstance(self.data.dtype, types.Number): msg = '{} The object must be a number. Given self.data.dtype: {}' raise TypingError(msg.format(_func_name, self.data.dtype)) if not isinstance(fill_value, (types.Omitted, types.Number, types.NoneType)) and fill_value is not None: raise TypingError('{} The object must be a number. Given fill_value: {}'.format(_func_name, fill_value)) if not isinstance(freq, (types.Omitted, types.NoneType)) and freq is not None: raise TypingError('{} Unsupported parameters. Given freq: {}'.format(_func_name, freq)) if not isinstance(axis, (types.Omitted, int, types.Integer)) and not axis: raise TypingError('{} Unsupported parameters. Given axis: {}'.format(_func_name, axis)) fill_is_default = isinstance(fill_value, (types.Omitted, types.NoneType)) or fill_value is None series_np_dtype = [numpy_support.as_dtype(self.data.dtype)] fill_np_dtype = [numpy.float64 if fill_is_default else numpy_support.as_dtype(fill_value)] fill_dtype = types.float64 if fill_is_default else fill_value common_dtype = find_common_dtype_from_numpy_dtypes([], [self.data.dtype, fill_dtype]) if fill_is_default: def hpat_pandas_series_shift_impl(self, periods=1, freq=None, axis=0, fill_value=None): if axis != 0: raise TypingError('Method shift(). Unsupported parameters. Given axis != 0') arr = numpy.empty(shape=len(self._data), dtype=common_dtype) if periods > 0: arr[:periods] = numpy.nan arr[periods:] = self._data[:-periods] elif periods < 0: arr[periods:] = numpy.nan arr[:periods] = self._data[-periods:] else: arr[:] = self._data return pandas.Series(data=arr, index=self._index, name=self._name) return hpat_pandas_series_shift_impl def hpat_pandas_series_shift_impl(self, periods=1, freq=None, axis=0, fill_value=None): if axis != 0: raise TypingError('Method shift(). Unsupported parameters. Given axis != 0') arr = numpy.empty(len(self._data), dtype=common_dtype) if periods > 0: arr[:periods] = fill_value arr[periods:] = self._data[:-periods] elif periods < 0: arr[periods:] = fill_value arr[:periods] = self._data[-periods:] else: arr[:] = self._data return pandas.Series(data=arr, index=self._index, name=self._name) return hpat_pandas_series_shift_impl @sdc_overload_method(SeriesType, 'isin') def hpat_pandas_series_isin(self, values): """ Pandas Series method :meth:`pandas.Series.isin` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_isin_list1 Parameters ----------- values : :obj:`list` or :obj:`set` object specifies values to look for in the series Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object indicating if each element of self is in values """ _func_name = 'Method isin().' if not isinstance(self, SeriesType): raise TypingError( '{} The object must be a pandas.series. Given self: {}'.format(_func_name, self)) if not isinstance(values, (types.Set, types.List)): raise TypingError( '{} The argument must be set or list-like object. Given values: {}'.format(_func_name, values)) def hpat_pandas_series_isin_impl(self, values): # TODO: replace with below line when Numba supports np.isin in nopython mode # return pandas.Series(np.isin(self._data, values)) return pandas.Series(data=[(x in values) for x in self._data], index=self._index, name=self._name) return hpat_pandas_series_isin_impl @sdc_overload_method(SeriesType, 'append') def hpat_pandas_series_append(self, to_append, ignore_index=False, verify_integrity=False): """ Pandas Series method :meth:`pandas.Series.append` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_append* Parameters ----------- self: :obj:`pandas.Series` input series to_append : :obj:`pandas.Series` object or :obj:`list` or :obj:`set` Series (or list or tuple of Series) to append with self ignore_index: :obj:`bool`, default False If True, do not use the index labels. Supported as literal value only verify_integrity: :obj:`bool`, default False If True, raise Exception on creating index with duplicates. *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object Concatenated Series """ _func_name = 'Method append().' if not isinstance(self, SeriesType): raise TypingError( '{} The object must be a pandas.series. Given self: {}'.format(_func_name, self)) if not (isinstance(to_append, SeriesType) or (isinstance(to_append, (types.UniTuple, types.List)) and isinstance(to_append.dtype, SeriesType))): raise TypingError( '{} The argument must be a pandas.series or list/tuple of pandas.series. \ Given to_append: {}'.format(_func_name, to_append)) # currently we will always raise this in the end, i.e. if no impl was found # TODO: find a way to stop compilation early and not proceed with unliteral step if not (isinstance(ignore_index, types.Literal) and isinstance(ignore_index, types.Boolean) or isinstance(ignore_index, types.Omitted) or ignore_index is False): raise TypingError( '{} The ignore_index must be a literal Boolean constant. Given: {}'.format(_func_name, ignore_index)) if not (verify_integrity is False or isinstance(verify_integrity, types.Omitted)): raise TypingError( '{} Unsupported parameters. Given verify_integrity: {}'.format(_func_name, verify_integrity)) # ignore_index value has to be known at compile time to select between implementations with different signatures ignore_index_is_false = (common_functions.has_literal_value(ignore_index, False) or common_functions.has_python_value(ignore_index, False) or isinstance(ignore_index, types.Omitted)) to_append_is_series = isinstance(to_append, SeriesType) if ignore_index_is_false: def hpat_pandas_series_append_impl(self, to_append, ignore_index=False, verify_integrity=False): if to_append_is_series == True: # noqa new_data = common_functions.hpat_arrays_append(self._data, to_append._data) new_index = common_functions.hpat_arrays_append(self.index, to_append.index) else: data_arrays_to_append = [series._data for series in to_append] index_arrays_to_append = [series.index for series in to_append] new_data = common_functions.hpat_arrays_append(self._data, data_arrays_to_append) new_index = common_functions.hpat_arrays_append(self.index, index_arrays_to_append) return pandas.Series(new_data, new_index) return hpat_pandas_series_append_impl else: def hpat_pandas_series_append_ignore_index_impl(self, to_append, ignore_index=False, verify_integrity=False): if to_append_is_series == True: # noqa new_data = common_functions.hpat_arrays_append(self._data, to_append._data) else: arrays_to_append = [series._data for series in to_append] new_data = common_functions.hpat_arrays_append(self._data, arrays_to_append) return pandas.Series(new_data, None) return hpat_pandas_series_append_ignore_index_impl @sdc_overload_method(SeriesType, 'copy') def hpat_pandas_series_copy(self, deep=True): """ Pandas Series method :meth:`pandas.Series.copy` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_copy_str1 Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_copy_int1 Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_copy_deep Parameters ----------- self: :class:`pandas.Series` input arg deep: :obj:`bool`, default :obj:`True` Make a deep copy, including a copy of the data and the indices. With deep=False neither the indices nor the data are copied. [SDC limitations]: - deep=False: shallow copy of index is not supported Returns ------- :obj:`pandas.Series` or :obj:`pandas.DataFrame` Object type matches caller. """ ty_checker = TypeChecker('Method Series.copy().') ty_checker.check(self, SeriesType) if not isinstance(deep, (types.Omitted, types.Boolean)) and not deep: ty_checker.raise_exc(self.data, 'boolean', 'deep') if isinstance(self.index, types.NoneType): def hpat_pandas_series_copy_impl(self, deep=True): if deep: return pandas.Series(data=self._data.copy(), name=self._name) else: return pandas.Series(data=self._data, name=self._name) return hpat_pandas_series_copy_impl else: def hpat_pandas_series_copy_impl(self, deep=True): if deep: return pandas.Series(data=self._data.copy(), index=self._index.copy(), name=self._name) else: # Shallow copy of index is not supported yet return pandas.Series(data=self._data, index=self._index.copy(), name=self._name) return hpat_pandas_series_copy_impl @sdc_overload_method(SeriesType, 'corr') def hpat_pandas_series_corr(self, other, method='pearson', min_periods=None): """ Pandas Series method :meth:`pandas.Series.corr` implementation. Note: Unsupported mixed numeric and string data .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_corr Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_corr_unsupported_dtype Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_corr_unsupported_period Parameters ---------- self: :obj:`pandas.Series` input series other: :obj:`pandas.Series` input series method: *unsupported min_periods: :obj:`int`, default None Returns ------- :obj:`float` returns :obj:`float` object """ ty_checker = TypeChecker('Method corr().') ty_checker.check(self, SeriesType) ty_checker.check(other, SeriesType) if not isinstance(self.data.dtype, types.Number): ty_checker.raise_exc(self.data, 'number', 'self.data') if not isinstance(other.data.dtype, types.Number): ty_checker.raise_exc(other.data, 'number', 'other.data') if not isinstance(min_periods, (int, types.Integer, types.Omitted, types.NoneType)) and min_periods is not None: ty_checker.raise_exc(min_periods, 'int64', 'min_periods') def hpat_pandas_series_corr_impl(self, other, method='pearson', min_periods=None): if min_periods is None: min_periods = 1 if len(self._data) == 0 or len(other._data) == 0: return numpy.nan self_arr = self._data[:min(len(self._data), len(other._data))] other_arr = other._data[:min(len(self._data), len(other._data))] invalid = numpy.isnan(self_arr) | numpy.isnan(other_arr) if invalid.any(): self_arr = self_arr[~invalid] other_arr = other_arr[~invalid] if len(self_arr) < min_periods: return numpy.nan new_self = pandas.Series(self_arr) new_other = pandas.Series(other_arr) n = new_self.count() ma = new_self.sum() mb = new_other.sum() a = n * (self_arr * other_arr).sum() - ma * mb b1 = n * (self_arr * self_arr).sum() - ma * ma b2 = n * (other_arr * other_arr).sum() - mb * mb if b1 == 0 or b2 == 0: return numpy.nan return a / numpy.sqrt(b1 * b2) return hpat_pandas_series_corr_impl @sdc_overload_method(SeriesType, 'head') def hpat_pandas_series_head(self, n=5): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.head Examples -------- .. literalinclude:: ../../../examples/series/series_head.py :language: python :lines: 27- :caption: Getting the first n rows. :name: ex_series_head .. command-output:: python ./series/series_head.py :cwd: ../../../examples .. seealso:: :ref:`DataFrame.tail <pandas.DataFrame.tail>` Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.head` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_head* Parameters ----------- n: :obj:`int`, default 5 input argument, default 5 Returns ------- :obj:`pandas.Series` returns: The first n rows of the caller object. """ _func_name = 'Method head().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(n, (types.Integer, types.Omitted)) and n != 5: ty_checker.raise_exc(n, 'int', 'n') if isinstance(self.index, types.NoneType): def hpat_pandas_series_head_impl(self, n=5): return pandas.Series(data=self._data[:n], name=self._name) return hpat_pandas_series_head_impl else: def hpat_pandas_series_head_index_impl(self, n=5): return pandas.Series(data=self._data[:n], index=self._index[:n], name=self._name) return hpat_pandas_series_head_index_impl @sdc_overload_method(SeriesType, 'groupby') def hpat_pandas_series_groupby( self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False): """ Pandas Series method :meth:`pandas.Series.groupby` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_groupby_count Parameters ----------- self: :class:`pandas.Series` input arg by: :obj:`pandas.Series` object Used to determine the groups for the groupby axis: *unsupported* level: *unsupported* as_index: *unsupported* sort: *unsupported* group_keys: *unsupported* squeeze: *unsupported* observed: *unsupported* Returns ------- :obj:`pandas.SeriesGroupBy` returns :obj:`pandas.SeriesGroupBy` object """ _func_name = 'Method Series.groupby().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if by is None and axis is None: raise TypingError("{} You have to supply one of 'by' or 'axis' parameters".format(_func_name)) if level is not None and not isinstance(level, (types.Integer, types.NoneType, types.Omitted)): raise TypingError("{} 'level' must be an Integer. Given: {}".format(_func_name, level)) def hpat_pandas_series_groupby_impl( self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False): # TODO Needs to implement parameters value check # if level is not None and (level < -1 or level > 0): # raise ValueError("Method Series.groupby(). level > 0 or level < -1 only valid with MultiIndex") return pandas.core.groupby.SeriesGroupBy(self) return hpat_pandas_series_groupby_impl @sdc_overload_method(SeriesType, 'isnull') def hpat_pandas_series_isnull(self): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.isnull Examples -------- .. literalinclude:: ../../../examples/series/series_isnull.py :language: python :lines: 27- :caption: Detect missing values. :name: ex_series_isnull .. command-output:: python ./series/series_isnull.py :cwd: ../../../examples Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.isnull` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_isnull* Parameters ----------- self : :obj:`pandas.Series` object input argument Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method isnull().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if isinstance(self.data.dtype, (types.Integer, types.Float)): def hpat_pandas_series_isnull_impl(self): return pandas.Series(data=numpy.isnan(self._data), index=self._index, name=self._name) return hpat_pandas_series_isnull_impl if isinstance(self.data.dtype, types.UnicodeType): def hpat_pandas_series_isnull_impl(self): result = numpy.empty(len(self._data), numpy.bool_) byte_size = 8 # iterate over bits in StringArrayType null_bitmap and fill array indicating if array's element are NaN for i in range(len(self._data)): bmap_idx = i // byte_size bit_idx = i % byte_size bmap = self._data.null_bitmap[bmap_idx] bit_value = (bmap >> bit_idx) & 1 result[i] = bit_value == 0 return pandas.Series(result, index=self._index, name=self._name) return hpat_pandas_series_isnull_impl @sdc_overload_method(SeriesType, 'isna') def hpat_pandas_series_isna(self): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.isna Examples -------- .. literalinclude:: ../../../examples/series/series_isna.py :language: python :lines: 27- :caption: Detect missing values. :name: ex_series_isna .. command-output:: python ./series/series_isna.py :cwd: ../../../examples .. seealso:: :ref:`Series.isnull <pandas.Series.isnull>` Alias of isna. :ref:`Series.notna <pandas.Series.notna>` Boolean inverse of isna. :ref:`Series.dropna <pandas.Series.dropna>` Omit axes labels with missing values. `pandas.absolute <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.isna.html#pandas.isna>`_ Top-level isna. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.isna` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_isna* Parameters ----------- self : :obj:`pandas.Series` object input argument Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method isna().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if isinstance(self.data.dtype, (types.Integer, types.Float)): def hpat_pandas_series_isna_impl(self): return pandas.Series(data=numpy.isnan(self._data), index=self._index, name=self._name) return hpat_pandas_series_isna_impl if isinstance(self.data.dtype, types.UnicodeType): def hpat_pandas_series_isna_impl(self): result = numpy.empty(len(self._data), numpy.bool_) byte_size = 8 # iterate over bits in StringArrayType null_bitmap and fill array indicating if array's element are NaN for i in range(len(self._data)): bmap_idx = i // byte_size bit_idx = i % byte_size bmap = self._data.null_bitmap[bmap_idx] bit_value = (bmap >> bit_idx) & 1 result[i] = bit_value == 0 return pandas.Series(result, index=self._index, name=self._name) return hpat_pandas_series_isna_impl @sdc_overload_method(SeriesType, 'notna') def hpat_pandas_series_notna(self): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.notna Examples -------- .. literalinclude:: ../../../examples/series/series_notna.py :language: python :lines: 27- :caption: Detect existing (non-missing) values. :name: ex_series_notna .. command-output:: python ./series/series_notna.py :cwd: ../../../examples .. seealso:: :ref:`Series.notnull <pandas.Series.notnull>` Alias of notna. :ref:`Series.isna <pandas.Series.isna>` Boolean inverse of notna. :ref:`Series.dropna <pandas.Series.dropna>` Omit axes labels with missing values. `pandas.absolute <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.notna.html#pandas.notna>`_ Top-level notna. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.notna` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_notna* Parameters ----------- self : :obj:`pandas.Series` object input series Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method notna().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if isinstance(self.data.dtype, types.Number): def hpat_pandas_series_notna_impl(self): return pandas.Series(numpy.invert(numpy.isnan(self._data)), index=self._index, name=self._name) return hpat_pandas_series_notna_impl if isinstance(self.data.dtype, types.UnicodeType): def hpat_pandas_series_notna_impl(self): result = self.isna() return pandas.Series(numpy.invert(result._data), index=self._index, name=self._name) return hpat_pandas_series_notna_impl @sdc_overload_method(SeriesType, 'ne') def hpat_pandas_series_ne(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.ne Examples -------- .. literalinclude:: ../../../examples/series/series_ne.py :language: python :lines: 27- :caption: Element-wise not equal of one Series by another (binary operator ne) :name: ex_series_ne .. command-output:: python ./series/series_ne.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.ne` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op8* Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method ne().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(level, types.Omitted) or level is None): ty_checker.raise_exc(level, 'None', 'level') if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_ne_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data != other._data) return hpat_pandas_series_ne_impl if isinstance(other, types.Number): def hpat_pandas_series_ne_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data != other) return hpat_pandas_series_ne_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'add') def hpat_pandas_series_add(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.add Examples -------- .. literalinclude:: ../../../examples/series/series_add.py :language: python :lines: 27- :caption: Getting the addition of Series and other :name: ex_series_add .. command-output:: python ./series/series_add.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.radd <pandas.Series.radd>` Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.add` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: :obj:`int` default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method add().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_add_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 """ return pandas.Series(self._data + other._data) return hpat_pandas_series_add_impl if isinstance(other, types.Integer) or isinstance(other, types.Float): def hpat_pandas_series_add_number_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_integer_scalar Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_float_scalar """ if axis != 0: raise ValueError('Method add(). The object axis\n expected: 0') return pandas.Series(self._data + other) return hpat_pandas_series_add_number_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'sub') def hpat_pandas_series_sub(self, other, level=None, fill_value=None, axis=0): """ Pandas Series method :meth:`pandas.Series.sub` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method sub().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not (isinstance(level, types.Omitted) or level is None): raise TypingError( '{} Unsupported parameters. Given level: {}, fill_value: {}, axis: {}'.format(_func_name, level, fill_value, axis)) if not (isinstance(fill_value, types.Omitted) or fill_value is None): raise TypingError( '{} Unsupported parameters. Given level: {}, fill_value: {}, axis: {}'.format(_func_name, level, fill_value, axis)) if not (isinstance(axis, types.Omitted) or axis == 0): raise TypingError( '{} Unsupported parameters. Given level: {}, fill_value: {}, axis: {}'.format(_func_name, level, fill_value, axis)) if isinstance(other, SeriesType): def hpat_pandas_series_sub_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 """ return pandas.Series(self._data - other._data) return hpat_pandas_series_sub_impl if isinstance(other, types.Integer) or isinstance(other, types.Float): def hpat_pandas_series_sub_number_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_integer_scalar Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_float_scalar """ return pandas.Series(self._data - other) return hpat_pandas_series_sub_number_impl raise TypingError('{} The object must be a pandas.series or scalar. Given other: {}'.format(_func_name, other)) @sdc_overload_method(SeriesType, 'sum') def hpat_pandas_series_sum( self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0, ): """ Pandas Series method :meth:`pandas.Series.sum` implementation. .. only:: developer Tests: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_sum* Parameters ---------- self: :class:`pandas.Series` input series axis: *unsupported* skipna: :obj:`bool`, default :obj:`True` Exclude NA/null values when computing the result. level: *unsupported* numeric_only: *unsupported* min_count: *unsupported* Returns ------- :obj:`float` scalar or Series (if level specified) """ _func_name = 'Method sum().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not (isinstance(axis, (types.Integer, types.Omitted)) or axis is None): raise TypingError('{} The axis must be an Integer. Currently unsupported. Given: {}'.format(_func_name, axis)) if not (isinstance(skipna, (types.Boolean, types.Omitted, types.NoneType)) or skipna is None): raise TypingError('{} The skipna must be a Boolean. Given: {}'.format(_func_name, skipna)) if not (isinstance(level, (types.Integer, types.StringLiteral, types.Omitted, types.NoneType)) or level is None): raise TypingError( '{} The level must be an Integer or level name. Currently unsupported. Given: {}'.format( _func_name, level)) if not (isinstance(numeric_only, (types.Boolean, types.Omitted)) or numeric_only is None): raise TypingError( '{} The numeric_only must be a Boolean. Currently unsupported. Given: {}'.format( _func_name, numeric_only)) if not (isinstance(min_count, (types.Integer, types.Omitted)) or min_count == 0): raise TypingError( '{} The min_count must be an Integer. Currently unsupported. Given: {}'.format( _func_name, min_count)) def hpat_pandas_series_sum_impl( self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0, ): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_sum1 """ if skipna is None: _skipna = True else: _skipna = skipna if _skipna: return numpy.nansum(self._data) return numpy.sum(self._data) return hpat_pandas_series_sum_impl @sdc_overload_method(SeriesType, 'take') def hpat_pandas_series_take(self, indices, axis=0, is_copy=False): """ Pandas Series method :meth:`pandas.Series.take` implementation. .. only:: developer Tests: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_take_index_default python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_take_index_default_unboxing python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_take_index_int python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_take_index_int_unboxing python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_take_index_str python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_take_index_str_unboxing Parameters ---------- self: :obj:`pandas.Series` input series indices: :obj:`array-like` An array of ints indicating which positions to take axis: {0 or `index`, 1 or `columns`, None}, default 0 The axis on which to select elements. 0 means that we are selecting rows, 1 means that we are selecting columns. *unsupported* is_copy: :obj:`bool`, default True Whether to return a copy of the original object or not. *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object containing the elements taken from the object """ ty_checker = TypeChecker('Method take().') ty_checker.check(self, SeriesType) if (not isinstance(axis, (int, types.Integer, str, types.UnicodeType, types.StringLiteral, types.Omitted)) and axis not in (0, 'index')): ty_checker.raise_exc(axis, 'integer or string', 'axis') if not isinstance(is_copy, (bool, types.Boolean, types.Omitted)) and is_copy is not False: ty_checker.raise_exc(is_copy, 'boolean', 'is_copy') if not isinstance(indices, (types.List, types.Array)): ty_checker.raise_exc(indices, 'array-like', 'indices') if isinstance(self.index, types.NoneType) or self.index is None: def hpat_pandas_series_take_noindex_impl(self, indices, axis=0, is_copy=False): local_data = [self._data[i] for i in indices] return pandas.Series(local_data, indices) return hpat_pandas_series_take_noindex_impl def hpat_pandas_series_take_impl(self, indices, axis=0, is_copy=False): local_data = [self._data[i] for i in indices] local_index = [self._index[i] for i in indices] return pandas.Series(local_data, local_index) return hpat_pandas_series_take_impl @sdc_overload_method(SeriesType, 'idxmax') def hpat_pandas_series_idxmax(self, axis=None, skipna=True): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.idxmax Examples -------- .. literalinclude:: ../../../examples/series/series_idxmax.py :language: python :lines: 27- :caption: Getting the row label of the maximum value. :name: ex_series_idxmax .. command-output:: python ./series/series_idxmax.py :cwd: ../../../examples .. note:: Parameter axis is currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.idxmin <pandas.Series.idxmin>` Return index label of the first occurrence of minimum of values. `numpy.absolute <https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html#numpy.argmax>`_ Return indices of the maximum values along the given axis. :ref:`DataFrame.idxmax <pandas.DataFrame.idxmax>` Return index of first occurrence of maximum over requested axis. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.idxmax` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_idxmax* Parameters ----------- axis : :obj:`int`, :obj:`str`, default: None Axis along which the operation acts 0/None - row-wise operation 1 - column-wise operation *unsupported* skipna: :obj:`bool`, default: True exclude NA/null values Returns ------- :obj:`pandas.Series.index` or nan returns: Label of the minimum value. """ _func_name = 'Method idxmax().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(self.data.dtype, types.Number): ty_checker.raise_exc(self.data.dtype, 'int, float', 'self.data.dtype') if not (isinstance(skipna, (types.Omitted, types.Boolean, bool)) or skipna is True): ty_checker.raise_exc(skipna, 'bool', 'skipna') if not (isinstance(axis, types.Omitted) or axis is None): ty_checker.raise_exc(axis, 'None', 'axis') if isinstance(self.index, types.NoneType) or self.index is None: def hpat_pandas_series_idxmax_impl(self, axis=None, skipna=True): return numpy.argmax(self._data) return hpat_pandas_series_idxmax_impl else: def hpat_pandas_series_idxmax_index_impl(self, axis=None, skipna=True): # no numpy.nanargmax is supported by Numba at this time result = numpy.argmax(self._data) return self._index[int(result)] return hpat_pandas_series_idxmax_index_impl @sdc_overload_method(SeriesType, 'mul') def hpat_pandas_series_mul(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.mul Examples -------- .. literalinclude:: ../../../examples/series/series_mul.py :language: python :lines: 27- :caption: Element-wise multiplication of two Series :name: ex_series_mul .. command-output:: python ./series/series_mul.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.rmul <pandas.Series.rmul>` Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.mul` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: :obj:`int` default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method mul().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(level, types.Omitted) and level is not None: ty_checker.raise_exc(level, 'None', 'level') if not isinstance(fill_value, types.Omitted) and fill_value is not None: ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not isinstance(axis, types.Omitted) and axis != 0: ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_mul_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 """ if axis != 0: raise ValueError('Method mul(). The object axis\n expected: 0') return pandas.Series(self._data * other._data) return hpat_pandas_series_mul_impl if isinstance(other, types.Integer) or isinstance(other, types.Float): def hpat_pandas_series_mul_number_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_integer_scalar Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_float_scalar """ if axis != 0: raise ValueError('Method mul(). The object axis\n expected: 0') return pandas.Series(self._data * other) return hpat_pandas_series_mul_number_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'div') def hpat_pandas_series_div(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.div Examples -------- .. literalinclude:: ../../../examples/series/series_div.py :language: python :lines: 27- :caption: Element-wise division of one Series by another (binary operator div) :name: ex_series_div .. command-output:: python ./series/series_div.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.rdiv <pandas.Series.rdiv>` Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.div` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: :obj:`int` default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method div().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(level, types.Omitted) or level is None): ty_checker.raise_exc(level, 'None', 'level') if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_div_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 """ if axis != 0: raise ValueError('Method div(). The object axis\n expected: 0') return pandas.Series(self._data / other._data) return hpat_pandas_series_div_impl if isinstance(other, types.Integer) or isinstance(other, types.Float): def hpat_pandas_series_div_number_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_integer_scalar Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_float_scalar """ if axis != 0: raise ValueError('Method div(). The object axis\n expected: 0') return pandas.Series(self._data / other) return hpat_pandas_series_div_number_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'truediv') def hpat_pandas_series_truediv(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.truediv Examples -------- .. literalinclude:: ../../../examples/series/series_truediv.py :language: python :lines: 27- :caption: Element-wise division of one Series by another (binary operator truediv) :name: ex_series_truediv .. command-output:: python ./series/series_truediv.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.rtruediv <pandas.Series.rtruediv>` Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series :meth:`pandas.Series.truediv` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method truediv().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(level, types.Omitted) or level is None): ty_checker.raise_exc(level, 'None', 'level') if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_truediv_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 """ if axis != 0: raise ValueError('Method truediv(). The object axis\n expected: 0') return pandas.Series(self._data / other._data) return hpat_pandas_series_truediv_impl if isinstance(other, types.Integer) or isinstance(other, types.Float): def hpat_pandas_series_truediv_number_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_integer_scalar Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_float_scalar """ if axis != 0: raise ValueError('Method truediv(). The object axis\n expected: 0') return pandas.Series(self._data / other) return hpat_pandas_series_truediv_number_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'floordiv') def hpat_pandas_series_floordiv(self, other, level=None, fill_value=None, axis=0): """ Pandas Series method :meth:`pandas.Series.floordiv` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method floordiv().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not (isinstance(level, types.Omitted) or level is None): raise TypingError( '{} Unsupported parameters. Given level: {}, fill_value: {}, axis: {}'.format(_func_name, level, fill_value, axis)) if not (isinstance(fill_value, types.Omitted) or fill_value is None): raise TypingError( '{} Unsupported parameters. Given level: {}, fill_value: {}, axis: {}'.format(_func_name, level, fill_value, axis)) if not (isinstance(axis, types.Omitted) or axis == 0): raise TypingError( '{} Unsupported parameters. Given level: {}, fill_value: {}, axis: {}'.format(_func_name, level, fill_value, axis)) if isinstance(other, SeriesType): def hpat_pandas_series_floordiv_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 """ return pandas.Series(self._data // other._data) return hpat_pandas_series_floordiv_impl if isinstance(other, types.Integer) or isinstance(other, types.Float): def hpat_pandas_series_floordiv_number_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_integer_scalar Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_float_scalar """ return pandas.Series(self._data // other) return hpat_pandas_series_floordiv_number_impl raise TypingError('{} The object must be a pandas.series or scalar. Given other: {}'.format(_func_name, other)) @sdc_overload_method(SeriesType, 'pow') def hpat_pandas_series_pow(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.pow Examples -------- .. literalinclude:: ../../../examples/series/series_pow.py :language: python :lines: 27- :caption: Element-wise power of one Series by another (binary operator pow) :name: ex_series_pow .. command-output:: python ./series/series_pow.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.rpow <pandas.Series.rpow>` Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.pow` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op5* Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method pow().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(level, types.Omitted) or level is None): ty_checker.raise_exc(level, 'None', 'level') if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_pow_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data ** other._data) return hpat_pandas_series_pow_impl if isinstance(other, types.Number): def hpat_pandas_series_pow_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data ** other) return hpat_pandas_series_pow_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'prod') def hpat_pandas_series_prod(self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0): """ Pandas Series method :meth:`pandas.Series.prod` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_prod* Parameters ----------- self: :obj:`pandas.Series` input series axis: {index (0)} Axis for the function to be applied on. *unsupported* skipna: :obj:`bool`, default :obj:`True` Exclude nan values when computing the result level: :obj:`int`, :obj:`str`, default :obj:`None` If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar. *unsupported* numeric_only: :obj:`bool`, default :obj:`None` Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. *unsupported* min_count: :obj:`int`, default 0 The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. *unsupported* Returns ------- :obj: Returns scalar or Series (if level specified) """ _func_name = 'Method prod().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not isinstance(self.data.dtype, (types.Integer, types.Float)): raise TypingError('{} Non numeric values unsupported. Given: {}'.format(_func_name, self.data.data.dtype)) if not (isinstance(skipna, (types.Omitted, types.Boolean, types.NoneType)) or skipna is None or skipna is True): raise TypingError("{} 'skipna' must be a boolean type. Given: {}".format(_func_name, skipna)) if not (isinstance(axis, (types.Omitted, types.NoneType)) or axis is None) \ or not (isinstance(level, (types.Omitted, types.NoneType)) or level is None) \ or not (isinstance(numeric_only, (types.Omitted, types.NoneType)) or numeric_only is None) \ or not (isinstance(min_count, (types.Omitted, types.Integer)) or min_count == 0): raise TypingError( '{} Unsupported parameters. Given axis: {}, level: {}, numeric_only: {}, min_count: {}'.format( _func_name, axis, level, numeric_only, min_count)) def hpat_pandas_series_prod_impl(self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0): if skipna is None: _skipna = True else: _skipna = skipna if _skipna: return numpy.nanprod(self._data) else: return numpy.prod(self._data) return hpat_pandas_series_prod_impl @sdc_overload_method(SeriesType, 'quantile') def hpat_pandas_series_quantile(self, q=0.5, interpolation='linear'): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.quantile Examples -------- .. literalinclude:: ../../../examples/series/series_quantile.py :language: python :lines: 27- :caption: Computing quantile for the Series :name: ex_series_quantile .. command-output:: python ./series/series_quantile.py :cwd: ../../../examples .. note:: Parameter interpolation is currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: `numpy.absolute <https://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html#numpy.percentile>`_ Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.quantile` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_quantile python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_quantile_q_vector Parameters ----------- q : :obj: float or array-like object, default 0.5 the quantile(s) to compute interpolation: 'linear', 'lower', 'higher', 'midpoint', 'nearest', default `linear` *unsupported* by Numba Returns ------- :obj:`pandas.Series` or float """ _func_name = 'Method quantile().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(interpolation, types.Omitted) and interpolation is not 'linear': ty_checker.raise_exc(interpolation, 'str', 'interpolation') if not isinstance(q, (int, float, list, types.Number, types.Omitted, types.List)): ty_checker.raise_exc(q, 'int, float, list', 'q') def hpat_pandas_series_quantile_impl(self, q=0.5, interpolation='linear'): return numpy.quantile(self._data, q) return hpat_pandas_series_quantile_impl @sdc_overload_method(SeriesType, 'rename') def hpat_pandas_series_rename(self, index=None, copy=True, inplace=False, level=None): """ Pandas Series method :meth:`pandas.Series.rename` implementation. Alter Series index labels or name. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_rename Parameters ----------- index : :obj:`scalar` or `hashable sequence` or `dict` or `function` Dict-like or functions are transformations to apply to the index. Scalar or hashable sequence-like will alter the Series.name attribute. Only scalar value is supported. copy : :obj:`bool`, default :obj:`True` Whether to copy underlying data. inplace : :obj:`bool`, default :obj:`False` Whether to return a new Series. If True then value of copy is ignored. level : :obj:`int` or `str` In case of a MultiIndex, only rename labels in the specified level. *Not supported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` with index labels or name altered. """ ty_checker = TypeChecker('Method rename().') ty_checker.check(self, SeriesType) if not isinstance(index, (types.Omitted, types.UnicodeType, types.StringLiteral, str, types.Integer, types.Boolean, types.Hashable, types.Float, types.NPDatetime, types.NPTimedelta, types.Number)) and index is not None: ty_checker.raise_exc(index, 'string', 'index') if not isinstance(copy, (types.Omitted, types.Boolean, bool)): ty_checker.raise_exc(copy, 'boolean', 'copy') if not isinstance(inplace, (types.Omitted, types.Boolean, bool)): ty_checker.raise_exc(inplace, 'boolean', 'inplace') if not isinstance(level, (types.Omitted, types.UnicodeType, types.StringLiteral, types.Integer)) and level is not None: ty_checker.raise_exc(level, 'Integer or srting', 'level') def hpat_pandas_series_rename_idx_impl(self, index=None, copy=True, inplace=False, level=None): if copy is True: series_data = self._data.copy() series_index = self._index.copy() else: series_data = self._data series_index = self._index return pandas.Series(data=series_data, index=series_index, name=index) def hpat_pandas_series_rename_noidx_impl(self, index=None, copy=True, inplace=False, level=None): if copy is True: series_data = self._data.copy() else: series_data = self._data return pandas.Series(data=series_data, index=self._index, name=index) if isinstance(self.index, types.NoneType): return hpat_pandas_series_rename_noidx_impl return hpat_pandas_series_rename_idx_impl @sdc_overload_method(SeriesType, 'min') def hpat_pandas_series_min(self, axis=None, skipna=None, level=None, numeric_only=None): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.min Examples -------- .. literalinclude:: ../../../examples/series/series_min.py :language: python :lines: 27- :caption: Getting the minimum value of Series elements :name: ex_series_min .. command-output:: python ./series/series_min.py :cwd: ../../../examples .. note:: Parameters axis, level, numeric_only are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.sum <pandas.Series.sum>` Return the sum. :ref:`Series.min <pandas.Series.min>` Return the minimum. :ref:`Series.max <pandas.Series.max>` Return the maximum. :ref:`Series.idxmin <pandas.Series.idxmin>` Return the index of the minimum. :ref:`Series.idxmax <pandas.Series.idxmax>` Return the index of the maximum. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.min` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_min* Parameters ----------- axis: *unsupported* skipna: :obj:`bool` object Exclude nan values when computing the result level: *unsupported* numeric_only: *unsupported* Returns ------- :obj: returns :obj: scalar """ _func_name = 'Method min().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(self.data.dtype, (types.Integer, types.Float)): ty_checker.raise_exc(self.data.dtype, 'int, float', 'self.data.dtype') if not (isinstance(skipna, (types.Omitted, types.Boolean, types.NoneType)) or skipna is True or skipna is None): ty_checker.raise_exc(skipna, 'bool', 'skipna') if not isinstance(axis, types.Omitted) and axis is not None: ty_checker.raise_exc(axis, 'None', 'axis') if not isinstance(level, (types.Omitted, types.NoneType)) and level is not None: ty_checker.raise_exc(level, 'None', 'level') if not isinstance(numeric_only, types.Omitted) and numeric_only is not None: ty_checker.raise_exc(numeric_only, 'None', 'numeric_only') def hpat_pandas_series_min_impl(self, axis=None, skipna=None, level=None, numeric_only=None): if skipna is None: _skipna = True else: _skipna = skipna if _skipna: return numpy.nanmin(self._data) return self._data.min() return hpat_pandas_series_min_impl @sdc_overload_method(SeriesType, 'max') def hpat_pandas_series_max(self, axis=None, skipna=None, level=None, numeric_only=None): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.max Examples -------- .. literalinclude:: ../../../examples/series/series_max.py :language: python :lines: 27- :caption: Getting the maximum value of Series elements :name: ex_series_max .. command-output:: python ./series/series_max.py :cwd: ../../../examples .. note:: Parameters axis, level, numeric_only are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.sum <pandas.Series.sum>` Return the sum. :ref:`Series.min <pandas.Series.min>` Return the minimum. :ref:`Series.max <pandas.Series.max>` Return the maximum. :ref:`Series.idxmin <pandas.Series.idxmin>` Return the index of the minimum. :ref:`Series.idxmax <pandas.Series.idxmax>` Return the index of the maximum. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.max` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_max* Parameters ----------- axis: *unsupported* skipna: :obj:`bool` object Exclude nan values when computing the result level: *unsupported* numeric_only: *unsupported* Returns ------- :obj: returns :obj: scalar """ _func_name = 'Method max().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(self.data.dtype, (types.Integer, types.Float)): ty_checker.raise_exc(self.data.dtype, 'int, float', 'self.data.dtype') if not (isinstance(skipna, (types.Omitted, types.Boolean, types.NoneType)) or skipna is True or skipna is None): ty_checker.raise_exc(skipna, 'bool', 'skipna') if not isinstance(axis, types.Omitted) and axis is not None: ty_checker.raise_exc(axis, 'None', 'axis') if not isinstance(level, (types.Omitted, types.NoneType)) and level is not None: ty_checker.raise_exc(level, 'None', 'level') if not isinstance(numeric_only, types.Omitted) and numeric_only is not None: ty_checker.raise_exc(numeric_only, 'None', 'numeric_only') def hpat_pandas_series_max_impl(self, axis=None, skipna=None, level=None, numeric_only=None): if skipna is None: _skipna = True else: _skipna = skipna if _skipna: return numpy.nanmax(self._data) return self._data.max() return hpat_pandas_series_max_impl @sdc_overload_method(SeriesType, 'mean') def hpat_pandas_series_mean(self, axis=None, skipna=None, level=None, numeric_only=None): """ Pandas Series method :meth:`pandas.Series.mean` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_mean* Parameters ----------- axis: {index (0)} Axis for the function to be applied on. *unsupported* skipna: :obj:`bool`, default True Exclude NA/null values when computing the result. level: :obj:`int` or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar. *unsupported* numeric_only: :obj:`bool`, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. *unsupported* Returns ------- :obj: Return the mean of the values for the requested axis. """ _func_name = 'Method mean().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not isinstance(self.data.dtype, types.Number): raise TypingError( '{} Currently function supports only numeric values. Given data type: {}'.format( _func_name, self.data.dtype)) if not isinstance(skipna, (types.Omitted, types.Boolean, types.NoneType)) and skipna is not None: raise TypingError( '{} The parameter must be a boolean type. Given type skipna: {}'.format(_func_name, skipna)) if not (isinstance(axis, types.Omitted) or axis is None) \ or not (isinstance(level, (types.Omitted, types.NoneType)) or level is None) \ or not (isinstance(numeric_only, types.Omitted) or numeric_only is None): raise TypingError( '{} Unsupported parameters. Given axis: {}, level: {}, numeric_only: {}'.format(_func_name, axis, level, numeric_only)) def hpat_pandas_series_mean_impl(self, axis=None, skipna=None, level=None, numeric_only=None): if skipna is None: _skipna = True else: _skipna = skipna if _skipna: return numpy.nanmean(self._data) return self._data.mean() return hpat_pandas_series_mean_impl @sdc_overload_method(SeriesType, 'mod') def hpat_pandas_series_mod(self, other, level=None, fill_value=None, axis=0): """ Pandas Series method :meth:`pandas.Series.mod` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method mod().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not (isinstance(level, types.Omitted) or level is None): raise TypingError( '{} Unsupported parameters. Given level: {}, fill_value: {}, axis: {}'.format(_func_name, level, fill_value, axis)) if not (isinstance(fill_value, types.Omitted) or fill_value is None): raise TypingError( '{} Unsupported parameters. Given level: {}, fill_value: {}, axis: {}'.format(_func_name, level, fill_value, axis)) if not (isinstance(axis, types.Omitted) or axis == 0): raise TypingError( '{} Unsupported parameters. Given level: {}, fill_value: {}, axis: {}'.format(_func_name, level, fill_value, axis)) if isinstance(other, SeriesType): def hpat_pandas_series_mod_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5 """ return pandas.Series(self._data % other._data) return hpat_pandas_series_mod_impl if isinstance(other, types.Integer) or isinstance(other, types.Float): def hpat_pandas_series_mod_impl(self, other, level=None, fill_value=None, axis=0): """ Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_integer_scalar Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op5_float_scalar """ return pandas.Series(self._data % other) return hpat_pandas_series_mod_impl raise TypingError( '{} The object must be a pandas.series and argument must be a number. Given: {} and other: {}'.format( _func_name, self, other)) @sdc_overload_method(SeriesType, 'eq') def hpat_pandas_series_eq(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.eq Examples -------- .. literalinclude:: ../../../examples/series/series_eq.py :language: python :lines: 27- :caption: Element-wise equal of one Series by another (binary operator eq) :name: ex_series_eq .. command-output:: python ./series/series_mod.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.eq` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op8* Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method eq().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(level, types.Omitted) or level is None): ty_checker.raise_exc(level, 'None', 'level') if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_eq_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data == other._data) return hpat_pandas_series_eq_impl if isinstance(other, types.Integer) or isinstance(other, types.Float): def hpat_pandas_series_eq_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data == other) return hpat_pandas_series_eq_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'ge') def hpat_pandas_series_ge(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.ge Examples -------- .. literalinclude:: ../../../examples/series/series_ge.py :language: python :lines: 27- :caption: Element-wise greater than or equal of one Series by another (binary operator ge) :name: ex_series_ge .. command-output:: python ./series/series_ge.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.ge` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op8* Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method ge().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(level, types.Omitted) or level is None): ty_checker.raise_exc(level, 'None', 'level') if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_ge_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data >= other._data) return hpat_pandas_series_ge_impl if isinstance(other, types.Number): def hpat_pandas_series_ge_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data >= other) return hpat_pandas_series_ge_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'idxmin') def hpat_pandas_series_idxmin(self, axis=None, skipna=True): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.idxmin Examples -------- .. literalinclude:: ../../../examples/series/series_idxmin.py :language: python :lines: 27- :caption: Getting the row label of the minimum value. :name: ex_series_idxmin .. command-output:: python ./series/series_idxmin.py :cwd: ../../../examples .. note:: Parameter axis is currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.idxmax <pandas.Series.idxmax>` Return index label of the first occurrence of maximum of values. `numpy.absolute <https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html#numpy.argmin>`_ Return indices of the minimum values along the given axis. :ref:`DataFrame.idxmin <pandas.DataFrame.idxmin>` Return index of first occurrence of minimum over requested axis. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.idxmin` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_idxmin* Parameters ----------- axis : :obj:`int`, :obj:`str`, default: None Axis along which the operation acts 0/None - row-wise operation 1 - column-wise operation *unsupported* skipna: :obj:`bool`, default: True exclude NA/null values Returns ------- :obj:`pandas.Series.index` or nan returns: Label of the minimum value. """ _func_name = 'Method idxmin().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(self.data.dtype, types.Number): ty_checker.raise_exc(self.data.dtype, 'int, float', 'self.data.dtype') if not (isinstance(skipna, (types.Omitted, types.Boolean, bool)) or skipna is True): ty_checker.raise_exc(skipna, 'bool', 'skipna') if not (isinstance(axis, types.Omitted) or axis is None): ty_checker.raise_exc(axis, 'None', 'axis') if isinstance(self.index, types.NoneType) or self.index is None: def hpat_pandas_series_idxmin_impl(self, axis=None, skipna=True): return numpy.argmin(self._data) return hpat_pandas_series_idxmin_impl else: def hpat_pandas_series_idxmin_index_impl(self, axis=None, skipna=True): # no numpy.nanargmin is supported by Numba at this time result = numpy.argmin(self._data) return self._index[int(result)] return hpat_pandas_series_idxmin_index_impl @sdc_overload_method(SeriesType, 'lt') def hpat_pandas_series_lt(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.lt Examples -------- .. literalinclude:: ../../../examples/series/series_lt.py :language: python :lines: 27- :caption: Element-wise less than of one Series by another (binary operator lt) :name: ex_series_lt .. command-output:: python ./series/series_lt.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.lt` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op8* Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method lt().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(level, types.Omitted) or level is None): ty_checker.raise_exc(level, 'None', 'level') if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_lt_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data < other._data) return hpat_pandas_series_lt_impl if isinstance(other, types.Number): def hpat_pandas_series_lt_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data < other) return hpat_pandas_series_lt_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'gt') def hpat_pandas_series_gt(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.gt Examples -------- .. literalinclude:: ../../../examples/series/series_gt.py :language: python :lines: 27- :caption: Element-wise greater than of one Series by another (binary operator gt) :name: ex_series_gt .. command-output:: python ./series/series_gt.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.gt` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op8* Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method gt().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(level, types.Omitted) or level is None): ty_checker.raise_exc(level, 'None', 'level') if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_gt_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data > other._data) return hpat_pandas_series_gt_impl if isinstance(other, types.Number): def hpat_pandas_series_gt_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data > other) return hpat_pandas_series_gt_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'le') def hpat_pandas_series_le(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.le Examples -------- .. literalinclude:: ../../../examples/series/series_le.py :language: python :lines: 27- :caption: Element-wise less than or equal of one Series by another (binary operator le) :name: ex_series_le .. command-output:: python ./series/series_le.py :cwd: ../../../examples .. note:: Parameters level, fill_value, axis are currently unsupported by Intel Scalable Dataframe Compiler Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.le` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op8* Parameters ---------- self: :class:`pandas.Series` input arg other: :obj:`pandas.Series`, :obj:`int` or :obj:`float` input arg level: :obj:`int` or name *unsupported* fill_value: :obj:`float` or None, default None *unsupported* axis: default 0 *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method le().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not (isinstance(level, types.Omitted) or level is None): ty_checker.raise_exc(level, 'None', 'level') if not (isinstance(fill_value, types.Omitted) or fill_value is None): ty_checker.raise_exc(fill_value, 'None', 'fill_value') if not (isinstance(axis, types.Omitted) or axis == 0): ty_checker.raise_exc(axis, 'int', 'axis') if isinstance(other, SeriesType): def hpat_pandas_series_le_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data <= other._data) return hpat_pandas_series_le_impl if isinstance(other, types.Number): def hpat_pandas_series_le_impl(self, other, level=None, fill_value=None, axis=0): return pandas.Series(self._data <= other) return hpat_pandas_series_le_impl ty_checker.raise_exc(other, 'Series, int, float', 'other') @sdc_overload_method(SeriesType, 'abs') def hpat_pandas_series_abs(self): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.abs Examples -------- .. literalinclude:: ../../../examples/series/series_abs.py :language: python :lines: 27- :caption: Getting the absolute value of each element in Series :name: ex_series_abs .. command-output:: python ./series/series_abs.py :cwd: ../../../examples .. seealso:: `numpy.absolute <https://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html>`_ Calculate the absolute value element-wise. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.abs` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_abs1 Parameters ----------- self: :obj:`pandas.Series` input series Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` containing the absolute value of elements """ _func_name = 'Method abs().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(self.dtype, (types.Integer, types.Float)): raise TypingError( '{} The function only applies to elements that are all numeric. Given data type: {}'.format(_func_name, self.dtype)) def hpat_pandas_series_abs_impl(self): return pandas.Series(numpy.abs(self._data)) return hpat_pandas_series_abs_impl @sdc_overload_method(SeriesType, 'unique') def hpat_pandas_series_unique(self): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.unique Examples -------- .. literalinclude:: ../../../examples/series/series_unique.py :language: python :lines: 27- :caption: Getting unique values in Series :name: ex_series_unique .. command-output:: python ./series/series_unique.py :cwd: ../../../examples Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.unique` implementation. Note: Return values order is unspecified .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_unique_sorted Parameters ----------- self: :class:`pandas.Series` input arg Returns ------- :obj:`numpy.array` returns :obj:`numpy.array` ndarray """ ty_checker = TypeChecker('Method unique().') ty_checker.check(self, SeriesType) if isinstance(self.data, StringArrayType): def hpat_pandas_series_unique_str_impl(self): ''' Returns sorted unique elements of an array Note: Can't use Numpy due to StringArrayType has no ravel() for noPython mode. Also, NotImplementedError: unicode_type cannot be represented as a Numpy dtype Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_unique_str ''' str_set = set(self._data) return to_array(str_set) return hpat_pandas_series_unique_str_impl def hpat_pandas_series_unique_impl(self): ''' Returns sorted unique elements of an array Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_unique ''' return numpy.unique(self._data) return hpat_pandas_series_unique_impl @sdc_overload_method(SeriesType, 'cumsum') def hpat_pandas_series_cumsum(self, axis=None, skipna=True): """ Pandas Series method :meth:`pandas.Series.cumsum` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_cumsum Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_cumsum_unboxing Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_cumsum_full Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_cumsum_str Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_cumsum_unsupported_axis Parameters ---------- self: :obj:`pandas.Series` input series axis: :obj:`int`, :obj:`str` Axis along which the operation acts 0/None/'index' - row-wise operation 1/'columns' - column-wise operation *unsupported* skipna: :obj:`bool` exclude NA/null values *args: *unsupported* Returns ------- :obj:`scalar`, :obj:`pandas.Series` returns :obj:`scalar` or :obj:`pandas.Series` object """ _func_name = 'Method cumsum().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not isinstance(self.data.dtype, types.Number): msg = '{} The object must be a number. Given self.data.dtype: {}' raise TypingError(msg.format(_func_name, self.data.dtype)) if not isinstance(axis, (types.Omitted, types.NoneType)) and axis is not None: raise TypingError('{} Unsupported parameters. Given axis: {}'.format(_func_name, axis)) def hpat_pandas_series_cumsum_impl(self, axis=None, skipna=True): if skipna: # nampy.nancumsum replaces NANs with 0, series.cumsum does not, so replace back 0 with NANs local_data = numpy.nancumsum(self._data) local_data[numpy.isnan(self._data)] = numpy.nan return pandas.Series(local_data) return pandas.Series(self._data.cumsum()) return hpat_pandas_series_cumsum_impl @sdc_overload_method(SeriesType, 'nunique') def hpat_pandas_series_nunique(self, dropna=True): """ Pandas Series method :meth:`pandas.Series.nunique` implementation. Note: Unsupported mixed numeric and string data .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_nunique Parameters ----------- self: :obj:`pandas.Series` input series dropna: :obj:`bool`, default True Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method nunique().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if isinstance(self.data, StringArrayType): def hpat_pandas_series_nunique_str_impl(self, dropna=True): """ It is better to merge with Numeric branch """ data = self._data if dropna: nan_mask = self.isna() data = self._data[~nan_mask._data] unique_values = set(data) return len(unique_values) return hpat_pandas_series_nunique_str_impl def hpat_pandas_series_nunique_impl(self, dropna=True): """ This function for Numeric data because NumPy dosn't support StringArrayType Algo looks a bit ambigous because, currently, set() can not be used with NumPy with Numba JIT """ data_mask_for_nan = numpy.isnan(self._data) nan_exists = numpy.any(data_mask_for_nan) data_no_nan = self._data[~data_mask_for_nan] data_set = set(data_no_nan) if dropna or not nan_exists: return len(data_set) else: return len(data_set) + 1 return hpat_pandas_series_nunique_impl @sdc_overload_method(SeriesType, 'count') def hpat_pandas_series_count(self, level=None): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.count Examples -------- .. literalinclude:: ../../../examples/series/series_count.py :language: python :lines: 27- :caption: Counting non-NaN values in Series :name: ex_series_count .. command-output:: python ./series/series_count.py :cwd: ../../../examples .. note:: Parameter level is currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.value_counts <pandas.Series.value_counts>` :ref:`Series.value_counts <pandas.Series.value_counts>` :ref:`Series.str.len <pandas.Series.str.len>` Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.count` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_count Parameters ----------- self: :obj:`pandas.Series` input series level: :obj:`int` or name *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ _func_name = 'Method count().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(level, (types.Omitted, types.NoneType)) and level is not None: ty_checker.raise_exc(level, 'None', 'level') if isinstance(self.data, StringArrayType): def hpat_pandas_series_count_str_impl(self, level=None): nan_mask = self.isna() return numpy.sum(nan_mask._data == 0) return hpat_pandas_series_count_str_impl def hpat_pandas_series_count_impl(self, level=None): """ Return number of non-NA/null observations in the object Returns number of unique elements in the object Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_count """ data_no_nan = self._data[~numpy.isnan(self._data)] return len(data_no_nan) return hpat_pandas_series_count_impl @sdc_overload_method(SeriesType, 'median') def hpat_pandas_series_median(self, axis=None, skipna=None, level=None, numeric_only=None): """ Pandas Series method :meth:`pandas.Series.median` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_median1* Parameters ----------- self: :obj:`pandas.Series` input series axis: :obj:`int` or :obj:`string` {0 or `index`, None}, default None The axis for the function to be applied on. *unsupported* skipna: :obj:`bool`, default True exclude NA/null values when computing the result level: :obj:`int` or :obj:`string`, default None *unsupported* numeric_only: :obj:`bool` or None, default None *unsupported* Returns ------- :obj:`float` or :obj:`pandas.Series` (if level is specified) median of values in the series """ _func_name = 'Method median().' if not isinstance(self, SeriesType): raise TypingError( '{} The object must be a pandas.series. Given self: {}'.format(_func_name, self)) if not isinstance(self.dtype, types.Number): raise TypingError( '{} The function only applies to elements that are all numeric. Given data type: {}'.format( _func_name, self.dtype)) if not (isinstance(axis, (types.Integer, types.UnicodeType, types.Omitted)) or axis is None): raise TypingError( '{} The axis must be an Integer or a String. Currently unsupported. Given: {}'.format( _func_name, axis)) if not (isinstance(skipna, (types.Boolean, types.Omitted, types.NoneType)) or skipna or skipna is None): raise TypingError('{} The is_copy must be a boolean. Given: {}'.format(_func_name, skipna)) if not ((level is None or isinstance(level, (types.Omitted, types.NoneType))) and (numeric_only is None or isinstance(numeric_only, types.Omitted)) and (axis is None or isinstance(axis, types.Omitted)) ): raise TypingError( '{} Unsupported parameters. Given level: {}, numeric_only: {}, axis: {}'.format( _func_name, level, numeric_only, axis)) def hpat_pandas_series_median_impl(self, axis=None, skipna=None, level=None, numeric_only=None): if skipna is None: _skipna = True else: _skipna = skipna if _skipna: return numpy.nanmedian(self._data) return numpy.median(self._data) return hpat_pandas_series_median_impl @sdc_overload_method(SeriesType, 'argsort') def hpat_pandas_series_argsort(self, axis=0, kind='quicksort', order=None): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.argsort Examples -------- .. literalinclude:: ../../../examples/series/series_argsort.py :language: python :lines: 27- :caption: Override ndarray.argsort. :name: ex_series_argsort .. command-output:: python ./series/series_argsort.py :cwd: ../../../examples .. note:: Parameters axis, kind, order are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: `numpy.absolute <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.argsort.html#numpy.ndarray.argsort>`_ Return indices of the minimum values along the given axis. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.argsort` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_argsort* Parameters ----------- self: :class:`pandas.Series` input series axis: :obj:`int` Has no effect but is accepted for compatibility with numpy. *unsupported* kind: :obj:'str', {'mergesort', 'quicksort', 'heapsort'}, default: 'quicksort' Choice of sorting algorithm. See np.sort for more information. 'mergesort' is the only stable algorithm *uses python func - sorted() for str and numpy func - sort() for num* *'heapsort' unsupported* order: :obj:`str` or :obj:`list of str`, default: None Has no effect but is accepted for compatibility with numpy. *unsupported* Returns ------- :obj:`pandas.Series` returns: Positions of values within the sort order with -1 indicating nan values. """ _func_name = 'Method argsort().' ty_checker = TypeChecker(_func_name) ty_checker.check(self, SeriesType) if not isinstance(self.data.dtype, types.Number): ty_checker.raise_exc(self.data.dtype, 'int, float', 'self.data.dtype') if not (isinstance(axis, types.Omitted) or isinstance(axis, types.Integer) or axis == 0): ty_checker.raise_exc(axis, 'int64', 'axis') if not isinstance(kind, (types.Omitted, str, types.UnicodeType, types.StringLiteral)): ty_checker.raise_exc(kind, 'quicksort', 'kind') if not isinstance(order, (str, types.UnicodeType, types.StringLiteral, types.Omitted, types.NoneType, types.List))\ and order is not None: ty_checker.raise_exc(order, 'None', 'order') if not isinstance(self.index, types.NoneType): def hpat_pandas_series_argsort_idx_impl(self, axis=0, kind='quicksort', order=None): if kind != 'quicksort' and kind != 'mergesort': raise ValueError("Method argsort(). Unsupported parameter. Given 'kind' != 'quicksort' or 'mergesort'") if kind == 'mergesort': #It is impossible to use numpy.argsort(self._data, kind=kind) since numba gives typing error sort = numpy.argsort(self._data, kind='mergesort') else: sort = numpy.argsort(self._data) na = self.isna().sum() result = numpy.empty(len(self._data), dtype=numpy.int64) na_data_arr = sdc.hiframes.api.get_nan_mask(self._data) if kind == 'mergesort': sort_nona = numpy.argsort(self._data[~na_data_arr], kind='mergesort') else: sort_nona = numpy.argsort(self._data[~na_data_arr]) q = 0 for id, i in enumerate(sort): if id in set(sort[len(self._data) - na:]): q += 1 else: result[id] = sort_nona[id - q] for i in sort[len(self._data) - na:]: result[i] = -1 return pandas.Series(result, self._index) return hpat_pandas_series_argsort_idx_impl def hpat_pandas_series_argsort_noidx_impl(self, axis=0, kind='quicksort', order=None): if kind != 'quicksort' and kind != 'mergesort': raise ValueError("Method argsort(). Unsupported parameter. Given 'kind' != 'quicksort' or 'mergesort'") if kind == 'mergesort': sort = numpy.argsort(self._data, kind='mergesort') else: sort = numpy.argsort(self._data) na = self.isna().sum() result = numpy.empty(len(self._data), dtype=numpy.int64) na_data_arr = sdc.hiframes.api.get_nan_mask(self._data) if kind == 'mergesort': sort_nona = numpy.argsort(self._data[~na_data_arr], kind='mergesort') else: sort_nona = numpy.argsort(self._data[~na_data_arr]) q = 0 for id, i in enumerate(sort): if id in set(sort[len(self._data) - na:]): q += 1 else: result[id] = sort_nona[id - q] for i in sort[len(self._data) - na:]: result[i] = -1 return pandas.Series(result) return hpat_pandas_series_argsort_noidx_impl @sdc_overload_method(SeriesType, 'sort_values') def hpat_pandas_series_sort_values(self, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last'): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.sort_values Examples -------- .. literalinclude:: ../../../examples/series/series_sort_values.py :language: python :lines: 27- :caption: Sort by the values. :name: ex_series_sort_values .. command-output:: python ./series/series_sort_values.py :cwd: ../../../examples .. note:: Parameters axis, kind, na_position are currently unsupported by Intel Scalable Dataframe Compiler .. seealso:: :ref:`Series.sort_index <pandas.Series.sort_index>` Sort by the Series indices. :ref:`DataFrame.sort_values <pandas.DataFrame.sort_values>` Sort DataFrame by the values along either axis. :ref:`DataFrame.sort_index <pandas.DataFrame.sort_index>` Sort DataFrame by indices. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas Series method :meth:`pandas.Series.sort_values` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_sort_values* Parameters ----------- self: :class:'pandas.Series' input series axis: :obj:`int` or :obj:`string` {0 or `index`}, default 0 Axis to direct sorting. For Series only one axis ('index' or 0) exists. ascending: :obj:'bool', default: True If True, sort values in ascending order, otherwise descending. inplace: :obj:`bool`, default False If True, do operation inplace and return None. *unsupported* kind: :obj:'str' or None, {'mergesort', 'quicksort', 'heapsort'}, default: 'quicksort' Choice of sorting algorithm. Currently only 'mergesort' and 'quicksort' are supported as literal values. na_position: {'first' or 'last'}, default 'last' Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at the end. Returns ------- :obj:`pandas.Series` """ _func_name = 'Method sort_values().' ty_checker = TypeChecker('Method sort_values().') ty_checker.check(self, SeriesType) axis_supported_types = (int, types.Omitted, types.Integer, types.StringLiteral, types.UnicodeType) if not isinstance(axis, axis_supported_types): ty_checker.raise_exc(axis, 'integer or string', 'axis') ascending_supported_types = (bool, types.Omitted, types.Boolean) if not isinstance(ascending, ascending_supported_types): ty_checker.raise_exc(ascending, 'boolean', 'ascending') kind_supported_types = (str, types.Omitted, types.NoneType, types.StringLiteral, types.UnicodeType) if not isinstance(kind, kind_supported_types): ty_checker.raise_exc(kind, 'string', 'kind') kind_is_none_or_default = isinstance(kind, (str, types.Omitted, types.NoneType)) na_position_supported_types = (str, types.Omitted, types.StringLiteral, types.UnicodeType) if not isinstance(na_position, na_position_supported_types): ty_checker.raise_exc(na_position, 'string', 'na_position') if not (inplace is False or isinstance(inplace, types.Omitted)): raise TypingError('{} Unsupported parameters. Given inplace: {}'.format(_func_name, inplace)) def _sdc_pandas_series_sort_values_impl( self, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last'): common_functions._sdc_pandas_series_check_axis(axis) if not (kind_is_none_or_default or kind in ('quicksort', 'mergesort')): raise ValueError("Method sort_values(). Unsupported parameter. Given kind != 'quicksort', 'mergesort'") if na_position not in ('last', 'first'): raise ValueError("Method sort_values(). Unsupported parameter. Given na_position != 'last', 'first'") data_nan_mask = sdc.hiframes.api.get_nan_mask(self._data) good = ~data_nan_mask if kind_is_none_or_default == True: # noqa argsort_res = sdc_arrays_argsort(self._data[good], kind='quicksort') else: argsort_res = sdc_arrays_argsort(self._data[good], kind=kind) if not ascending: argsort_res = argsort_res[::-1] idx = numpy.arange(len(self), dtype=numpy.int32) sorted_index = numpy.empty(len(self), dtype=numpy.int32) if na_position == "last": nans_start, nans_stop = good.sum(), len(self) sorted_index[:nans_start] = idx[good][argsort_res] sorted_index[nans_start: nans_stop] = idx[data_nan_mask] elif na_position == "first": nans_start, nans_stop = 0, data_nan_mask.sum() sorted_index[nans_stop:] = idx[good][argsort_res] sorted_index[:nans_stop] = idx[data_nan_mask] result_data = self._data[sorted_index] result_index = self.index[sorted_index] return pandas.Series(data=result_data, index=result_index, name=self._name) return _sdc_pandas_series_sort_values_impl @sdc_overload_method(SeriesType, 'dropna') def hpat_pandas_series_dropna(self, axis=0, inplace=False): """ Pandas Series method :meth:`pandas.Series.dropna` implementation. .. only:: developer Tests: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_dropna* Parameters ---------- self: :obj:`pandas.Series` input series axis: :obj:`int` or :obj:`string` {0 or `index`}, default 0 There is only one axis to drop values from. inplace: :obj:`bool`, default False If True, do operation inplace and return None. *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object with NA entries dropped from it. """ _func_name = 'Method dropna().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not (isinstance(axis, (types.Integer, types.StringLiteral, types.UnicodeType, types.Omitted)) or axis == 0): raise TypingError('{} The axis must be an Integer or String. Given: {}'.format(_func_name, axis)) if not (inplace is False or isinstance(inplace, types.Omitted)): raise TypingError('{} Unsupported parameters. Given inplace: {}'.format(_func_name, inplace)) def hpat_pandas_series_dropna_impl(self, axis=0, inplace=False): # generate Series index if needed by using SeriesType.index (i.e. not self._index) na_data_arr = sdc.hiframes.api.get_nan_mask(self._data) data = self._data[~na_data_arr] index = self.index[~na_data_arr] return pandas.Series(data, index, self._name) return hpat_pandas_series_dropna_impl @sdc_overload_method(SeriesType, 'fillna') def hpat_pandas_series_fillna(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None): """ Pandas Series method :meth:`pandas.Series.fillna` implementation. .. only:: developer Tests: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_fillna* Parameters ---------- self: :obj:`pandas.Series` input series value: scalar of the same dtype as input Series (other types currently unsupported), default None Value to use to fill the NA elements method: :obj:`string` {`backfill`, `bfill`, `pad`, `ffill`, None}, default None Method to use for filling holes in reindexed Series. *unsupported* axis: :obj:`int` or :obj:`string` {0 or `index`}, default None There is only one axis to drop values from. inplace: :obj:`bool`, default False If True, do operation inplace and return None. Supported as literal value only limit: :obj:`int`, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. *unsupported* downcast: :obj:`dict` or :obj:`string` {`infer`}, default None Controls logic of downcasting elements to particular dtype *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` with missed values filled. """ _func_name = 'Method fillna().' if not isinstance(self, SeriesType): raise TypingError('{} The object must be a pandas.series. Given: {}'.format(_func_name, self)) if not (isinstance(axis, (types.Integer, types.StringLiteral, types.UnicodeType, types.Omitted)) or axis is None): raise TypingError('{} The axis must be an Integer or String. Given: {}'.format(_func_name, axis)) if not (isinstance(inplace, types.Literal) and isinstance(inplace, types.Boolean) or isinstance(inplace, types.Omitted) or inplace is False): raise TypingError('{} The inplace must be a literal Boolean constant. Given: {}'.format(_func_name, inplace)) if not ( (method is None or isinstance(method, types.Omitted)) and (limit is None or isinstance(limit, types.Omitted)) and (downcast is None or isinstance(downcast, types.Omitted)) ): raise TypingError('{} Unsupported parameters. Given method: {}, limit: {}, downcast: {}'.format( _func_name, method, limit, downcast)) # inplace value has to be known at compile time to select between implementations with different signatures if ((isinstance(inplace, types.Literal) and inplace.literal_value == True) or (isinstance(inplace, bool) and inplace == True)): # do operation inplace, fill the NA/NaNs in the same array and return None if isinstance(self.dtype, types.UnicodeType): # TODO: StringArrayType cannot resize inplace, and assigning a copy back to self._data is not possible now raise TypingError('{} Not implemented when Series dtype is {} and\ inplace={}'.format(_func_name, self.dtype, inplace)) elif isinstance(self.dtype, (types.Integer, types.Boolean)): def hpat_pandas_series_no_nan_fillna_impl(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None): # no NaNs in series of Integers or Booleans return None return hpat_pandas_series_no_nan_fillna_impl else: def hpat_pandas_series_fillna_impl(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None): na_data_arr = sdc.hiframes.api.get_nan_mask(self._data) self._data[na_data_arr] = value return None return hpat_pandas_series_fillna_impl else: # non inplace implementations, copy array, fill the NA/NaN and return a new Series if isinstance(self.dtype, types.UnicodeType): # For StringArrayType implementation is taken from _series_fillna_str_alloc_impl # (can be called directly when it's index handling is fixed) def hpat_pandas_series_str_fillna_impl(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None): n = len(self._data) num_chars = 0 # get total chars in new array for i in prange(n): s = self._data[i] if sdc.hiframes.api.isna(self._data, i): num_chars += len(value) else: num_chars += len(s) filled_data = pre_alloc_string_array(n, num_chars) for i in prange(n): if sdc.hiframes.api.isna(self._data, i): filled_data[i] = value else: filled_data[i] = self._data[i] return pandas.Series(filled_data, self._index, self._name) return hpat_pandas_series_str_fillna_impl elif isinstance(self.dtype, (types.Integer, types.Boolean)): def hpat_pandas_series_no_nan_fillna_impl(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None): return pandas.Series(numpy.copy(self._data), self._index, self._name) return hpat_pandas_series_no_nan_fillna_impl else: def hpat_pandas_series_fillna_impl(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None): na_data_arr = sdc.hiframes.api.get_nan_mask(self._data) filled_data = numpy.copy(self._data) filled_data[na_data_arr] = value return pandas.Series(filled_data, self._index, self._name) return hpat_pandas_series_fillna_impl @sdc_overload_method(SeriesType, 'cov') def hpat_pandas_series_cov(self, other, min_periods=None): """ Pandas Series method :meth:`pandas.Series.cov` implementation. Note: Unsupported mixed numeric and string data .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_cov Parameters ---------- self: :obj:`pandas.Series` input series other: :obj:`pandas.Series` input series min_periods: :obj:`int`, default None Returns ------- :obj:`float` returns :obj:`float` object """ ty_checker = TypeChecker('Method cov().') ty_checker.check(self, SeriesType) ty_checker.check(other, SeriesType) if not isinstance(self.data.dtype, types.Number): ty_checker.raise_exc(self.data.dtype, 'number', 'self.data') if not isinstance(other.data.dtype, types.Number): ty_checker.raise_exc(other.data.dtype, 'number', 'other.data') if not isinstance(min_periods, (types.Integer, types.Omitted, types.NoneType)) and min_periods is not None: ty_checker.raise_exc(min_periods, 'int64', 'min_periods') def hpat_pandas_series_cov_impl(self, other, min_periods=None): if min_periods is None or min_periods < 2: min_periods = 2 min_len = min(len(self._data), len(other._data)) if min_len == 0: return numpy.nan other_sum = 0. self_sum = 0. self_other_sum = 0. total_count = 0 for i in prange(min_len): s = self._data[i] o = other._data[i] if not (numpy.isnan(s) or numpy.isnan(o)): self_sum += s other_sum += o self_other_sum += s*o total_count += 1 if total_count < min_periods: return numpy.nan return (self_other_sum - self_sum*other_sum/total_count)/(total_count - 1) return hpat_pandas_series_cov_impl @sdc_overload_method(SeriesType, 'pct_change') def hpat_pandas_series_pct_change(self, periods=1, fill_method='pad', limit=None, freq=None): """ Pandas Series method :meth:`pandas.Series.pct_change` implementation. Note: Unsupported mixed numeric and string data .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_pct_change Parameters ----------- self: :obj:`pandas.Series` input series periods: :obj:`int`, default 1 Periods to shift for forming percent change. fill_method: :obj:`str`, default 'pad' How to handle NAs before computing percent changes. limit: :obj:`int`, default Nogne The number of consecutive NAs to fill before stopping. *unsupported* freq: :obj: DateOffset, timedelta, or offset alias string, optional Increment to use from time series API (e.g. 'M' or BDay()). *unsupported* Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object """ ty_checker = TypeChecker('Method pct_change().') ty_checker.check(self, SeriesType) if not isinstance(self.data.dtype, types.Number): ty_checker.raise_exc(self.data.dtype, 'number', 'self.data') if not isinstance(periods, (types.Integer, types.Omitted)): ty_checker.raise_exc(periods, 'int64', 'periods') if not isinstance(fill_method, (str, types.UnicodeType, types.StringLiteral, types.NoneType, types.Omitted)): ty_checker.raise_exc(fill_method, 'string', 'fill_method') if not isinstance(limit, (types.Omitted, types.NoneType)): ty_checker.raise_exc(limit, 'None', 'limit') if not isinstance(freq, (types.Omitted, types.NoneType)): ty_checker.raise_exc(freq, 'None', 'freq') def hpat_pandas_series_pct_change_impl(self, periods=1, fill_method='pad', limit=None, freq=None): if not (fill_method is None or fill_method in ['pad', 'ffill', 'backfill', 'bfill']): raise ValueError( "Method pct_change(). Unsupported parameter. The function uses fill_method pad (ffill) or backfill (bfill) or None.") local_series = self.copy() if fill_method is not None: # replacement method fillna for given method # ========================================= # Example: # s = [1.1, 0.3, np.nan, 1, np.inf, 0, 1.1, np.nan, 2.2, np.inf, 2, 2] # result = [1.1, 0.3, 0.3, 1, inf, 0, 1.1, 1.1, 2.2, inf, 2, 2] # ========================================== for i in range(len(local_series._data)): # check each element on numpy.nan if numpy.isnan(local_series._data[i]): if fill_method in ['pad', 'ffill']: # if it first element is nan, element will be is nan # if it not first element, element will be is nearest is not nan element # take a step back while will not find is not nan element # if before the first element you did not find one, the element will be equal nan if i == 0: local_series._data[i] = numpy.nan else: k = 1 while numpy.isnan(local_series._data[i - k]): if i - k == 0: local_series._data[i] = numpy.nan break k += 1 local_series._data[i] = local_series._data[i - k] elif fill_method in ['backfill', 'bfill']: # if it last element is nan, element will be is nan # if it not last element, element will be is nearest is not nan element # take a step front while will not find is not nan element # if before the last element you did not find one, the element will be equal nan if i == len(local_series._data)-1: local_series._data[i] = numpy.nan else: k = 1 while numpy.isnan(local_series._data[i + k]): if i + k == len(local_series._data) - 1: local_series._data[i] = numpy.nan break k += 1 local_series._data[i] = local_series._data[i + k] rshift = local_series.shift(periods=periods, freq=freq) rdiv = local_series.div(rshift) result = rdiv._data - 1 return pandas.Series(result) return hpat_pandas_series_pct_change_impl @sdc_overload_method(SeriesType, 'describe') def hpat_pandas_series_describe(self, percentiles=None, include=None, exclude=None): """ Pandas Series method :meth:`pandas.Series.describe` implementation. Note: Differs from Pandas in returning statistics as Series of strings when applied to Series of strings or date-time values .. only:: developer Tests: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_describe* Parameters ---------- self: :obj:`pandas.Series` Input series percentiles: :obj:`list-like` The percentiles to include in the output. The default is [.25, .5, .75] All should fall between 0 and 1 and no duplicates are allowed. include: 'all', :obj:`list-like` of dtypes or None, default None A white list of data types to include in the result. Ignored for Series. exclude: :obj:`list-like` of dtypes or None, default None A black list of data types to omit from the result. Ignored for Series. Returns ------- :obj:`pandas.Series` returns :obj:`pandas.Series` object containing summary statistics of the Series """ ty_checker = TypeChecker('Method describe().') ty_checker.check(self, SeriesType) if not (isinstance(percentiles, (types.List, types.Array, types.UniTuple)) and isinstance(percentiles.dtype, types.Number) or isinstance(percentiles, (types.Omitted, types.NoneType)) or percentiles is None): ty_checker.raise_exc(percentiles, 'list-like', 'percentiles') is_percentiles_none = percentiles is None or isinstance(percentiles, (types.Omitted, types.NoneType)) if isinstance(self.dtype, types.Number): def hpat_pandas_series_describe_numeric_impl(self, percentiles=None, include=None, exclude=None): if is_percentiles_none == False: # noqa percentiles_list = list(percentiles) median_in_percentiles = 0.5 in percentiles_list if not median_in_percentiles: percentiles_list.append(0.5) sorted_percentiles = sorted(percentiles_list) # check percentiles have correct values: arr = numpy.asarray(sorted_percentiles) if len(numpy.unique(arr)) != len(arr): raise ValueError("percentiles cannot contain duplicates") if numpy.any(arr[(arr < 0) * (arr > 1)]): raise ValueError("percentiles should all be in the interval [0, 1].") # TODO: support proper rounding of percentiles like in pandas.io.formats.format.format_percentiles # requires numpy.round(precision), numpy.isclose to be supported by Numba percentiles_indexes = common_functions._sdc_pandas_format_percentiles(arr) else: sorted_percentiles = [0.25, 0.5, 0.75] percentiles_indexes = ['25%', '50%', '75%'] index_strings = ['count', 'mean', 'std', 'min'] index_strings.extend(percentiles_indexes) index_strings.append('max') values = [] values.append(numpy.float64(self.count())) values.append(self.mean()) values.append(self.std()) values.append(self.min()) for p in sorted_percentiles: values.append(self.quantile(p)) values.append(self.max()) return pandas.Series(values, index_strings) return hpat_pandas_series_describe_numeric_impl elif isinstance(self.dtype, types.UnicodeType): def hpat_pandas_series_describe_string_impl(self, percentiles=None, include=None, exclude=None): objcounts = self.value_counts() index_strings = ['count', 'unique', 'top', 'freq'] # use list of strings for the output series, since Numba doesn't support np.arrays with object dtype values = [] values.append(str(self.count())) values.append(str(len(self.unique()))) values.append(str(objcounts.index[0])) values.append(str(objcounts.iloc[0])) return pandas.Series(values, index_strings) return hpat_pandas_series_describe_string_impl elif isinstance(self.dtype, (types.NPDatetime, types.NPTimedelta)): # TODO: provide specialization for (types.NPDatetime, types.NPTimedelta) # needs dropna for date-time series, conversion to int and tz_convert to be implemented return None return None <file_sep># -*- coding: utf-8 -*- # ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** import time import numpy as np import pandas import numba import sdc from sdc.tests.tests_perf.test_perf_base import TestBase from sdc.tests.tests_perf.test_perf_utils import calc_compilation, get_times, perf_data_gen_fixed_len from sdc.tests.test_utils import test_global_input_data_float64 from sdc.io.csv_ext import to_varname def usecase_gen(call_expression): func_name = 'usecase_func' func_text = f"""\ def {func_name}(input_data): start_time = time.time() res = input_data.{call_expression} finish_time = time.time() return finish_time - start_time, res """ loc_vars = {} exec(func_text, globals(), loc_vars) _gen_impl = loc_vars[func_name] return _gen_impl def usecase_gen_two_par(name, par): func_name = 'usecase_func' func_text = f"""\ def {func_name}(A, B): start_time = time.time() res = A.{name}(B, {par}) finish_time = time.time() return finish_time - start_time, res """ loc_vars = {} exec(func_text, globals(), loc_vars) _gen_impl = loc_vars[func_name] return _gen_impl # python -m sdc.runtests sdc.tests.tests_perf.test_perf_df.TestDataFrameMethods class TestDataFrameMethods(TestBase): @classmethod def setUpClass(cls): super().setUpClass() def _test_jitted(self, pyfunc, record, *args, **kwargs): # compilation time record["compile_results"] = calc_compilation(pyfunc, *args, **kwargs) cfunc = numba.njit(pyfunc) # Warming up cfunc(*args, **kwargs) # execution and boxing time record["test_results"], record["boxing_results"] = \ get_times(cfunc, *args, **kwargs) def _test_python(self, pyfunc, record, *args, **kwargs): record["test_results"], _ = \ get_times(pyfunc, *args, **kwargs) def _test_case(self, pyfunc, data_name, total_data_length, test_name=None, input_data=test_global_input_data_float64): test_name = test_name or data_name full_input_data_length = sum(len(i) for i in input_data) for data_length in total_data_length: base = { "test_name": test_name, "data_size": data_length, } data = perf_data_gen_fixed_len(input_data, full_input_data_length, data_length) test_data = pandas.DataFrame({f"f{i}": data for i in range(3)}) record = base.copy() record["test_type"] = 'SDC' self._test_jitted(pyfunc, record, test_data) self.test_results.add(**record) record = base.copy() record["test_type"] = 'Python' self._test_python(pyfunc, record, test_data) self.test_results.add(**record) def _test_df_binary_operations(self, pyfunc, name, total_data_length, test_name=None, input_data=test_global_input_data_float64): np.random.seed(0) hpat_func = sdc.jit(pyfunc) for data_length in total_data_length: # TODO: replace with generic function to generate random sequence of floats data1 = np.random.ranf(data_length) data2 = np.random.ranf(data_length) A = pandas.DataFrame({f"f{i}": data1 for i in range(3)}) B = pandas.DataFrame({f"f{i}": data2 for i in range(3)}) compile_results = calc_compilation(pyfunc, A, B, iter_number=self.iter_number) # Warming up hpat_func(A, B) exec_times, boxing_times = get_times(hpat_func, A, B, iter_number=self.iter_number) self.test_results.add(name, 'JIT', A.size, exec_times, boxing_times, compile_results=compile_results, num_threads=self.num_threads) exec_times, _ = get_times(pyfunc, A, B, iter_number=self.iter_number) self.test_results.add(name, 'Reference', A.size, exec_times, num_threads=self.num_threads) def test_gen(name, params, data_length): func_name = 'func' func_text = f"""\ def {func_name}(self): self._test_case(usecase_gen('{name}({params})'), '{name}', {data_length}, 'DataFrame.{name}') """ global_vars = {'usecase_gen': usecase_gen} loc_vars = {} exec(func_text, global_vars, loc_vars) _gen_impl = loc_vars[func_name] return _gen_impl def test_gen_two_par(name, params, data_length): func_name = 'func' func_text = f"""\ def {func_name}(self): self._test_df_binary_operations(usecase_gen_two_par('{name}', '{params}'), '{name}', {data_length}, 'DataFrame.{name}') """ global_vars = {'usecase_gen_two_par': usecase_gen_two_par} loc_vars = {} exec(func_text, global_vars, loc_vars) _gen_impl = loc_vars[func_name] return _gen_impl cases = [ ('count', '', [10 ** 7]), ('drop', 'columns="f0"', [10 ** 8]), ('max', '', [10 ** 7]), ('mean', '', [10 ** 7]), ('median', '', [10 ** 7]), ('min', '', [10 ** 7]), ('pct_change', '', [10 ** 7]), ('prod', '', [10 ** 7]), ('std', '', [10 ** 7]), ('sum', '', [10 ** 7]), ('var', '', [10 ** 7]), ] cases_two_par = [ ('append', '', [10 ** 7]), ] def gen(cases, method): for params in cases: func, param, length = params name = func if param: name += "_" + to_varname(param).replace('__', '_') func_name = 'test_df_{}'.format(name) setattr(TestDataFrameMethods, func_name, method(func, param, length)) gen(cases, test_gen) gen(cases_two_par, test_gen_two_par) <file_sep># ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** import string import unittest import itertools import os import pandas as pd import platform import numpy as np import numba import sdc from itertools import product from numba.errors import TypingError from sdc.tests.test_base import TestCase from sdc.tests.test_utils import (count_array_REPs, count_parfor_REPs, count_parfor_OneDs, count_array_OneDs, dist_IR_contains, skip_numba_jit, skip_sdc_jit, test_global_input_data_float64) from sdc.hiframes.rolling import supported_rolling_funcs LONG_TEST = (int(os.environ['SDC_LONG_ROLLING_TEST']) != 0 if 'SDC_LONG_ROLLING_TEST' in os.environ else False) test_funcs = ('mean', 'max',) if LONG_TEST: # all functions except apply, cov, corr test_funcs = supported_rolling_funcs[:-3] def series_rolling_std_usecase(series, window, min_periods, ddof): return series.rolling(window, min_periods).std(ddof) def series_rolling_var_usecase(series, window, min_periods, ddof): return series.rolling(window, min_periods).var(ddof) class TestRolling(TestCase): @skip_numba_jit def test_fixed1(self): # test sequentially with manually created dfs wins = (3,) if LONG_TEST: wins = (2, 3, 5) centers = (False, True) for func_name in test_funcs: func_text = "def test_impl(df, w, c):\n return df.rolling(w, center=c).{}()\n".format(func_name) loc_vars = {} exec(func_text, {}, loc_vars) test_impl = loc_vars['test_impl'] hpat_func = self.jit(test_impl) for args in itertools.product(wins, centers): df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}) pd.testing.assert_frame_equal(hpat_func(df, *args), test_impl(df, *args)) df = pd.DataFrame({'B': [0, 1, 2, -2, 4]}) pd.testing.assert_frame_equal(hpat_func(df, *args), test_impl(df, *args)) @skip_numba_jit def test_fixed2(self): # test sequentially with generated dfs sizes = (121,) wins = (3,) if LONG_TEST: sizes = (1, 2, 10, 11, 121, 1000) wins = (2, 3, 5) centers = (False, True) for func_name in test_funcs: func_text = "def test_impl(df, w, c):\n return df.rolling(w, center=c).{}()\n".format(func_name) loc_vars = {} exec(func_text, {}, loc_vars) test_impl = loc_vars['test_impl'] hpat_func = self.jit(test_impl) for n, w, c in itertools.product(sizes, wins, centers): df = pd.DataFrame({'B': np.arange(n)}) pd.testing.assert_frame_equal(hpat_func(df, w, c), test_impl(df, w, c)) @skip_numba_jit def test_fixed_apply1(self): # test sequentially with manually created dfs def test_impl(df, w, c): return df.rolling(w, center=c).apply(lambda a: a.sum()) hpat_func = self.jit(test_impl) wins = (3,) if LONG_TEST: wins = (2, 3, 5) centers = (False, True) for args in itertools.product(wins, centers): df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}) pd.testing.assert_frame_equal(hpat_func(df, *args), test_impl(df, *args)) df = pd.DataFrame({'B': [0, 1, 2, -2, 4]}) pd.testing.assert_frame_equal(hpat_func(df, *args), test_impl(df, *args)) @skip_numba_jit def test_fixed_apply2(self): # test sequentially with generated dfs def test_impl(df, w, c): return df.rolling(w, center=c).apply(lambda a: a.sum()) hpat_func = self.jit(test_impl) sizes = (121,) wins = (3,) if LONG_TEST: sizes = (1, 2, 10, 11, 121, 1000) wins = (2, 3, 5) centers = (False, True) for n, w, c in itertools.product(sizes, wins, centers): df = pd.DataFrame({'B': np.arange(n)}) pd.testing.assert_frame_equal(hpat_func(df, w, c), test_impl(df, w, c)) @skip_numba_jit def test_fixed_parallel1(self): def test_impl(n, w, center): df = pd.DataFrame({'B': np.arange(n)}) R = df.rolling(w, center=center).sum() return R.B.sum() hpat_func = self.jit(test_impl) sizes = (121,) wins = (5,) if LONG_TEST: sizes = (1, 2, 10, 11, 121, 1000) wins = (2, 4, 5, 10, 11) centers = (False, True) for args in itertools.product(sizes, wins, centers): self.assertEqual(hpat_func(*args), test_impl(*args), "rolling fixed window with {}".format(args)) self.assertEqual(count_array_REPs(), 0) self.assertEqual(count_parfor_REPs(), 0) @skip_numba_jit def test_fixed_parallel_apply1(self): def test_impl(n, w, center): df = pd.DataFrame({'B': np.arange(n)}) R = df.rolling(w, center=center).apply(lambda a: a.sum()) return R.B.sum() hpat_func = self.jit(test_impl) sizes = (121,) wins = (5,) if LONG_TEST: sizes = (1, 2, 10, 11, 121, 1000) wins = (2, 4, 5, 10, 11) centers = (False, True) for args in itertools.product(sizes, wins, centers): self.assertEqual(hpat_func(*args), test_impl(*args), "rolling fixed window with {}".format(args)) self.assertEqual(count_array_REPs(), 0) self.assertEqual(count_parfor_REPs(), 0) @skip_numba_jit def test_variable1(self): # test sequentially with manually created dfs df1 = pd.DataFrame({'B': [0, 1, 2, np.nan, 4], 'time': [pd.Timestamp('20130101 09:00:00'), pd.Timestamp('20130101 09:00:02'), pd.Timestamp('20130101 09:00:03'), pd.Timestamp('20130101 09:00:05'), pd.Timestamp('20130101 09:00:06')]}) df2 = pd.DataFrame({'B': [0, 1, 2, -2, 4], 'time': [pd.Timestamp('20130101 09:00:01'), pd.Timestamp('20130101 09:00:02'), pd.Timestamp('20130101 09:00:03'), pd.Timestamp('20130101 09:00:04'), pd.Timestamp('20130101 09:00:09')]}) wins = ('2s',) if LONG_TEST: wins = ('1s', '2s', '3s', '4s') # all functions except apply for w, func_name in itertools.product(wins, test_funcs): func_text = "def test_impl(df):\n return df.rolling('{}', on='time').{}()\n".format(w, func_name) loc_vars = {} exec(func_text, {}, loc_vars) test_impl = loc_vars['test_impl'] hpat_func = self.jit(test_impl) # XXX: skipping min/max for this test since the behavior of Pandas # is inconsistent: it assigns NaN to last output instead of 4! if func_name not in ('min', 'max'): pd.testing.assert_frame_equal(hpat_func(df1), test_impl(df1)) pd.testing.assert_frame_equal(hpat_func(df2), test_impl(df2)) @skip_numba_jit def test_variable2(self): # test sequentially with generated dfs wins = ('2s',) sizes = (121,) if LONG_TEST: wins = ('1s', '2s', '3s', '4s') sizes = (1, 2, 10, 11, 121, 1000) # all functions except apply for w, func_name in itertools.product(wins, test_funcs): func_text = "def test_impl(df):\n return df.rolling('{}', on='time').{}()\n".format(w, func_name) loc_vars = {} exec(func_text, {}, loc_vars) test_impl = loc_vars['test_impl'] hpat_func = self.jit(test_impl) for n in sizes: time = pd.date_range(start='1/1/2018', periods=n, freq='s') df = pd.DataFrame({'B': np.arange(n), 'time': time}) pd.testing.assert_frame_equal(hpat_func(df), test_impl(df)) @skip_numba_jit def test_variable_apply1(self): # test sequentially with manually created dfs df1 = pd.DataFrame({'B': [0, 1, 2, np.nan, 4], 'time': [pd.Timestamp('20130101 09:00:00'), pd.Timestamp('20130101 09:00:02'), pd.Timestamp('20130101 09:00:03'), pd.Timestamp('20130101 09:00:05'), pd.Timestamp('20130101 09:00:06')]}) df2 = pd.DataFrame({'B': [0, 1, 2, -2, 4], 'time': [pd.Timestamp('20130101 09:00:01'), pd.Timestamp('20130101 09:00:02'), pd.Timestamp('20130101 09:00:03'), pd.Timestamp('20130101 09:00:04'), pd.Timestamp('20130101 09:00:09')]}) wins = ('2s',) if LONG_TEST: wins = ('1s', '2s', '3s', '4s') # all functions except apply for w in wins: func_text = "def test_impl(df):\n return df.rolling('{}', on='time').apply(lambda a: a.sum())\n".format(w) loc_vars = {} exec(func_text, {}, loc_vars) test_impl = loc_vars['test_impl'] hpat_func = self.jit(test_impl) pd.testing.assert_frame_equal(hpat_func(df1), test_impl(df1)) pd.testing.assert_frame_equal(hpat_func(df2), test_impl(df2)) @skip_numba_jit def test_variable_apply2(self): # test sequentially with generated dfs wins = ('2s',) sizes = (121,) if LONG_TEST: wins = ('1s', '2s', '3s', '4s') # TODO: this crashes on Travis (3 process config) with size 1 sizes = (2, 10, 11, 121, 1000) # all functions except apply for w in wins: func_text = "def test_impl(df):\n return df.rolling('{}', on='time').apply(lambda a: a.sum())\n".format(w) loc_vars = {} exec(func_text, {}, loc_vars) test_impl = loc_vars['test_impl'] hpat_func = self.jit(test_impl) for n in sizes: time = pd.date_range(start='1/1/2018', periods=n, freq='s') df = pd.DataFrame({'B': np.arange(n), 'time': time}) pd.testing.assert_frame_equal(hpat_func(df), test_impl(df)) @skip_numba_jit @unittest.skipIf(platform.system() == 'Windows', "ValueError: time must be monotonic") def test_variable_parallel1(self): wins = ('2s',) sizes = (121,) if LONG_TEST: wins = ('1s', '2s', '3s', '4s') # XXX: Pandas returns time = [np.nan] for size==1 for some reason sizes = (2, 10, 11, 121, 1000) # all functions except apply for w, func_name in itertools.product(wins, test_funcs): func_text = "def test_impl(n):\n" func_text += " df = pd.DataFrame({'B': np.arange(n), 'time': " func_text += " pd.DatetimeIndex(np.arange(n) * 1000000000)})\n" func_text += " res = df.rolling('{}', on='time').{}()\n".format(w, func_name) func_text += " return res.B.sum()\n" loc_vars = {} exec(func_text, {'pd': pd, 'np': np}, loc_vars) test_impl = loc_vars['test_impl'] hpat_func = self.jit(test_impl) for n in sizes: np.testing.assert_almost_equal(hpat_func(n), test_impl(n)) self.assertEqual(count_array_REPs(), 0) self.assertEqual(count_parfor_REPs(), 0) @skip_numba_jit @unittest.skipIf(platform.system() == 'Windows', "ValueError: time must be monotonic") def test_variable_apply_parallel1(self): wins = ('2s',) sizes = (121,) if LONG_TEST: wins = ('1s', '2s', '3s', '4s') # XXX: Pandas returns time = [np.nan] for size==1 for some reason sizes = (2, 10, 11, 121, 1000) # all functions except apply for w in wins: func_text = "def test_impl(n):\n" func_text += " df = pd.DataFrame({'B': np.arange(n), 'time': " func_text += " pd.DatetimeIndex(np.arange(n) * 1000000000)})\n" func_text += " res = df.rolling('{}', on='time').apply(lambda a: a.sum())\n".format(w) func_text += " return res.B.sum()\n" loc_vars = {} exec(func_text, {'pd': pd, 'np': np}, loc_vars) test_impl = loc_vars['test_impl'] hpat_func = self.jit(test_impl) for n in sizes: np.testing.assert_almost_equal(hpat_func(n), test_impl(n)) self.assertEqual(count_array_REPs(), 0) self.assertEqual(count_parfor_REPs(), 0) @skip_numba_jit def test_series_fixed1(self): # test series rolling functions # all functions except apply S1 = pd.Series([0, 1, 2, np.nan, 4]) S2 = pd.Series([0, 1, 2, -2, 4]) wins = (3,) if LONG_TEST: wins = (2, 3, 5) centers = (False, True) for func_name in test_funcs: func_text = "def test_impl(S, w, c):\n return S.rolling(w, center=c).{}()\n".format(func_name) loc_vars = {} exec(func_text, {}, loc_vars) test_impl = loc_vars['test_impl'] hpat_func = self.jit(test_impl) for args in itertools.product(wins, centers): pd.testing.assert_series_equal(hpat_func(S1, *args), test_impl(S1, *args)) pd.testing.assert_series_equal(hpat_func(S2, *args), test_impl(S2, *args)) # test apply def apply_test_impl(S, w, c): return S.rolling(w, center=c).apply(lambda a: a.sum()) hpat_func = self.jit(apply_test_impl) for args in itertools.product(wins, centers): pd.testing.assert_series_equal(hpat_func(S1, *args), apply_test_impl(S1, *args)) pd.testing.assert_series_equal(hpat_func(S2, *args), apply_test_impl(S2, *args)) @skip_numba_jit def test_series_cov1(self): # test series rolling functions # all functions except apply S1 = pd.Series([0, 1, 2, np.nan, 4]) S2 = pd.Series([0, 1, 2, -2, 4]) wins = (3,) if LONG_TEST: wins = (2, 3, 5) centers = (False, True) def test_impl(S, S2, w, c): return S.rolling(w, center=c).cov(S2) hpat_func = self.jit(test_impl) for args in itertools.product([S1, S2], [S1, S2], wins, centers): pd.testing.assert_series_equal(hpat_func(*args), test_impl(*args)) pd.testing.assert_series_equal(hpat_func(*args), test_impl(*args)) def test_impl2(S, S2, w, c): return S.rolling(w, center=c).corr(S2) hpat_func = self.jit(test_impl2) for args in itertools.product([S1, S2], [S1, S2], wins, centers): pd.testing.assert_series_equal(hpat_func(*args), test_impl2(*args)) pd.testing.assert_series_equal(hpat_func(*args), test_impl2(*args)) @skip_numba_jit def test_df_cov1(self): # test series rolling functions # all functions except apply df1 = pd.DataFrame({'A': [0, 1, 2, np.nan, 4], 'B': np.ones(5)}) df2 = pd.DataFrame({'A': [0, 1, 2, -2, 4], 'C': np.ones(5)}) wins = (3,) if LONG_TEST: wins = (2, 3, 5) centers = (False, True) def test_impl(df, df2, w, c): return df.rolling(w, center=c).cov(df2) hpat_func = self.jit(test_impl) for args in itertools.product([df1, df2], [df1, df2], wins, centers): pd.testing.assert_frame_equal(hpat_func(*args), test_impl(*args)) pd.testing.assert_frame_equal(hpat_func(*args), test_impl(*args)) def test_impl2(df, df2, w, c): return df.rolling(w, center=c).corr(df2) hpat_func = self.jit(test_impl2) for args in itertools.product([df1, df2], [df1, df2], wins, centers): pd.testing.assert_frame_equal(hpat_func(*args), test_impl2(*args)) pd.testing.assert_frame_equal(hpat_func(*args), test_impl2(*args)) def _get_assert_equal(self, obj): if isinstance(obj, pd.Series): return pd.testing.assert_series_equal elif isinstance(obj, pd.DataFrame): return pd.testing.assert_frame_equal elif isinstance(obj, np.ndarray): return np.testing.assert_array_equal return self.assertEqual def _test_rolling_unsupported_values(self, obj): def test_impl(obj, window, min_periods, center, win_type, on, axis, closed): return obj.rolling(window, min_periods, center, win_type, on, axis, closed).min() hpat_func = self.jit(test_impl) with self.assertRaises(ValueError) as raises: hpat_func(obj, -1, None, False, None, None, 0, None) self.assertIn('window must be non-negative', str(raises.exception)) with self.assertRaises(ValueError) as raises: hpat_func(obj, 1, -1, False, None, None, 0, None) self.assertIn('min_periods must be >= 0', str(raises.exception)) with self.assertRaises(ValueError) as raises: hpat_func(obj, 1, 2, False, None, None, 0, None) self.assertIn('min_periods must be <= window', str(raises.exception)) with self.assertRaises(ValueError) as raises: hpat_func(obj, 1, 2, False, None, None, 0, None) self.assertIn('min_periods must be <= window', str(raises.exception)) msg_tmpl = 'Method rolling(). The object {}\n expected: {}' with self.assertRaises(ValueError) as raises: hpat_func(obj, 1, None, True, None, None, 0, None) msg = msg_tmpl.format('center', 'False') self.assertIn(msg, str(raises.exception)) with self.assertRaises(ValueError) as raises: hpat_func(obj, 1, None, False, 'None', None, 0, None) msg = msg_tmpl.format('win_type', 'None') self.assertIn(msg, str(raises.exception)) with self.assertRaises(ValueError) as raises: hpat_func(obj, 1, None, False, None, 'None', 0, None) msg = msg_tmpl.format('on', 'None') self.assertIn(msg, str(raises.exception)) with self.assertRaises(ValueError) as raises: hpat_func(obj, 1, None, False, None, None, 1, None) msg = msg_tmpl.format('axis', '0') self.assertIn(msg, str(raises.exception)) with self.assertRaises(ValueError) as raises: hpat_func(obj, 1, None, False, None, None, 0, 'None') msg = msg_tmpl.format('closed', 'None') self.assertIn(msg, str(raises.exception)) def _test_rolling_unsupported_types(self, obj): def test_impl(obj, window, min_periods, center, win_type, on, axis, closed): return obj.rolling(window, min_periods, center, win_type, on, axis, closed).min() hpat_func = self.jit(test_impl) msg_tmpl = 'Method rolling(). The object {}\n given: {}\n expected: {}' with self.assertRaises(TypingError) as raises: hpat_func(obj, '1', None, False, None, None, 0, None) msg = msg_tmpl.format('window', 'unicode_type', 'int') self.assertIn(msg, str(raises.exception)) with self.assertRaises(TypingError) as raises: hpat_func(obj, 1, '1', False, None, None, 0, None) msg = msg_tmpl.format('min_periods', 'unicode_type', 'None, int') self.assertIn(msg, str(raises.exception)) with self.assertRaises(TypingError) as raises: hpat_func(obj, 1, None, 0, None, None, 0, None) msg = msg_tmpl.format('center', 'int64', 'bool') self.assertIn(msg, str(raises.exception)) with self.assertRaises(TypingError) as raises: hpat_func(obj, 1, None, False, -1, None, 0, None) msg = msg_tmpl.format('win_type', 'int64', 'str') self.assertIn(msg, str(raises.exception)) with self.assertRaises(TypingError) as raises: hpat_func(obj, 1, None, False, None, -1, 0, None) msg = msg_tmpl.format('on', 'int64', 'str') self.assertIn(msg, str(raises.exception)) with self.assertRaises(TypingError) as raises: hpat_func(obj, 1, None, False, None, None, None, None) msg = msg_tmpl.format('axis', 'none', 'int, str') self.assertIn(msg, str(raises.exception)) with self.assertRaises(TypingError) as raises: hpat_func(obj, 1, None, False, None, None, 0, -1) msg = msg_tmpl.format('closed', 'int64', 'str') self.assertIn(msg, str(raises.exception)) def _test_rolling_min(self, obj): def test_impl(obj, window, min_periods): return obj.rolling(window, min_periods).min() hpat_func = self.jit(test_impl) assert_equal = self._get_assert_equal(obj) # TODO: fix the issue when window = 0 for window in range(1, len(obj) + 2): for min_periods in range(window + 1): with self.subTest(obj=obj, window=window, min_periods=min_periods): jit_result = hpat_func(obj, window, min_periods) ref_result = test_impl(obj, window, min_periods) assert_equal(jit_result, ref_result) @skip_sdc_jit('DataFrame.rolling.min() unsupported exceptions') def test_df_rolling_unsupported_values(self): all_data = test_global_input_data_float64 length = min(len(d) for d in all_data) data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)} df = pd.DataFrame(data) self._test_rolling_unsupported_values(df) @skip_sdc_jit('DataFrame.rolling.min() unsupported exceptions') def test_df_rolling_unsupported_types(self): all_data = test_global_input_data_float64 length = min(len(d) for d in all_data) data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)} df = pd.DataFrame(data) self._test_rolling_unsupported_types(df) @skip_sdc_jit('DataFrame.rolling.min() unsupported') def test_df_rolling_min(self): all_data = test_global_input_data_float64 length = min(len(d) for d in all_data) data = {n: d[:length] for n, d in zip(string.ascii_uppercase, all_data)} df = pd.DataFrame(data) self._test_rolling_min(df) @skip_sdc_jit('Series.rolling.min() unsupported exceptions') def test_series_rolling_unsupported_values(self): series = pd.Series(test_global_input_data_float64[0]) self._test_rolling_unsupported_values(series) @skip_sdc_jit('Series.rolling.min() unsupported exceptions') def test_series_rolling_unsupported_types(self): series = pd.Series(test_global_input_data_float64[0]) self._test_rolling_unsupported_types(series) @skip_sdc_jit('Series.rolling.apply() unsupported Series index') def test_series_rolling_apply_mean(self): def test_impl(series, window, min_periods): def func(x): if len(x) == 0: return np.nan return x.mean() return series.rolling(window, min_periods).apply(func) hpat_func = self.jit(test_impl) all_data = [ list(range(10)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(0, len(series) + 3, 2): for min_periods in range(0, window + 1, 2): with self.subTest(series=series, window=window, min_periods=min_periods): jit_result = hpat_func(series, window, min_periods) ref_result = test_impl(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.apply() unsupported exceptions') def test_series_rolling_apply_unsupported_types(self): def test_impl(raw): def func(x): if len(x) == 0: return np.nan return np.median(x) series = pd.Series([1., -1., 0., 0.1, -0.1]) return series.rolling(3).apply(func, raw=raw) hpat_func = self.jit(test_impl) with self.assertRaises(TypingError) as raises: hpat_func(1) msg = 'Method rolling.apply(). The object raw\n given: int64\n expected: bool' self.assertIn(msg, str(raises.exception)) @unittest.skip('Series.rolling.apply() unsupported args') def test_series_rolling_apply_args(self): def test_impl(series, window, min_periods, q): def func(x, q): if len(x) == 0: return np.nan return np.quantile(x, q) return series.rolling(window, min_periods).apply(func, raw=None, args=(q,)) hpat_func = self.jit(test_impl) all_data = [ list(range(10)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(0, len(series) + 3, 2): for min_periods in range(0, window + 1, 2): for q in [0.25, 0.5, 0.75]: with self.subTest(series=series, window=window, min_periods=min_periods, q=q): jit_result = hpat_func(series, window, min_periods, q) ref_result = test_impl(series, window, min_periods, q) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.corr() unsupported Series index') def test_series_rolling_corr(self): def test_impl(series, window, min_periods, other): return series.rolling(window, min_periods).corr(other) hpat_func = self.jit(test_impl) all_data = [ list(range(10)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] for main_data, other_data in product(all_data, all_data): series = pd.Series(main_data) other = pd.Series(other_data) for window in range(0, len(series) + 3, 2): for min_periods in range(0, window, 2): with self.subTest(series=series, other=other, window=window, min_periods=min_periods): ref_result = test_impl(series, window, min_periods, other) jit_result = hpat_func(series, window, min_periods, other) pd.testing.assert_series_equal(ref_result, jit_result) @skip_sdc_jit('Series.rolling.corr() unsupported Series index') def test_series_rolling_corr_with_no_other(self): def test_impl(series, window, min_periods): return series.rolling(window, min_periods).corr() hpat_func = self.jit(test_impl) all_data = [ list(range(10)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] for data in all_data: series = pd.Series(data) for window in range(0, len(series) + 3, 2): for min_periods in range(0, window, 2): with self.subTest(series=series, window=window, min_periods=min_periods): jit_result = hpat_func(series, window, min_periods) ref_result = test_impl(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.corr() unsupported exceptions') def test_series_rolling_corr_unsupported_types(self): def test_impl(pairwise): series = pd.Series([1., -1., 0., 0.1, -0.1]) return series.rolling(3, 3).corr(pairwise=pairwise) hpat_func = self.jit(test_impl) with self.assertRaises(TypingError) as raises: hpat_func(1) msg = 'Method rolling.corr(). The object pairwise\n given: int64\n expected: bool' self.assertIn(msg, str(raises.exception)) @skip_sdc_jit('Series.rolling.count() unsupported Series index') def test_series_rolling_count(self): def test_impl(series, window, min_periods): return series.rolling(window, min_periods).count() hpat_func = self.jit(test_impl) all_data = test_global_input_data_float64 indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(0, len(series) + 3, 2): for min_periods in range(0, window + 1, 2): with self.subTest(series=series, window=window, min_periods=min_periods): jit_result = hpat_func(series, window, min_periods) ref_result = test_impl(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.cov() unsupported Series index') def test_series_rolling_cov(self): def test_impl(series, window, min_periods, other, ddof): return series.rolling(window, min_periods).cov(other, ddof=ddof) hpat_func = self.jit(test_impl) all_data = [ list(range(5)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] for main_data, other_data in product(all_data, all_data): series = pd.Series(main_data) other = pd.Series(other_data) for window in range(0, len(series) + 3, 2): for min_periods, ddof in product(range(0, window, 2), [0, 1]): with self.subTest(series=series, other=other, window=window, min_periods=min_periods, ddof=ddof): jit_result = hpat_func(series, window, min_periods, other, ddof) ref_result = test_impl(series, window, min_periods, other, ddof) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.cov() unsupported Series index') def test_series_rolling_cov_default(self): def test_impl(series, window, min_periods): return series.rolling(window, min_periods).cov() hpat_func = self.jit(test_impl) all_data = [ list(range(5)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] for data in all_data: series = pd.Series(data) for window in range(0, len(series) + 3, 2): for min_periods in range(0, window, 2): with self.subTest(series=series, window=window, min_periods=min_periods): jit_result = hpat_func(series, window, min_periods) ref_result = test_impl(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.cov() unsupported Series index') @unittest.expectedFailure def test_series_rolling_cov_issue_floating_point_rounding(self): """Cover issue of different float rounding in Python and SDC/Numba""" def test_impl(series, window, min_periods, other, ddof): return series.rolling(window, min_periods).cov(other, ddof=ddof) hpat_func = self.jit(test_impl) series = pd.Series(list(range(10))) other = pd.Series([1., -1., 0., 0.1, -0.1]) jit_result = hpat_func(series, 6, 0, other, 1) ref_result = test_impl(series, 6, 0, other, 1) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.cov() unsupported exceptions') def test_series_rolling_cov_unsupported_types(self): def test_impl(pairwise, ddof): series = pd.Series([1., -1., 0., 0.1, -0.1]) return series.rolling(3, 3).cov(pairwise=pairwise, ddof=ddof) hpat_func = self.jit(test_impl) msg_tmpl = 'Method rolling.cov(). The object {}\n given: {}\n expected: {}' with self.assertRaises(TypingError) as raises: hpat_func(1, 1) msg = msg_tmpl.format('pairwise', 'int64', 'bool') self.assertIn(msg, str(raises.exception)) with self.assertRaises(TypingError) as raises: hpat_func(None, '1') msg = msg_tmpl.format('ddof', 'unicode_type', 'int') self.assertIn(msg, str(raises.exception)) @skip_sdc_jit('Series.rolling.kurt() unsupported Series index') def test_series_rolling_kurt(self): def test_impl(series, window, min_periods): return series.rolling(window, min_periods).kurt() hpat_func = self.jit(test_impl) all_data = test_global_input_data_float64 indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(4, len(series) + 1): for min_periods in range(window + 1): with self.subTest(series=series, window=window, min_periods=min_periods): ref_result = test_impl(series, window, min_periods) jit_result = hpat_func(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.max() unsupported Series index') def test_series_rolling_max(self): def test_impl(series, window, min_periods): return series.rolling(window, min_periods).max() hpat_func = self.jit(test_impl) all_data = test_global_input_data_float64 indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') # TODO: fix the issue when window = 0 for window in range(1, len(series) + 2): for min_periods in range(window + 1): with self.subTest(series=series, window=window, min_periods=min_periods): jit_result = hpat_func(series, window, min_periods) ref_result = test_impl(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.mean() unsupported Series index') def test_series_rolling_mean(self): def test_impl(series, window, min_periods): return series.rolling(window, min_periods).mean() hpat_func = self.jit(test_impl) all_data = [ list(range(10)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(0, len(series) + 3, 2): for min_periods in range(0, window + 1, 2): with self.subTest(series=series, window=window, min_periods=min_periods): jit_result = hpat_func(series, window, min_periods) ref_result = test_impl(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.median() unsupported Series index') def test_series_rolling_median(self): def test_impl(series, window, min_periods): return series.rolling(window, min_periods).median() hpat_func = self.jit(test_impl) all_data = test_global_input_data_float64 indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(0, len(series) + 3, 2): for min_periods in range(0, window + 1, 2): with self.subTest(series=series, window=window, min_periods=min_periods): jit_result = hpat_func(series, window, min_periods) ref_result = test_impl(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.min() unsupported Series index') def test_series_rolling_min(self): all_data = test_global_input_data_float64 indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') self._test_rolling_min(series) @skip_sdc_jit('Series.rolling.quantile() unsupported Series index') def test_series_rolling_quantile(self): def test_impl(series, window, min_periods, quantile): return series.rolling(window, min_periods).quantile(quantile) hpat_func = self.jit(test_impl) all_data = [ list(range(10)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] indices = [list(range(len(data)))[::-1] for data in all_data] quantiles = [0, 0.25, 0.5, 0.75, 1] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(0, len(series) + 3, 2): for min_periods, q in product(range(0, window, 2), quantiles): with self.subTest(series=series, window=window, min_periods=min_periods, quantiles=q): jit_result = hpat_func(series, window, min_periods, q) ref_result = test_impl(series, window, min_periods, q) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.quantile() unsupported exceptions') def test_series_rolling_quantile_exception_unsupported_types(self): def test_impl(quantile, interpolation): series = pd.Series([1., -1., 0., 0.1, -0.1]) return series.rolling(3, 2).quantile(quantile, interpolation) hpat_func = self.jit(test_impl) msg_tmpl = 'Method rolling.quantile(). The object {}\n given: {}\n expected: {}' with self.assertRaises(TypingError) as raises: hpat_func('0.5', 'linear') msg = msg_tmpl.format('quantile', 'unicode_type', 'float') self.assertIn(msg, str(raises.exception)) with self.assertRaises(TypingError) as raises: hpat_func(0.5, None) msg = msg_tmpl.format('interpolation', 'none', 'str') self.assertIn(msg, str(raises.exception)) @skip_sdc_jit('Series.rolling.quantile() unsupported exceptions') def test_series_rolling_quantile_exception_unsupported_values(self): def test_impl(quantile, interpolation): series = pd.Series([1., -1., 0., 0.1, -0.1]) return series.rolling(3, 2).quantile(quantile, interpolation) hpat_func = self.jit(test_impl) with self.assertRaises(ValueError) as raises: hpat_func(2, 'linear') self.assertIn('quantile value not in [0, 1]', str(raises.exception)) with self.assertRaises(ValueError) as raises: hpat_func(0.5, 'lower') self.assertIn('interpolation value not "linear"', str(raises.exception)) @skip_sdc_jit('Series.rolling.skew() unsupported Series index') def test_series_rolling_skew(self): def test_impl(series, window, min_periods): return series.rolling(window, min_periods).skew() hpat_func = self.jit(test_impl) all_data = test_global_input_data_float64 indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(3, len(series) + 1): for min_periods in range(window + 1): with self.subTest(series=series, window=window, min_periods=min_periods): ref_result = test_impl(series, window, min_periods) jit_result = hpat_func(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.std() unsupported Series index') def test_series_rolling_std(self): test_impl = series_rolling_std_usecase hpat_func = self.jit(test_impl) all_data = [ list(range(10)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(0, len(series) + 3, 2): for min_periods, ddof in product(range(0, window, 2), [0, 1]): with self.subTest(series=series, window=window, min_periods=min_periods, ddof=ddof): jit_result = hpat_func(series, window, min_periods, ddof) ref_result = test_impl(series, window, min_periods, ddof) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.std() unsupported exceptions') def test_series_rolling_std_exception_unsupported_ddof(self): test_impl = series_rolling_std_usecase hpat_func = self.jit(test_impl) series = pd.Series([1., -1., 0., 0.1, -0.1]) with self.assertRaises(TypingError) as raises: hpat_func(series, 3, 2, '1') msg = 'Method rolling.std(). The object ddof\n given: unicode_type\n expected: int' self.assertIn(msg, str(raises.exception)) @skip_sdc_jit('Series.rolling.sum() unsupported Series index') def test_series_rolling_sum(self): def test_impl(series, window, min_periods): return series.rolling(window, min_periods).sum() hpat_func = self.jit(test_impl) all_data = [ list(range(10)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(0, len(series) + 3, 2): for min_periods in range(0, window + 1, 2): with self.subTest(series=series, window=window, min_periods=min_periods): jit_result = hpat_func(series, window, min_periods) ref_result = test_impl(series, window, min_periods) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.var() unsupported Series index') def test_series_rolling_var(self): test_impl = series_rolling_var_usecase hpat_func = self.jit(test_impl) all_data = [ list(range(10)), [1., -1., 0., 0.1, -0.1], [1., np.inf, np.inf, -1., 0., np.inf, np.NINF, np.NINF], [np.nan, np.inf, np.inf, np.nan, np.nan, np.nan, np.NINF, np.NZERO] ] indices = [list(range(len(data)))[::-1] for data in all_data] for data, index in zip(all_data, indices): series = pd.Series(data, index, name='A') for window in range(0, len(series) + 3, 2): for min_periods, ddof in product(range(0, window, 2), [0, 1]): with self.subTest(series=series, window=window, min_periods=min_periods, ddof=ddof): jit_result = hpat_func(series, window, min_periods, ddof) ref_result = test_impl(series, window, min_periods, ddof) pd.testing.assert_series_equal(jit_result, ref_result) @skip_sdc_jit('Series.rolling.var() unsupported exceptions') def test_series_rolling_var_exception_unsupported_ddof(self): test_impl = series_rolling_var_usecase hpat_func = self.jit(test_impl) series = pd.Series([1., -1., 0., 0.1, -0.1]) with self.assertRaises(TypingError) as raises: hpat_func(series, 3, 2, '1') msg = 'Method rolling.var(). The object ddof\n given: unicode_type\n expected: int' self.assertIn(msg, str(raises.exception)) if __name__ == "__main__": unittest.main() <file_sep># ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** """ | This file contains function templates used by the auto-generation script during build """ # below imports are copied into the auto-generated source file as-is # for the auto-generation script to work ensure they are not mixed up with code import numba import numpy import operator import pandas from numba.errors import TypingError from numba import types import sdc from sdc.datatypes.common_functions import TypeChecker from sdc.datatypes.common_functions import (check_index_is_numeric, find_common_dtype_from_numpy_dtypes, sdc_join_series_indexes, sdc_check_indexes_equal, check_types_comparable) from sdc.hiframes.pd_series_type import SeriesType from sdc.str_arr_ext import (string_array_type, num_total_chars, str_arr_is_na) from sdc.utils import sdc_overload def sdc_pandas_series_operator_binop(self, other): """ Pandas Series operator :attr:`pandas.Series.binop` implementation Note: Currently implemented for numeric Series only. Differs from Pandas in returning Series with fixed dtype :obj:`float64` .. only:: developer **Test**: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op1* python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op2* python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_operator_binop* Parameters ---------- series: :obj:`pandas.Series` Input series other: :obj:`pandas.Series` or :obj:`scalar` Series or scalar value to be used as a second argument of binary operation Returns ------- :obj:`pandas.Series` The result of the operation """ _func_name = 'Operator binop().' ty_checker = TypeChecker('Operator binop().') if not isinstance(self, SeriesType): return None if not isinstance(other, (SeriesType, types.Number)): ty_checker.raise_exc(other, 'pandas.series or scalar', 'other') if isinstance(other, SeriesType): none_or_numeric_indexes = ((isinstance(self.index, types.NoneType) or check_index_is_numeric(self)) and (isinstance(other.index, types.NoneType) or check_index_is_numeric(other))) series_data_comparable = check_types_comparable(self.data, other.data) series_indexes_comparable = check_types_comparable(self.index, other.index) or none_or_numeric_indexes if isinstance(other, SeriesType) and not series_data_comparable: raise TypingError('{} Not supported for series with not-comparable data. \ Given: self.data={}, other.data={}'.format(_func_name, self.data, other.data)) if isinstance(other, SeriesType) and not series_indexes_comparable: raise TypingError('{} Not implemented for series with not-comparable indexes. \ Given: self.index={}, other.index={}'.format(_func_name, self.index, other.index)) # specializations for numeric series - TODO: support arithmetic operation on StringArrays if (isinstance(other, types.Number)): def _series_operator_binop_scalar_impl(self, other): result_data = self._data.astype(numpy.float64) + numpy.float64(other) return pandas.Series(result_data, index=self._index, name=self._name) return _series_operator_binop_scalar_impl elif (isinstance(other, SeriesType)): # optimization for series with default indexes, that can be aligned differently if (isinstance(self.index, types.NoneType) and isinstance(other.index, types.NoneType)): def _series_operator_binop_none_indexes_impl(self, other): if (len(self._data) == len(other._data)): result_data = self._data.astype(numpy.float64) result_data = result_data + other._data.astype(numpy.float64) return pandas.Series(result_data) else: left_size, right_size = len(self._data), len(other._data) min_data_size = min(left_size, right_size) max_data_size = max(left_size, right_size) result_data = numpy.empty(max_data_size, dtype=numpy.float64) if (left_size == min_data_size): result_data[:min_data_size] = self._data result_data[min_data_size:] = numpy.nan result_data = result_data + other._data.astype(numpy.float64) else: result_data[:min_data_size] = other._data result_data[min_data_size:] = numpy.nan result_data = self._data.astype(numpy.float64) + result_data return pandas.Series(result_data, self._index) return _series_operator_binop_none_indexes_impl else: # for numeric indexes find common dtype to be used when creating joined index if none_or_numeric_indexes: ty_left_index_dtype = types.int64 if isinstance(self.index, types.NoneType) else self.index.dtype ty_right_index_dtype = types.int64 if isinstance(other.index, types.NoneType) else other.index.dtype numba_index_common_dtype = find_common_dtype_from_numpy_dtypes( [ty_left_index_dtype, ty_right_index_dtype], []) def _series_operator_binop_common_impl(self, other): left_index, right_index = self.index, other.index # check if indexes are equal and series don't have to be aligned if sdc_check_indexes_equal(left_index, right_index): result_data = self._data.astype(numpy.float64) result_data = result_data + other._data.astype(numpy.float64) if none_or_numeric_indexes == True: # noqa result_index = left_index.astype(numba_index_common_dtype) else: result_index = self._index return pandas.Series(result_data, index=result_index) # TODO: replace below with core join(how='outer', return_indexers=True) when implemented joined_index, left_indexer, right_indexer = sdc_join_series_indexes(left_index, right_index) joined_index_range = numpy.arange(len(joined_index)) left_values = numpy.asarray( [self._data[left_indexer[i]] for i in joined_index_range], numpy.float64 ) left_values[left_indexer == -1] = numpy.nan right_values = numpy.asarray( [other._data[right_indexer[i]] for i in joined_index_range], numpy.float64 ) right_values[right_indexer == -1] = numpy.nan result_data = left_values + right_values return pandas.Series(result_data, joined_index) return _series_operator_binop_common_impl return None def sdc_pandas_series_operator_comp_binop(self, other): """ Pandas Series operator :attr:`pandas.Series.comp_binop` implementation .. only:: developer **Test**: python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_op7* python -m sdc.runtests -k sdc.tests.test_series.TestSeries.test_series_operator_comp_binop* Parameters ---------- series: :obj:`pandas.Series` Input series other: :obj:`pandas.Series` or :obj:`scalar` Series or scalar value to be used as a second argument of binary operation Returns ------- :obj:`pandas.Series` The result of the operation """ _func_name = 'Operator comp_binop().' ty_checker = TypeChecker('Operator comp_binop().') if not isinstance(self, SeriesType): return None if not isinstance(other, (SeriesType, types.Number)): ty_checker.raise_exc(other, 'pandas.series or scalar', 'other') if isinstance(other, SeriesType): none_or_numeric_indexes = ((isinstance(self.index, types.NoneType) or check_index_is_numeric(self)) and (isinstance(other.index, types.NoneType) or check_index_is_numeric(other))) series_data_comparable = check_types_comparable(self.data, other.data) series_indexes_comparable = check_types_comparable(self.index, other.index) or none_or_numeric_indexes if isinstance(other, SeriesType) and not series_data_comparable: raise TypingError('{} Not supported for series with not-comparable data. \ Given: self.data={}, other.data={}'.format(_func_name, self.data, other.data)) if isinstance(other, SeriesType) and not series_indexes_comparable: raise TypingError('{} Not implemented for series with not-comparable indexes. \ Given: self.index={}, other.index={}'.format(_func_name, self.index, other.index)) # specializations for numeric series if (isinstance(other, types.Number)): def _series_operator_comp_binop_scalar_impl(self, other): return pandas.Series(self._data < other, index=self._index, name=self._name) return _series_operator_comp_binop_scalar_impl elif (isinstance(other, SeriesType)): # optimization for series with default indexes, that can be aligned differently if (isinstance(self.index, types.NoneType) and isinstance(other.index, types.NoneType)): def _series_operator_comp_binop_none_indexes_impl(self, other): left_size, right_size = len(self._data), len(other._data) if (left_size == right_size): return pandas.Series(self._data < other._data) else: raise ValueError("Can only compare identically-labeled Series objects") return _series_operator_comp_binop_none_indexes_impl else: if none_or_numeric_indexes: ty_left_index_dtype = types.int64 if isinstance(self.index, types.NoneType) else self.index.dtype ty_right_index_dtype = types.int64 if isinstance(other.index, types.NoneType) else other.index.dtype numba_index_common_dtype = find_common_dtype_from_numpy_dtypes( [ty_left_index_dtype, ty_right_index_dtype], []) def _series_operator_comp_binop_common_impl(self, other): left_index, right_index = self.index, other.index if sdc_check_indexes_equal(left_index, right_index): if none_or_numeric_indexes == True: # noqa new_index = left_index.astype(numba_index_common_dtype) else: new_index = self._index return pandas.Series(self._data < other._data, new_index) else: raise ValueError("Can only compare identically-labeled Series objects") return _series_operator_comp_binop_common_impl return None <file_sep># -*- coding: utf-8 -*- # ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** import pandas as pd import numpy as np import time import random import pandas import sdc from .test_perf_base import TestBase from sdc.tests.test_utils import test_global_input_data_float64 from .test_perf_utils import calc_compilation, get_times, perf_data_gen_fixed_len from sdc.io.csv_ext import to_varname def usecase_gen(call_expression): func_name = 'usecase_func' func_text = f"""\ def {func_name}(input_data): start_time = time.time() res = input_data.{call_expression} finish_time = time.time() return finish_time - start_time, res """ loc_vars = {} exec(func_text, globals(), loc_vars) _gen_impl = loc_vars[func_name] return _gen_impl def usecase_gen_two_par(name, par): func_name = 'usecase_func' func_text = f"""\ def {func_name}(A, B): start_time = time.time() res = A.{name}(B, {par}) finish_time = time.time() return finish_time - start_time, res """ loc_vars = {} exec(func_text, globals(), loc_vars) _gen_impl = loc_vars[func_name] return _gen_impl def usecase_series_astype_int(input_data): # astype to int8 start_time = time.time() input_data.astype(np.int8) finish_time = time.time() res_time = finish_time - start_time return res_time, input_data def usecase_series_chain_add_and_sum(A, B): start_time = time.time() res = (A + B).sum() finish_time = time.time() res_time = finish_time - start_time return res_time, res # python -m sdc.runtests sdc.tests.tests_perf.test_perf_series.TestSeriesMethods class TestSeriesMethods(TestBase): @classmethod def setUpClass(cls): super().setUpClass() def _test_jitted(self, pyfunc, record, *args, **kwargs): # compilation time record["compile_results"] = calc_compilation(pyfunc, *args, **kwargs) sdc_func = sdc.jit(pyfunc) # Warming up sdc_func(*args, **kwargs) # execution and boxing time record["test_results"], record["boxing_results"] = \ get_times(sdc_func, *args, **kwargs) def _test_python(self, pyfunc, record, *args, **kwargs): record["test_results"], _ = \ get_times(pyfunc, *args, **kwargs) def _test_case(self, pyfunc, name, total_data_length, input_data=test_global_input_data_float64): full_input_data_length = sum(len(i) for i in input_data) for data_length in total_data_length: base = { "test_name": name, "data_size": data_length, } data = perf_data_gen_fixed_len(input_data, full_input_data_length, data_length) test_data = pandas.Series(data) record = base.copy() record["test_type"] = 'SDC' self._test_jitted(pyfunc, record, test_data) self.test_results.add(**record) record = base.copy() record["test_type"] = 'Python' self._test_python(pyfunc, record, test_data) self.test_results.add(**record) def _test_series_binary_operations(self, pyfunc, name, total_data_length, input_data=None): np.random.seed(0) hpat_func = sdc.jit(pyfunc) for data_length in total_data_length: # TODO: replace with generic function to generate random sequence of floats data1 = np.random.ranf(data_length) data2 = np.random.ranf(data_length) A = pd.Series(data1) B = pd.Series(data2) compile_results = calc_compilation(pyfunc, A, B, iter_number=self.iter_number) # Warming up hpat_func(A, B) exec_times, boxing_times = get_times(hpat_func, A, B, iter_number=self.iter_number) self.test_results.add(name, 'JIT', A.size, exec_times, boxing_times, compile_results=compile_results, num_threads=self.num_threads) exec_times, _ = get_times(pyfunc, A, B, iter_number=self.iter_number) self.test_results.add(name, 'Reference', A.size, exec_times, num_threads=self.num_threads) def test_series_float_astype_int(self): self._test_case(usecase_gen('astype(np.int8)'), 'series_astype_int', [10 ** 5], input_data=[test_global_input_data_float64[0]]) def test_series_chain_add_and_sum(self): self._test_series_binary_operations(usecase_series_chain_add_and_sum, 'series_chain_add_and_sum', [20 * 10 ** 7, 25 * 10 ** 7, 30 * 10 ** 7]) def test_gen(name, params, data_length, call_expression): func_name = 'func' if call_expression is None: call_expression = '{}({})'.format(name, params) func_text = f"""\ def {func_name}(self): self._test_case(usecase_gen('{call_expression}'), 'series_{name}', {data_length}) """ global_vars = {'usecase_gen': usecase_gen} loc_vars = {} exec(func_text, global_vars, loc_vars) _gen_impl = loc_vars[func_name] return _gen_impl def test_gen_two_par(name, params, data_length): func_name = 'func' func_text = f"""\ def {func_name}(self): self._test_series_binary_operations(usecase_gen_two_par('{name}', '{params}'), 'series_{name}', {data_length}) """ global_vars = {'usecase_gen_two_par': usecase_gen_two_par} loc_vars = {} exec(func_text, global_vars, loc_vars) _gen_impl = loc_vars[func_name] return _gen_impl cases = [ ('abs', '', [3 * 10 ** 8]), ('apply', 'lambda x: x', [10 ** 7]), ('argsort', '', [10 ** 5]), ('at', '', [10 ** 7], 'at[3]'), ('copy', '', [10 ** 8]), ('count', '', [2 * 10 ** 9]), ('cumsum', '', [2 * 10 ** 8]), ('describe', '', [10 ** 7]), ('dropna', '', [2 * 10 ** 8]), ('fillna', '-1', [2 * 10 ** 7]), ('head', '', [10 ** 8]), ('idxmax', '', [10 ** 9]), ('idxmin', '', [10 ** 9]), ('isna', '', [2 * 10 ** 7]), ('max', '', [10 ** 9]), ('mean', '', [10 ** 8]), ('median', '', [10 ** 8]), ('min', '', [10 ** 9]), ('min', 'skipna=True', [10 ** 7]), ('nlargest', '', [4 * 10 ** 7]), ('nsmallest', '', [10 ** 9]), ('nunique', '', [10 ** 5]), ('prod', '', [5 * 10 ** 8]), ('pct_change', 'periods=1, limit=None, freq=None', [10 ** 7]), ('quantile', '', [10 ** 8]), ('shift', '', [5 * 10 ** 8]), ('sort_values', '', [10 ** 5]), ('std', '', [10 ** 7]), ('sum', '', [10 ** 9]), ('value_counts', '', [3 * 10 ** 5]), ('var', '', [5 * 10 ** 8]), ('unique', '', [10 ** 5]), ] cases_two_par = [ ('add', '', [10 ** 7]), ('append', '', [10 ** 7]), ('corr', '', [10 ** 7]), ('cov', '', [10 ** 8]), ('div', '', [10 ** 7]), ('eq', '', [10 ** 7]), ('floordiv', '', [10 ** 7]), ('ge', '', [10 ** 7]), ('pow', '', [10 ** 7]), ] for params in cases: if len(params) == 4: func, param, length, call_expression = params else: func, param, length = params call_expression = None name = func if param: name += "_" + to_varname(param).replace('__', '_') func_name = 'test_series_float_{}'.format(name) setattr(TestSeriesMethods, func_name, test_gen(func, param, length, call_expression)) for params in cases_two_par: func, param, length = params name = func if param: name += to_varname(param) func_name = 'test_series_float_{}'.format(name) setattr(TestSeriesMethods, func_name, test_gen_two_par(func, param, length)) <file_sep># ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** import pandas from sdc.datatypes.common_functions import TypeChecker from sdc.datatypes.hpat_pandas_dataframe_rolling_types import DataFrameRollingType from sdc.hiframes.pd_dataframe_ext import get_dataframe_data from sdc.utils import sdc_overload_method sdc_pandas_dataframe_rolling_docstring_tmpl = """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.core.window.Rolling.{method_name} {limitations_block} Examples -------- .. literalinclude:: ../../../examples/dataframe/rolling/dataframe_rolling_{method_name}.py :language: python :lines: 27- :caption: {example_caption} :name: ex_dataframe_rolling_{method_name} .. command-output:: python ./dataframe/rolling/dataframe_rolling_{method_name}.py :cwd: ../../../examples .. seealso:: :ref:`DataFrame.rolling <pandas.DataFrame.rolling>` Calling object with a DataFrame. :ref:`DataFrame.rolling <pandas.DataFrame.rolling>` Calling object with a DataFrame. :ref:`DataFrame.{method_name} <pandas.DataFrame.{method_name}>` Similar method for DataFrame. :ref:`DataFrame.{method_name} <pandas.DataFrame.{method_name}>` Similar method for DataFrame. Intel Scalable Dataframe Compiler Developer Guide ************************************************* Pandas DataFrame method :meth:`pandas.DataFrame.rolling.{method_name}()` implementation. .. only:: developer Test: python -m sdc.runtests -k sdc.tests.test_rolling.TestRolling.test_dataframe_rolling_{method_name} Parameters ---------- self: :class:`pandas.DataFrame.rolling` input arg{extra_params} Returns ------- :obj:`pandas.DataFrame` returns :obj:`pandas.DataFrame` object """ def df_rolling_method_codegen(method_name, self, args=None, kws=None): args = args or [] kwargs = kws or {} rolling_params = ['window', 'min_periods', 'center', 'win_type', 'on', 'axis', 'closed'] rolling_params_as_str = ', '.join(f'self._{p}' for p in rolling_params) method_params = args + ['{}={}'.format(k, k) for k in kwargs] method_params_as_str = ', '.join(method_params) impl_params = ['self'] + args + ['{}={}'.format(k, v) for k, v in kwargs.items()] impl_params_as_str = ', '.join(impl_params) results = [] impl_name = f'_df_rolling_{method_name}_impl' func_lines = [f'def {impl_name}({impl_params_as_str}):'] for idx, col in enumerate(self.data.columns): res_data = f'result_data_{col}' func_lines += [ f' data_{col} = get_dataframe_data(self._data, {idx})', f' series_{col} = pandas.Series(data_{col})', f' rolling_{col} = series_{col}.rolling({rolling_params_as_str})', f' result_{col} = rolling_{col}.{method_name}({method_params_as_str})', f' {res_data} = result_{col}._data[:len(data_{col})]' ] results.append((col, res_data)) data = ', '.join(f'"{col}": {data}' for col, data in results) func_lines += [f' return pandas.DataFrame({{{data}}})'] func_text = '\n'.join(func_lines) global_vars = {'pandas': pandas, 'get_dataframe_data': get_dataframe_data} return func_text, global_vars def gen_df_rolling_method_impl(method_name, self, args=None, kws=None): func_text, global_vars = df_rolling_method_codegen(method_name, self, args=args, kws=kws) loc_vars = {} exec(func_text, global_vars, loc_vars) _impl = loc_vars[f'_df_rolling_{method_name}_impl'] return _impl @sdc_overload_method(DataFrameRollingType, 'min') def sdc_pandas_dataframe_rolling_min(self): ty_checker = TypeChecker('Method rolling.min().') ty_checker.check(self, DataFrameRollingType) return gen_df_rolling_method_impl('min', self) sdc_pandas_dataframe_rolling_min.__doc__ = sdc_pandas_dataframe_rolling_docstring_tmpl.format(**{ 'method_name': 'min', 'example_caption': 'Calculate the rolling minimum.', 'limitations_block': '', 'extra_params': '' }) <file_sep># ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** """ | This file contains internal common functions used in SDC implementation across different files """ import numpy import pandas import numba from numba.targets import quicksort from numba import types from numba.errors import TypingError from numba.extending import register_jitable from numba import numpy_support import sdc from sdc.str_arr_ext import (string_array_type, num_total_chars, append_string_array_to, str_arr_is_na, pre_alloc_string_array, str_arr_set_na, cp_str_list_to_array, make_str_arr_from_list) from sdc.utils import sdc_overload class TypeChecker: """ Validate object type and raise TypingError if the type is invalid, e.g.: Method nsmallest(). The object n given: bool expected: int """ msg_template = '{} The object {}\n given: {}\n expected: {}' def __init__(self, func_name): """ Parameters ---------- func_name: :obj:`str` name of the function where types checking """ self.func_name = func_name def raise_exc(self, data, expected_types, name=''): """ Raise exception with unified message Parameters ---------- data: :obj:`any` real type of the data expected_types: :obj:`str` expected types inserting directly to the exception name: :obj:`str` name of the parameter """ msg = self.msg_template.format(self.func_name, name, data, expected_types) raise TypingError(msg) def check(self, data, accepted_type, name=''): """ Check data type belongs to specified type Parameters ---------- data: :obj:`any` real type of the data accepted_type: :obj:`type` accepted type name: :obj:`str` name of the parameter """ if not isinstance(data, accepted_type): self.raise_exc(data, accepted_type.__name__, name=name) def has_literal_value(var, value): """Used during typing to check that variable var is a Numba literal value equal to value""" if not isinstance(var, types.Literal): return False if value is None or isinstance(value, type(bool)): return var.literal_value is value else: return var.literal_value == value def has_python_value(var, value): """Used during typing to check that variable var was resolved as Python type and has specific value""" if not isinstance(var, type(value)): return False if value is None or isinstance(value, type(bool)): return var is value else: return var == value def check_is_numeric_array(type_var): """Used during typing to check that type_var is a numeric numpy arrays""" return isinstance(type_var, types.Array) and isinstance(type_var.dtype, types.Number) def check_index_is_numeric(ty_series): """Used during typing to check that series has numeric index""" return check_is_numeric_array(ty_series.index) def check_types_comparable(ty_left, ty_right): """Used during typing to check that underlying arrays of specified types can be compared""" return ((ty_left == string_array_type and ty_right == string_array_type) or (check_is_numeric_array(ty_left) and check_is_numeric_array(ty_right))) def hpat_arrays_append(A, B): pass @sdc_overload(hpat_arrays_append, jit_options={'parallel': False}) def hpat_arrays_append_overload(A, B): """Function for appending underlying arrays (A and B) or list/tuple of arrays B to an array A""" if isinstance(A, types.Array): if isinstance(B, types.Array): def _append_single_numeric_impl(A, B): return numpy.concatenate((A, B,)) return _append_single_numeric_impl elif isinstance(B, (types.UniTuple, types.List)): # TODO: this heavily relies on B being a homogeneous tuple/list - find a better way # to resolve common dtype of heterogeneous sequence of arrays numba_common_dtype = find_common_dtype_from_numpy_dtypes([A.dtype, B.dtype.dtype], []) # TODO: refactor to use numpy.concatenate when Numba supports building a tuple at runtime def _append_list_numeric_impl(A, B): total_length = len(A) + numpy.array([len(arr) for arr in B]).sum() new_data = numpy.empty(total_length, numba_common_dtype) stop = len(A) new_data[:stop] = A for arr in B: start = stop stop = start + len(arr) new_data[start:stop] = arr return new_data return _append_list_numeric_impl elif A == string_array_type: if B == string_array_type: def _append_single_string_array_impl(A, B): total_size = len(A) + len(B) total_chars = num_total_chars(A) + num_total_chars(B) new_data = sdc.str_arr_ext.pre_alloc_string_array(total_size, total_chars) pos = 0 pos += append_string_array_to(new_data, pos, A) pos += append_string_array_to(new_data, pos, B) return new_data return _append_single_string_array_impl elif (isinstance(B, (types.UniTuple, types.List)) and B.dtype == string_array_type): def _append_list_string_array_impl(A, B): array_list = [A] + list(B) total_size = numpy.array([len(arr) for arr in array_list]).sum() total_chars = numpy.array([num_total_chars(arr) for arr in array_list]).sum() new_data = sdc.str_arr_ext.pre_alloc_string_array(total_size, total_chars) pos = 0 pos += append_string_array_to(new_data, pos, A) for arr in B: pos += append_string_array_to(new_data, pos, arr) return new_data return _append_list_string_array_impl @register_jitable def fill_array(data, size, fill_value=numpy.nan, push_back=True): """ Fill array with given values to reach the size """ if push_back: return numpy.append(data, numpy.repeat(fill_value, size - data.size)) return numpy.append(numpy.repeat(fill_value, size - data.size), data) @register_jitable def fill_str_array(data, size, push_back=True): """ Fill StringArrayType array with given values to reach the size """ string_array_size = len(data) nan_array_size = size - string_array_size num_chars = sdc.str_arr_ext.num_total_chars(data) result_data = sdc.str_arr_ext.pre_alloc_string_array(size, num_chars) # Keep NaN values of initial array arr_is_na_mask = numpy.array([sdc.hiframes.api.isna(data, i) for i in range(string_array_size)]) data_str_list = sdc.str_arr_ext.to_string_list(data) nan_list = [''] * nan_array_size result_list = data_str_list + nan_list if push_back else nan_list + data_str_list sdc.str_arr_ext.cp_str_list_to_array(result_data, result_list) # Batch=64 iteration to avoid threads competition batch_size = 64 if push_back: for i in numba.prange(size//batch_size + 1): for j in range(i*batch_size, min((i+1)*batch_size, size)): if j < string_array_size: if arr_is_na_mask[j]: str_arr_set_na(result_data, j) else: str_arr_set_na(result_data, j) else: for i in numba.prange(size//batch_size + 1): for j in range(i*batch_size, min((i+1)*batch_size, size)): if j < nan_array_size: str_arr_set_na(result_data, j) else: str_arr_j = j - nan_array_size if arr_is_na_mask[str_arr_j]: str_arr_set_na(result_data, j) return result_data @numba.njit def _hpat_ensure_array_capacity(new_size, arr): """ Function ensuring that the size of numpy array is at least as specified Returns newly allocated array of bigger size with copied elements if existing size is less than requested """ k = len(arr) if k >= new_size: return arr n = k while n < new_size: n = 2 * n res = numpy.empty(n, arr.dtype) res[:k] = arr[:k] return res def find_common_dtype_from_numpy_dtypes(array_types, scalar_types): """Used to find common numba dtype for a sequences of numba dtypes each representing some numpy dtype""" np_array_dtypes = [numpy_support.as_dtype(dtype) for dtype in array_types] np_scalar_dtypes = [numpy_support.as_dtype(dtype) for dtype in scalar_types] np_common_dtype = numpy.find_common_type(np_array_dtypes, np_scalar_dtypes) numba_common_dtype = numpy_support.from_dtype(np_common_dtype) return numba_common_dtype def sdc_join_series_indexes(left, right): pass @sdc_overload(sdc_join_series_indexes, jit_options={'parallel': False}) def sdc_join_series_indexes_overload(left, right): """Function for joining arrays left and right in a way similar to pandas.join 'outer' algorithm""" # TODO: eliminate code duplication by merging implementations for numeric and StringArray # requires equivalents of numpy.arsort and _hpat_ensure_array_capacity for StringArrays if (isinstance(left, types.Array) and isinstance(right, types.Array)): numba_common_dtype = find_common_dtype_from_numpy_dtypes([left.dtype, right.dtype], []) if isinstance(numba_common_dtype, types.Number): def sdc_join_series_indexes_impl(left, right): # allocate result arrays lsize = len(left) rsize = len(right) est_total_size = int(1.1 * (lsize + rsize)) lidx = numpy.empty(est_total_size, numpy.int64) ridx = numpy.empty(est_total_size, numpy.int64) joined = numpy.empty(est_total_size, numba_common_dtype) # sort arrays saving the old positions sorted_left = numpy.argsort(left, kind='mergesort') sorted_right = numpy.argsort(right, kind='mergesort') i, j, k = 0, 0, 0 while (i < lsize and j < rsize): joined = _hpat_ensure_array_capacity(k + 1, joined) lidx = _hpat_ensure_array_capacity(k + 1, lidx) ridx = _hpat_ensure_array_capacity(k + 1, ridx) left_index = left[sorted_left[i]] right_index = right[sorted_right[j]] if (left_index < right_index): joined[k] = left_index lidx[k] = sorted_left[i] ridx[k] = -1 i += 1 k += 1 elif (left_index > right_index): joined[k] = right_index lidx[k] = -1 ridx[k] = sorted_right[j] j += 1 k += 1 else: # find ends of sequences of equal index values in left and right ni, nj = i, j while (ni < lsize and left[sorted_left[ni]] == left_index): ni += 1 while (nj < rsize and right[sorted_right[nj]] == right_index): nj += 1 # join the blocks found into results for s in numpy.arange(i, ni, 1): block_size = nj - j to_joined = numpy.repeat(left_index, block_size) to_lidx = numpy.repeat(sorted_left[s], block_size) to_ridx = numpy.array([sorted_right[k] for k in numpy.arange(j, nj, 1)], numpy.int64) joined = _hpat_ensure_array_capacity(k + block_size, joined) lidx = _hpat_ensure_array_capacity(k + block_size, lidx) ridx = _hpat_ensure_array_capacity(k + block_size, ridx) joined[k:k + block_size] = to_joined lidx[k:k + block_size] = to_lidx ridx[k:k + block_size] = to_ridx k += block_size i = ni j = nj # fill the end of joined with remaining part of left or right if i < lsize: block_size = lsize - i joined = _hpat_ensure_array_capacity(k + block_size, joined) lidx = _hpat_ensure_array_capacity(k + block_size, lidx) ridx = _hpat_ensure_array_capacity(k + block_size, ridx) ridx[k: k + block_size] = numpy.repeat(-1, block_size) while i < lsize: joined[k] = left[sorted_left[i]] lidx[k] = sorted_left[i] i += 1 k += 1 elif j < rsize: block_size = rsize - j joined = _hpat_ensure_array_capacity(k + block_size, joined) lidx = _hpat_ensure_array_capacity(k + block_size, lidx) ridx = _hpat_ensure_array_capacity(k + block_size, ridx) lidx[k: k + block_size] = numpy.repeat(-1, block_size) while j < rsize: joined[k] = right[sorted_right[j]] ridx[k] = sorted_right[j] j += 1 k += 1 return joined[:k], lidx[:k], ridx[:k] return sdc_join_series_indexes_impl else: # TODO: support joining indexes with common dtype=object - requires Numba # support of such numpy arrays in nopython mode, for now just return None return None elif (left == string_array_type and right == string_array_type): def sdc_join_series_indexes_impl(left, right): # allocate result arrays lsize = len(left) rsize = len(right) est_total_size = int(1.1 * (lsize + rsize)) lidx = numpy.empty(est_total_size, numpy.int64) ridx = numpy.empty(est_total_size, numpy.int64) # use Series.sort_values since argsort for StringArrays not implemented original_left_series = pandas.Series(left) original_right_series = pandas.Series(right) # sort arrays saving the old positions left_series = original_left_series.sort_values(kind='mergesort') right_series = original_right_series.sort_values(kind='mergesort') sorted_left = left_series._index sorted_right = right_series._index i, j, k = 0, 0, 0 while (i < lsize and j < rsize): lidx = _hpat_ensure_array_capacity(k + 1, lidx) ridx = _hpat_ensure_array_capacity(k + 1, ridx) left_index = left[sorted_left[i]] right_index = right[sorted_right[j]] if (left_index < right_index): lidx[k] = sorted_left[i] ridx[k] = -1 i += 1 k += 1 elif (left_index > right_index): lidx[k] = -1 ridx[k] = sorted_right[j] j += 1 k += 1 else: # find ends of sequences of equal index values in left and right ni, nj = i, j while (ni < lsize and left[sorted_left[ni]] == left_index): ni += 1 while (nj < rsize and right[sorted_right[nj]] == right_index): nj += 1 # join the blocks found into results for s in numpy.arange(i, ni, 1): block_size = nj - j to_lidx = numpy.repeat(sorted_left[s], block_size) to_ridx = numpy.array([sorted_right[k] for k in numpy.arange(j, nj, 1)], numpy.int64) lidx = _hpat_ensure_array_capacity(k + block_size, lidx) ridx = _hpat_ensure_array_capacity(k + block_size, ridx) lidx[k:k + block_size] = to_lidx ridx[k:k + block_size] = to_ridx k += block_size i = ni j = nj # fill the end of joined with remaining part of left or right if i < lsize: block_size = lsize - i lidx = _hpat_ensure_array_capacity(k + block_size, lidx) ridx = _hpat_ensure_array_capacity(k + block_size, ridx) ridx[k: k + block_size] = numpy.repeat(-1, block_size) while i < lsize: lidx[k] = sorted_left[i] i += 1 k += 1 elif j < rsize: block_size = rsize - j lidx = _hpat_ensure_array_capacity(k + block_size, lidx) ridx = _hpat_ensure_array_capacity(k + block_size, ridx) lidx[k: k + block_size] = numpy.repeat(-1, block_size) while j < rsize: ridx[k] = sorted_right[j] j += 1 k += 1 # count total number of characters and allocate joined array total_joined_size = k num_chars_in_joined = 0 for i in numpy.arange(total_joined_size): if lidx[i] != -1: num_chars_in_joined += len(left[lidx[i]]) elif ridx[i] != -1: num_chars_in_joined += len(right[ridx[i]]) joined = pre_alloc_string_array(total_joined_size, num_chars_in_joined) # iterate over joined and fill it with indexes using lidx and ridx indexers for i in numpy.arange(total_joined_size): if lidx[i] != -1: joined[i] = left[lidx[i]] if (str_arr_is_na(left, lidx[i])): str_arr_set_na(joined, i) elif ridx[i] != -1: joined[i] = right[ridx[i]] if (str_arr_is_na(right, ridx[i])): str_arr_set_na(joined, i) else: str_arr_set_na(joined, i) return joined, lidx, ridx return sdc_join_series_indexes_impl return None def sdc_check_indexes_equal(left, right): pass @sdc_overload(sdc_check_indexes_equal, jit_options={'parallel': False}) def sdc_check_indexes_equal_overload(A, B): """Function for checking arrays A and B of the same type are equal""" if isinstance(A, types.Array): def sdc_check_indexes_equal_numeric_impl(A, B): return numpy.array_equal(A, B) return sdc_check_indexes_equal_numeric_impl elif A == string_array_type: def sdc_check_indexes_equal_string_impl(A, B): # TODO: replace with StringArrays comparison is_index_equal = (len(A) == len(B) and num_total_chars(A) == num_total_chars(B)) for i in numpy.arange(len(A)): if (A[i] != B[i] or str_arr_is_na(A, i) is not str_arr_is_na(B, i)): return False return is_index_equal return sdc_check_indexes_equal_string_impl @numba.njit def _sdc_pandas_format_percentiles(arr): """ Function converting float array of percentiles to a list of strings formatted the same as in pandas.io.formats.format.format_percentiles """ percentiles_strs = [] for percentile in arr: p_as_string = str(percentile * 100) trim_index = len(p_as_string) - 1 while trim_index >= 0: if p_as_string[trim_index] == '0': trim_index -= 1 continue elif p_as_string[trim_index] == '.': break trim_index += 1 break if trim_index < 0: p_as_string_trimmed = '0' else: p_as_string_trimmed = p_as_string[:trim_index] percentiles_strs.append(p_as_string_trimmed + '%') return percentiles_strs def sdc_arrays_argsort(A, kind='quicksort'): pass @sdc_overload(sdc_arrays_argsort, jit_options={'parallel': False}) def sdc_arrays_argsort_overload(A, kind='quicksort'): """Function overloading argsort for different 1D array types""" # kind is not known at compile time, so get this function here and use in impl if needed quicksort_func = quicksort.make_jit_quicksort().run_quicksort if isinstance(A, types.Array): def _sdc_arrays_argsort_numeric_impl(A, kind='quicksort'): return numpy.argsort(A, kind=kind) return _sdc_arrays_argsort_numeric_impl elif A == string_array_type: def _sdc_arrays_argsort_str_impl(A, kind='quicksort'): nan_mask = sdc.hiframes.api.get_nan_mask(A) idx = numpy.arange(len(A)) old_nan_positions = idx[nan_mask] data = A[~nan_mask] keys = idx[~nan_mask] if kind == 'quicksort': zipped = list(zip(list(data), list(keys))) zipped = quicksort_func(zipped) argsorted = [zipped[i][1] for i in numpy.arange(len(data))] elif kind == 'mergesort': sdc.hiframes.sort.local_sort((data, ), (keys, )) argsorted = list(keys) else: raise ValueError("Unrecognized kind of sort in sdc_arrays_argsort") argsorted.extend(old_nan_positions) return numpy.asarray(argsorted, dtype=numpy.int32) return _sdc_arrays_argsort_str_impl return None def _sdc_pandas_series_check_axis(axis): pass @sdc_overload(_sdc_pandas_series_check_axis, jit_options={'parallel': False}) def _sdc_pandas_series_check_axis_overload(axis): if isinstance(axis, types.UnicodeType): def _sdc_pandas_series_check_axis_impl(axis): if axis != 'index': raise ValueError("Method sort_values(). Unsupported parameter. Given axis != 'index'") return _sdc_pandas_series_check_axis_impl elif isinstance(axis, types.Integer): def _sdc_pandas_series_check_axis_impl(axis): if axis != 0: raise ValueError("Method sort_values(). Unsupported parameter. Given axis != 0") return _sdc_pandas_series_check_axis_impl return None
5e53f1d39eefce6879ab80672af9c5baeaa52b52
[ "Python" ]
7
Python
awesomeDataTool/sdc
5e90ac4370af975f71c05ac10cfe43076a84747f
bde24ddb7656d8d647474c8765393d758dbfc114
refs/heads/master
<repo_name>arjunrn/tetris-bc<file_sep>/tests/block_test.py import unittest from block import Block class MyTestCase(unittest.TestCase): def setUp(self): self.block = Block() def test_movement(self): original_mask = self.block.mask() self.block.rotate_clockwise() self.block.move_right(True) self.block.rotate_clockwise() self.block.move_right(True) self.block.rotate_counter() self.block.move_left(True) self.block.rotate_counter() self.block.move_left(True) new_mask = self.block.mask() self.assertEqual(original_mask, new_mask) if __name__ == '__main__': unittest.main() <file_sep>/tetris.py import arena import termcolor from block import Block if __name__ == '__main__': a = arena.Arena() while True: b = Block() if a.block is None: if not a.add_block(block=b): termcolor.cprint('Game Over. Block cannot be added') exit(0) termcolor.cprint(a, color='blue') while True: termcolor.cprint('[a/A] Move Left', color='yellow') termcolor.cprint('[d/D] Move Right', color='yellow') termcolor.cprint('[w/W] Rotate Counter Clockwise', color='yellow') termcolor.cprint('[s/S] Rotate Clockwise', color='yellow') termcolor.cprint('[n/N] Next', color='yellow') termcolor.cprint('[x/X] Exit', color='yellow') choice = raw_input(termcolor.colored('Enter Choice: ', color='yellow')) choice = choice.lower() if choice == 'd': a.move_right() break elif choice == 'a': a.move_left() break elif choice == 'w': a.rotate_cc() break elif choice == 's': a.rotate() break elif choice == 'n' or choice == '': break elif choice == 'x': exit(0) else: termcolor.cprint('Invalid Input', color='red') continue a.step()<file_sep>/README.md # tetris-bc ## Instruction to run. 1. Create a virtualenv if you need it. 2. Activate the virtualenv. 3. Install the dependenices with the command pip install -r virtualenv 4. Run the program. python tetris.py <file_sep>/block.py import random shapes = [ [ (1, 1, 1, 1) ], [ (1, 0), (1, 0), (1, 1) ], [ (0, 1), (0, 1), (1, 1) ], [ (0, 1), (1, 1), (1, 0) ], [ (1, 1), (1, 1) ] ] class Block: def __init__(self): self.shape = random.choice(shapes) self.position = (0, 0) @property def width(self): """ Convenience for width of block :return: the height of the block """ return len(self.shape[0]) @property def height(self): return len(self.shape) def mask(self): """ A matrix like mask is created which is used to interpolate with exisiting blocks. :return: a 2 dimensional matrix with the blocks positions as 1's and empty as 0's """ m = [[0 for _ in range(20)] for _ in range(20)] for i, row in enumerate(self.shape): for j, element in enumerate(row): x = self.position[0] + i y = self.position[1] + j if x >= 20 or y >= 20: return False, None m[x][y] = element return True, m def move_left(self, set_pos=False): """ Moves the block left. :param set_pos: simulate only :return: result of operation """ new_p = (self.position[0], self.position[1] - 1) if not (0 <= new_p[0] < 20 and 0 <= new_p[1] < 20): return False, None if set_pos: self.position = new_p return True, new_p def move_right(self, set_pos=False): """ Move the block right :param set_pos: Simulate only. :return: The result of the operation. """ new_p = (self.position[0], self.position[1] + 1) if not (0 <= (new_p[0] + self.height) < 20 and 0 <= (new_p[1] + self.width - 1) < 20): return False, None if set_pos: self.position = new_p return True, new_p def rotate_clockwise(self): """ Rotate the block clockwise. :return: The result of the operation """ new_shape = zip(*self.shape[::-1]) if (self.position[1] + len(new_shape[0])) > 20 or (self.position[0] + len(new_shape)) > 20: return False self.shape = new_shape return True def rotate_counter(self): """ Rotate the block counter clockwise. :return: The result of the opeartion. """ new_shape = zip(*self.shape)[::-1] if (self.position[1] + len(new_shape[0])) > 20 or (self.position[0] + len(new_shape)) > 20: return False self.shape = new_shape return True def print_mask(self): """ Convenience method to print the current mask. """ _, m = self.mask() for row in m: p = [] for e in row: p.append('-' if e == 0 else '*') print(''.join(p)) def down(self): """ Move the block down one position. """ new_y = self.position[0] + 1 if new_y > 20: raise RuntimeError('Moved outside. Should be detected') self.position = new_y, self.position[1]<file_sep>/arena.py from copy import deepcopy import random class Arena: def __init__(self): self.block = None self.area = [[0 for _ in range(20)] for _ in range(20)] def __str__(self): printable = [] if self.block: _, mask = self.block.mask() merged = self.merge(mask) else: merged = self.area for row in merged: printable.append(''.join(['*', ''.join(['*' if e == 1 else ' ' for e in row]), '*'])) printable.append('*' * 22) return '\n'.join(printable) def add_block(self, block): """ The block to be added to the arena is passed here. :param block: The `block.Block` type object. :return: True if the block can be added. False otherwise """ if self.block is not None: raise RuntimeError('Existing block in arena') block.position = block.position[0], random.randint(0, 20 - block.width) _, mask = block.mask() for i in range(20): for j in range(20): if self.area[i][j] == 1 and mask[i][j] == 1: return False self.block = block return True def move_right(self): """ Move the current block towards the right. :return: Result of the operation. """ dummy = deepcopy(self.block) dummy.move_right(True) if self.conflict(dummy.mask()[1]): return False result, _ = self.block.move_right(True) return result def move_left(self): """ Move the current block to the left """ dummy = deepcopy(self.block) dummy.move_left(True) if self.conflict(dummy.mask()[1]): return False result, _ = self.block.move_left(True) return result def rotate_cc(self): """ Rotate the current block counter-clockwise :return: The result of the operation. """ dummy = deepcopy(self.block) dummy.rotate_counter() if self.conflict(dummy.mask()[1]): return False return self.block.rotate_counter() def rotate(self): dummy = deepcopy(self.block) dummy.rotate_clockwise() if self.conflict(dummy.mask()[1]): return False return self.block.rotate_clockwise() def step(self): """ Step the game one step forward. Also detect if current block is at end of decent. """ dummy_block = deepcopy(self.block) dummy_block.down() _, mask = dummy_block.mask() if self.conflict(mask): self.area = self.merge(self.block.mask()[1]) self.block = None return self.block.down() if self.reached_bottom(): self.area = self.merge(self.block.mask()[1]) self.block = None def conflict(self, mask): """ Check if there is a conflict with the current arena configuration and the proposed block position :param mask: The mask for the block. :return: True if there is conflict, False otherwise. """ for i in range(20): for j in range(20): if self.area[i][j] == 1 and mask[i][j] == 1: return True return False def merge(self, mask): """ Merge the current arena configuration and the block position to get universal view. :param mask: The mask to used to produce the final configuration. :return: The final configuration as a 2 dimensional array. """ merged = [[0 for _ in range(20)] for _ in range(20)] for i in range(20): for j in range(20): merged[i][j] = mask[i][j] + self.area[i][j] return merged def reached_bottom(self): """ Check if the block is at the bottom of the areana. :return: The result of the check. """ if self.block.height + self.block.position[0] >= 20: return True else: return False
46d86ef9847743ebf2129791f0265a16d7d5eb7f
[ "Markdown", "Python" ]
5
Python
arjunrn/tetris-bc
edb81402e7a7d20a31138a8f7396a2fa220ef4b3
deed273e3a19f8530aa9d88a8d662ca46cb5bc04
refs/heads/master
<repo_name>tdignan87/QuizMania<file_sep>/assets/js/quiz.js let noOfQuestions = [5, 10, 15]; let difficultySetting = ["easy", "medium", "hard"]; let difficulty = null; let questions = null; let allQuestions = []; let userScore = 0; let questionTotal = document.getElementById("questionCount"); let choiceAnswers = $(".choice-answer"); /** * Fetches the API Categories if successful connection to API. Simen gave me this part of the code. */ window.onload = function() { $("#question_grid").css({ display: "none" }); $("#score_grid").css({ display: "none" }); $("#main-status").css({ display: "none" }); $("#next-btn").hide(); $("#api-status").css({ display: "none" }); $.each(noOfQuestions, function(val, text) { $('#dropdown-choices-questions').append($(`<option>${text}</option>`)); }); $.each(difficultySetting, function(val, text) { $('#dropdown-choices-difficulty').append($(`<option>${text}</option>`)); }); }; /* * Play submit function IF statements to ensure criteria is selected before game will allow to play. All options must be selected before questions will be generated. DOM items * Will show depending on what items are selected. */ $("#play-submit-btn").click(function() { if (($("#dropdown-choices-difficulty option:selected").index() > 0) && ($("#dropdown-choices-questions option:selected").index() > 0)) { difficulty = $("#dropdown-choices-difficulty option:selected").text(); questions = $("#dropdown-choices-questions option:selected").text(); $(".quiz-page").css({ display: "block" }) $("#options-container-choices").css({ display: "none" }) $("#options-container-choices").css({ display: "none" }) $("#jumbo-picture-main").css({ display: "none" }) $("#play-submit-btn").css({ display: "none" }) $("#main-status").css({ display: "none" }) $("#next-btn").show(); getQuestions(); } else { $("#main-status").css({ display: "block" }) } }); /* * click function for play submit button. Once pressed the score is saved to local storage */ $("#success-btn").click(function() { localStorage.setItem("userScore", userScore); alert("Score saved as " + localStorage.getItem("userScore") + "!"); window.location.replace("index.html"); $("#main-status").css({ display: "none" }); }); /** * Retrieve API and convert response data into JSON format. Any errors are logged to console */ function getQuestions() { fetch(`https://opentdb.com/api.php?amount=${questions}&category=9&difficulty=${difficulty}&type=multiple`) .then(response => response.json()) .then(rawData => { generateQuestionsAnswers(rawData); }) .catch(error => { console.log(error) $("#api-status").css({ display: "block" }) } ); } /** * create options and answers array using the API's correct_answer and incorrect_answers. Data index is stored. Selected value is null until value is selected. Data is pushed * in an Array allQuestions. */ function generateQuestionsAnswers(data) { $.each(data.results, function(index, item) { let question = {}; question.Question = item.question; let randomNumber = Math.floor(Math.random() * 3) + 1; switch (randomNumber) { case 1: question.OptionA = item.correct_answer; question.OptionB = item.incorrect_answers[0]; question.OptionC = item.incorrect_answers[1]; question.OptionD = item.incorrect_answers[2]; question.CorrectOption = 'A'; break; case 2: question.OptionB = item.correct_answer; question.OptionA = item.incorrect_answers[0]; question.OptionC = item.incorrect_answers[1]; question.OptionD = item.incorrect_answers[2]; question.CorrectOption = 'B'; break; case 3: question.OptionC = item.correct_answer; question.OptionA = item.incorrect_answers[0]; question.OptionB = item.incorrect_answers[1]; question.OptionD = item.incorrect_answers[2]; question.CorrectOption = 'C'; break; case 4: question.OptionD = item.correct_answer; question.OptionA = item.incorrect_answers[0]; question.OptionB = item.incorrect_answers[1]; question.OptionC = item.incorrect_answers[2]; question.CorrectOption = 'D'; break; } question.UserSelectedOption = ''; question.Enabled = true; allQuestions.push(question); }); populateQuestion(0); } /** * Take populated question and insert into the DOM. */ function populateQuestion(index) { if (index >= 0 && index < allQuestions.length) { $("#question-main").empty(); $(`#available-answers`).empty(); let question = allQuestions[index]; $("#question-main").append(`<h3 id="question-main">${question.Question}</h3>`); let optionA = "<div class='col-sm'><p class='choice-options'>A</p><p class='choice-answer' id='answer-opt' onclick=\"showAnswer(" + index + ", 'A')\">" + question.OptionA + "</p></div>"; $("#available-answers").append(optionA); let optionB = "<div class='col-sm'><p class='choice-options'>B</p><p class='choice-answer' id='answer-opt' onclick=\"showAnswer(" + index + ", 'B')\">" + question.OptionB + "</p></div>"; $("#available-answers").append(optionB); let optionC = "<div class='col-sm'><p class='choice-options'>C</p><p class='choice-answer' id='answer-opt' onclick=\"showAnswer(" + index + ", 'C')\">" + question.OptionC + "</p></div>"; $("#available-answers").append(optionC); let optionD = "<div class='col-sm'><p class='choice-options'>D</p><p class='choice-answer' id='answer-opt' onclick=\"showAnswer(" + index + ", 'D')\">" + question.OptionD + "</p></div>"; $("#available-answers").append(optionD); $("#next-btn").click(function() { if (index < allQuestions.length - 1) { (navigateQuestion(index)); } if (index + 1 == allQuestions.length) { $("#next-btn").css({ display: "none" }) } }); /* * Shows the question currently on versus total questions selected */ questionTotal.innerText = `Question:${index + 1}/${allQuestions.length}`; } } function showAnswer(index, option) { if (index >= 0 && index < allQuestions.length) { let question = allQuestions[index]; question.UserSelectedOption = option; switch (question.CorrectOption) { case 'A': $(".choice-answer:eq(0)").css("background-color", "green"); break; case 'B': $(".choice-answer:eq(1)").css("background-color", "green"); break; case 'C': $(".choice-answer:eq(2)").css("background-color", "green"); break; case 'D': $(".choice-answer:eq(3)").css("background-color", "green"); break; } /** * if correctOption in API doesnt match user input background color will go red */ if (question.CorrectOption != question.UserSelectedOption) { switch (question.UserSelectedOption) { case 'A': $(".choice-answer:eq(0)").css("background-color", "red"); break; case 'B': $(".choice-answer:eq(1)").css("background-color", "red"); break; case 'C': $(".choice-answer:eq(2)").css("background-color", "red"); break; case 'D': $(".choice-answer:eq(3)").css("background-color", "red"); break; } } else { userScore = userScore + 10; document.getElementById("score-result").innerText = userScore; } } } /** * Gets next question and displays it to user */ function navigateQuestion(index) { if (index >= 0 && index < allQuestions.length) { populateQuestion(index + 1); } } /* * Loader */ document.onreadystatechange = function() { if (document.readyState !== "complete") { document.querySelector( "body").style.visibility = "hidden"; document.querySelector( "#loader").style.visibility = "visible"; } else { document.querySelector( "#loader").style.display = "none"; document.querySelector( "body").style.visibility = "visible"; } }<file_sep>/README.md # QuizMania - The Fun Trivia Quiz Game!!!! Welcome to my project. Please read through the READ ME and check out this project. If you have any questions or suggestions please let me know!. ![Mutli Device Screenshot](https://github.com/tdignan87/QMWireframes/blob/master/Images/trivia-background.jpg) ## Contents ## * UX * Project Goals * Target Audience Goals * Developer Goals * User Requirements and Expectations * Design Choices * Fonts * Colours * Styling * Images * Backgrounds * Wireframes * Features * Features Deployed * Features that will be implemented in the future * Technologies Used * Testing * Bugs * Deployment * Credits ## UX (User Experience) ### Project Goals The goal of this project is to create a simple to use trivia quiz game for kids and adults. The project is aimed at families of all ages. The website needs to be appealing enough so users want to interact with the site and participate in the quiz. Minimual content is key also. #### User Goals: * A website that allows viewers to enjoy playing the game. * Attractive and responsive design for all devices. * Simple and easy to use with minimal scrolling. * Score interaction for competing with friends or family. * Contact us with improvements via a form. * Functionality to chose difficulty and set number of questions. #### User Stories ##### Mr.Stonehouse: <em>"As a user i would like my child to be able to play this game easily."</em> ##### <NAME>: <em>"The key for this game is ease of use with minimal content on the page. Most trivia or quiz websites are packed with content not suitable for my tablet or mobile. This site does exactly what it's suppost to do with no annoying pop-ups". </em> ##### <NAME>: <em>"As a 12 year old i like the colours of this page as they make the site look fun.It's good to play a game like this i don't need to register or download an app". </em> #### Site Owner Goals: * Create a fun friendly webpage that user's can use to play the trivia game. * Ability for users to email any improvements and recommendations. * Ability for user to select difficulty and number of questions. ## User Requirements and Expectations: * Navigate the website using the navbar to go to different areas on the page. * Select difficulty & number of questions and site will adjust accordingly. * Form works correctly for submitting ideas to the owner. * Answer buttons will change colours if wrong or correct answer is selected. * Quiz will let me know what answers are incorrect. #### Expectations: * Site to generate random questions and give four possible answers. * Site to allow user to select difficulty. * Can click answers and site will respond with correct color for wrong (red) or green (correct). * Fully responsive design for all devices. * Content and colours are visually appealing. ## Design Choices: The theme of this project is a trivia quiz game, so my design choices are heavily influenced by a choice of positive colours. ##### Fonts: I chose the font <a href="https://fonts.google.com/specimen/Bubblegum+Sans">Bubblegum Sans</a> as it looks fun and compliments the colour scheme of the game. The decision to use this font is to provide a "fun" experience for the user. ##### Colour: I checked online at other trivia games and came across a variety of bright coloured websites and dark and dull websites. I decided to go with bright and vibrant colours as they are more appealing to kids as well as adults. * Background Colours: #FFA500<strong> Dark orange</strong>. I Chose this as the primary colour as it looks like it will blend well with the other colours. * Navigation Colour: #fed8b1<strong> Light Orange</strong>. I chose this secondary colour for my navbar and controls as it blends well with the dark orange. * Container Colours: #fed8b1<strong> Light Orange</strong>. I chose this colour for my sections as it blends well with the dark orange background. * Dropdown Menu Items: #fed8b1<strong> Light Orange</strong>. I chose this colour as it blends well with the background. * Save Score Button: Bootstrap Success Btn <strong>Green</strong>. I chose this colour for my save score button as it easily stands out above all the other colours so the it visually stands out to the user. ##### Styling: I use bootstrap to style my website with a responsive design. This means it was easier to set up the controls for responsive design. ##### Background: I chose a simple orange background for the entire web application. ## Wireframes: I built the wireframes for this project using Balsamiq mockups. I did a basic design for Mobile/Tablets and then a web application prior to designing the UI. I found using Balsamiq very useful as it helped me to structurally arrange the elements on my page. You can view the wireframes here: <a href="https://github.com/tdignan87/QuizMania/tree/master/Wireframes">Click here for Wireframes</a> ## Features: * Sliding Navigation * Interactive questions and answers ## Technologies Used: ### Languages: * HTML * CSS * Javascript ### Scripting Languages: * JSON ### Tools & Libraries: * jQuery: <a href="https://jquery.com/"> Click here for jQuery</a> * Git: <a href="https://github.com/"> Click here for Github</a> * Bootstrap:<a href="https://getbootstrap.com/"> Click here for Bootstrap</a> * OpenTrivia API: <a href="https://opentdb.com/"> Click here for OpenTriviaDB</a> * Google Fonts: <a href="https://fonts.google.com/"> Click here for Google Fonts</a> ## Testing: This is the first time i have written any software using data from a API. I ensured i tested every line of code and thoroughly went through all my code in blocks to understand the log and test in the console. I have learned a great deal from doing this of how API's work, and how Javascript can collect data from them. Testing was done by myself and also by peers and fellow students. #### Test Planning: Prior to doing any coding i knew i had to do the work in "blocks" to achieve my overall goal otherwise I would get overwelmed and skip core things. My wireframes helped greatly as it allowed me to pick a section and then work on that specific area until the functionality and code was all working before moving onto the next. In future projects i would like to automatic testing to help me debug and test my work. #### Test Example: ### Overall Features: <strong>Site Responsiveness:</strong> * Fully responsive and mobile friendly is a requirement for this project so i used Bootstrap as the HTML framework. I used chrome developer tools for testing the different break points. * <strong>Implementation:</strong> Using live server browser in VS code allowed me to work on my project in a practical way alongside the developer tools for testing different things. *<strong>Interactive:</strong> Using JS to show and hide specific parts of the page when the user is ready to begin the quiz. This will keep everything on one page when in mobile design. This was checked using chrome developer tools. ### Future Features: * When game is completed i would like the ability for the user to enter there name and then save the data to local storage. The user can then view the last top 10 scores on the page when playing alongside friends. * A loading spinner when the page is first rendered. ## Bugs During Development: ### Bug 1 - Option categories from API Array not loading in the application: Solution: I was not calling the category in the function so my dropdown was not loading the API data. The category function was being called which loads the API data. ### Bug 2 - Available answers not combining properly across the four answer choices: Solution: <p> tags were remaining in HTML so the JS append was not populating the data correctly. The template literals should also have contained a +1 for incrementing in the Array. ### Bug 3 - If statement on the play button submit was only working for one of the if statements not not all the nested statements: Solution: I changed the || operator to the && operator which means all conditions in the if statements must be true. The || operator means if only one condition is true. ### Bug 4 - API was down and site would not move on. No warning for user that the site isn't working. Solution: Added catch statement and notice on the form to display to user that service isnt working and to try again later. ### Known Bugs * I had categories loading into the API as choice option but the API is broken on too many of them. I decided to remove categories. ## Deployment: QuizMania was developed using VS code, using git and github to host the repository. When i was deploying QuizMania the following steps were made: * Created folder on local machine for the project * Installed GIT on Windows * Clicked source control icon on left of VS code panel * Created a local repository on my directory * Opened command palette (Ctrl+Shift+P) and copied in my remote repository URL * Did a small change then pushed to remote repository * Checked remote repository to check it was successfully pulling in the changes. ### Running QuizMania locally Cloning Quizmania from Github: * Navigate to 'https://github.com/tdignan87/QuizMania'. * Click the green "Clone or Download" button. * Copy the URL in the dropdown box. * Using your favorite IDE open up your preferred terminal. * Navigate to your desired file location. * Copy the following code and input into your terminal to clone QuizMania. ## Closing Notes: Creating this project has taught me a lot about how to use API data to display information on a webpage. Working with Javascript and jQuery has been good experience for me as i only have basic experience in C# desktop development. In the future i would like to extend this quiz to be able to show top scores to the user. ## Credits: * <NAME> (Code Institute Mentor) LinkedIn: <a href="https://www.linkedin.com/in/simendaehlin/">Click for LinkedIn</a> * Code institute tutor support * Stack Overflow * Javascript & jQuery by <NAME>
6f6e4b484b4fd1c7547aea89ac1ac5b88d480461
[ "JavaScript", "Markdown" ]
2
JavaScript
tdignan87/QuizMania
6f87a7be15320a56c9e513746dd780bbefb32754
a4d46ebbaa5a1b0a2d81b3c67f76657d5f923e0f
refs/heads/master
<repo_name>mkaczmarek93/ExacoInternshipAndroid<file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/model/Coord.kt package pl.exaco.internship.android.weatherdemo.model import com.google.gson.annotations.SerializedName data class Coord( @SerializedName("lon") val lon: Double = 0.toDouble(), @SerializedName("lat") val lat: Double = 0.toDouble() )<file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/service/impl/FutureWeatherManager.java package pl.exaco.internship.android.weatherdemo.service.impl; import android.util.Log; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.EBean; import java.util.ArrayList; import java.util.List; import pl.exaco.internship.android.weatherdemo.model.CityWeather; import pl.exaco.internship.android.weatherdemo.model.FutureWeather; import pl.exaco.internship.android.weatherdemo.service.IFutureWeatherManager; import pl.exaco.internship.android.weatherdemo.service.RequestCallback; import pl.exaco.internship.android.weatherdemo.service.api.WeatherApi; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; @EBean(scope = EBean.Scope.Singleton) public class FutureWeatherManager extends BaseManager implements IFutureWeatherManager { private WeatherApi api; @AfterInject void initService() { api = retrofit.create(WeatherApi.class); } @Override public void getFutureWeatherByCity(Integer cityId, RequestCallback<List<CityWeather>> callback) { api.getFutureWeather(cityId.toString()).enqueue(new Callback<FutureWeather>() { @Override public void onResponse(Call<FutureWeather> call, Response<FutureWeather> response) { if(null != response && response.body() != null) { callback.onSuccess(response.body().getList()); } else { callback.onSuccess(new ArrayList<>()); } } @Override public void onFailure(Call<FutureWeather> call, Throwable t) { callback.onError(t); } }); } } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/service/IWeatherManager.java package pl.exaco.internship.android.weatherdemo.service; import java.util.List; import pl.exaco.internship.android.weatherdemo.model.City; import pl.exaco.internship.android.weatherdemo.model.CityWeather; public interface IWeatherManager { void getWeatherForCities(List<City> cities, RequestCallback<List<CityWeather>> callback); } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/ui/weather/WeatherAdapter.java package pl.exaco.internship.android.weatherdemo.ui.weather; import android.content.Context; import android.databinding.DataBindingUtil; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import pl.exaco.internship.android.weatherdemo.R; import pl.exaco.internship.android.weatherdemo.databinding.ItemWeatherBinding; import pl.exaco.internship.android.weatherdemo.model.CityWeather; public class WeatherAdapter extends RecyclerView.Adapter<WeatherAdapter.WeatherViewHolder> { private final List<CityWeather> items = new ArrayList<>(); private final Context context; WeatherAdapter(Context context) { this.context = context; } void setItems(@NonNull List<CityWeather> items) { this.items.clear(); this.items.addAll(items); this.notifyDataSetChanged(); } @Override public int getItemCount() { return items.size(); } @Override public WeatherViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View itemView = LayoutInflater.from(context).inflate(R.layout.item_weather, parent, false); RecyclerView.ViewHolder holder = new WeatherViewHolder(itemView); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mClickListener.onClick(view); } }); return new WeatherViewHolder(itemView); } @Override public void onBindViewHolder(WeatherViewHolder holder, int position) { if (getItemCount() > position) { final CityWeather weather = items.get(position); holder.binData(weather); } } private View.OnClickListener mClickListener; public void setClickListener(View.OnClickListener callback) { mClickListener = callback; } class WeatherViewHolder extends RecyclerView.ViewHolder { ItemWeatherBinding binding; public WeatherViewHolder(View itemView) { super(itemView); binding = DataBindingUtil.bind(itemView); } void binData(CityWeather data) { binding.setCityWeather(data); binding.setDescription(data.getCityWeather().get(0)); } } } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/model/FutureWeather.kt package pl.exaco.internship.android.weatherdemo.model import com.google.gson.annotations.SerializedName data class FutureWeather( @SerializedName("cod") val cod: String, @SerializedName("message") val message: Double, @SerializedName("cnt") val cnt: Int, @SerializedName("list") val list: List<CityWeather> ) <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/service/impl/WeatherManager.java package pl.exaco.internship.android.weatherdemo.service.impl; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.EBean; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import pl.exaco.internship.android.weatherdemo.model.CitiesWeather; import pl.exaco.internship.android.weatherdemo.model.City; import pl.exaco.internship.android.weatherdemo.model.CityWeather; import pl.exaco.internship.android.weatherdemo.service.IWeatherManager; import pl.exaco.internship.android.weatherdemo.service.RequestCallback; import pl.exaco.internship.android.weatherdemo.service.api.WeatherApi; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; @EBean(scope = EBean.Scope.Singleton) public class WeatherManager extends BaseManager implements IWeatherManager { private WeatherApi api; @AfterInject void initService() { api = retrofit.create(WeatherApi.class); } @Override public void getWeatherForCities(List<City> cities, final RequestCallback<List<CityWeather>> callback) { List<String> temp = new ArrayList<>(); for (City city : cities) { if (city != null) { temp.add(String.valueOf(city.getId())); } } api.getWeather(StringUtils.join(temp, ",")).enqueue(new Callback<CitiesWeather>() { @Override public void onResponse(Call<CitiesWeather> call, Response<CitiesWeather> response) { if (null != response && response.body() != null) { callback.onSuccess(response.body().getList()); } else { callback.onSuccess(new ArrayList<>()); } } @Override public void onFailure(Call<CitiesWeather> call, Throwable t) { callback.onError(t); } }); } } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/model/CityWeather.kt package pl.exaco.internship.android.weatherdemo.model import com.google.gson.annotations.SerializedName data class CityWeather( @SerializedName("coord") val coord: Coord? = null, @SerializedName("sys") val sys: Sys? = null, @SerializedName("weather") val cityWeather: List<Weather>? = null, @SerializedName("main") val main: Main? = null, @SerializedName("visibility") val visibility: Int = 0, @SerializedName("wind") val wind: Wind? = null, @SerializedName("clouds") val clouds: Clouds? = null, @SerializedName("dt") val dt: Int = 0, @SerializedName("id") val id: Int = 0, @SerializedName("name") val name: String? = null, @SerializedName("dt_txt") val dtText : String? = null )<file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/model/City.kt package pl.exaco.internship.android.weatherdemo.model import com.google.gson.annotations.SerializedName data class City( @SerializedName("id") val id: Int = 0, @SerializedName("name") val name: String? = null, @SerializedName("country") val country: String? = null, @SerializedName("coord") val coord: Coord? = null )<file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/ui/weather/FutureWeatherActivity.java package pl.exaco.internship.android.weatherdemo.ui.weather; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Toast; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.BindingObject; import org.androidannotations.annotations.DataBound; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.OptionsMenu; import java.util.List; import pl.exaco.internship.android.weatherdemo.R; import pl.exaco.internship.android.weatherdemo.databinding.ActivityCitiesBinding; import pl.exaco.internship.android.weatherdemo.databinding.ActivityFutureWeatherBinding; import pl.exaco.internship.android.weatherdemo.model.City; import pl.exaco.internship.android.weatherdemo.model.CityWeather; import pl.exaco.internship.android.weatherdemo.service.IServiceFactory; import pl.exaco.internship.android.weatherdemo.service.impl.ServiceFactory; @EActivity(R.layout.content_future_weather) @DataBound public class FutureWeatherActivity extends AppCompatActivity implements FutureWeatherContract.View{ private static final String TAG = FutureWeatherActivity.class.getSimpleName(); @Bean(ServiceFactory.class) IServiceFactory serviceFactory; @BindingObject ActivityFutureWeatherBinding binding; private FutureWeatherAdapter adapter; private FutureWeatherContract.Presenter presenter; @AfterViews void viewCreated() { binding.recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new FutureWeatherAdapter(this); binding.recyclerView.setAdapter(adapter); presenter = new FutureWeatherPresenter(this, serviceFactory); Log.e(TAG, "view created"); Intent intent = getIntent(); Integer id = intent.getIntExtra("id", -1); Log.e(TAG, "id = " + id); getData(id); } private void getData(Integer id) { Log.e(TAG, "JEJEJEJEJEJEJJEJEJEJJE"); presenter.getFutureWeather(id); } @Override public void onSuccess(List<CityWeather> data) { if (data != null && !data.isEmpty()) { binding.recyclerView.setVisibility(View.VISIBLE); adapter.setItems(data); Log.e(TAG, "Successs"); } else { Log.e(TAG, "activity failure"); } } @Override public void onFailure() { Log.e(TAG, "activity failure x2"); } } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/service/utils/MockedWhether.kt package pl.exaco.internship.android.weatherdemo.service.utils import pl.exaco.internship.android.weatherdemo.model.* import java.util.* object MockedWhether { fun mockedWhether(count: Int): CitiesWeather { val weathers = ArrayList<CityWeather>() val cityWeather = ArrayList<Weather>() cityWeather.add(Weather(0, "Słonecznie", "bez zachmurzeń", "04n")) val whether = CityWeather( Coord(15.0, -12.5), Sys(0, 0, 0.0, "PL", 1435610796, 1435650870), cityWeather, Main(), 0, Wind(), Clouds(), 0, 0, "Mock Name" ) for (i in 0 until count) { weathers.add(whether.copy()) } return CitiesWeather(count, weathers) } } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/service/utils/ApiKeyInterceptor.java package pl.exaco.internship.android.weatherdemo.service.utils; import java.io.IOException; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public class ApiKeyInterceptor implements Interceptor { private static final String UNITS = "units"; private static final String UNITS_VALUE = "metric"; private static final String APP_ID = "APPID"; private static final String API_KEY = "<KEY>"; private static final String LANGUAGE = "lang"; private static final String LANGUAGE_VAL = "pl"; @Override public Response intercept(Interceptor.Chain chain) throws IOException { final HttpUrl httpUrl = chain .request() .url() .newBuilder() .addQueryParameter(APP_ID, API_KEY) .addQueryParameter(UNITS, UNITS_VALUE) .addQueryParameter(LANGUAGE, LANGUAGE_VAL) .build(); final Request request = chain .request() .newBuilder() .url(httpUrl) .build(); return chain.proceed(request); } } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/service/impl/ServiceFactory.java package pl.exaco.internship.android.weatherdemo.service.impl; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import pl.exaco.internship.android.weatherdemo.service.ICitiesManager; import pl.exaco.internship.android.weatherdemo.service.IFutureWeatherManager; import pl.exaco.internship.android.weatherdemo.service.IServiceFactory; import pl.exaco.internship.android.weatherdemo.service.IWeatherManager; @EBean(scope = EBean.Scope.Singleton) public class ServiceFactory implements IServiceFactory { @Bean(CitiesManager.class) ICitiesManager citiesManager; @Bean(WeatherManager.class) IWeatherManager weatherManager; @Bean(FutureWeatherManager.class) IFutureWeatherManager futureWeatherManager; @Override public ICitiesManager getCitiesManager() { return citiesManager; } @Override public IWeatherManager getWeatherManager() { return weatherManager; } @Override public IFutureWeatherManager getFutureWeatherManager() { return futureWeatherManager; } } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/service/impl/CitiesManager.java package pl.exaco.internship.android.weatherdemo.service.impl; import android.os.AsyncTask; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.androidannotations.annotations.App; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.List; import pl.exaco.internship.android.weatherdemo.R; import pl.exaco.internship.android.weatherdemo.WeatherApplication; import pl.exaco.internship.android.weatherdemo.db.IPrefDataStore; import pl.exaco.internship.android.weatherdemo.db.impl.PrefDataStore; import pl.exaco.internship.android.weatherdemo.model.City; import pl.exaco.internship.android.weatherdemo.service.ICitiesManager; import pl.exaco.internship.android.weatherdemo.service.RequestCallback; @EBean(scope = EBean.Scope.Singleton) public class CitiesManager extends BaseManager implements ICitiesManager { @Bean(value = PrefDataStore.class) IPrefDataStore prefDataStore; @App WeatherApplication app; @Override public List<City> getSavedCities() { return prefDataStore.getSavedCities(); } @Override public void loadCities(RequestCallback<List<City>> callback) { AsyncTask.execute(() -> { try { final InputStream raw = app.getResources().openRawResource(R.raw.cities); final BufferedReader br = new BufferedReader(new InputStreamReader(raw)); final Type type = TypeToken.getParameterized(List.class, City.class).getType(); final List<City> cities = new Gson().fromJson(br, type); callback.onSuccess(cities); } catch (Exception e) { callback.onError(e); } }); } @Override public void addCity(City city) { prefDataStore.addNewCity(city); } } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/model/CitiesWeather.kt package pl.exaco.internship.android.weatherdemo.model import com.google.gson.annotations.SerializedName data class CitiesWeather( @SerializedName("cnt") val count: Int = 0, @SerializedName("list") val list: List<CityWeather>? = null, @SerializedName("dt_txt") val dateString: String? = null, @SerializedName("humidity") private val humidity: Int = 0, @SerializedName("pressure") private val pressure: Double = 0.0 )<file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/model/Main.kt package pl.exaco.internship.android.weatherdemo.model import com.google.gson.annotations.SerializedName data class Main( @SerializedName("temp") val temp: String? = null, @SerializedName("pressure") val pressure: Double = 0.toDouble(), @SerializedName("humidity") val humidity: Double = 0.toDouble(), @SerializedName("temp_min") val tempMin: Double = 0.toDouble(), @SerializedName("temp_max") val tempMax: Double = 0.toDouble() )<file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/ui/weather/FutureWeatherPresenter.java package pl.exaco.internship.android.weatherdemo.ui.weather; import android.util.Log; import java.util.List; import pl.exaco.internship.android.weatherdemo.model.CityWeather; import pl.exaco.internship.android.weatherdemo.model.FutureWeather; import pl.exaco.internship.android.weatherdemo.service.IFutureWeatherManager; import pl.exaco.internship.android.weatherdemo.service.IServiceFactory; import pl.exaco.internship.android.weatherdemo.service.RequestCallback; public class FutureWeatherPresenter implements FutureWeatherContract.Presenter { private static final String TAG = FutureWeatherPresenter.class.getSimpleName(); private final FutureWeatherContract.View view; private final IFutureWeatherManager futureWeatherManager; public FutureWeatherPresenter(FutureWeatherContract.View view, IServiceFactory serviceFactory) { this.view = view; this.futureWeatherManager = serviceFactory.getFutureWeatherManager(); } @Override public void getFutureWeather(Integer cityId) { futureWeatherManager.getFutureWeatherByCity(cityId, new RequestCallback<List<CityWeather>>() { @Override public void onSuccess(List<CityWeather> data) { view.onSuccess(data); Log.e(TAG, "Success future weather"); } @Override public void onError(Throwable throwable) { Log.e(TAG, "Future weather failure"); } }); } } <file_sep>/new_git.sh #!/bin/bash rm -rf .git git init git add . git commit -m "Initial commit" git remote add origin <EMAIL>:m_kaczmarek/weather-demo-quest.git git push -u --force origin master<file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/model/Clouds.kt package pl.exaco.internship.android.weatherdemo.model import com.google.gson.annotations.SerializedName data class Clouds( @SerializedName("all") val all: Double = 0.toDouble() ) <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/model/Sys.kt package pl.exaco.internship.android.weatherdemo.model import com.google.gson.annotations.SerializedName data class Sys( @SerializedName("type") val type: Int = 0, @SerializedName("id") val id: Int = 0, @SerializedName("message") val message: Double = 0.toDouble(), @SerializedName("country") val country: String? = null, @SerializedName("sunrise") val sunrise: Long = 0, @SerializedName("sunset") val sunset: Long = 0 )<file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/service/ICitiesManager.java package pl.exaco.internship.android.weatherdemo.service; import java.util.List; import pl.exaco.internship.android.weatherdemo.model.City; public interface ICitiesManager { List<City> getSavedCities(); void loadCities(RequestCallback<List<City>> callback); void addCity(City city); } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/service/RequestCallback.java package pl.exaco.internship.android.weatherdemo.service; public interface RequestCallback<T> { void onSuccess(T data); void onError(Throwable throwable); } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/ui/city/CityActivity.java package pl.exaco.internship.android.weatherdemo.ui.city; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.SearchView; import android.view.View; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.BindingObject; import org.androidannotations.annotations.DataBound; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import java.util.List; import pl.exaco.internship.android.weatherdemo.R; import pl.exaco.internship.android.weatherdemo.databinding.ActivityFindCityBinding; import pl.exaco.internship.android.weatherdemo.model.City; import pl.exaco.internship.android.weatherdemo.service.IServiceFactory; import pl.exaco.internship.android.weatherdemo.service.impl.ServiceFactory; @DataBound @EActivity(R.layout.activity_city) public class CityActivity extends AppCompatActivity implements CityContract.View { @BindingObject ActivityFindCityBinding binding; @Bean(ServiceFactory.class) IServiceFactory serviceFactory; CityContract.Presenter presenter; CityAdapter adapter; @AfterViews void onViewCreated() { presenter = new CityPresenter(this, serviceFactory); adapter = new CityAdapter(this, city -> { presenter.addCity(city); setResult(Activity.RESULT_OK); finish(); }); binding.recyclerView.setLayoutManager(new LinearLayoutManager(this)); binding.recyclerView.setHasFixedSize(false); binding.recyclerView.setAdapter(adapter); binding.search.onActionViewExpanded(); binding.search.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText, count -> filterResult(count)); return true; } }); loadData(); } private void filterResult(int count) { binding.setHasItems(count > 0); if (count > 0) { binding.noData.setVisibility(View.GONE); } else { binding.noData.setVisibility(View.VISIBLE); } } private void loadData() { binding.progressBar.setVisibility(View.VISIBLE); binding.recyclerView.setVisibility(View.GONE); binding.search.setVisibility(View.GONE); binding.noData.setVisibility(View.GONE); presenter.loadCities(); } @UiThread @Override public void onCitiesLoaded(List<City> cities) { binding.progressBar.setVisibility(View.GONE); binding.search.setVisibility(View.VISIBLE); if (cities.isEmpty()) { binding.noData.setVisibility(View.VISIBLE); } binding.setHasItems(!cities.isEmpty()); adapter.setItems(cities); } } <file_sep>/app/src/main/java/pl/exaco/internship/android/weatherdemo/ui/weather/FutureWeatherAdapter.java package pl.exaco.internship.android.weatherdemo.ui.weather; import android.content.Context; import android.databinding.DataBindingUtil; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import pl.exaco.internship.android.weatherdemo.R; import pl.exaco.internship.android.weatherdemo.databinding.ItemFutureWeatherBinding; import pl.exaco.internship.android.weatherdemo.databinding.ItemWeatherBinding; import pl.exaco.internship.android.weatherdemo.model.CityWeather; public class FutureWeatherAdapter extends RecyclerView.Adapter<FutureWeatherAdapter.FutureWeatherViewHolder> { private final List<CityWeather> items = new ArrayList<>(); private final Context context; public FutureWeatherAdapter(Context context) { this.context = context; } void setItems(@NonNull List<CityWeather> items) { this.items.clear(); this.items.addAll(items); this.notifyDataSetChanged(); } @Override public int getItemCount() { return items.size(); } @Override public FutureWeatherViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View itemView = LayoutInflater.from(context).inflate(R.layout.item_future_weather, parent, false); return new FutureWeatherViewHolder(itemView); } @Override public void onBindViewHolder(FutureWeatherViewHolder holder, int position) { if (getItemCount() > position) { final CityWeather weather = items.get(position); holder.binData(weather); } } class FutureWeatherViewHolder extends RecyclerView.ViewHolder { ItemFutureWeatherBinding binding; public FutureWeatherViewHolder(View itemView) { super(itemView); binding = DataBindingUtil.bind(itemView); } void binData(CityWeather data) { binding.setCityWeather(data); binding.setDescription(data.getCityWeather().get(0)); } } }
a7a7cf33e4feb4a63bf42daa9280515fbe9b2687
[ "Java", "Kotlin", "Shell" ]
23
Kotlin
mkaczmarek93/ExacoInternshipAndroid
f88722f9d787045ec3abef9d72e4520686644411
c8a4639f609c2adb7603c35ec1fe17151afd313a
refs/heads/main
<repo_name>ZolliePy/architect<file_sep>/vendor/composer/autoload_static.php <?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInit70b0db667fe1aaf53ef191a4ac20492c { public static $files = array ( '7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', 'c964ee0ededf28c96ebd9db5099ef910' => __DIR__ . '/..' . '/guzzlehttp/promises/src/functions_include.php', 'a0edc8309cc5e1d60e3047b5df6b7052' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/functions_include.php', '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', ); public static $prefixLengthsPsr4 = array ( 'Z' => array ( 'ZollieProject\\Study\\' => 20, ), 'P' => array ( 'Psr\\Http\\Message\\' => 17, 'Psr\\Http\\Client\\' => 16, ), 'I' => array ( 'IcyApril\\ChapterOne\\' => 20, ), 'G' => array ( 'GuzzleHttp\\Psr7\\' => 16, 'GuzzleHttp\\Promise\\' => 19, 'GuzzleHttp\\' => 11, ), ); public static $prefixDirsPsr4 = array ( 'ZollieProject\\Study\\' => array ( 0 => __DIR__ . '/../..' . '/src/zollieproject/study', ), 'Psr\\Http\\Message\\' => array ( 0 => __DIR__ . '/..' . '/psr/http-message/src', ), 'Psr\\Http\\Client\\' => array ( 0 => __DIR__ . '/..' . '/psr/http-client/src', ), 'IcyApril\\ChapterOne\\' => array ( 0 => __DIR__ . '/../..' . '/src/icyapril/chapterone', ), 'GuzzleHttp\\Psr7\\' => array ( 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', ), 'GuzzleHttp\\Promise\\' => array ( 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', ), 'GuzzleHttp\\' => array ( 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', ), ); public static $classMap = array ( 'Nette\\ArgumentOutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\DeprecatedException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\DirectoryNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\FileNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\IOException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\InvalidArgumentException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\InvalidStateException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Iterators\\CachingIterator' => __DIR__ . '/..' . '/nette/utils/src/Iterators/CachingIterator.php', 'Nette\\Iterators\\Mapper' => __DIR__ . '/..' . '/nette/utils/src/Iterators/Mapper.php', 'Nette\\Localization\\ITranslator' => __DIR__ . '/..' . '/nette/utils/src/Utils/ITranslator.php', 'Nette\\MemberAccessException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\NotImplementedException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\NotSupportedException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\OutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\PhpGenerator\\ClassType' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/ClassType.php', 'Nette\\PhpGenerator\\Closure' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Closure.php', 'Nette\\PhpGenerator\\Constant' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Constant.php', 'Nette\\PhpGenerator\\Dumper' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Dumper.php', 'Nette\\PhpGenerator\\Factory' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Factory.php', 'Nette\\PhpGenerator\\GlobalFunction' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/GlobalFunction.php', 'Nette\\PhpGenerator\\Helpers' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Helpers.php', 'Nette\\PhpGenerator\\Literal' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Literal.php', 'Nette\\PhpGenerator\\Method' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Method.php', 'Nette\\PhpGenerator\\Parameter' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Parameter.php', 'Nette\\PhpGenerator\\PhpFile' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/PhpFile.php', 'Nette\\PhpGenerator\\PhpLiteral' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/PhpLiteral.php', 'Nette\\PhpGenerator\\PhpNamespace' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/PhpNamespace.php', 'Nette\\PhpGenerator\\Printer' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Printer.php', 'Nette\\PhpGenerator\\Property' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Property.php', 'Nette\\PhpGenerator\\PsrPrinter' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/PsrPrinter.php', 'Nette\\PhpGenerator\\Traits\\CommentAware' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Traits/CommentAware.php', 'Nette\\PhpGenerator\\Traits\\FunctionLike' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Traits/FunctionLike.php', 'Nette\\PhpGenerator\\Traits\\NameAware' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Traits/NameAware.php', 'Nette\\PhpGenerator\\Traits\\VisibilityAware' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Traits/VisibilityAware.php', 'Nette\\PhpGenerator\\Type' => __DIR__ . '/..' . '/nette/php-generator/src/PhpGenerator/Type.php', 'Nette\\SmartObject' => __DIR__ . '/..' . '/nette/utils/src/Utils/SmartObject.php', 'Nette\\StaticClass' => __DIR__ . '/..' . '/nette/utils/src/Utils/StaticClass.php', 'Nette\\UnexpectedValueException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\ArrayHash' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayHash.php', 'Nette\\Utils\\ArrayList' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayList.php', 'Nette\\Utils\\Arrays' => __DIR__ . '/..' . '/nette/utils/src/Utils/Arrays.php', 'Nette\\Utils\\AssertionException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\Callback' => __DIR__ . '/..' . '/nette/utils/src/Utils/Callback.php', 'Nette\\Utils\\DateTime' => __DIR__ . '/..' . '/nette/utils/src/Utils/DateTime.php', 'Nette\\Utils\\FileSystem' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileSystem.php', 'Nette\\Utils\\Helpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/Helpers.php', 'Nette\\Utils\\Html' => __DIR__ . '/..' . '/nette/utils/src/Utils/Html.php', 'Nette\\Utils\\IHtmlString' => __DIR__ . '/..' . '/nette/utils/src/Utils/IHtmlString.php', 'Nette\\Utils\\Image' => __DIR__ . '/..' . '/nette/utils/src/Utils/Image.php', 'Nette\\Utils\\ImageException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\Json' => __DIR__ . '/..' . '/nette/utils/src/Utils/Json.php', 'Nette\\Utils\\JsonException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\ObjectHelpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/ObjectHelpers.php', 'Nette\\Utils\\ObjectMixin' => __DIR__ . '/..' . '/nette/utils/src/Utils/ObjectMixin.php', 'Nette\\Utils\\Paginator' => __DIR__ . '/..' . '/nette/utils/src/Utils/Paginator.php', 'Nette\\Utils\\Random' => __DIR__ . '/..' . '/nette/utils/src/Utils/Random.php', 'Nette\\Utils\\Reflection' => __DIR__ . '/..' . '/nette/utils/src/Utils/Reflection.php', 'Nette\\Utils\\RegexpException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\Strings' => __DIR__ . '/..' . '/nette/utils/src/Utils/Strings.php', 'Nette\\Utils\\UnknownImageFileException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\Validators' => __DIR__ . '/..' . '/nette/utils/src/Utils/Validators.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInit70b0db667fe1aaf53ef191a4ac20492c::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInit70b0db667fe1aaf53ef191a4ac20492c::$prefixDirsPsr4; $loader->classMap = ComposerStaticInit70b0db667fe1aaf53ef191a4ac20492c::$classMap; }, null, ClassLoader::class); } } <file_sep>/src/zollieproject/study/title.php <?php /* this class helps in giving the basic details to a publication */ namespace ZollieProject\Study; trait Title { /** * Title of the publication * * @var string * @since 1.0.0 */ private $title = null; /** * Short description of the publication * * @var string * @since 1.0.0 */ public $short_desc = null; /** * Constructor creating the publication title and short description * * @param string $identifier The primary key of the user to load (optional). * * @since 1.7.0 */ public function giveTitle(string $title) { $this->title = $title; // echo "<br><h2>The title is: " . $this->title; } public function shortDescription(string $short_desc) { $this->short_desc = $short_desc; echo "<br><h2>The short description is: " . $this->short_desc; } public function getTitle() { return $this->title; } } <file_sep>/src/zollieproject/study/bookcategory.php <?php namespace ZollieProject\Study; use \ZollieProject\Study\Category; class bookCategory extends Category { // name of the category protected $book_category_name; public function __construct(string $cat_name) { $this->book_category_name = $cat_name; } public function getCategory() { return $this->book_category_name; } public function print() { parent::printOut(); } } <file_sep>/src/icyapril/chapterone/book.php <?php namespace IcyApril\ChapterOne; use \ZollieProject\Study\Title; use \ZollieProject\Study\bookCategory; class Book { use Title; public $bookCategory; // public $title; public function __construct() { echo "Ohh my friend, we just started here again...:)"; } public function setCategory(bookCategory $bookCategory) { $this->bookCategory = $bookCategory; // echo "<br>This book is in the category: " . $this->bookCategory->book_category_name; // print using the bookCategory->print() method $this->bookCategory->print(); // using the Category abstract class inherited printOut() method directly. echo "<br>Third from abstract printOut() function: "; $this->bookCategory->printOut(); } } <file_sep>/src/zollieproject/study/category.php <?php namespace ZollieProject\Study; /* This class is giving the base of categories of publications */ abstract class Category { // protected $children; // protected $adult; // protected $programming; public $cat_name; // Force Extending class to define this method abstract public function getCategory(); /* not every function has to be abstact in an abstract class - commonly used functions can be defined in the abstact class **/ public function printOut() { echo "<br>Secondly from abstract parent, this book is in: " . $this->getCategory() . "<br>"; } } <file_sep>/index.php <?php require_once('vendor/autoload.php'); use IcyApril\ChapterOne\Book; use ZollieProject\Study\bookCategory; $title1 = 'Excuse Me'; $myFirstBook = new Book(); // it just give back a text "...we just started..." $myFirstBook->giveTitle($title1); echo "<br><h2>From index page - The title is: " . $myFirstBook->getTitle(); $descShort = "This book is all about money..."; $myFirstBook->shortDescription($descShort); $childrenCatgr = new bookCategory("children"); $myFirstBook->setCategory($childrenCatgr); echo "<br><h3>Heyyy, hooo</h3>";
cd677f818f0aab7e014e84e41f0933df87d59851
[ "PHP" ]
6
PHP
ZolliePy/architect
8a5d3bb01f50c76ae4866143a77fe3b7a084f40d
c017add64d3105ee57423a353d1b0a78a6153e64
refs/heads/master
<file_sep> 'use strict'; (function(angular){ //由于默认angular提供的异步请求对象不支持自定义回调函数名 //angular随机分配的回调函数名不被豆瓣支持 var http= angular.module('moviecat.services.http',[]); http.service('HttpService',['$window','$document',function($window,$document){ //url :http://api.douban.com/aaa -->script -->html自动执行 this.jsonp =function(url,data,callback){ // 1 挂载回调函数 var fnSuffix=Math.random().toString().replace('.',''); var cbFuncName='my_json_cb_'+fnSuffix; //不推荐 $window[cbFuncName]=callback; // 2 将data转换为url字符串的形式 // {id:1,name:'zhangsan'} id=1&name='zhangsan' var querystring= url.indexOf('?')==-1?'?':'&'; for(var key in data){ querystring+=key+'='+data[key]+'&'; } // 3 处理url中的回调参数 // url+=callback=函数名 querystring+='callback='+cbFuncName; // 4 创建一个script标签 var scriptElement=$document[0].createElement('script'); scriptElement.src=url+querystring; // 注意此时还不能将其append页面上 // 5 将script标签放到页面中 $document[0].body.appendChild(scriptElement); // append过后页面会自动对这个地址发送请求,请求完成后自动执行 }; }]); })(angular);<file_sep> (function(){ 'use strict'; // 创建正在热映模块 var module= angular.module('moviecat.top250', ['ngRoute','moviecat.services.http']); //配置模块的路由 module.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/top250/:page', { templateUrl: 'top250/view.html?v='+Math.random(), controller: 'Top250Controller' }); }]) module.controller('Top250Controller', ['$scope','$routeParams','$route','HttpService',function($scope,$routeParams,$route,HttpService) { var count=10;//每一页的条数 var page=parseInt($routeParams.page);//页码 var start=(page-1)*count;//起始记录 //控制器 分为两步: 1设计暴露数据 2设计暴露行为 $scope.loading=true; //开始加载 $scope.title=''; $scope.subjects=[]; $scope.message=''; $scope.totalCount=0; $scope.totalPages=0; $scope.currentPage=page; //该匿名函数需要挂载在全局作用域,才能被调用 HttpService.jsonp('http://api.douban.com//v2/movie/top250',{start:start,count:count},function(data){ console.log(data); $scope.title=data.title; $scope.subjects=data.subjects; $scope.totalCount=data.total; $scope.totalPages=Math.ceil($scope.totalCount/count); $scope.loading=false; // $apply的作用就是让指定的表达式重新同步 $scope.$apply(); }); //暴露一个上一页 下一页的行为 $scope.go=function(page){ //一定要做一个合法范围的校验 if(page>=1 && page<=$scope.totalPages){ $route.updateParams({page:page}); } } }]); })(angular); // var doubanApiAddress='http://api.douban.com/v2/movie/in_theaters'; // //测试$http服务 // //在Angular中使用JSONP的方式做跨域请求 // //必须给当前地址加上一个参数 callback=JSON_CALLBACK,实际请求地址angular会将JSON_CALLBACK替换http://api.douban.com/v2/movie/in_theaters?callback=angular.callbacks._0,但是豆瓣api不知callback=angular.callbacks._0,的函数名 // $http.jsonp(doubanApiAddress+'?callback=JSON_CALLBACK').then(function(res){ // //此处代码是异步请求完成之后才执行(需要等一段时间) // if(res.status==200){ // $scope.subjects=res.data.subjects; // }else{ // $scope.message='获取数据失败:'+res.statusText; // } // },function(err){ // console.log(err); // $scope.message='获取数据失败:'+err.statusText; // });
fe282b60ae02ef8ac6e506a95546e98aaefee43d
[ "JavaScript" ]
2
JavaScript
liulei18/moviecat
2637ad60bd6fd68f83d569095acc2ce3d970a9de
21bb30b4da70139386edd095ecc2ac56bd0561ee
refs/heads/master
<file_sep>app .directive('looksFeedItem', function($rootScope, apiRepository,$state){ return { restrict: 'EA' , templateUrl: "uiComponents/looksFeedItem/looksFeedItem.html" , controller:function($scope){ //$scope.media = apiRepository.getHeadlines(); } , link:function($scope, $element, $attrs){ var mediaId = $attrs.mediaid; var theItemImg = $element.find('img') $scope.thisMainDisplayImg = "img/myavanahairjourneyapp.png"; var mediaSrc = apiRepository.getMedia(mediaId).success(function(data){ img = new Image(); img.onload = function() { theItemImg[0].src = data.imageUrl; $scope.thisMainDisplayImg = data.imageUrl }; img.onerror = function(){ //$element.addClass("ng-hide-add"); } img.src = data.imageUrl if(data.likes == null){ $scope.thisLikes = "0" }else{ $scope.thisLikes = data.likes; } if(data.comments == null){ $scope.thisComments = "0" }else{ $scope.thisComments = data.comments; } $scope.thisUserProgileImg = data.profileImageUrl; $scope.des = data.description; //$scope.thisUserImage = data.imageUrl; }); $scope.mediaClicked = function(postObj){ postObj.mainImageUrl = $scope.thisMainDisplayImg; postObj.userProfileImage = $scope.thisUserProgileImg; postObj.comments = $scope.thisComments; postObj.likes = $scope.thisLikes; postObj.des = $scope.des; postObj.username = $scope.userUsername postObj.media_id = postObj.id; postObj.profileUrlId = postObj.UserProfileImageId; if (postObj.UserId){ postObj.user_id = postObj.UserId; }; //postObj.UserId = postObj.UserId; $rootScope.currentPostMainImage = $scope.thisMainDisplayImg; $rootScope.currentPostUserImage = $scope.thisUserProgileImg; $state.go('app.viewpost', { post: JSON.stringify(postObj)}) } /* var theItemImg = $element.find('img') theItemImg[0].src = mediaSrc.url; */ } } });<file_sep>var cb = new ClearBlade(); angular.module('starter.services', []) .factory('Chats', function() { // Might use a resource here that returns a JSON array // Some fake testing data var chats = [{ id: 0, name: '<NAME>', lastText: 'You on your way?', face: 'img/ben.png' }, { id: 1, name: '<NAME>', lastText: 'Hey, it\'s me', face: 'img/max.png' }, { id: 2, name: '<NAME>', lastText: 'I should buy a boat', face: 'img/adam.jpg' }, { id: 3, name: '<NAME>', lastText: 'Look at my mukluks!', face: 'img/perry.png' }, { id: 4, name: '<NAME>', lastText: 'This is wicked good ice cream.', face: 'img/mike.png' }]; var getdevices = function(){ cb.init({ URI: 'https://machineq.clearblade.com', // e.g., 'https://platform.clearblade.com/' systemKey: 'e8edb9920bac9df3faf1f79cc5bd01', systemSecret: '<KEY>', email: "<EMAIL>", // use registerEmail instead if you wish to create a new user password: "<PASSWORD>", callback: initCallback, }); function initCallback(err, cbb) { var callback = function (err, data) { if (err) { console.log("fetch error : " + JSON.stringify(data)); } else { //data = JSON.parse(JSON.stringify(data)); data.sort(function(x, y){ return x.time - y.time; }) return data } }; var query = cb.Query({collectionName: "Sensor Data"}); query.fetch(callback); // err is a boolean, cb has APIs and constructors attached } } return { all: function() { return chats; }, remove: function(chat) { chats.splice(chats.indexOf(chat), 1); }, get: function(chatId) { for (var i = 0; i < chats.length; i++) { if (chats[i].id === parseInt(chatId)) { return chats[i]; } } return null; }, getdevices:getdevices }; }); <file_sep>app .controller('ProfileCtrl', function($scope,$state, $rootScope,$localStorage,$stateParams,apiRepository,$ionicModal,$cordovaImagePicker,$ionicPlatform,$cordovaCamera,$ionicPopup,$cordovaToast,$sce,$cordovaInAppBrowser,$timeout,$ionicScrollDelegate,$q){ //console.log("Dash"); $scope.moreUserPostCanBeLoaded = false; $scope.image= 'img/myavanalogonotext.png'; $scope.imageNotChosen = true; $scope.fullName = $localStorage.user.user.fullName; $scope.email = $localStorage.user.user.email; $scope.testSrc = undefined; $scope.searching = false; $scope.profileTitle = "Profile" $scope.noFriends = false; $scope.hairAnalysisProfileStyle = { 'height': Math.floor((document.getElementById("profileContent").offsetWidth * .28) + document.getElementById("profileContent").offsetWidth) + 'px', 'width':'100%' } if($stateParams.userId == $localStorage.user.user.id){ $scope.hairUrl = "http://www.myavana.com/" + $localStorage.user.user.username; $scope.userHairUrl = $sce.trustAsResourceUrl($scope.hairUrl); $rootScope.thisIsMyProfile = true; $scope.canFollow = false; } else{ $rootScope.thisIsMyProfile = false; } $scope.changeSearchState = function(){ if ($scope.searching == true) { $scope.searching = false; $scope.profileTitle = "Profile"; $scope.theSearchText = ""; } else{ $scope.searching = true; $scope.profileTitle = ""; } } /*Change Profile Modal*/ $ionicModal.fromTemplateUrl('pages/changeprofilemodal/changeprofilemodal.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.profileModal = modal }) $scope.openProfileModal = function() { $scope.profileModal.show() } $scope.closeProfileModal = function() { $scope.profileModal.hide(); }; $scope.changeProfileImage = function(theMediaId){ apiRepository.changeProfileImage(theMediaId).success(function(data){ $scope.image = data.profileImageUrl; $scope.closeProfileModal(); }) } /*Comment Modal Code*/ $scope.uploadInProgress = false; $ionicModal.fromTemplateUrl('pages/uploadModal/uploadModal.html', { scope: $scope, animation: 'slide-in-up' }).then(function(jmodal) { $scope.journeyModal = jmodal }) $scope.openJourneyModal = function() { $scope.journeyModal.show() } $scope.closeJourneyModal = function() { $scope.journeyModal.hide(); }; function getAllConsultations(){ apiRepository.getConsultationAll().success(function(data){ for (var i = 0; i < data.length; i++) { var theDate = new Date(data[i].consultation_date); data[i].consultation_date = (theDate.getMonth() + 1) + '/' + (theDate.getDate()) + '/' + (theDate.getFullYear()); if (data[i].consultation_typWearHair != 'undefined' && data[i].consultation_typWearHair != undefined){ data[i].consultation_typWearHair = JSON.parse(data[i].consultation_typWearHair); }else{ data[i].consultation_typWearHair = []; } if (data[i].consultation_likeToWearHair != 'undefined' && data[i].consultation_likeToWearHair != undefined){ data[i].consultation_likeToWearHair = JSON.parse(data[i].consultation_likeToWearHair); }else{ data[i].consultation_likeToWearHair = []; } if (data[i].consultation_products != 'undefined' && data[i].consultation_products != undefined){ data[i].consultation_products = JSON.parse(data[i].consultation_products); }else{ data[i].consultation_products = []; } if (data[i].consultation_challenges != 'undefined' && data[i].consultation_challenges != undefined){ data[i].consultation_challenges = JSON.parse(data[i].consultation_challenges); }else{ data[i].consultation_challenges = []; } }; $scope.allUserConsultations = data; //console.log(data); }) } getAllConsultations(); /*consulModal Modal*/ $ionicModal.fromTemplateUrl('pages/viewConsultation/viewConsultation.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.consulModal = modal }) $scope.openConsulModal = function() { $scope.consulModal.show() } $scope.closeConsulModal = function() { $scope.consulModal.hide(); }; var activeTags = {}; activeTags.typ = ['In its natural state','Wash and go','Straightened (with heat)','Protective styles (braids, twists, etc)','Set styles (twists, rollers, bantu knots, etc)','Weave/wigs']; activeTags.chall = ['Dryness','Product Buildup','Oily hair','Breakage','Frizzy','Shedding','Dull','Porous','Physical Damage: (heat, braids. weaves)','Chemical/color damage','Manageability/ Tangled','Dry Scalp','Dandruff','Dermatitis','Oily Scalp','Flaky Scalp','Sensitive Scalp']; $scope.loadHairTags = function(query) { return activeTags.typ; }; $scope.loadChallenges = function(query) { //return activeTags.chall; activeTags.chall = []; var deferred = $q.defer(); apiRepository.challSearch(query).success(function(data){ for (var i = 0; i < data.length; i++) { activeTags.chall.push(data[i].challenge) }; deferred.resolve(activeTags.chall); //return data; }) return deferred.promise; }; $scope.loadProductTages = function(query) { //return activeTags.products; activeTags.prods = []; var deferred = $q.defer(); apiRepository.prodSearch(query).success(function(data){ for (var i = 0; i < data.length; i++) { activeTags.prods.push(data[i].brandName + "- " + data[i].name) }; deferred.resolve(activeTags.prods); //return data; }) return deferred.promise; }; /*consulModal Modal*/ $ionicModal.fromTemplateUrl('pages/newConsultation/newConsultation.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.newConsulModal = modal }) $scope.openNewConsulModal = function() { $scope.newConsulModal.show() } $scope.closeNewConsulModal = function() { $scope.newConsulModal.hide(); }; $scope.requestConsultation = function(consulObj){ //console.log(consulObj); apiRepository.reqConsultation(consulObj).success(function(data){ if (data.error){ toastr.error('Sorry.', 'Pending Request', {timeOut: 5000}) }; $scope.closeNewConsulModal(); getAllConsultations(); }) } /*add Salon Modal*/ $ionicModal.fromTemplateUrl('pages/addSalon/addSalon.html', { scope: $scope, animation: 'slide-in-up' }).then(function(smodal) { $scope.newSalonModal = smodal }) var dbProducts; apiRepository.getAllStylist().success(function(data){ // load products suggestion if (!data.error) { dbProducts = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'), queryTokenizer: Bloodhound.tokenizers.whitespace, local: data, }); } }); $scope.openSalonModal = function() { $scope.newSalonModal.show(); $('#salonField').typeahead({ hint: true, highlight: true, minLength: 1 }, { display: 'name', source: dbProducts, templates: { empty: 'No results found', suggestion: function ( data ) { return '<div style="padding:10px"><h5>' + 'Name: ' + data.name+ '</h5><p>' + " Address: "+ data.address +' '+ data.zipcode +'</p></div>'; } } }); $('.typeahead').bind('typeahead:select', function(ev, suggestion) { $scope.theSalonId = suggestion.id; }); } $scope.closeSalonModal = function() { $scope.newSalonModal.hide(); }; $scope.userSalons = []; function getMySalons(){ apiRepository.getMySalons().success(function(data){ $scope.userSalons = data; //console.log(data); }) } getMySalons(); $scope.addSalon = function(){ if ($scope.theSalonId) { theSalonId = $scope.theSalonId; apiRepository.addMySalon(theSalonId).success(function(data){ if (!data.error){ $cordovaToast.show('salon added', 'long', 'bottom').then(function(success) { // success }, function (error) { // error }); }; $scope.closeSalonModal(); getMySalons(); }) }else{ $cordovaToast.show('Not a salon sorry', 'long', 'bottom').then(function(success) { // success }, function (error) { // error }); } } $scope.deleteSalon = function(salonID){ apiRepository.deleteMySalon(salonID).success(function(data){ if(!data.error){ $cordovaToast.show('salon deleted', 'long', 'bottom').then(function(success) { // success }, function (error) { // error }); getMySalons(); } }) } $scope.mysqlTimeStampToDate = function(thedate){ var theDate = new Date(thedate); return (theDate.getMonth() + 1) + '/' + (theDate.getDate()) + '/' + (theDate.getFullYear()); } $scope.viewConsultation = function(theConsultation){ /* if (theConsultation.consultation_typWearHair){ theConsultation.consultation_typWearHair = JSON.parse(theConsultation.consultation_typWearHair); }else{ theConsultation.consultation_typWearHair = []; } if (theConsultation.consultation_likeToWearHair){ theConsultation.consultation_likeToWearHair = JSON.parse(theConsultation.consultation_likeToWearHair); }else{ theConsultation.consultation_likeToWearHair = []; } if (theConsultation.consultation_challenges){ theConsultation.consultation_challenges = JSON.parse(theConsultation.consultation_challenges); }else{ theConsultation.consultation_challenges = []; } if (theConsultation.consultation_products){ theConsultation.consultation_products = JSON.parse(theConsultation.consultation_products); }else{ theConsultation.consultation_products = []; } */ $scope.consultationReq = theConsultation; $scope.openConsulModal(); } $scope.followUser = function(){ apiRepository.follow($stateParams.userId).success(function(data){ if(!data.msg){ $scope.canFollow = false; } else{ $scope.canFollow = true; } }) } $scope.unFollowUser = function(){ apiRepository.unFollow($stateParams.userId).success(function(data){ if(data.msg == 'unfollowed'){ $scope.canFollow = true; } else{ $scope.canFollow = false; } }) } $scope.updateProfile = function(newName,newEmail){ if (newEmail) { apiRepository.userUpdateEmail(newEmail).success(function(data){ if(data.msg == 'updated email'){ $scope.userNewEmail = "" $cordovaToast .show('updated Email', 'long', 'bottom') .then(function(success) { // success }, function (error) { // error }); $scope.email = newEmail; } }) }; if (newName) { apiRepository.userUpdateFullName(newName).success(function(data){ if(data.msg == 'updated fullName'){ $scope.userNewName = "" $cordovaToast .show('updated Name', 'long', 'bottom') .then(function(success) { // success }, function (error) { // error }); $scope.fullName = newName; } }) }; } $rootScope.refreshHairJourney = function(){ apiRepository.getUserMedia($stateParams.userId,0).success(function(data){ $scope.userPosts = data.Media; if ($scope.userPosts.length == 0){ $scope.noLooks = true; $scope.moreUserPostCanBeLoaded = false; }else{ $scope.noLooks = false; $scope.moreUserPostCanBeLoaded = true; } }); } $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ // do something $rootScope.contentIndex = 0; if (fromState.name == 'app.viewpost' && toState.name == 'app.profile') { $rootScope.refreshHairJourney(); }else if (fromState.name == 'app.profile' && toState.name == 'app.profile'){ console.log('Profile state shown twice') console.log(toParams.userId); if (toParams.userId == $localStorage.user.user.id){ $rootScope.thisIsMyProfile = true; $scope.canFollow = false; }; }; }) $scope.canLoadMorePost = function(){ if ($scope.moreUserPostCanBeLoaded == true){ return true; }else if(!$scope.userPosts){ return false; } else{ return false; } }; $scope.loadMoreData = function(){ var currentNumOfPost = $scope.userPosts.length; if (currentNumOfPost % 20 == 0){ apiRepository.getUserMedia($stateParams.userId,currentNumOfPost).success(function(data){ if (data.returned != 0){ for (var i = 0; i < data.Media.length; i++) { $scope.userPosts.push(data.Media[i]) }; $scope.moreUserPostCanBeLoaded = true; $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $scope.moreUserPostCanBeLoaded = false; } }) }else{ $scope.moreUserPostCanBeLoaded = false; } } $rootScope.changeProfileContent = function(indexOfContent){ $rootScope.contentIndex = indexOfContent; if (indexOfContent != 1) { $scope.searching = false; }; $ionicScrollDelegate.scrollTop(); } $scope.goToServices = function(){ var url = 'http://myavana.com/pages/services/'; var options = { }; $cordovaInAppBrowser.open(url, '_system', options); } if(!$scope.userPosts){ apiRepository.getUser($stateParams.userId).success(function(data){ $scope.userUsername = data.username $rootScope.refreshHairJourney(); /* apiRepository.getTheUsersProfileImage(data.UserProfileImageId).success(function(data){ $scope.userProfileImage = data.profileImageUrl }) */ apiRepository.getTheUsersProfileImage(data.UserProfileImageId).success(function(data){ $scope.image = 'img/myavanalogonotext.png'; profileImg = new Image(); profileImg.onload = function() { $scope.image = data.profileImageUrl; /*once loaded show the image*/ //$element[0].src = img.src; //$element.addClass("ng-hide-add"); //$scope.thisMainDisplayImg = img.src }; profileImg.onerror = function(){ if (data.UserProfileImageId && data.UserProfileImageId != "") { $scope.image = 'https://s3.amazonaws.com/myavana/userUploads/'+data.UserProfileImageId+'.jpeg'; }; //$element.addClass("ng-hide-add"); } profileImg.src = data.profileImageUrl }) }) } $scope.moreFriendsCanBeLoaded = true; apiRepository.getGirlfriendsV2($stateParams.userId,0).success(function(data){ $scope.canFollow = true; $scope.userFriends = data if (data.length == 0){ $scope.noFriends = true; }else{ $scope.noFriends = false; } /* for (var i = 0; i <= data.length -1; i++) { if (data[i].FollowingId == $localStorage.user.user.id) { $scope.canFollow = false; return; }; }; */ apiRepository.canUserFollow($localStorage.user.user.id,$stateParams.userId).success(function(data){ console.log(data); if (data.length != 0){ $scope.canFollow = false; }; }) }) $scope.loadMoreFriends = function(){ var currentNumOfFriends = $scope.userFriends.length; if (currentNumOfFriends % 25 == 0){ apiRepository.getGirlfriendsV2($stateParams.userId,currentNumOfFriends).success(function(data){ if (data.returned != 0){ for (var i = 0; i < data.length; i++) { $scope.userFriends.push(data[i]) }; $scope.moreFriendsCanBeLoaded = true; $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $scope.moreFriendsCanBeLoaded = false; } }) }else{ $scope.moreFriendsCanBeLoaded = false; } } $scope.canLoadMoreFriends = function(){ if ($scope.moreFriendsCanBeLoaded == true){ return true; }else{ return false; } }; $scope.activeTags = []; apiRepository.getProducts().success(function(data){ if (data.error) { toastr.error('Oops.', 'Problem getting product tags', {timeOut: 4000}) }else{ for (var i = 0; i <= data.length - 1; i++) { $scope.activeTags.push(data[i].name) }; $scope.loadTags = function(query) { return $scope.activeTags; }; $scope.allProdTags = data } }) });<file_sep>module.exports = function(grunt){ // Project configuration. grunt.initConfig({ concat: { // Concat all the Angular Directives in the uiComponents Folder uiComponents: { src: ['www/uiComponents/**/*.js'], dest: 'www/js/uiComponentsBuilt.js', }, pages: { src: ['www/pages/**/*.js'], dest: 'www/js/pagesBuilt.js', }, cssComponents: { src: ['www/pages/**/*.css', 'www/uiComponents/**/*.css'], dest: 'www/css/components.css', } }, watch: { uiComponents:{ files:['www/uiComponents/**/*.js'], tasks:['concat:uiComponents'], }, pages:{ files:['www/pages/**/*.js'], tasks:['concat:pages'], }, cssComponents:{ files:['www/pages/**/*.css', 'www/uiComponents/**/*.css'], task:['concat:cssComponents'] } } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['concat', 'watch']); };
969995ae98fe159defaf554b7939c30b2f6d454e
[ "JavaScript" ]
4
JavaScript
Segfaultpng/projectroot
82c6be5a0fa5b28a8e49d57ad3eabd0a450f5cbf
cd8a9f3213baa5337eae0c93859046db618c8475
refs/heads/master
<file_sep> --- SERVER ESX = nil local cars = {} TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) ESX.RegisterServerCallback('esx_carkeys:getOwnedVehicles', function (source, cb) local xPlayer = ESX.GetPlayerFromId(source) MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner', { ['@owner'] = xPlayer.identifier }, function (result) cb(result) end) end) ESX.RegisterServerCallback('esx_carkeys:getKeysByPlate', function (source, cb, plate) MySQL.Async.fetchAll('SELECT COUNT(id) AS total FROM owned_keys where plate=@plate', { ['@plate'] = plate }, function(result) cb(result) end) end) ESX.RegisterServerCallback('esx_carkeys:getKeysByIdentifier', function (source, cb) local xPlayer = ESX.GetPlayerFromId(source) MySQL.Async.fetchAll('SELECT a.id as id, a.plate as plate, a.owner as owner, b.vehicle as vehicle, count(a.id) as nbKey FROM `owned_keys` as a INNER JOIN `owned_vehicles` as b ON a.plate = b.plate where a.owner=@owner group by a.plate' , { ['@owner'] = xPlayer.identifier }, function(result) cb(result) end) end) RegisterServerEvent('esx_carkeys:createKeys') AddEventHandler('esx_carkeys:createKeys', function (plate, count) local _source = source local xPlayer = ESX.GetPlayerFromId(_source) for i = 1, count do MySQL.Async.execute('INSERT INTO owned_keys (plate, owner) VALUES (@plate,@owner)', { ['@plate'] = plate, ['@owner'] = xPlayer.identifier }) end end) RegisterServerEvent('esx_carkeys:giveKey') AddEventHandler('esx_carkeys:giveKey', function (idKey, playerId, plate) local _source = source local xPlayer = ESX.GetPlayerFromId(_source) local closestPlayer = ESX.GetPlayerFromId(playerId) MySQL.Async.execute('UPDATE `owned_keys` SET `owner`=@newOwner WHERE `id` = @id', { ['@newOwner'] = closestPlayer.identifier, ['@id'] = idKey }) TriggerClientEvent('esx:showNotification', playerId, 'Vous avez reçu une clé de véhicule ~g~ '.. plate ..' !\n') end) RegisterServerEvent('esx_carkeys:dropKey') AddEventHandler('esx_carkeys:dropKey', function (idKey) MySQL.Async.execute('DELETE FROM `owned_keys` WHERE `id` = @id', { ['@id'] = idKey }) end) ESX.RegisterServerCallback('esx_carkeys:checkKey', function (source, cb, plate) local _source = source local xPlayer = ESX.GetPlayerFromId(_source) MySQL.Async.fetchAll( 'SELECT * FROM owned_keys WHERE plate = @plate AND owner = @identifier', { ['@plate'] = plate, ['@identifier'] = xPlayer.identifier }, function(result) local found = false if result[1] ~= nil then if xPlayer.identifier == result[1].owner then found = true end end if found then cb(true) else cb(false) end end) end)<file_sep>CREATE TABLE `owned_keys` ( `id` int NOT NULL AUTO_INCREMENT, `plate` VARCHAR(50) NOT NULL, `owner` VARCHAR(22) NOT NULL, PRIMARY KEY (`id`) );<file_sep>Config = {} Config.DrawDistance = 100.0 Config.MarkerColor = { r = 120, g = 120, b = 240 } Config.Locale = 'fr' Config.enableLimitKeys = true -- False si on ne veut pas de limite de clé Config.maxCreateKeys = 5 -- si Config.enableLimitKeys = true Config.EnablePed = true -- False pour ne plus avoir de pop de NPC sur la zone Config.Ped = 'g_m_y_ballaeast_01' Config.PedData = { ["ballas"] = { id = 1, VoiceName = "GENERIC_HI_RANDOM", Ambiance ="AMMUCITY", modelHash ="g_m_y_ballaeast_01", heading = 133.68167114, Pos = { x = 170.159591, y = -1799.635498, z = 29.315976, h = 320.89810180 } }, } Config.Locksmiths = { ["centre_ville"] = { Pos = { x = 170.320526, y = -1799.37779, z = 28.315877 }, Size = { x = 1.5, y = 1.5, z = 1.0 }, Type = -1, PedDataKey = 'ballas', blip = true }, } <file_sep>-- Client -- Script fait de A à Z par Amnesia -- Déclaration des variables globales ESX = nil xPlayer = nil local Blips = {} local pedConfig = {} local HasAlreadyEnteredMarker = false local LastZone = nil local CurrentAction = nil local CurrentActionMsg = '' local CurrentActionData = {} local generalLoaded = false local PlayingAnim = false local xPlayer = nil local Keys = { ["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57, ["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177, ["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18, ["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182, ["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81, ["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70, ["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178, ["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173, ["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118 } Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end end) RegisterNetEvent('esx:playerLoaded') AddEventHandler('esx:playerLoaded', function(_xPlayer) xPlayer = _xPlayer CreateBlips() end) function CreateBlips() for k,v in pairs(Config.Locksmiths) do if v.blip == true then Blips[k] = AddBlipForCoord(v.Pos.x, v.Pos.y, v.Pos.z) SetBlipSprite (Blips[k], 255) SetBlipDisplay(Blips[k], 2) SetBlipScale (Blips[k], 1.0) SetBlipAsShortRange(Blips[k], true) BeginTextCommandSetBlipName("STRING") --AddTextComponentSubstringPlayerName('Serrurier') EndTextCommandSetBlipName('Serrurier') end end end -- Display markers Citizen.CreateThread(function() while true do Citizen.Wait(0) local coords = GetEntityCoords(PlayerPedId()) for k,v in pairs(Config.Locksmiths) do if(v.Type ~= -1 and GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < Config.DrawDistance) then DrawMarker(v.Type, v.Pos.x, v.Pos.y, v.Pos.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, v.Size.x, v.Size.y, v.Size.z, Config.MarkerColor.r, Config.MarkerColor.g, Config.MarkerColor.b, 100, false, true, 2, false, false, false, false) end end end end) -- Create NPC Mission Citizen.CreateThread(function() Citizen.Wait(1) if (not generalLoaded) and Config.EnablePed then for k,v in pairs(Config.Locksmiths) do pedConfig = Config.PedData[v.PedDataKey] RequestModel(GetHashKey(pedConfig.modelHash)) while not HasModelLoaded(GetHashKey(pedConfig.modelHash)) do Citizen.Wait(10) end pedConfig.id = CreatePed(28, pedConfig.modelHash, pedConfig.Pos.x, pedConfig.Pos.y, pedConfig.Pos.z, pedConfig.Pos.h, false, false) SetPedFleeAttributes(pedConfig.id, 0, 0) SetAmbientVoiceName(pedConfig.id, pedConfig.Ambiance) SetPedDropsWeaponsWhenDead(pedConfig.id, false) SetPedDiesWhenInjured(pedConfig.id, false) Citizen.Wait(1500) SetEntityInvincible(pedConfig.id , true) FreezeEntityPosition(pedConfig.id, true) end end generalLoaded = true end) -- Enter / Exit marker events Citizen.CreateThread(function () while true do Citizen.Wait(0) local coords = GetEntityCoords(PlayerPedId()) local isInMarker = false local currentZone = nil for k,v in pairs(Config.Locksmiths) do if(GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < v.Size.x) then isInMarker = true currentZone = 'Locksmiths' end end if (isInMarker and not HasAlreadyEnteredMarker) or (isInMarker and LastZone ~= currentZone) then HasAlreadyEnteredMarker = true LastZone = currentZone TriggerEvent('esx_carkeys:hasEnteredMarker', currentZone) end if not isInMarker and HasAlreadyEnteredMarker then HasAlreadyEnteredMarker = false TriggerEvent('esx_carkeys:hasExitedMarker', LastZone) end end end) AddEventHandler('esx_carkeys:hasEnteredMarker', function (zone) if zone == 'Locksmiths' then CurrentAction = 'locksmith_menu' CurrentActionMsg = 'Appuyez sur ~INPUT_CONTEXT~ pour parler au serrurier' CurrentActionData = {} end end) AddEventHandler('esx_carkeys:hasExitedMarker', function (zone) if not IsInShopMenu then ESX.UI.Menu.CloseAll() end CurrentAction = nil end) -- Key control Citizen.CreateThread(function() while true do Citizen.Wait(10) if CurrentAction == nil then Citizen.Wait(500) else ESX.ShowHelpNotification(CurrentActionMsg) if IsControlJustReleased(0, Keys['E']) then if CurrentAction == 'locksmith_menu' then OpenLocksmithMenu() end CurrentAction = nil end end end end) RegisterNetEvent("esx_carkeys:showOwnedKeys") AddEventHandler("esx_carkeys:showOwnedKeys", function() menuOwnedKeys() end) RegisterNetEvent("esx_carkeys:lockUnLockVehicle") AddEventHandler("esx_carkeys:lockUnLockVehicle", function() OpenCloseVehicle() end) -- Fonction de création et d'affichage du menu du serrurier function OpenLocksmithMenu() ESX.TriggerServerCallback('esx_carkeys:getOwnedVehicles', function (vehicles) local elements = {} local plate = nil local carKeys = 0 for i=1, #vehicles, 1 do table.insert(elements, { label = 'Plaque: ' .. vehicles[i].plate .. ' 500$/clé', value = vehicles[i].plate }) end ESX.UI.Menu.CloseAll() ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'locksmith_create', { title = 'Créer clé', align = 'top-left', elements = elements }, function (data, menu) _plate = data.current.value plate = _plate menu.close() -- TODO: recuperer le nombre de clé de la plaque pour mettre une limite => carKeys ESX.TriggerServerCallback('esx_carkeys:getKeysByPlate', function (totalCarKeys, plate) menuCreation(_plate, totalCarKeys[1].total) end) end, function (data, menu) menu.close() end) end) end function menuCreation(plate, carKeys ) ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'menuDiag',{ title = ('Nombre de clé à créer ? (' .. Config.maxCreateKeys ..' max)'), align = 'top-left', }, function(data, menu) if Config.enableLimitKeys then -- Check que la valeur saisie ne soit pas supérieur à la valeur en config if (tonumber(data.value) ~= nil and tonumber(data.value) <= Config.maxCreateKeys) then -- check si le véhicule na pas déja le nombre max de clés if ( carKeys >= Config.maxCreateKeys ) then ESX.ShowNotification('Trop de clé') menu.close() else ESX.ShowNotification('Création de ' .. tonumber(data.value) .. ' clés en cours') TriggerServerEvent('esx_carkeys:createKeys', plate, tonumber(data.value) ) menu.close() end else ESX.ShowNotification('Nombre supérieur à MaxConfig ou format incorrect') menu.close() end else ESX.ShowNotification('Création de la clé en cours') TriggerServerEvent('esx_carkeys:createKeys', plate, tonumber(data.value) ) menu.close() end end, function(data, menu) menu.close() menu_main() -- Permet de retourner au menu principal à l'appuis sur backspace end) end function OpenCloseVehicle() local playerPed = GetPlayerPed(-1) local coords = GetEntityCoords(playerPed, true) local vehicle = nil if IsPedInAnyVehicle(playerPed, false) then vehicle = GetVehiclePedIsIn(playerPed, false) else vehicle = GetClosestVehicle(coords.x, coords.y, coords.z, 7.0, 0, 71) end ESX.TriggerServerCallback('esx_carkeys:checkKey', function(gotkey) if gotkey then local locked = GetVehicleDoorLockStatus(vehicle) if locked == 1 or locked == 0 then -- if unlocked SetVehicleDoorsLocked(vehicle, 2) PlayVehicleDoorCloseSound(vehicle, 1) ESX.ShowNotification("Vous avez ~r~fermé~s~ le véhicule.") elseif locked == 2 then -- if locked SetVehicleDoorsLocked(vehicle, 1) PlayVehicleDoorOpenSound(vehicle, 0) ESX.ShowNotification("Vous avez ~g~ouvert~s~ le véhicule.") end else ESX.ShowNotification("~r~Vous n'avez pas les clés de ce véhicule.") end end, GetVehicleNumberPlateText(vehicle)) end function split(s, delimiter) result = {}; for match in (s..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match); end return result; end function menuOwnedKeys() ESX.TriggerServerCallback('esx_carkeys:getKeysByIdentifier', function (keys) local elements = { head = {('Plaque'),('Nombre de clés'), ('Actions')}, rows = {} } for index,keyRow in pairs(keys) do table.insert(elements.rows, { data = "Plaques", cols = { keyRow.plate, keyRow.nbKey, '{{' .. ('Donner') .. '|give-'.. keyRow.plate .. '-'.. keyRow.id ..'}} {{' .. ('Jeter') .. '|drop-'.. keyRow.plate .. '-'.. keyRow.id ..'}}', } }) end ESX.UI.Menu.Open('list', GetCurrentResourceName(), 'menuList', elements, function(data, menu) splitingString = split(data.value, "-") action = splitingString[1] plate = splitingString[2] id = splitingString[3] if action == 'give' then local closestPlayer, closestDistance = ESX.Game.GetClosestPlayer() if closestPlayer == -1 or closestDistance > 3.0 then ESX.ShowNotification("Aucun joueur à proximité") else --TriggerServerEvent('NB:recruterplayer', GetPlayerServerId(closestPlayer), job,grade) --ESX.ShowNotification('Vous avez donnée une clé à ' .. ..'') ESX.ShowNotification('Vous avez donné une clé pour le véhicule ~g~ '.. plate ..' !\n') TriggerServerEvent('esx_carkeys:giveKey', id, GetPlayerServerId(closestPlayer), plate ) end menu.close() elseif action == 'drop' then ESX.ShowNotification('Vous avez jeté une clé pour le véhicule ~r~ '.. plate ..' !\n') TriggerServerEvent('esx_carkeys:dropKey', id, GetPlayerServerId(closestPlayer), plate ) menu.close() end end, function(data, menu) menu.close() end) end) end
4235038c0fa199dbe728c046c03537618b5e3c5d
[ "SQL", "Lua" ]
4
Lua
Amnesia80/esx_carkeys
04b30dc60fc5b6e93bbaa4c981ec6b89cf9c7f9c
44e63fde97d9e6079fc81090eefae89d6f916472
refs/heads/master
<repo_name>heybigname/eventsourcery-order-fulfillment<file_sep>/laravel/routes/web.php <?php namespace App\Http\Controllers; // Customer Interface group(['fake-customer-session'], function() { test_route('/', function() { return view('index'); }); test_route('place-order', function() { return view('place-order'); }); test_route('make-payment', function() { return view('make-payment'); }); test_route('payment-received', function() { return view('payment-received'); }); }); // Employee Interface group(['fake-employee-session'], function() { test_route('confirm-order', function() { return view('confirm-order'); }); test_route('fulfill-order', function() { return view('fulfill-order'); }); });<file_sep>/src/EventSourcing/Id.php <?php namespace OrderFulfillment\EventSourcing; abstract class Id { /** @var string */ protected $id; protected function __construct($id) { $this->id = $id; } public static function fromString($id) : Id { if ( ! is_string($id)) { throw new \InvalidArgumentException("Tried to create " . static::class . " from string but received type " . (is_object($id) ? get_class($id) : $id) . '.'); } return new static($id); } public function toString() : string { return $this->id; } public function __toString() : string { return $this->toString(); } public function equals(self $that) : bool { if (get_class($this) !== get_class($that)) { throw new CannotCompareDifferentIds; } return $this->id === $that->id; } } <file_sep>/src/EventSourcing/EventStore.php <?php namespace OrderFulfillment\EventSourcing; interface EventStore { public function storeStream(StreamEvents $events) : void; public function storeEvent(DomainEvent $event) : void; public function allFor(StreamId $id) : DomainEvents; } <file_sep>/spec/EventSourcing/DomainEventSerializerSpec.php <?php namespace spec\OrderFulfillment\EventSourcing; use OrderFulfillment\EventSourcing\DomainEvent; use OrderFulfillment\EventSourcing\DomainEventClassMap; use PhpSpec\ObjectBehavior; class DomainEventSerializerSpec extends ObjectBehavior { function let() { $classMap = new DomainEventClassMap(); $this->beConstructedWith($classMap); $classMap->add('TestDomainEvent', TestDomainEvent::class); } function it_can_serialize_events() { $this->serialize(new TestDomainEvent(12)) ->shouldReturn('{"number":12}'); } function it_can_deserialize_events() { $this->deserialize((object) [ 'event_name' => 'TestDomainEvent', 'event_data' => ['number' => 6] ])->shouldContainEvent( new TestDomainEvent(6) ); } function it_can_give_the_name_of_an_event_class() { $this->eventNameFor(new TestDomainEvent())->shouldBe('TestDomainEvent'); } } <file_sep>/scripts/start-event-dispatch-queue-worker.sh #!/bin/bash /usr/bin/php artisan queue:work --queue=event_dispatch <file_sep>/spec/EventSourcing/TestEventStoreSpy.php <?php namespace spec\OrderFulfillment\EventSourcing; use OrderFulfillment\EventSourcing\DomainEvent; use OrderFulfillment\EventSourcing\DomainEvents; use OrderFulfillment\EventSourcing\EventStore; use OrderFulfillment\EventSourcing\StreamEvent; use OrderFulfillment\EventSourcing\StreamEvents; use OrderFulfillment\EventSourcing\StreamId; class TestEventStoreSpy implements EventStore { private $events = []; public function storeStream(StreamEvents $events) : void { $this->events = array_merge($this->events, $events->map(function(StreamEvent $streamEvent) { return $streamEvent->event(); })->toArray() ); } public function storeEvent(DomainEvent $event) : void { $this->events[] = $event; } public function allFor(StreamId $id) : DomainEvents { } public function storedEvents(): DomainEvents { return DomainEvents::make($this->events); } }<file_sep>/spec/PhpSpec/EqualValueMatcher.php <?php namespace spec\OrderFulfillment\PhpSpec; use PhpSpec\Exception\Example\FailureException; use PhpSpec\Matcher\Matcher; class EqualValueMatcher implements Matcher { /** * Checks if matcher supports provided subject and matcher name. * * @param string $name * @param mixed $subject * @param array $arguments * * @return Boolean */ public function supports($name, $subject, array $arguments) { return $name == 'equalValue'; } /** * Evaluates positive match. * * @param string $name * @param mixed $subject * @param array $arguments */ public function positiveMatch($name, $subject, array $arguments) { // compare scalars if (is_scalar($subject) && is_scalar($arguments[0])) { return $subject === $arguments[0]; } // don't compare scalars vs objects if (is_scalar($subject) || is_scalar($arguments[0])) { $item1 = is_scalar($subject) ? "<label>scalar</label> value <value>{$subject}</value>" : '<label>object</label> of type <value>' . get_class($subject) . '</value>'; $item2 = is_scalar($arguments[0]) ? "<label>scalar</label> value <value>{$arguments[0]}</value>" : '<label>object</label> of type <value>' . get_class($arguments[0]) . '</value>'; throw new FailureException("Cannot compare $item1 with $item2."); } // compare objects if (get_class($subject) !== get_class($arguments[0])) { throw new FailureException("Values of types <label>" . get_class($subject) . "</label> and <label>" . get_class($arguments[0]) . "</label> cannot be compared."); } if ( ! $subject->equals($arguments[0])) { throw new FailureException('Value of type <label>' . get_class($subject) . "</label> <value>{$subject->toString()}</value> should equal <value>{$arguments[0]->toString()}</value> but does not."); } } /** * Evaluates negative match. * * @param string $name * @param mixed $subject * @param array $arguments */ public function negativeMatch($name, $subject, array $arguments) { if ($subject->equals($arguments[0])) { throw new FailureException('<label>' . get_class($subject) . "</label> <value>{$subject->toString()}</value> should not equal <value>{$arguments[0]->toString()}</value> but does."); } } /** * Returns matcher priority. * * @return integer */ public function getPriority() { } }<file_sep>/scripts/start-standard-queue-worker.sh #!/bin/bash /usr/bin/php artisan queue:work --queue=default --tries=3 <file_sep>/src/EventSourcing/DomainEventSerializer.php <?php namespace OrderFulfillment\EventSourcing; class DomainEventSerializer { /** @var DomainEventClassMap */ private $eventClasses; public function __construct(DomainEventClassMap $eventClasses) { $this->eventClasses = $eventClasses; } public function serialize(DomainEvent $event): string { return json_encode($event->serialize()); } public function deserialize(\stdClass $serializedEvent): DomainEvent { $class = $this->eventClasses->classFor($serializedEvent->event_name); return $class::deserialize($serializedEvent->event_data); } public function eventNameFor(DomainEvent $e): string { $className = explode('\\', get_class($e)); return $className[count($className) - 1]; } } <file_sep>/src/LaravelEventSourcingDrivers/RelationalEventStore.php <?php namespace OrderFulfillment\LaravelEventSourcingDrivers; use \DB; use Illuminate\Support\Collection; use OrderFulfillment\EventSourcing\DomainEvent; use OrderFulfillment\EventSourcing\DomainEvents; use OrderFulfillment\EventSourcing\EventStore; use OrderFulfillment\EventSourcing\DomainEventSerializer; use OrderFulfillment\EventSourcing\StreamEvents; use OrderFulfillment\EventSourcing\StreamId; use OrderFulfillment\EventSourcing\StreamVersion; class RelationalEventStore implements EventStore { /** @var DomainEventSerializer */ private $serializer; private $table = 'event_store'; public function __construct(DomainEventSerializer $serializer) { $this->serializer = $serializer; } public function allFor(StreamId $id) : DomainEvents { return DomainEvents::make( $this->eventDataFor($id) ->map('buildEventFromPayload') ->toArray()); } private function eventDataFor(StreamId $id) : Collection { return DB::table($this->table) ->where('stream_id', '=', $id->toString()) ->orderBy('stream_version', 'asc') ->get(); } public function storeStream(StreamEvents $events) : void { // store events $events->each(function($stream) { $this->store($stream->id(), $stream->event(), $stream->version()); }); // queue event dispatch $job = new DispatchDomainEvents($events->toDomainEvents()); dispatch($job->onQueue('event_dispatch')); } public function storeEvent(DomainEvent $event) : void { $this->store( StreamId::fromString(0), $event, StreamVersion::zero(), '' ); $job = new DispatchDomainEvents(DomainEvents::make($event)); dispatch($job->onQueue('event_dispatch')); } private function store(StreamId $id, DomainEvent $event, StreamVersion $version, $metadata = '') : void { DB::table($this->table)->insert([ 'stream_id' => $id->toString(), 'stream_version' => $version->toInt(), 'event_name' => $this->serializer->eventNameFor($event), 'event_data' => $this->serializer->serialize($event), 'raised_at' => date('Y-m-d H:i:s'), 'meta_data' => $metadata, ]); } } <file_sep>/README.md # Routing ## Middleware fake-customer-session fake-employee-session
89862c4fecae7ff36c97fe4a3217d9e0e02ef447
[ "Markdown", "PHP", "Shell" ]
11
PHP
heybigname/eventsourcery-order-fulfillment
0c7b328e6fcff44ae34e5c493be2e4a584b9ffe3
b4099cb1d3e47190184e4101fdc7e4a6e9945a50
refs/heads/master
<repo_name>mw00847/spectrochempy<file_sep>/docs/userguide/analysis/peak_finding.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.7.9 # --- # %% [markdown] # # Peak Maxima Finding # # This tutorial shows how to find peaks and determine peak maxima with spectrochempy. As prerequisite, the user is # expected to have read the [Import](../IO/import.ipynb), [Import IR](../IO/importIR.ipynb), # [slicing](../processing/slicing.ipynb) tutorials. # # %% [markdown] # Fist, as usual, we need to load the API. # %% import spectrochempy as scp # %% [markdown] # ## Loading an experimental dataset # %% [markdown] # A typical IR dataset (CO adsorption on supported CoMo catalyst in the 2300-1900 cm-1 region) will be used throughout. # %% [markdown] # We load the data using the generic API method `read` (the type of data is inferred from the extension) # %% ds = scp.read('irdata/CO@Mo_Al2O3.SPG') # %% ds.y -= ds.y.data[0] # start time a 0 for the first spectrum ds.y.title = 'Time' ds.y = ds.y.to('minutes') # %% [markdown] # Let's set some preferences for plotting # %% prefs = ds.preferences prefs.method_1D = 'scatter+pen' prefs.method_2D = 'stack' prefs.colorbar = True prefs.colormap = 'Dark2' # %% [markdown] # We select the desired region and plot it. # %% reg = ds[:, 2300.:1900.] _ = reg.plot() # %% [markdown] # ## Find maxima by manual inspection of the plot # %% Once a given maximum has been approximately located manually with the mouse, it is possible to obtain [markdown] # For instance, after zooming on the highest peak of the last spectrum, # one finds that it is locate at ~ 2115.5 cm$^{-1}$. The exact x-coordinate value can the be obtained using the # following code # (see the [slicing tutorial](../processing/slicing.ipynb) for more info): # %% pos = reg.x[2115.5].values pos # %% [markdown] # We can easily get the list of all individual maximas at this position # %% maximas = reg[:, pos.m].squeeze() _ = maximas.plot(marker='s', ls='--', color='blue') # %% execution={"iopub.execute_input": "2020-06-22T12:21:38.304Z", "iopub.status.busy": "2020-06-22T12:21:38.285Z", ax = reg.plot() x = pos.max() y = maximas.max() ax.set_ylim(-0.01, 0.3) _ = ax.annotate(f'{x:~0.2fP} {y:~.3fP}', xy=(2115.5, maximas.max()), xytext=(30, -20), textcoords='offset points', bbox=dict(boxstyle="round4,pad=.7", fc="0.9"), arrowprops=dict(arrowstyle="->", connectionstyle="angle3")) # %% [markdown] # ## Find maxima with an automated method: `find_peaks()` # %% [markdown] # Exploring the spectra manually is useful, but cannot be made systematically in large datasets with many - possibly # shifting peaks. The maxima of a given spectrum can be found automatically by the find_peaks() method which is based # on [scpy.signal.find_peaks()](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html). # It returns two outputs: `peaks` a NDDataset grouping the peak maxima (wavenumbers and absorbances) and `properties` # a dictionary containing properties of the returned peaks (it is empty if no particular option is selected, # [see below](#options) for more information). # %% [markdown] # ### Default behaviour # %% [markdown] # Applying this method on the last spectrum without any option will yield 7 peaks : # %% last = reg[-1] peaks, _ = last.find_peaks() # we do not catch the second output (properties) as it is void in this case # %% [markdown] # `peaks` is a NDDataset. Its `x` attribute gives the peak position # %% peaks.x.values # %% [markdown] # The code below shows how the peaks found by this method can be marked on the plot: # %% ax = last.plot_pen() # output the spectrum on ax. ax will receive next plot too pks = peaks + 0.01 # add a small offset on the y positiion of the markers _ = pks.plot_scatter(ax=ax, marker='v', color='black', clear=False, # we need to keep the previous outpout on ax data_only=True, # we dont need to redraw all things like labels, etc... ylim=(-0.01, 0.35)) for p in pks: x, y = p.x.values, p.values + .02 _ = ax.annotate(f'{x.m:0.0f}', xy=(x.m, y.m), xytext=(-5, 0), rotation=90, textcoords='offset points') # %% [markdown] # Now we will do a peak-finding for the whole dataset: # %% peakslist = [s.find_peaks()[0] for s in reg] # %% ax = reg.plot() for peaks in peakslist: peaks.plot_scatter(ax=ax, marker='v', ms=3, color='red', clear=False, data_only=True, ylim=(-0.01, 0.30)) # %% [markdown] # It should be noted that this method finds only true maxima, not shoulders (!). For the detection of such underlying # peaks, the use of methods based on derivatives or advanced detection methods - which will be treated in separate # tutorial - are required. Once their maxima of a given peak have been found, it is possible, for instance, # to plot its evolution with, e.g. the time. For instance for the peaks located at 2220-2180 cm$^{-1}$: # %% # Find peak's position positions = [s.find_peaks()[0].x.values.m for s in reg[:, 2220.:2180.]] # Make a NDDataset evol = scp.NDDataset(positions, title="Wavenumber at the maximum", units="1 /cm") evol.x = scp.Coord(reg.y, title='Acquisition time') # the x coordinate is st to the acquisition time for each specra evol.preferences.method_1D = 'scatter+pen' # plot it _ = evol.plot(ls=':') # %% [markdown] # ### Options of `find_peaks()` <a id='options'></a> # %% [markdown] # The default behaviour of find_peaks() will return *all* the detected maxima. The user can choose various options to # select among these peaks: # # **Parameters relative to "peak intensity":** # - `height`: minimal required height of the peaks (single number) or minimal and maximal heights # (sequence of two numbers) # - `prominence`: minimal prominence of the peak to be detected # (single number) or minimal and maximal prominence (sequence of 2 numbers). In brief the "prominence" of a peak # measures how much a peak stands out from its surrounding and is the vertical distance between the peak and its # lowest "contour line". It should not be confused with the height as a peak can have an important height but a small # prominence when surronded by other peaks (see below for an illustration). # - in addition to the prominence, the user can define `wlen`, the width (in points) of the window used to look # at neighboring minima, the peak maximum being is at the center of the window. # - `threshold`: a single number (the minimal required threshold) or a sequence of two numbers (minimal and maximal). # The thresholds are the difference of height of the # maximum with its two neighboring points (useful to detect spikes for instance) # # **Parameters relative to "peak spacing":** # - `distance`: the required minimal horizontal distance between neighbouring peaks. Smaller peaks are removed first. # - `width`: Required minimal width of peaks in samples (single number) or minimal and maximal width. The width is # assessed from the peak height, # prominence and neighboring signal. - In addition the user can define `rel_height` (a float between 0. and 1. used # to compute the width - see the [scipy documentation]( # https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.peak_widths.html) for further details. # - Finally we mention en passant a last parameter, `plateau_size()` used for selecting peaks having truly flat tops ( # as in e.g. square-boxed signals). # # The use of some of these options for the last spectrum of the dataset is examplified in the following: # %% s = reg[-1].squeeze() # we use squeeze it because one of the dimensions for this dataset of shape (1, N) is useless # %% # default settings peaks, properties = s.find_peaks() ax = s.plot_pen(color='black') peaks.plot_scatter(ax=ax, label='default', marker='v', ms=4, color='black', clear=False, data_only=True) # find peaks heights than 0.05 (NB: the spectra are shifted for the display. # Refer to the 1st spectrum for true heights) peaks, properties = s.find_peaks(height=0.05) color = 'blue' label = '0.05<height' offset = 0.05 (s + offset).plot_pen(color=color, clear=False) (peaks + offset).plot_scatter(ax=ax, label=label, m='v', mfc=color, mec=color, ms=5, clear=False, data_only=True) # find peaks heights between 0.05 and 0.2 (the highest peak won't be detected) peaks, properties = s.find_peaks(height=(0.05, 0.2)) color = 'green' label = '0.05<height<0.2' offset = 0.1 (s + offset).plot_pen(color=color, clear=False) (peaks + offset).plot_scatter(ax=ax, label=label, m='v', mfc=color, mec=color, ms=5, clear=False, data_only=True) # find peaks with prominence >= 0.05 (only the two most prominent peaks are detected) peaks, properties = s.find_peaks(prominence=0.05) color = 'purple' label = 'prominence=0.05' offset = 0.15 (s + offset).plot_pen(color=color, clear=False) (peaks + offset).plot_scatter(ax=ax, label=label, m='v', mfc=color, mec=color, ms=5, clear=False, data_only=True) # find peaks with distance >= 10 (only tht highest of the two maxima at ~ 2075 is detected) peaks, properties = s.find_peaks(distance=10) color = 'red' label = 'distance>10' offset = 0.20 (s + offset).plot_pen(color=color, clear=False) (peaks + offset).plot_scatter(ax=ax, label=label, m='v', mfc=color, mec=color, ms=5, clear=False, data_only=True) # find peaks with width >= 10 (none of the two maxima at ~ 2075 is detected) peaks, properties = s.find_peaks(width=10) color = 'grey' label = 'width>10' offset = 0.25 (s + offset).plot_pen(color=color, clear=False) (peaks + offset).plot_scatter(ax=ax, label=label, m='v', mfc=color, mec=color, ms=5, clear=False, data_only=True) _ = ax.legend() # %% [markdown] # ### More on peak properties # # If the concept of "peak height" is pretty clear, it is worth examining further some peak properties as defined and # used in `find_peaks()`. They can be obtained (and used) by passing the parameters `height`, `prominence`, # `threshold` and `width`. Then `find_peaks()` will return the corresponding properties of the detected peaks in the # `properties` dictionary. # # #### Prominence # # The prominence of a peak can be defined as the vertical distance from the peak’s maximum to the *lowest horizontal # line passing through a minimum but not containing any higher peak*. This is illustrated below for the three most # prominent peaks of the above spectra: # # <img src="images/prominence.png" alt="prominence_def" width="350" align="center" /> # # Let's illustrate this for the second highest peak which height is comprised between ~ 0.15 and 0.22 and see which # properties are returned when, on top of `height`, we pass `prominence=0`: this will return the properties # associated to the prominence and warrant that this peak will not be rejected on the prominence criterion. # %% peaks, properties = s.find_peaks(height=(0.15, 0.22), prominence=0) properties # %% The actual prominence of the peak is this 0.0689, a value significantly lower that is peak height ( [markdown] # The peak prominence is 0.0689, a much lower value than the height (0.1995), as could be expected by the illustration # above. # # The algorithm used to determine the left and right 'bases' is illustrated below: # - (1) extend a line to the left and right of the maximum until until it reaches the window border (here on # the left) or the signal (here on the right. # - (2) find the minimum value within the intervals defined above. These # points are the peak's bases. # - (3) use the higher base (here the right base) and peak maximum to calculate the # prominence. # # <img src="images/prominence_algo.png" alt="prominence_algo" width="350" align="center" /> # # The following code shows how to plot the maximum and the two "base points" from the previous output of `find_peaks()`: # %% ax = s.plot_pen() # plots the maximum _ = peaks.plot_scatter(ax=ax, marker='v', mfc='green', mec='green', data_only=True, clear=False) wl, wr = properties['left_bases'][0], properties['right_bases'][0] # wavenumbers of of left and right bases for w in (wl, wr): ax.axvline(w, linestyle='--') # add vertical line at the bases ax.plot(w, s[w].data, 'v', color='red') # and a red mark #TODO: add functtion to plot this easily ax = ax.set_xlim(2310.0, 1900.0) # change x limits to better see the 'left_base' # %% It leads to base marks at their expected locations. We can further check that the prominence of the [markdown] # We can check that the correct value of the peak prominence is obtained by the difference between its height # and the highest base, here the 'right_base': # %% prominence = peaks[0].values.m - s[wr].values.m print(f"calc. prominence = {prominence:0.4f}") # %% Finally, we illustrate how the use of the `wlen` parameter - which limits the search of the "base [markdown] # Finally, the figure below shows how the prominence can be affected by `wlen`, the size of the window used to # determine the peaks' bases. # # <img src="images/prominence_wlen.png" alt="prominence_def" width="700" align="center" /> # # As illustrated above a reduction of the window should reduce the prominence of the peak. This impact can be checked # with the code below: # %% peak, properties = s.find_peaks(height=0.2, prominence=0) print(f"prominence with full spectrum: {properties['prominences'][0]:0.4f}") peak, properties = s.find_peaks(height=0.2, prominence=0, wlen=50.0) # a float should be explicitely passed, else will be considered as points print(f"prominence with reduced window: {properties['prominences'][0]:0.4f}") # %% [markdown] # #### Width # %% The peak widths, as returned by `find_peaks()` can be *very approximate* and for precise assessment, [markdown] # The find_peaks() method also returns the peak widths. As we will see below, the method is **very approximate** and # more advanced methods (such as peak fitting, also implemented in spectrochempy should be used (see e.g., # [this example](https://www.spectrochempy.fr/dev/gallery/auto_examples/fitting/plot_fit.html#sphx-glr-gallery-auto # -examples-fitting-plot-fit-py)). On the other hand, **the magnitude of the width is generally fine**. # # This estimate is based on an algorithm similar to that used for the "bases" above, except that the horizontal # line starts from a `width_height` computed from the peak height subtracted by a *fraction* of the peak prominence # defined bay `rel_height` (default = 0.5). The algorithm is illustrated below for the two most prominent peaks: # # <img src="images/width_algo.jpg" alt="width_algo" width="900" align="center" /> # # When the `width` keyword is used, `properties` disctionarry returns the prominence parameters (as it is used for # the calculation of the width), the width and the left and right interpolated positions ("ips") of the intersection # of the horizontal line with the spectrum: # %% peaks, properties = s.find_peaks(height=0.2, width=0) properties # %% The code below shows how these heights and widths can be extracted from the dictionary and plotted [markdown] # The code below shows how these data can be extracted and then plotted: # %% # extraction of data (for better readbility pof the code below) height = properties['peak_heights'][0] width_height = properties['width_heights'][0] wl = properties['left_ips'][0] wr = properties['right_ips'][0] ax = s.plot_pen() _ = peaks.plot_scatter(ax=ax, marker='v', mfc='green', mec='green', data_only=True, clear=False) _ = ax.axhline(height, linestyle='--', color='blue') _ = ax.axhline(width_height, linestyle='--', color='red') _ = ax.axvline(wl, linestyle='--', color='green') _ = ax.axvline(wr, linestyle='--', color='green') # %% As stressed above, we see here that the peak width is very approximate and probably exaggerated in [markdown] # It is obvious here that the peak width is overestimated in the present case due to the presence of the second peak on # the left. Here a better estimate would be obtained by considering the right half-width, or reducing the `rel_height` # parameter as shown below. # %% [markdown] # ### A code snippet to display properties # # The self-contained code snippet below can be used to display in a matplolib plot and print the various # peak properties of a single peak as returned by `find_peaks()`: # %% # user defined parameters ------------------------------ s = reg[-1] # define a single-row NDDataset s.preferences.method_1D = 'pen' # peak selection parameters; should be set to return a single peak height = 0.08 # minimal height or min and max heights) prominence = 0.0 # minimal prominence or min and max prominences width = 0.0 # minimal width or min and max widths threshold = None # minimal threshold or min and max threshold) # prominence and width parameter wlen = None # the length of the window used to compute the prominence rel_height = 0.47 # the fraction of the prominence used to compute the width # code: find peaks, plot and print properties ------------------- peaks, properties = s.find_peaks(height=height, prominence=prominence, wlen=wlen, threshold=threshold, width=width, rel_height=rel_height) table_pos = " ".join([f"{peaks[i].x.values.m:<10.3f}" for i in range(len(peaks))]) print(f'{"peak_position":>16}: {table_pos}') for key in properties: table_property = " ".join([f"{properties[key][i]:<10.3f}" for i in range(len(peaks))]) print(f'{key[:-1]:>16}: {table_property}') ax = s.plot() peaks.plot_scatter(ax=ax, marker='v', mfc='green', mec='green', data_only=True, clear=False) for i in range(len(peaks)): for w in (properties['left_bases'][i], properties['right_bases'][i]): ax.plot(w, s[0, w].data.T, 'v', color='red') for w in (properties['left_ips'][i], properties['right_ips'][i]): ax.axvline(w, linestyle='--', color='green') # %% [markdown] # -- this is the end of this tutorial -- <file_sep>/tests/test_dataset/test_ndcoordrange.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from traitlets import TraitError, HasTraits from spectrochempy.core.dataset.coordrange import trim_ranges from spectrochempy.utils import Range from spectrochempy.utils.testing import raises # ====================================================================================================================== # trim_ranges # ====================================================================================================================== def test_trim_ranges(): r = trim_ranges() assert r == [] r = trim_ranges(3, 2) assert r[0] == [2, 3] r = trim_ranges((3, 2), (4.4, 10), (4, 5)) assert r[-1] == [4, 10] assert r == [[2, 3], [4, 10]] r = trim_ranges((3, 2), (4.4, 10), (4, 5), reversed=True) assert r == [[10, 4], [3, 2]] # ====================================================================================================================== # Range # ====================================================================================================================== def test_range(): class MyClass(HasTraits): r = Range() # Initialized with some default values c = MyClass() c.r = [10, 5] assert c.r == [5, 10] with raises(TraitError): c.r = [10, 5, 1] <file_sep>/spectrochempy/core/fitting/models.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module holds the definitions all the various models """ __all__ = [] import numpy as np ############ # # # 1D # # # ############ # ====================================================================================================================== # PolynomialBaseline # ====================================================================================================================== class polynomialbaseline(object): """ Arbitrary-degree polynomial (degree limited to 10, however). As a linear baseline is automatically calculated, this polynom is always of greater or equal to order 2 (parabolic function). .. math:: f(x) = ampl * \\sum_{i=2}^{max} c_i*x^i """ args = ['ampl'] args.extend(['c_%d' % i for i in range(2, 11)]) script = """MODEL: baseline%(id)d\nshape: polynomialbaseline # This polynom starts at the order 2 # as a linear baseline is additionnaly fitted automatically # parameters must be in the form c_i where i is an integer as shown below $ ampl: %(scale).3g, 0.0, None $ c_2: 1.0, None, None * c_3: 0.0, None, None * c_4: 0.0, None, None # etc... """ def f(self, x, ampl, *c_, **kargs): c = [0.0, 0.0] c.extend(c_) return ampl * np.polyval(np.array(tuple(c))[::-1], x - x[x.size / 2]) # ====================================================================================================================== # #=============================================================================== # # Gaussian2DModel # #=============================================================================== # class gaussian2dmodel(object): # """ # Two dimensional Gaussian model (*not* normalized - peak value is 1). # # .. math:: # A e^{\\frac{-(x-\\iso_x)^2}{2 \\gb_x^2}} e^{\\frac{-(y-\\iso_y)^2}{2 \\gb_y^2}} # # """ # args = ['amp','gbx','gby','posx','posy'] # def f(self, xy, amp, gbx, gby, posx, posy, **kargs): # gbx = float(gbx) # gby = float(gby) # x,y = xy # xo = x-posx # xdenom = 2*gbx*gbx # yo = y-posy # ydenom = 2*gby*gby # return amp*np.exp(-xo*xo/xdenom-yo*yo/ydenom) # ====================================================================================================================== # ====================================================================================================================== # GaussianModel # ====================================================================================================================== class gaussianmodel(object): """ Normalized 1D gaussian function : .. math:: f(x) = \\frac{ampl}{\\sqrt{2 \\pi \\sigma^2} } \\exp({\\frac{-(x-pos)^2}{2 \\sigma^2}}) where :math:`\\sigma = \\frac{width}{2.3548}` """ args = ['ampl', 'width', 'pos'] script = """MODEL: line%(id)d\nshape: gaussianmodel $ ampl: %(ampl).3f, 0.0, None $ width: %(width).3f, 0.0, None $ pos: %(pos).3f, %(poslb).3f, %(poshb).3f """ def f(self, x, ampl, width, pos, **kargs): gb = width / 2.3548 tsq = (x - pos) * 2 ** -0.5 / gb w = np.exp(-tsq * tsq) * (2 * np.pi) ** -0.5 / gb w = w * abs(x[1] - x[0]) return ampl * w # ====================================================================================================================== # LorentzianModel # ====================================================================================================================== class lorentzianmodel(object): """ A standard Lorentzian function (also known as the Cauchy distribution): .. math:: f(x) = \\frac{ampl * \\lambda}{\\pi [(x-pos)^2+ \\lambda^2]} where :math:`\\lambda = \\frac{width}{2}` """ args = ['ampl', 'width', 'pos'] script = """MODEL: line%(id)d\nshape: lorentzianmodel $ ampl: %(ampl).3f, 0.0, None $ width: %(width).3f, 0.0, None $ pos: %(pos).3f, %(poslb).3f, %(poshb).3f """ def f(self, x, ampl, width, pos, **kargs): lb = width / 2. w = lb / np.pi / (x * x - 2 * x * pos + pos * pos + lb * lb) w = w * abs(x[1] - x[0]) return ampl * w # ====================================================================================================================== # VoigtModel # ====================================================================================================================== class voigtmodel(object): """ A Voigt model constructed as the convolution of a :class:`GaussianModel` and a :class:`LorentzianModel` -- commonly used for spectral line fitting. """ args = ['ampl', 'width', 'ratio', 'pos'] script = """MODEL: line%(id)d\nshape: voigtmodel $ ampl: %(ampl).3f, 0.0, None $ width: %(width).3f, 0.0, None $ pos: %(pos).3f, %(poslb).3f, %(poshb).3f $ ratio: 0.1, 0.0, 1.0 """ def f(self, x, ampl, width, ratio, pos, **kargs): from scipy.special import wofz gb = ratio * width / 2.3548 lb = (1. - ratio) * width / 2. if gb < 1.e-16: return lorentzianmodel().f(x, ampl, lb * 2., pos, **kargs) else: w = wofz(((x - pos) + 1.0j * lb) * 2 ** -0.5 / gb) w = w.real * (2. * np.pi) ** -0.5 / gb w = w * abs(x[1] - x[0]) return ampl * w # ====================================================================================================================== # Assymetric Voigt Model # ====================================================================================================================== class assymvoigtmodel(object): """ An assymetric Voigt model <NAME> and <NAME>, Vibrational Spectroscopy, 2008, 47, 66-69 """ args = ['ampl', 'width', 'ratio', 'assym', 'pos'] script = """MODEL: line%(id)d\nshape: voigtmodel $ ampl: %(ampl).3f, 0.0, None $ width: %(width).3f, 0.0, None $ pos: %(pos).3f, %(poslb).3f, %(poshb).3f $ ratio: 0.1, 0.0, 1.0 $ assym: 0.1, 0.0, 1.0 """ def lorentz(self, x, g_, pos): w = (2. / (np.pi * g_)) / (1. + 4. * ((x - pos) / g_) ** 2) return w def gaussian(self, x, g_, pos): a = np.sqrt(4. * np.log(2.) / np.pi) / g_ b = -4. * np.log(2.) * ((x - pos) / g_) ** 2 w = a * np.exp(b) return w def g(self, x, width, a): return def f(self, x, ampl, width, ratio, assym, pos, **kargs): g = 2. * width / (1. + np.exp(assym * (x - pos))) # sigmoid variation of width w = ratio * self.lorentz(x, g, pos) \ + (1. - ratio) * self.gaussian(x, g, pos) w = w * abs(x[1] - x[0]) return ampl * w ################# # # # GENERAL # # # ################# # ====================================================================================================================== # getmodel # ====================================================================================================================== def getmodel(x, y=None, modelname=None, par=None, **kargs): """Get the model for a given x vector. Parameters ----------- x : ndarray Array of frequency where to evaluate the model values returned by the f function. y : ndarray or None None for 1D, or index for the second dimension modelname : str name of the model class to use. par : :class:`Parameters` instance parameter to pass to the f function kargs : any Keywords arguments to pass the the f function Returns ------- ndarray : float an array containing the calculated model. """ model = par.model[modelname] modelcls = globals()[model] # take an instance of the model a = modelcls() # get the parameters for the given model args = [] for p in a.args: try: args.append(par['%s_%s' % (p, modelname)]) except KeyError as e: if p.startswith('c_'): # probably the end of the list # due to a limited polynomial degree pass else: raise ValueError(e.message) x = np.array(x, dtype=np.float64) if y is not None: y = np.array(y, dtype=np.float64) if y is None: return a.f(x, *args, **kargs) else: return a.f(x, y, *args, **kargs) if __name__ == '__main__': pass <file_sep>/spectrochempy/utils/testing.py # -*- coding: utf-8 -*- # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, # Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in # the root directory # ===================================================================================================================== __all__ = ["assert_equal", "assert_array_equal", "assert_array_almost_equal", 'assert_dataset_equal', 'assert_dataset_almost_equal', 'assert_project_equal', 'assert_project_almost_equal', "assert_approx_equal", "assert_raises", "raises", "catch_warnings", "RandomSeedContext", ] import operator import functools import warnings import numpy as np # import matplotlib.pyplot as plt # from matplotlib.testing.compare import calculate_rms, ImageAssertionError from numpy.testing import (assert_equal, assert_array_equal, assert_array_almost_equal, assert_approx_equal, assert_raises, assert_array_compare) # ====================================================================================================================== # NDDataset comparison # ====================================================================================================================== def gisinf(x): """like isinf, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- isinf and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised. This should be removed once this problem is solved at the Ufunc level.""" from numpy.core import isinf, errstate with errstate(invalid='ignore'): st = isinf(x) if isinstance(st, type(NotImplemented)): raise TypeError("isinf not supported for this type") return st def compare_datasets(this, other, approx=False, decimal=6, data_only=False): from spectrochempy.core.dataset.ndarray import NDArray from spectrochempy.units import ur, Quantity def compare(x, y): from numpy.core import number, float_, result_type, array from numpy.core.numerictypes import issubdtype from numpy.core.fromnumeric import any as npany try: if npany(gisinf(x)) or npany(gisinf(y)): xinfid = gisinf(x) yinfid = gisinf(y) if not (xinfid == yinfid).all(): return False # if one item, x and y is +- inf if x.size == y.size == 1: return x == y x = x[~xinfid] y = y[~yinfid] except (TypeError, NotImplementedError): pass # make sure y is an inexact type to avoid abs(MIN_INT); will cause # casting of x later. dtype = result_type(y, 1.) y = array(y, dtype=dtype, copy=False, subok=True) z = abs(x - y) if not issubdtype(z.dtype, number): z = z.astype(float_) # handle object arrays return z < 1.5 * 10.0 ** (-decimal) eq = True if not isinstance(other, NDArray): # try to make some assumption to make useful comparison. if isinstance(other, Quantity): otherdata = other.magnitude otherunits = other.units elif isinstance(other, (float, int, np.ndarray)): otherdata = other otherunits = False else: raise AssertionError(f'{this} and {other} objects are too different to be ' f'compared.') if not this.has_units and not otherunits: eq = np.all(this._data == otherdata) elif this.has_units and otherunits: eq = np.all(this._data * this._units == otherdata * otherunits) else: raise AssertionError(f'units of {this} and {other} objects does not match') return eq thistype = this.implements() if data_only: attrs = ['data'] else: attrs = this.__dir__() exclude = ( 'filename', 'preferences', 'description', 'history', 'date', 'modified', 'modeldata', 'origin', 'roi', 'linear', 'offset', 'increment', 'size', 'name', 'show_datapoints') for attr in exclude: # these attibutes are not used for comparison (comparison based on # data and units!) if attr in attrs: if attr in attrs: attrs.remove(attr) # if 'title' in attrs: # attrs.remove('title') #TODO: should we use title for comparison? for attr in attrs: if attr != 'units': sattr = getattr(this, f'_{attr}') if this.linear and attr == 'data': # allow comparison of # LinearCoord # and Coord sattr = this.data if hasattr(other, f'_{attr}'): oattr = getattr(other, f'_{attr}') if other.linear and attr == 'data': oattr = other.data # to avoid deprecation warning issue for unequal array if sattr is None and oattr is not None: raise AssertionError(f'`{attr}` of {this} is None.') if oattr is None and sattr is not None: raise AssertionError(f'{attr} of {other} is None.') if hasattr(oattr, 'size') and hasattr(sattr, 'size') and oattr.size != sattr.size: # particular case of mask if attr != 'mask': raise AssertionError(f'{thistype}.{attr} sizes are different.') else: if other.mask != this.mask: raise AssertionError(f'{this} and {other} masks are different.') if attr in ['data', 'mask']: if approx: assert_array_compare(compare, sattr, oattr, header=(f'{thistype}.{attr} attributes ar' f'e not almost equal to %d decimals' % decimal), precision=decimal) else: assert_array_compare(operator.__eq__, sattr, oattr, header=f'{thistype}.{attr} ' f'attributes are not ' f'equal') elif attr in ['coordset']: if (sattr is None and oattr is not None) or (oattr is None and sattr is not None): raise AssertionError('One of the coordset is None') elif sattr is None and oattr is None: res = True else: for item in zip(sattr, oattr): res = compare_datasets(*item, approx=approx, decimal=decimal) if not res: raise AssertionError(f'coords differs:\n{res}') else: eq &= np.all(sattr == oattr) if not eq: raise AssertionError(f'The {attr} attributes of {this} and {other} are ' f'different.') else: return False else: # unitlesss and dimensionless are supposed equals sattr = this._units if sattr is None: sattr = ur.dimensionless if hasattr(other, '_units'): oattr = other._units if oattr is None: oattr = ur.dimensionless eq &= np.all(sattr == oattr) if not eq: raise AssertionError(f"attributes `{attr}` are not equals or one is " f"missing: \n{sattr} != {oattr}") else: raise AssertionError(f'{other} has no units') return True # ...................................................................................................................... def assert_dataset_equal(nd1, nd2, **kwargs): kwargs['approx'] = False assert_dataset_almost_equal(nd1, nd2, **kwargs) return True # ...................................................................................................................... def assert_dataset_almost_equal(nd1, nd2, **kwargs): decimal = kwargs.get('decimal', 6) approx = kwargs.get('approx', True) data_only = kwargs.get('data_only', False) # if True, compare only based on data (not labels and so on) compare_datasets(nd1, nd2, approx=approx, decimal=decimal, data_only=data_only) return True def assert_project_equal(proj1, proj2, **kwargs): assert_project_almost_equal(proj1, proj2, approx=False) return True # ...................................................................................................................... def assert_project_almost_equal(proj1, proj2, **kwargs): for nd1, nd2 in zip(proj1.datasets, proj2.datasets): compare_datasets(nd1, nd2, **kwargs) for pr1, pr2 in zip(proj1.projects, proj2.projects): assert_project_almost_equal(pr1, pr2, **kwargs) for sc1, sc2 in zip(proj1.scripts, proj2.scripts): assert_script_equal(sc1, sc2, **kwargs) return True # ...................................................................................................................... def assert_script_equal(sc1, sc2, **kwargs): if sc1 != sc2: raise AssertionError(f'Scripts are differents: {sc1.content} != {sc2.content}') # ====================================================================================================================== # RandomSeedContext # ====================================================================================================================== # ............................................................................. class RandomSeedContext(object): """ A context manager (for use with the ``with`` statement) that will seed the numpy random number generator (RNG) to a specific value, and then restore the RNG state back to whatever it was before. (Copied from Astropy, licence BSD-3) Parameters ---------- seed : int The value to use to seed the numpy RNG Examples -------- A typical use case might be:: with RandomSeedContext(<some seed value you pick>): from numpy import random randarr = random.randn(100) ... run your test using `randarr` ... """ def __init__(self, seed): self.seed = seed def __enter__(self): from numpy import random self.startstate = random.get_state() random.seed(self.seed) def __exit__(self, exc_type, exc_value, traceback): from numpy import random random.set_state(self.startstate) # ====================================================================================================================== # raises and assertions (mostly copied from astropy) # ====================================================================================================================== # ............................................................................. def assert_equal_units(unit1, unit2): from pint import DimensionalityError try: x = (1. * unit1) / (1. * unit2) except DimensionalityError: return False if x.dimensionless: return True return False # ............................................................................. class raises(object): """ A decorator to mark that a test should raise a given exception. Use as follows:: @raises(ZeroDivisionError) def test_foo(): x = 1/0 This can also be used a context manager, in which case it is just an alias for the ``pytest.raises`` context manager (because the two have the same name this help avoid confusion by being flexible). (Copied from Astropy, licence BSD-3) """ # pep-8 naming exception -- this is a decorator class def __init__(self, exc): self._exc = exc self._ctx = None def __call__(self, func): @functools.wraps(func) def run_raises_test(*args, **kwargs): import pytest pytest.raises(self._exc, func, *args, **kwargs) return run_raises_test def __enter__(self): import pytest self._ctx = pytest.raises(self._exc) return self._ctx.__enter__() def __exit__(self, *exc_info): return self._ctx.__exit__(*exc_info) # ............................................................................. class catch_warnings(warnings.catch_warnings): """ A high-powered version of warnings.catch_warnings to use for testing and to make sure that there is no dependence on the order in which the tests are run. This completely blitzes any memory of any warnings that have appeared before so that all warnings will be caught and displayed. ``*args`` is a set of warning classes to collect. If no arguments are provided, all warnings are collected. Use as follows:: with catch_warnings(MyCustomWarning) as w : do.something.bad() assert len(w) > 0 (Copied from Astropy, licence BSD-3) """ def __init__(self, *classes): super(catch_warnings, self).__init__(record=True) self.classes = classes def __enter__(self): warning_list = super(catch_warnings, self).__enter__() if len(self.classes) == 0: warnings.simplefilter('always') else: warnings.simplefilter('ignore') for cls in self.classes: warnings.simplefilter('always', cls) return warning_list def __exit__(self, type, value, traceback): pass # TODO: work on this # # # ---------------------------------------------------------------------------------------------------------------------- # # Matplotlib testing utilities # # # ---------------------------------------------------------------------------------------------------------------------- # # figures_dir = os.path.join(os.path.expanduser("~"), ".spectrochempy", # "figures") # os.makedirs(figures_dir, exist_ok=True) # # # # # ............................................................................. # def _compute_rms(x, y): # return calculate_rms(x, y) # # # # # ............................................................................. # def _image_compare(imgpath1, imgpath2, REDO_ON_TYPEERROR): # # compare two images saved in files imgpath1 and imgpath2 # # from matplotlib.pyplot import imread # from skimage.measure import compare_ssim as ssim # # # read image # try: # img1 = imread(imgpath1) # except IOError: # img1 = imread(imgpath1 + '.png') # try: # img2 = imread(imgpath2) # except IOError: # img2 = imread(imgpath2 + '.png') # # try: # sim = ssim(img1, img2, # data_range=img1.max() - img2.min(), # multichannel=True) * 100. # rms = _compute_rms(img1, img2) # # except ValueError: # rms = sim = -1 # # except TypeError as e: # # this happen sometimes and erratically during testing using # # pytest-xdist (parallele testing). This is work-around the problem # if e.args[0] == "unsupported operand type(s) " \ # "for - : 'PngImageFile' and 'int'" and not # REDO_ON_TYPEERROR: # REDO_ON_TYPEERROR = True # rms = sim = -1 # else: # raise # # return (sim, rms, REDO_ON_TYPEERROR) # # # # # ............................................................................. # def compare_images(imgpath1, imgpath2, # max_rms=None, # min_similarity=None, ): # sim, rms, _ = _image_compare(imgpath1, imgpath2, False) # # EPSILON = np.finfo(float).eps # CHECKSIM = (min_similarity is not None) # SIM = min_similarity if CHECKSIM else 100. - EPSILON # MESSSIM = "(similarity : {:.2f}%)".format(sim) # CHECKRMS = (max_rms is not None and not CHECKSIM) # RMS = max_rms if CHECKRMS else EPSILON # MESSRMS = "(rms : {:.2f})".format(rms) # # if sim < 0 or rms < 0: # message = "Sizes of the images are different" # elif CHECKRMS and rms <= RMS: # message = "identical images {}".format(MESSRMS) # elif (CHECKSIM or not CHECKRMS) and sim >= SIM: # message = "identical/similar images {}".format(MESSSIM) # else: # message = "different images {}".format(MESSSIM) # # return message # # # # # ............................................................................. # def same_images(imgpath1, imgpath2): # if compare_images(imgpath1, imgpath2).startswith('identical'): # return True # # # # # ............................................................................. # def image_comparison(reference=None, # extension=None, # max_rms=None, # min_similarity=None, # force_creation=False, # savedpi=150): # """ # image file comparison decorator. # # Performs a comparison of the images generated by the decorated function. # If none of min_similarity and max_rms if set, # automatic similarity check is done : # # Parameters # ---------- # reference : list of image filename for the references # # List the image filenames of the reference figures # (located in ``.spectrochempy/figures``) which correspond in # the same order to # the various figures created in the decorated fonction. if # these files doesn't exist an error is generated, except if the # force_creation argument is True. This should allow the creation # of a reference figures, the first time the corresponding figures are # created. # # extension : str, optional, default=``png`` # # Extension to be used to save figure, among # (eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff) # # force_creation : `bool`, optional, default=`False`. # # if this flag is True, the figures created in the decorated # function are # saved in the reference figures directory ( # ``.spectrocchempy/figures``) # # min_similarity : float (percent). # # If set, then it will be used to decide if an image is the same ( # similar) # or not. In this case max_rms is not used. # # max_rms : float # # rms stands for `Root Mean Square`. If set, then it will # be used to decide if an image is the same # (less than the acceptable rms). Not used if min_similarity also set. # # savedpi : int, optional, default=150 # # dot per inch of the generated figures # # """ # from spectrochempy.utils import is_sequence # # if not reference: # raise ValueError('no reference image provided. Stopped') # # if not extension: # extension = 'png' # # if not is_sequence(reference): # reference = list(reference) # # def make_image_comparison(func): # # @functools.wraps(func) # def wrapper(*args, **kwargs): # # # check the existence of the file if force creation is False # for ref in reference: # filename = os.path.join(figures_dir, # '{}.{}'.format(ref, extension)) # if not os.path.exists(filename) and not force_creation: # raise ValueError( # 'One or more reference file do not exist.\n' # 'Creation can be forced from the generated ' # 'figure, by setting force_creation flag to True') # # # get the nums of the already existing figures # # that, obviously,should not considered in # # this comparison # fignums = plt.get_fignums() # # # execute the function generating the figures # # rest style to basic 'lcs' style # _ = func(*args, **kwargs) # # # get the new fignums if any # curfignums = plt.get_fignums() # for x in fignums: # # remove not newly created # curfignums.remove(x) # # if not curfignums: # # no figure where generated # raise RuntimeError(f'No figure was generated by the "{ # func.__name__}" function. Stopped') # # if len(reference) != len(curfignums): # raise ValueError("number of reference figures provided # doesn't match the number of generated # figures.") # # # Comparison # REDO_ON_TYPEERROR = False # # while True: # errors = "" # for fignum, ref in zip(curfignums, reference): # referfile = os.path.join(figures_dir, # '{}.{}'.format(ref, extension)) # # fig = plt.figure(fignum) # work around to set # # the correct style: we # # we have saved the rcParams # # in the figure attributes # plt.rcParams.update(fig.rcParams) # fig = plt.figure(fignum) # # if force_creation: # # make the figure for reference and bypass # # the rest of the test # tmpfile = referfile # else: # # else we create a temporary file to save the figure # fd, tmpfile = tempfile.mkstemp( # prefix='temp{}-'.format(fignum), # suffix='.{}'.format(extension), text=True) # os.close(fd) # # fig.savefig(tmpfile, dpi=savedpi) # # sim, rms = 100.0, 0.0 # if not force_creation: # # we do not need to loose time # # if we have just created the figure # sim, rms, REDO_ON_TYPEERROR = _image_compare( # referfile, # tmpfile, # REDO_ON_TYPEERROR) # EPSILON = np.finfo(float).eps # CHECKSIM = (min_similarity is not None) # SIM = min_similarity if CHECKSIM else 100. - EPSILON # MESSSIM = "(similarity : {:.2f}%)".format(sim) # CHECKRMS = (max_rms is not None and not CHECKSIM) # RMS = max_rms if CHECKRMS else EPSILON # MESSRMS = "(rms : {:.2f})".format(rms) # # if sim < 0 or rms < 0: # message = "Sizes of the images are different" # elif CHECKRMS and rms <= RMS: # message = "identical images {}".format(MESSRMS) # elif (CHECKSIM or not CHECKRMS) and sim >= SIM: # message = "identical/similar images {}".format( # MESSSIM) # else: # message = "different images {}".format(MESSSIM) # # message += "\n\t reference : {}".format( # os.path.basename(referfile)) # message += "\n\t generated : {}\n".format( # tmpfile) # # if not message.startswith("identical"): # errors += message # else: # print(message) # # if errors and not REDO_ON_TYPEERROR: # # raise an error if one of the image is different from # the # # reference image # raise ImageAssertionError("\n" + errors) # # if not REDO_ON_TYPEERROR: # break # # return # # return wrapper # # return make_image_comparison # ---------------------------------------------------------------------------------------------------------------------- # main # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/docs/userguide/plotting/plotting.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Plotting # %% [markdown] # ## Load the API # %% [markdown] # First, before anything else, we import the spectrochempy API: # %% from spectrochempy import * # %% [markdown] # ## Loading the data # %% [markdown] # For sake of demonstration of the plotting capabilities of SpectroChemPy (based on [Matplotlib]( # https://matplotlib.org)), let's first import a NDDataset from a file and make some (optional) preparation of the # data to display. # %% dataset = NDDataset.read('irdata/nh4y-activation.spg') # %% [markdown] # ## Preparing the data # %% [markdown] # We keep only the region that we want to display # %% dataset = dataset[:, 4000.:650.] # %% [markdown] # We change the y coordinated so that times start at 0 and put it in minutes # %% dataset.y -= dataset.y[0] dataset.y.ito("minutes") dataset.y.title = 'Time on stream' # %% [markdown] # We will also mask a region that we do not want to display # %% dataset[:, 1290.:920.] = MASKED # %% [markdown] # ## Selecting the output window # %% [markdown] # For the examples below, we use inline matplotlib figures (non interactive): this can be forced using the magic # function before loading spectrochempy.: # ```ipython3 # %matplotlib inline # ``` # but it is also the default in `Jupyter lab` (so we don't really need to specify this). Note that when such magic # function has been used, it is not possible to change the setting, except by resseting the notebook kernel. # # If one wants interactive displays (with selection, zooming, etc...) one can use: # ```ipython3 # %matplotlib widget # ``` # However, this suffer (at least for us) some incompatibilities in `jupyter lab`... it is worth to try! # If you can not get it working in `jupyter lab` and you need interactivity, you can use the following: # ```ipython3 # %matplotlib # ``` # which has the effect of displaying the figures in independant windows using default matplotlib backend (e.g., # `Tk`), with all the interactivity of matplotlib. # # But you can explicitly request a different GUI backend: # ```ipython3 # %matplotlib qt # ``` # %% # %matplotlib inline # %% [markdown] # ## Using Plotly (experimental) # %% [markdown] # For a better experience of interactivity inside a notebook, SpectroChemPy also offer the possibillity to use Plotly. # # See the dedicated tutorial: [here](...) # %% [markdown] # ## Default plotting # %% [markdown] # To plot the previously loaded dataset, it is very simple: we use the `plot` command (generic plot). # # The current NDDataset is 2D, a **stack plot** is displayed by default, with a **viridis** colormap. # %% prefs = dataset.preferences prefs.reset() # Reset to default plot preferences _ = dataset.plot() # %% [markdown] # <div class="alert alert-block alert-info"> # <b>Tip: </b> # # Note, in the line above, that we used ` _ = ... ` syntax. # This is to avoid any ouput but the plot from this statement. # </div> # %% [markdown] # ## Changing the aspect of the plot # %% [markdown] # We can change the default plot configuration for this dataset (see below for an overview of the available # configuration parameters. # %% prefs.figure.figsize = (6, 3) # The default figsize is (6.8,4.4) prefs.colorbar = True # This add a color bar on a side prefs.colormap = 'magma' # The default colormap is viridis prefs.axes.facecolor = '.95' # Make the graph background colored in a ligth gray prefs.axes.grid = True _ = dataset.plot() # %% [markdown] # Note that, by default, <b>sans-serif</b> font are used for all text in the figure. # But if you prefer, <b>serif</b>, or <b>monospace</b> font can be used instead: # %% prefs.font.family = 'serif' _ = dataset.plot() # %% prefs.font.family = 'monospace' _ = dataset.plot() # %% [markdown] # ## Plotting 1D datasets # %% prefs.reset() d1D = dataset[-1] # select the last row of the previous 2D dataset _ = d1D.plot(color='r') # %% [markdown] # ## Adding titles and annotations # %% [markdown] # The plot function return a reference to the subplot `ax` on which the data have been plotted. # We can then use this reference to modify some element of the plot. # # For example, here we add a title and some annotations: # %% prefs.reset() prefs.colorbar = False prefs.colormap = 'terrain' prefs.font.family = 'monospace' ax = dataset.plot() ax.grid(False) # This temporary suppress the grid after the plot is done - not saved in prefs # set title title = ax.set_title('NH$_4$Y IR spectra during activation') title.set_color('red') title.set_fontstyle('italic') title.set_fontsize(14) # put some text ax.text(1200., 1, 'Masked region\n (saturation)', rotation=90) # put some fancy annotations (see matplotlib documentation to learn how to design this) _ = ax.annotate('OH groups', xy=(3600., 1.25), xytext=(-10, -50), textcoords='offset points', arrowprops=dict(arrowstyle="fancy", color="0.5", shrinkB=5, connectionstyle="arc3,rad=-0.3", ), ) # %% [markdown] # More information about annotation can be found in the [matplotlib documentation: annotations]( # https://matplotlib.org/tutorials/text/annotations.html) # %% [markdown] # ## Changing the plot style using matpotlib style sheets # %% [markdown] # The easiest way to to change the plot style may be to use presetted style such as those used in [matplotlib # styles](https://matplotlib.org/3.3.3/tutorials/introductory/customizing.html). This is directly included in the # preferences of SpectroChemPy # %% prefs.style = 'grayscale' _ = dataset.plot() # %% prefs.style = 'ggplot' _ = dataset.plot() # %% [markdown] # Other styles are : # * paper , which create figure suitable for two columns article (fig width: 3.4 inch) # * poster # * talk # %% [markdown] # the styles can be combined: # %% prefs.reset() prefs.style = 'grayscale', 'paper' _ = dataset.plot(colorbar=True) # %% [markdown] # Style specification can also be done directly in the plot method: # %% prefs.colormap = 'magma' _ = dataset.plot(style=['scpy', 'paper']) # %% [markdown] # To get a list of all available styles : # %% prefs.available_styles # %% [markdown] # Now to restore the default setting, you can use the reset function # %% prefs.reset() _ = dataset.plot() # %% [markdown] # ## Create your own style # %% [markdown] # If you want to create your own style for later use, you can use the command `makestyle` (**warning**: you can not # use `scpy` # which is the READONLY default style). # %% prefs.makestyle('scpy') # %% [markdown] # If no name is provided a default name is used :`mydefault` # %% prefs.makestyle() # %% [markdown] # **Example:** # # %% prefs.reset() prefs.colorbar = True prefs.colormap = 'jet' prefs.font.family = 'monospace' prefs.font.size = 14 prefs.axes.labelcolor = 'blue' prefs.axes.grid = True prefs.axes.grid_axis = 'x' _ = dataset.plot(); prefs.makestyle() # %% prefs.reset() _ = dataset.plot() # plot with the default scpy style # %% prefs.style = 'mydefault' _ = dataset.plot() # plot with our own style # %% [markdown] # ## Changing the type of plot # %% [markdown] # By default, plots are done in stack mode. # # If you like to have contour plot, you can use: # %% prefs.reset() prefs.method_2D = 'map' # this will change permanently the type of 2D plot prefs.colormap = 'magma' prefs.figure_figsize = (5, 3) _ = dataset.plot() # %% [markdown] # You can also, for an individual plot use specialised plot commands, such as plot_stack, plot_map, plot_waterfall, # or plot_image: # %% prefs.axes_facecolor = 'white' _ = dataset.plot_image(colorbar=True) # will use image_cmap preference! # %% prefs.reset() _ = dataset.plot_waterfall(figsize=(7, 4), y_reverse=True) # %% prefs.style = 'seaborn-paper' _ = dataset[3].plot(scatter=True, pen=False, me=30, ms=5) # %% [markdown] # ## Plotting several dataset on the same figure # %% [markdown] # We can plot several datasets on the same figure using the `clear` argument. # %% nspec = int(len(dataset) / 4) ds1 = dataset[:nspec] # split the dataset into too parts ds2 = dataset[nspec:] - 2. # add an ofset to the second part ax1 = ds1.plot_stack() _ = ds2.plot_stack(ax=ax1, clear=False, zlim=(-2.5, 4)) # %% [markdown] # For 1D datasets only, you can also use the `plot_multiple`mathod: # %% datasets = [dataset[0], dataset[10], dataset[20], dataset[50], dataset[53]] labels = ['sample {}'.format(label) for label in ["S1", "S10", "S20", "S50", "S53"]] prefs.reset() prefs.axes.facecolor = '.99' prefs.axes.grid = True _ = plot_multiple(method='scatter', me=10, datasets=datasets, labels=labels, legend='best') # %% [markdown] # ## Overview of the main configuration parameters # %% [markdown] # To display a dictionary of the current settings (**compared to those set by default** # at API startup), you can simply type : # %% prefs # %% [markdown] # <div class="alert alert-block alert-warning"> # <b>Warning</b> : # Note that in the `dataset.preferences` dictionary (`prefs`), the parameters have a slightly different name, e.g., # <b>figure_figsize</b> instead of <b>figure.fisize</b> which is the matplotlib syntax (In spectrochempy, # dot (`.`) cannot be used in paremeter name, and thus it is replaced by an underscore (`_`)) # # Actually, in the jupyter notebook, or in scripts, both syntax can be used to read or write most of the preferences # entries # # </div> # %% [markdown] # To display the current values of **all parameters** correspondint to one group, e.g. `lines`, type: # %% prefs.lines # %% [markdown] # To display **help** on a single parameter, type: # %% prefs.help('lines_linewidth') # %% [markdown] # To view **all parameters**: # %% prefs.all() # %% [markdown] # ## A last graph for the road and fun... # %% prefs.font.family = 'fantasy' import matplotlib.pyplot as plt with plt.xkcd(): # print(mpl.rcParams) prefs.lines.linewidth = 2 ax = dataset[-1].plot(figsize=(7.5, 4)) ax.text(2800., 1.5, "A XKCD plot!...") <file_sep>/spectrochempy/gui/callbacks.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements the DAsh callbacks. """ __all__ = [] import base64 import json from dash import no_update, callback_context from dash.dependencies import Input, Output, State import dash_html_components as html from dash.exceptions import PreventUpdate import dash_bootstrap_components as dbc import spectrochempy as scp class Callbacks(object): @staticmethod def parse_upload_contents(filename, contents, single=False): # # transform uploaded content to a NDDataset # content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) ds = scp.NDDataset.read(filename, content=decoded) return ds.write_json(to_string=True) @staticmethod def dataset_itemlist(ds): return [ html.H6(f'{ds.name}'), html.Code(f'{str(ds)}'), # dcc.Markdown(f'{ds.description}'), # *[dcc.Markdown(f'{d}') for d in ds.history], ] def dataset_list(self, *datasets): return [dbc.ListGroupItem([ dbc.Checkbox(id=f"dataset-checkbox-{i}", style={ 'float': 'right' }, checked=True), *self.dataset_itemlist(ds)]) for i, ds in enumerate(datasets)] def uploaded_dataset_list(self, *datasets): # # TODO: active can be set to True for highligthing selected File (however for the moment we limit to one # component) # TODO: write a callback for each entry # all_datasets = [ dbc.ListGroup(self.dataset_list(*datasets)) ] return all_datasets @staticmethod def set_ROI_and_offset(ds, xrf, yrf, xrl, xru, yrl, yru): dimx = ds.dims[-1] x = getattr(ds, dimx) x.offset = float(xrf) if xrf else 0 ds.history = f">>> ds.{dimx}.offset = {x.offset}')" x.roi = [float(xrl) if xrl else 0, float(xru) if xru else 0] ds.history = f">>> ds.{dimx}.roi = {x.roi}" if len(ds.dims) > 1: dimy = ds.dims[-2] y = getattr(ds, dimy) y.offset = float(yrf) if yrf else 0 ds.history = f">>> ds.{dimy}.offset = {y.offset}" y.roi = float(yrl) if yrl else 0, float(yru) if yru else 0 ds.history = f">>> ds.{dimy}.roi = {y.roi}" return ds def add_callbacks(self, app): """ Add all application calbacks """ # # ------------ # # DATA UPLOAD # # ------------ # @app.callback(Output('original-data', 'data'), # Input('upload-data', 'contents'), # State('upload-data', 'filename')) # def data_upload(list_of_contents, list_of_names): # # Store data in components # # data = {} # the data must be JSON serializable # # if list_of_contents is not None: # # data uploaded # z = zip(list_of_names, list_of_contents) # data = {n: self.parse_upload_contents(n, c) for n, c in z} # else: # raise PreventUpdate # return data # -------------- # PROJECT UPLOAD # -------------- @app.callback(Output('original-data', 'data'), Input('upload-project', 'contents'), State('upload-project', 'filename')) def project_upload(content, name): # Store project data in components data = {} # the data must be JSON serializable if content is not None: # data uploaded content_type, content_string = content.split(',') decoded = base64.b64decode(content_string) pj = scp.Project.load(content=decoded) data = pj.to_json() else: raise PreventUpdate return data # ---------------------- # SAVE INTERMEDIATE DATA # ---------------------- @app.callback([Output('intermediate-data', 'data'), Output('actual-x-roi', 'children'), Output('actual-y-roi', 'children'), Output('action-history', 'data')], [ # roi Input('x-roi-lower', 'value'), Input('x-roi-upper', 'value'), Input('y-roi-lower', 'value'), Input('y-roi-upper', 'value'), Input('x-offset', 'value'), Input('y-offset', 'value'), Input('original-data', 'modified_timestamp'), # new original data Input('confirm-mask', 'submit_n_clicks'), # modify masks Input('graph', 'selectedData'), # data for x-masks Input('graph', 'clickData'), # data for y-mask Input('graph-selector', 'value'), # transposed case? ], [State('original-data', 'data'), State('intermediate-data', 'data'), State('action-history', 'data')]) def save_intermediate_data(xrl, xru, yrl, yru, xrf, yrf, ts, submit_mask, selectedData, clickData, selector, data, saved, history): """ Main callback for updating the figure and some dash components """ # no original data? probably not yet uplaoded... exit without updating if data is None: raise PreventUpdate project = scp.Project.from_json(data) # extract the project information from original data store # datasets = [scp.read_json(content=c.encode()) for n, c in data.items()] # show processed flag processed = True if 'Processed' in selector else False # if we want to show the original data: # ------------------------------------- if not processed: ds = datasets[0] # set current ROI and offset if necessary self.set_ROI_and_offset(ds, xrf, yrf, xrl, xru, yrl, yru) # make output datasets[0] = ds data = {ds.filename: ds.write_json(to_string=True) for ds in datasets} return data, no_update, no_update, no_update # else we will output processed data # ---------------------------------- if saved: datasets = [scp.read_json(content=c.encode()) for n, c in saved.items()] # for now we work with only one spectrum ds = datasets[0] dss = ds.copy() # for further comparison of changes # set current ROI and offset if necessary self.set_ROI_and_offset(ds, xrf, yrf, xrl, xru, yrl, yru) # show transposed? transposed = True if 'Transposed' in selector else False # apply masks if submit_mask and selectedData: # set x-masks range = selectedData.get('range', None) if range is not None: x_selection = range['x'] if not transposed: ds[:, x_selection[1]:x_selection[0]] = scp.MASKED else: ds[x_selection[1]:x_selection[0]] = scp.MASKED # create output if ds == dss: # no change raise PreventUpdate datasets[0] = ds newdata = {ds.filename: ds.write_json(to_string=True) for ds in datasets} actx = f'Actual roi: {ds.x.roi_values[0]:~P} -> {ds.x.roi_values[1]:~P}' acty = f'Actual roi: {ds.y.roi_values[0]:~P} -> {ds.y.roi_values[1]:~P}' # update history # history is designed to be a list of python function, # able to be run later to reproduce all the transformations done ctx = callback_context.triggered if 'original-data' in ctx[0]['prop_id']: # Data just uploaded in Dash history = [f">>> ds = scp.read('{ds.filename}')"] else: # parameter changes for item in ctx: par = item['prop_id'] return newdata, actx, acty, history # ----------------------- # UPDATE DATA TAB CONTENT # ----------------------- @app.callback([Output('current-data', 'children'), Output('show-project', 'style'), Output('show-current-data', 'style'), Output('show-graph', 'is_open'), Output('x-roi', 'children'), Output('y-roi', 'children'), Output('x-roi-lower', 'value'), Output('x-roi-upper', 'value'), Output('y-roi-lower', 'value'), Output('y-roi-upper', 'value'), Output('x-roi-units', 'children'), Output('y-roi-units', 'children'), Output('x-offset', 'value'), Output('y-offset', 'value')], [Input('original-data', 'modified_timestamp')], [State('original-data', 'data'), State('intermediate-data', 'data')]) def update_tab_content(ts, data, saveddata): if ts is None: raise PreventUpdate dataloaded = None is_open = True xr = 'x' yr = 'y' xrl, xru = None, None yrl, yru = None, None xr_units = None yr_units = None xro = 0 yro = 0 style = dict({ 'display': 'none' }) if saveddata is not None: # take the saved data! data = saveddata # json.loads(saveddata) if data is not None: datasets = [scp.read_json(content=c.encode()) for n, c in data.items()] # for now we work with only one spectrum ds = datasets[0] dataloaded = self.uploaded_dataset_list(*datasets) is_open = False xr = ds.x.title # we assume homogeneous data (same kind of dimension) yr = ds.y.title xrl, xru = ds.x.roi yrl, yru = ds.y.roi xr_units = f'{ds.x.units:~P}' yr_units = f'{ds.y.units:~P}' xro = ds.x.offset yro = ds.y.offset style = dict({ 'display': 'block' }) return (dataloaded, style, style, not is_open, xr, yr, xrl, xru, yrl, yru, xr_units, yr_units, xro, yro) # ------------- # UPDATE FIGURE # ------------- @app.callback(Output('graph', 'figure'), [Input('intermediate-data', 'data'), Input('graph-selector', 'value'), # change on the type of figure to display (processed, transposed...) Input('graph-optimisation', 'value'), # change the optimisation level Input('zoom-reset', 'n_clicks'), # reset Zoom from button Input('cmap-select', 'value'), Input('select-mask', 'n_clicks') # Input('graph', 'relayoutData') ]) def update_figure(data, selector, optim, zoomreset, cmap, dragmode, ): # relayout): if data is None: raise PreventUpdate datasets = [scp.read_json(content=c.encode()) for n, c in data.items()] ds = datasets[0] dragmode = 'zoom' if dragmode is None or dragmode % 2 == 0 else 'select' figure = ds.plot(use_plotly=True, selector=selector, optimisation=optim, zoomreset=zoomreset, cmap=cmap, dragmode=dragmode, ) return figure # ------------------ # CLEAR DATA BUTTON # ------------------ @app.callback( [Output("original-data", "clear_data"), Output("intermediate-data", "clear_data")], [Input("close-data", "n_clicks")] ) def clear_data_click(n): if n is None: return False, False else: return True, True # ------------------- # DISPLAY CONTROL # ------------------- @app.callback( [Output("close-data", "style"), Output('data-tab', 'disabled'), Output('graph-tab', 'disabled'), Output('processing-tab', 'disabled')], [Input('current-data', 'children')]) def tab_display_control(children): if not children: return dict({ 'display': 'none' }), True, True, True else: return dict({ 'display': 'block' }), False, False, False # ---------------------------------- # MODIFY CLOSING/OPENING CARD BUTTON # ---------------------------------- for item in ['roi', 'current-data', 'mask', 'layout', 'xaxis', 'zaxis', 'baseline', 'peakpicking', 'subtraction']: @app.callback( [Output(f"open-{item}-more", "is_open"), Output(f"{item}-more", "children"), Output(f"{item}-more", "color")], [Input(f"{item}-more", "n_clicks")], [State(f"{item}-more", "children")] ) def on_click(n, state): if n is None or state.startswith('Close'): return False, "More", "info" else: return True, "Close this card", "warning" # ------------ # MENU PROJECT # ------------ @app.callback( [Output(f"project-name", "placeholder"), Output(f"project-name", "disabled"), Output(f"project-close", "disabled"), Output(f"project-save", "disabled")], [Input(f"project-new", "n_clicks"), Input(f"project-open", "n_clicks")] ) def on_menu_project(new, open): # ctx = callback_context.triggered if new is None and open is None: raise PreventUpdate ctx = callback_context.triggered if ctx and 'new' in ctx[0]['prop_id'] and ctx[0]['value'] is not None: return 'Untitled (edit to chnge this name)', False, False, False elif ctx and 'new' in ctx[0]['prop_id'] and ctx[0]['value'] is not None: return # Set masks # @app.callback() # GRAPH SELECTION AND HOVER # @app.callback( # Output('text-data', 'children'), # [Input('graph', 'hoverData')]) # def display_hover_data(hoverData): # return json.dumps(hoverData, indent=2) # # # @app.callback( # Output('text-data', 'children'), # [Input('graph', 'clickData')]) # def display_click_data(clickData): # return json.dumps(clickData, indent=2) # # # @app.callback( # Output('text-data', 'children'), # [Input('graph', 'selectedData')]) # def display_selected_data(selectedData): # return json.dumps(selectedData, indent=2) @app.callback( [Output('text-data', 'children'), Output('confirm-mask', 'displayed'), Output('confirm-mask', 'submit_n_clicks'), Output('confirm-mask', 'message')], [Input('graph', 'relayoutData'), Input('graph', 'hoverData'), Input('graph', 'selectedData'), Input('graph', 'clickData') ]) def display_relayout_data(relayoutData, hoverData, selectedData, clickData): ctx = callback_context text = json.dumps(hoverData, indent=2) + json.dumps(relayoutData, indent=2) + json.dumps(selectedData, indent=2) + \ json.dumps( clickData, indent=2) confirm = False message = '' nclicks = no_update if ctx.triggered[0]['prop_id'] == 'graph.selectedData': range = selectedData.get('range', None) if range is not None: x_selection = range['x'] message = f'Are you sure you want to mask data in the {x_selection} region?' confirm = True nclicks = 0 return text, confirm, nclicks, message # # Mask selection button aspect # @app.callback( [Output('select-mask', 'children'), Output('select-mask', 'color'), ], [Input('select-mask', 'n_clicks'), ] ) def mask_buttton_aspect(n): if n is None or n % 2 == 0: return "Select mask", "secondary" else: return "Stop mask selection", "danger" <file_sep>/spectrochempy/core/processors/fft.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2016 <NAME> # Laboratoire Catalyse et Spectrochimie, Caen, France. # # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT # See full LICENSE agreement in the root directory # ====================================================================================================================== __all__ = ["fft", "ifft", "mc", "ps", "ht"] __dataset_methods__ = __all__ import re import numpy as np from scipy.signal import hilbert from quaternion import as_float_array from spectrochempy.core import error_ from spectrochempy.units import ur from spectrochempy.core.dataset.coord import LinearCoord from spectrochempy.utils import largest_power_of_2, get_component, typequaternion, as_quaternion from spectrochempy.core.processors.utils import _units_agnostic_method from spectrochempy.core.processors.zero_filling import zf_size # ====================================================================================================================== # Private methods # ====================================================================================================================== def _fft(data): if data.dtype == typequaternion: dr = get_component(data, 'R') fr = np.fft.fftshift(np.fft.fft(dr), -1) di = get_component(data, 'I') fi = np.fft.fftshift(np.fft.fft(di), -1) # rebuild the quaternion data = as_quaternion(fr, fi) else: data = np.fft.fftshift(np.fft.fft(data), -1) return data def _ifft(data): if data.dtype == typequaternion: fr = get_component(data, 'R') dr = np.fft.ifft(np.fft.ifftshift(fr, -1)) fi = get_component(data, 'I') di = np.fft.ifft(np.fft.ifftshift(fi, -1)) # rebuild the quaternion data = as_quaternion(dr, di) else: data = np.fft.ifft(np.fft.ifftshift(data, -1)) return data def _fft_positive(data): if data.dtype == typequaternion: dr = get_component(data, 'R') fr = np.fft.fftshift(np.fft.ifft(dr).astype(data.dtype)) * data.shape[-1] di = get_component(data, 'I') fi = np.fft.fftshift(np.fft.ifft(di).astype(data.dtype)) * data.shape[-1] # rebuild the quaternion data = as_quaternion(fr, fi) else: data = np.fft.fftshift(np.fft.ifft(data).astype(data.dtype)) * data.shape[-1] return data def _ifft_positive(data): if data.dtype == typequaternion: fr = get_component(data, 'R') dr = np.fft.fft(np.fft.ifftshift(fr, -1)) * data.shape[-1] fi = get_component(data, 'I') di = np.fft.fft(np.fft.ifftshift(fi, -1)) * data.shape[-1] # rebuild the quaternion data = as_quaternion(dr, di) else: data = np.fft.fft(np.fft.ifftshift(data, -1)) * data.shape[-1] return data def _states_fft(data, tppi=False): # FFT transform according to STATES encoding # warning: at this point, data must have been swaped so the last dimension is the one used for FFT wt, yt, xt, zt = as_float_array(data).T # x and y are exchanged due to swaping of dims w, y, x, z = wt.T, yt.T, xt.T, zt.T sr = (w - 1j * y) / 2. si = (x - 1j * z) / 2. if tppi: sr[..., 1::2] = -sr[..., 1::2] si[..., 1::2] = -si[..., 1::2] fr = np.fft.fftshift(np.fft.fft(sr), -1) fi = np.fft.fftshift(np.fft.fft(si), -1) # rebuild the quaternion data = as_quaternion(fr, fi) return data def _echoanti_fft(data): # FFT transform according to ECHO-ANTIECHO encoding # warning: at this point, data must have been swaped so the last dimension is the one used for FFT wt, yt, xt, zt = as_float_array(data).T # x and y are exchanged due to swaping of dims w, y, x, z = wt.T, xt.T, yt.T, zt.T c = (w + y) + 1j * (w - y) s = (x + z) - 1j * (x - z) fc = np.fft.fftshift(np.fft.fft(c / 2.), -1) fs = np.fft.fftshift(np.fft.fft(s / 2.), -1) data = as_quaternion(fc, fs) return data def _tppi_fft(data): # FFT transform according to TPPI encoding # warning: at this point, data must have been swaped so the last dimension is the one used for FFT wt, yt, xt, zt = as_float_array(data).T # x and y are exchanged due to swaping of dims w, y, x, z = wt.T, xt.T, yt.T, zt.T sx = w + 1j * y sy = x + 1j * z sx[..., 1::2] = -sx[..., 1::2] sy[..., 1::2] = -sy[..., 1::2] fx = np.fft.fftshift(np.fft.fft(sx), -1) # reverse fy = np.fft.fftshift(np.fft.fft(sy), -1) # rebuild the quaternion data = as_quaternion(fx, fy) return data def _qf_fft(data): # FFT transform according to QF encoding data = np.fft.fftshift(np.fft.fft(np.conjugate(data)), -1) return data def _interferogram_fft(data): """ FFT transform for rapid-scan interferograms. Phase corrected using the Mertz method. """ def _get_zpd(data, mode='max'): if mode == 'max': return np.argmax(data, -1) elif mode == 'abs': return int(np.argmax(np.abs(data), -1)) zpd = _get_zpd(data, mode='abs') size = data.shape[-1] # Compute Mertz phase correction w = np.arange(0, zpd) / zpd ma = np.concatenate((w, w[::-1])) dma = np.zeros_like(data) dma[..., 0:2 * zpd] = data[..., 0:2 * zpd] * ma[0:2 * zpd] dma = np.roll(dma, -zpd) dma[0] = dma[0] / 2. dma[-1] = dma[-1] / 2. dma = np.fft.rfft(dma)[..., 0:size // 2] phase = np.arctan(dma.imag / dma.real) # Make final phase corrected spectrum w = np.arange(0, 2 * zpd) / (2 * zpd) mapod = np.ones_like(data) mapod[..., 0:2 * zpd] = w data = np.roll(data * mapod, int(-zpd)) data = np.fft.rfft(data)[..., 0:size // 2] * np.exp(-1j * phase) # The imaginary part can be now discarder return data.real[..., ::-1] / 2. # ====================================================================================================================== # Public methods # ====================================================================================================================== def ifft(dataset, size=None, **kwargs): """ Apply a inverse fast fourier transform. For multidimensional NDDataset, the apodization is by default performed on the last dimension. The data in the last dimension MUST be in frequency (or without dimension) or an error is raised. To make direct Fourier transform, i.e., from frequency to time domain, use the `fft` transform. Parameters ---------- dataset : |NDDataset| The dataset on which to apply the fft transformation. size : int, optional Size of the transformed dataset dimension - a shorter parameter is `si`. by default, the size is the closest power of two greater than the data size. **kwargs : dict Other parameters (see other parameters). Returns ------- out Transformed |NDDataset|. Other Parameters ---------------- dim : str or int, optional, default='x'. Specify on which dimension to apply this method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, optional, default=False. True if we make the transform inplace. If False, the function return a new object See Also -------- fft : Direct Fourier transform. """ return fft(dataset, size=size, inv=True, **kwargs) def fft(dataset, size=None, sizeff=None, inv=False, ppm=True, **kwargs): """ Apply a complex fast fourier transform. For multidimensional NDDataset, the apodization is by default performed on the last dimension. The data in the last dimension MUST be in time-domain (or without dimension) or an error is raised. To make reverse Fourier transform, i.e., from frequency to time domain, use the `ifft` transform (or equivalently, the `inv=True` parameters. Parameters ---------- dataset : |NDDataset| The dataset on which to apply the fft transformation. size : int, optional Size of the transformed dataset dimension - a shorter parameter is `si`. by default, the size is the closest power of two greater than the data size. sizeff : int, optional The number of effective data point to take into account for the transformation. By default it is equal to the data size, but may be smaller. inv : bool, optional, default=False If True, an inverse Fourier transform is performed - size parameter is not taken into account. ppm : bool, optional, default=True If True, and data are from NMR, then a ppm scale is calculated instead of frequency. **kwargs : dict Other parameters (see other parameters). Returns ------- out Transformed |NDDataset|. Other Parameters ---------------- dim : str or int, optional, default='x'. Specify on which dimension to apply this method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, optional, default=False. True if we make the transform inplace. If False, the function return a new object tdeff : int, optional Alias of sizeff (specific to NMR). If both sizeff and tdeff are passed, sizeff has the priority. See Also -------- ifft : Inverse Fourier transform. """ # datatype is_nmr = dataset.origin.lower() in ["topspin", ] is_ir = dataset.origin.lower() in ["omnic", "opus"] # On which axis do we want to apply transform (get axis from arguments) dim = kwargs.pop('dim', kwargs.pop('axis', -1)) axis, dim = dataset.get_axis(dim, negative_axis=True) # output dataset inplace or not inplace = kwargs.pop('inplace', False) if not inplace: # default new = dataset.copy() # copy to be sure not to modify this dataset else: new = dataset # The last dimension is always the dimension on which we apply the fourier transform. # If needed, we swap the dimensions to be sure to be in this situation swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) # must be done in place swaped = True # Select the last coordinates x = new.coordset[dim] # Performs some dimentionality checking error = False if not inv and not x.unitless and not x.dimensionless and x.units.dimensionality != '[time]': error_('fft apply only to dimensions with [time] dimensionality or dimensionless coords\n' 'fft processing was thus cancelled') error = True elif inv and not x.unitless and x.units.dimensionality != '1/[time]' and not x.dimensionless: error_('ifft apply only to dimensions with [frequency] dimensionality or with ppm units ' 'or dimensionless coords.\n ifft processing was thus cancelled') error = True # Should not be masked elif new.is_masked: error_('current fft or ifft processing does not support masked data as input.\n processing was thus cancelled') error = True # Coordinates should be uniformly spaced (linear coordinate) if not x.linear: # try to linearize it x.linear = True if not x.linear: # linearization failed error = True if hasattr(x, '_use_time_axis'): x._use_time_axis = True # we need to havze dimentionless or time units if not error: # OK we can proceed # time domain size td = None if not inv: td = x.size # if no size (or si) parameter then use the size of the data (size not used for inverse transform if size is None or inv: size = kwargs.get('si', x.size) # we default to the closest power of two larger of the data size if is_nmr: size = largest_power_of_2(size) # do we have an effective td to apply tdeff = sizeff if tdeff is None: tdeff = kwargs.get("tdeff", td) if tdeff is None or tdeff < 5 or tdeff > size: tdeff = size # Eventually apply the effective size new[..., tdeff:] = 0. # Should we work on complex or hypercomplex data # interleaved is in case of >2D data ( # TODO: >D not yet implemented in ndcomplex.py iscomplex = False if axis == -1: iscomplex = new.is_complex if new.is_quaternion or new.is_interleaved: iscomplex = True # If we are in NMR we have an additional complication due to the mode # of acquisition (sequential mode when ['QSEQ','TPPI','STATES-TPPI']) encoding = 'undefined' if not inv and 'encoding' in new.meta: encoding = new.meta.encoding[-1] qsim = (encoding in ['QSIM', 'DQD']) qseq = ('QSEQ' in encoding) states = ('STATES' in encoding) echoanti = ('ECHO-ANTIECHO' in encoding) tppi = ('TPPI' in encoding) qf = ('QF' in encoding) zf_size(new, size=size, inplace=True) # Perform the fft if qsim: # F2 fourier transform data = _fft(new.data) elif qseq: raise NotImplementedError('QSEQ not yet implemented') elif states: data = _states_fft(new.data, tppi) elif tppi: data = _tppi_fft(new.data) elif echoanti: data = _echoanti_fft(new.data) elif qf: # we must perform a real fourier transform of a time domain dataset data = _qf_fft(new.data) elif iscomplex and inv: # We assume no special encoding for inverse complex fft transform data = _ifft(new.data) elif not iscomplex and not inv and is_ir: # transform interferogram data = _interferogram_fft(new.data) elif not iscomplex and inv: raise NotImplementedError('Inverse FFT for real dimension') else: raise NotImplementedError(f'{encoding} not yet implemented. We recommend you to put an issue on ' f'Github, so we will not forget to work on this!.') # We need here to create a new dataset with new shape and axis new._data = data new.mask = False # create new coordinates for the transformed data if is_nmr: sfo1 = new.meta.sfo1[-1] bf1 = new.meta.bf1[-1] sf = new.meta.sf[-1] sw = new.meta.sw_h[-1] if new.meta.nuc1 is not None: nuc1 = new.meta.nuc1[-1] regex = r"([^a-zA-Z]+)([a-zA-Z]+)" m = re.match(regex, nuc1) if m is not None: mass = m[1] name = m[2] nucleus = '^{' + mass + '}' + name else: nucleus = "" else: nucleus = "" else: sfo1 = 0 * ur.Hz bf1 = sfo1 dw = x.spacing if isinstance(dw, list): print() sw = 1 / 2 / dw sf = -sw / 2 size = size // 2 if not inv: # time to frequency sizem = max(size - 1, 1) deltaf = -sw / sizem first = sfo1 - sf - deltaf * sizem / 2. # newcoord = type(x)(np.arange(size) * deltaf + first) newcoord = LinearCoord.arange(size) * deltaf + first newcoord.show_datapoints = False newcoord.name = x.name new.title = 'intensity' if is_nmr: newcoord.title = f'${nucleus}$ frequency' newcoord.ito("Hz") elif is_ir: new._units = None newcoord.title = 'wavenumbers' newcoord.ito("cm^-1") else: newcoord.title = 'frequency' newcoord.ito("Hz") else: # frequency or ppm to time sw = abs(x.data[-1] - x.data[0]) if x.units == 'ppm': sw = bf1.to("Hz") * sw / 1.0e6 deltat = (1. / sw).to('us') newcoord = LinearCoord.arange(size) * deltat newcoord.name = x.name newcoord.title = 'time' newcoord.ito("us") if is_nmr and not inv: newcoord.meta.larmor = bf1 # needed for ppm transformation ppm = kwargs.get('ppm', True) if ppm: newcoord.ito('ppm') newcoord.title = fr"$\delta\ {nucleus}$" new.coordset[dim] = newcoord # update history s = 'ifft' if inv else 'fft' new.history = f'{s} applied on dimension {dim}' # PHASE ? iscomplex = (new.is_complex or new.is_quaternion) if iscomplex and not inv: # phase frequency domain # if some phase related metadata do not exist yet, initialize them new.meta.readonly = False if not new.meta.phased: new.meta.phased = [False] * new.ndim if not new.meta.phc0: new.meta.phc0 = [0] * new.ndim if not new.meta.phc1: new.meta.phc1 = [0] * new.ndim if not new.meta.exptc: new.meta.exptc = [0] * new.ndim if not new.meta.pivot: new.meta.pivot = [0] * new.ndim # applied the stored phases new.pk(inplace=True) new.meta.pivot[-1] = abs(new).coordmax(dim=dim) new.meta.readonly = True # restore original data order if it was swaped if swaped: new.swapdims(axis, -1, inplace=True) # must be done inplace return new ft = fft ift = ifft # Modulus Calculation @_units_agnostic_method def mc(dataset): """ Modulus calculation. Calculates sqrt(real^2 + imag^2) """ return np.sqrt(dataset.real ** 2 + dataset.imag ** 2) @_units_agnostic_method def ps(dataset): """ Power spectrum. Squared version. Calculated real^2+imag^2 """ return dataset.real ** 2 + dataset.imag ** 2 @_units_agnostic_method def ht(dataset, N=None): """ Hilbert transform. Reconstruct imaginary data via hilbert transform. Copied from NMRGlue (BSD3 licence) Parameters ---------- data : ndarrat Array of NMR data. N : int or None Number of Fourier components. Returns ------- ndata : ndarray NMR data which has been Hilvert transformed. """ # create an empty output array fac = N / dataset.shape[-1] z = np.empty(dataset.shape, dtype=(dataset.flat[0] + dataset.flat[1] * 1.j).dtype) if dataset.ndim == 1: z[:] = hilbert(dataset.real, N)[:dataset.shape[-1]] * fac else: for i, vec in enumerate(dataset): z[i] = hilbert(vec.real, N)[:dataset.shape[-1]] * fac # correct the real data as sometimes it changes z.real = dataset.real return z # ====================================================================================================================== if __name__ == '__main__': # pragma: no cover pass <file_sep>/docs/gettingstarted/overview.py # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.8.0 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] slideshow={"slide_type": "slide"} # # Overview # %% [markdown] # The purpose of this page is to give you some quick examples of what can be done with SpectroChemPy. # # See the [gallery of examples](generated/auto_examples/index.html) and consult the [user's guide]( # ../user/index.html) for more information on using SpectroChemPy # # Before using the package, we must load the **API # (Application Programming Interface)** # # The simplest way is to import all objects and methods at once into your # python namespace. The loading step may take several seconds due to the # large number of methods to be imported into the API namespace. # %% from spectrochempy import * # %% [markdown] # ## NDDataset, the main object # %% [markdown] # NDDataset is a python object, actually a container, which can represent most of your multidimensional spectroscopic # data. # # For instance, in the following we read data from a series of FTIR experiments, provided by the OMNIC software: # %% ds = read('irdata/nh4y-activation.spg') # %% [markdown] # ### Display dataset information # %% [markdown] # Short information # %% ds # %% [markdown] # Detailled information: # %% ds # %% [markdown] # ### Plotting a dataset # %% _ = ds.plot() # %% [markdown] # ### Slicing a dataset # %% region = ds[:, 4000.0:2000.0] _ = region.plot() # %% [markdown] # ### Maths on datasets # %% jupyter={"source_hidden": true} region.y -= region.y[0] # make y coordinate reative to the first point region.y.title = 'time of dehydratation' region -= region[-1] # suppress the last spectra to all _ = region.plot(colorbar=True) # %% [markdown] # ### Processing a dataset # %% [markdown] # We just give here few examples # %% [markdown] # #### Smoothing # %% jupyter={"source_hidden": true} smoothed = region.smooth(window_length=51, window='hanning') _ = smoothed.plot(colormap='magma') # %% [markdown] # #### Baseline correction # %% jupyter={"source_hidden": true} region = ds[:, 4000.0:2000.0] smoothed = region.smooth(window_length=51, window='hanning') blc = BaselineCorrection(smoothed) basc = blc.compute([2000., 2300.], [3800., 3900.], method='multivariate', interpolation='pchip', npc=5) # %% jupyter={"source_hidden": true} _ = basc.plot() # %% [markdown] # ### Analyis # # #### IRIS processing # %% jupyter={"source_hidden": true} ds = NDDataset.read_omnic('irdata/CO@Mo_Al2O3.SPG')[:, 2250.:1950.] pressure = [0.00300, 0.00400, 0.00900, 0.01400, 0.02100, 0.02600, 0.03600, 0.05100, 0.09300, 0.15000, 0.20300, 0.30000, 0.40400, 0.50300, 0.60200, 0.70200, 0.80100, 0.90500, 1.00400] ds.y = Coord(pressure, title='Pressure', units='torr') _ = ds.plot(colormap='magma') # %% jupyter={"source_hidden": true} param = {'epsRange': [-8, -1, 50], 'lambdaRange': [-10, 1, 12], 'kernel': 'langmuir'} iris = IRIS(ds, param, verbose=False) _ = iris.plotdistribution(-7, colormap='magma') # %% <file_sep>/tests/test_analysis/test_pca.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Tests for the PCA module """ import pytest import numpy as np from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.analysis.pca import PCA from spectrochempy.utils import MASKED, show from spectrochempy.utils.testing import assert_array_almost_equal HAS_SCIKITLEARN = False try: from sklearn.decomposition import PCA as sklPCA HAS_SCIKITLEARN = True except ImportError: pass # test pca # --------- def test_pca(): dataset = NDDataset.read('irdata/nh4y-activation.spg') # with masks dataset[:, 1240.0:920.0] = MASKED # do not forget to use float in slicing pca = PCA(dataset) pca.printev(n_pc=5) assert str(pca)[:3] == '\nPC' pca.screeplot(n_pc=0.999) pca.screeplot(n_pc='auto') pca.scoreplot((1, 2)) pca.scoreplot(1, 2, 3) show() @pytest.mark.skipif(not HAS_SCIKITLEARN, reason="scikit-learn library not loaded") def test_compare_scikit_learn(): X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) pcas = sklPCA(n_components=2) pcas.fit(X) pca = PCA(NDDataset(X)) pca.printev(n_pc=2) assert_array_almost_equal(pca.sv.data, pcas.singular_values_) assert_array_almost_equal(pca.ev_ratio.data, pcas.explained_variance_ratio_ * 100.) dataset = NDDataset.read('irdata/nh4y-activation.spg') X = dataset.data pcas = sklPCA(n_components=5) pcas.fit(X) dataset = X.copy() pca = PCA(NDDataset(dataset)) pca.printev(n_pc=5) assert_array_almost_equal(pca.sv.data[:5], pcas.singular_values_[:5], 4) assert_array_almost_equal(pca.ev_ratio.data[:5], pcas.explained_variance_ratio_[:5] * 100., 4) <file_sep>/spectrochempy/core/writers/exporter.py # -*- coding: utf-8 -*- # # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ===================================================================================================================== # """ This module define a generic class to import files and contents. """ __all__ = ['write'] __dataset_methods__ = __all__ from traitlets import HasTraits, Any from spectrochempy.utils import pathclean, check_filename_to_save, patterns # ---------------------------------------------------------------------------------------------------------------------- class Exporter(HasTraits): # Exporter class object = Any def __init__(self): FILETYPES = [ ('scp', 'SpectroChemPy files (*.scp)'), ('labspec', 'LABSPEC exported files (*.txt)'), ('matlab', 'MATLAB files (*.mat)'), ('dso', 'Data Set Object files (*.dso)'), ('jcamp', 'JCAMP-DX files (*.jdx *dx)'), ('csv', 'CSV files (*.csv)'), ('excel', 'Microsoft Excel files (*.xls)'), ] self.filetypes = dict(FILETYPES) self.protocols = {} for protocol, filter in self.filetypes.items(): for s in patterns(filter, allcase=False): self.protocols[s[1:]] = protocol # .................................................................................................................. def __call__(self, *args, **kwargs): args = self._setup_object(*args) try: if 'filetypes' not in kwargs: kwargs['filetypes'] = list(self.filetypes.values()) if args and args[0] is not None: # filename protocol = self.protocols[pathclean(args[0]).suffix] kwargs['filetypes'] = [self.filetypes[protocol]] filename = check_filename_to_save(self.object, *args, **kwargs) if kwargs.get('suffix', ''): filename = filename.with_suffix(kwargs.get('suffix', '')) protocol = self.protocols[filename.suffix] write_ = getattr(self, f"_write_{protocol}") write_(self.object, filename, **kwargs) return filename except Exception as e: raise e # .................................................................................................................. def _setup_object(self, *args): # check if the first argument is an instance of NDDataset or Project args = list(args) if args and hasattr(args[0], 'implements') and args[0].implements() in ['NDDataset']: # the first arg is an instance of NDDataset self.object = args.pop(0) else: raise TypeError('the API write method needs a NDDataset object as the first argument') return args # ...................................................................................................................... def exportermethod(func): # Decorator setattr(Exporter, func.__name__, staticmethod(func)) return func # ---------------------------------------------------------------------------------------------------------------------- # Generic Read function # ---------------------------------------------------------------------------------------------------------------------- def write(dataset, filename=None, **kwargs): """ Write the current dataset. Parameters ---------- dataset : |NDDataset| Dataset to write. filename : str or pathlib objet, optional If not provided, a dialog is opened to select a file for writing. **kwargs : dict See other parameters. Returns ------- output_path Path of the output file. Other Parameters ---------------- protocol : {'scp', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for writing. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional Where to write the specified `filename`. If not specified, write in the current directory. description: str, optional A Custom description. csv_delimiter : str, optional Set the column delimiter in CSV file. By default it is the one set in SpectroChemPy `Preferences`. See Also -------- save : Generic function for saving a NDDataset in SpectroChemPy format. Examples --------- write a dataset (providing a windows type filename relative to the default ``Datadir``) >>> import spectrochempy as scp >>> nd = scp.read_opus('irdata/OPUS') >>> f = nd.write('opus.scp') >>> f.name 'opus.scp' """ exporter = Exporter() return exporter(dataset, filename, **kwargs) # ...................................................................................................................... @exportermethod def _write_scp(*args, **kwargs): dataset, filename = args dataset.filename = filename return dataset.dump(filename, **kwargs) # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/tests/test_dataset/test_ndcoordset.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from copy import copy import numpy as np import pytest from spectrochempy.core.dataset.ndarray import NDArray from spectrochempy.core.dataset.coord import Coord, LinearCoord from spectrochempy.core.dataset.coordset import CoordSet from spectrochempy.units import ur, DimensionalityError # ====================================================================================================================== # CoordSet # ====================================================================================================================== def test_coordset_init(coord0, coord1, coord2): coord3 = coord2.copy() coord3.title = 'titi' coordsa = CoordSet(coord0, coord3, coord2) # First syntax assert coordsa.names == ['x', 'y', 'z'] # coordinates are sorted in the coordset coordsb = CoordSet((coord0, coord3, coord2)) # second syntax with a tuple of coordinates assert coordsb.names == ['x', 'y', 'z'] # but warning coordsa1 = CoordSet( [coord0[:3], coord3[:3], coord2[:3]]) # A list means that it is a sub-coordset (different meaning) assert coordsa1.names == ['x'] assert coordsa1.x.names == ['_1', '_2', '_3'] coordsc = CoordSet(x=coord2, y=coord3, z=coord0) # third syntax assert coordsc.names == ['x', 'y', 'z'] coordsc1 = CoordSet({'x': coord2, 'y': coord3, 'z': coord0}) assert coordsc1.names == ['x', 'y', 'z'] coordsd = CoordSet(coord3, x=coord2, y=coord3, z=coord0) # conflict (keyw replace args) assert coordsa == coordsb assert coordsa == coordsc assert coordsa == coordsd assert coordsa == coordsc1 c = coordsa["x"] assert c == coord2 c = coordsa["y"] assert c == coord3 assert coordsa['wavenumber'] == coord0 coord4 = copy(coord2) coordsc = CoordSet([coord1[:3], coord2[:3], coord4[:3]]) assert coordsa != coordsc coordse = CoordSet(x=(coord1[:3], coord2[:3]), y=coord3, z=coord0) # coordset as coordinates assert coordse['x'].titles == CoordSet(coord1, coord2, sorted=False).titles assert coordse['x_2'] == coord2 assert coordse['titi'] == coord3 # iteration for coord in coordsa: assert isinstance(coord, Coord) for i, coord in enumerate(coordsa): assert isinstance(coord, Coord) assert repr(coord0) == 'Coord: [float64] cm^-1 (size: 10)' coords = CoordSet(coord0.copy(), coord0) assert repr(coords).startswith('CoordSet: [x:wavenumber, y:wavenumber]') with pytest.raises(ValueError): coords = CoordSet(2, 3) # Coord in CoordSet cannot be simple scalar coords = CoordSet(x=coord2, y=coord3, z=None) assert coords.names == ['x', 'y', 'z'] assert coords.z.is_empty coords = CoordSet(x=coord2, y=coord3, z=np.array((1, 2, 3))) assert coords.names == ['x', 'y', 'z'] assert coords.z.size == 3 with pytest.raises(KeyError): coords = CoordSet(x=coord2, y=coord3, fx=np.array((1, 2, 3))) # wrong key (must be a single char) with pytest.raises(ValueError): coords = CoordSet(x=coord2, y=coord3, z=3) # wrong coordinate value # set a coordset from another one coords = CoordSet(**coordse) assert coordse.names == ['x', 'y', 'z'] assert coords.names == ['x', 'y', 'z'] assert coords == coordse # not recommended coords2 = CoordSet(*coordse) # loose the names so the ordering may be different assert coords2.names == ['x', 'y', 'z'] assert coords.x == coords2.z def test_coordset_multicoord_for_a_single_dim(): # normal coord (single numerical array for a axis) coord1 = NDArray(data=np.linspace(1000., 4000., 5), labels='a b c d e'.split(), mask=None, units='cm^1', title='wavelengths') coord0 = NDArray(data=np.linspace(20, 500, 5), labels='very low-low-normal-high-very high'.split('-'), mask=None, units='K', title='temperature') # pass as a list of coord -> this become a subcoordset coordsa = CoordSet([coord1, coord0]) assert repr( coordsa) == 'CoordSet: [x:[_1:wavelengths, _2:temperature]]' # note the internal coordinates are not sorted assert not coordsa.is_same_dim assert coordsa.x.is_same_dim coordsb = coordsa.x # try to pass arguments, each being an coord coordsc = CoordSet(coord1, coord0) assert not coordsc.is_same_dim assert repr(coordsc) == 'CoordSet: [x:temperature, y:wavelengths]' # try to pass arguments where each are a coords coordsd = CoordSet(coordsa.x, coordsc) assert repr(coordsd) == "CoordSet: [x:[_1:temperature, _2:wavelengths], y:[_1:wavelengths, _2:temperature]]" assert not coordsd.is_same_dim assert np.all([item.is_same_dim for item in coordsd]) coordse = CoordSet(coordsb, coord1) assert repr(coordse) == "CoordSet: [x:wavelengths, y:[_1:wavelengths, _2:temperature]]" assert not coordse.is_same_dim assert coordse('y').is_same_dim co = coordse('x') assert isinstance(co, Coord) co = coordse('y') assert isinstance(co, CoordSet) assert co.name == 'y' assert co.names == ['_1', '_2'] assert co._1 == coord1 # no reordering for the sub-coordset co = coordse[-1:] assert isinstance(co, CoordSet) assert co[0].name == 'y' # should keep the original name (solved) assert co[0]["_1"] == coord1 def test_coordset_call(coord0, coord1): coordsa = CoordSet(coord0, coord1) assert str(coordsa) == 'CoordSet: [x:time-on-stream, y:wavenumber]' a = coordsa(1, 0) assert a == coordsa b = coordsa(1) assert b == coord0 # reordering c = coordsa('x') assert c == coord1 d = coordsa('time-on-stream') assert d == coord1 with pytest.raises(KeyError): coordsa('x_a') # do not exit coordsa('y_a') def test_coordset_get(coord0, coord1, coord2): coords = CoordSet(coord2, [coord0, coord0.copy()], coord1) coord = coords['temperature'] assert str(coord) == 'Coord: [float64] K (size: 3)' assert coord.name == 'z' coord = coords['wavenumber'] assert coord.name == '_1' coord = coords['y_2'] assert coord.name == '_2' coord = coords['_1'] assert coord.name == '_1' def test_coordset_del(coord0, coord1, coord2): coords = CoordSet(coord2, [coord0, coord0.copy()], coord1) assert str(coords) == repr( coords) == 'CoordSet: [x:time-on-stream, y:[_1:wavenumber, _2:wavenumber], z:temperature]' del coords['temperature'] assert str(coords) == repr(coords) == 'CoordSet: [x:time-on-stream, y:[_1:wavenumber, _2:wavenumber]]' del coords.y['wavenumber'] assert str(coords) == repr(coords) == 'CoordSet: [x:time-on-stream, y:[_2:wavenumber]]' coords = CoordSet(coord2, [coord0, coord0.copy()], coord1) del coords['wavenumber'] assert str(coords) == repr(coords) == 'CoordSet: [x:time-on-stream, y:[_2:wavenumber], z:temperature]' coords = CoordSet(coord2, [coord0, coord0.copy()], coord1) del coords.y_2 assert str(coords) == repr(coords) == 'CoordSet: [x:time-on-stream, y:[_1:wavenumber], z:temperature]' coords = CoordSet(coord2, [coord0, coord0.copy()], coord1) del coords.y._1 assert str(coords) == repr(coords) == 'CoordSet: [x:time-on-stream, y:[_2:wavenumber], z:temperature]' def test_coordset_copy(coord0, coord1): coord2 = LinearCoord.linspace(200., 300., 3, units="K", title='temperature') coordsa = CoordSet(coord0, coord1, coord2) coordsb = coordsa.copy() assert coordsa == coordsb assert coordsa is not coordsb assert coordsa(1) == coordsb(1) assert coordsa(1).name == coordsb(1).name # copy coords = CoordSet(coord0, coord0.copy()) coords1 = coords[:] assert coords is not coords1 import copy coords2 = copy.deepcopy(coords) assert coords == coords2 def test_coordset_implements(coord0, coord1): coordsa = CoordSet(coord0, coord1) assert coordsa.implements('CoordSet') assert coordsa.implements() == 'CoordSet' def test_coordset_sizes(coord0, coord1): coords = CoordSet(coord0, coord1) assert coords.sizes == [coords.x.size, coords.y.size] == [coord1.size, coord0.size] coords = CoordSet([coord0, coord0.copy()], coord1) assert coords.sizes == [coords.x.size, coords.y.size] == [coord1.size, coord0.size] assert coord0.size != coord0[:7].size with pytest.raises(ValueError): coords = CoordSet([coord0, coord0[:7]], coord1) def test_coordset_update(coord0, coord1): coords = CoordSet(coord0, coord1) coords.update(x=coord0) assert coords[1] == coords[0] == coord0 def test_coordset_str_repr(coord0, coord1, coord2): coords = CoordSet(coord2, [coord0, coord0.copy()], coord1) assert str(coords) == repr( coords) == 'CoordSet: [x:time-on-stream, y:[_1:wavenumber, _2:wavenumber], z:temperature]' assert repr(coords) == str(coords) def test_coordset_set(coord0, coord1, coord2): coords = CoordSet(coord2, [coord0, coord0.copy()], coord1) assert str(coords) == repr( coords) == 'CoordSet: [x:time-on-stream, y:[_1:wavenumber, _2:wavenumber], z:temperature]' coords.set_titles('time', 'dddd', 'celcius') assert str(coords) == 'CoordSet: [x:time, y:[_1:wavenumber, _2:wavenumber], z:celcius]' coords.set_titles(x='time', z='celcius', y_1='length') assert str(coords) == repr(coords) == 'CoordSet: [x:time, y:[_1:length, _2:wavenumber], z:celcius]' coords.set_titles('t', ('l', 'g'), x='x') assert str(coords) == 'CoordSet: [x:x, y:[_1:l, _2:g], z:celcius]' coords.set_titles(('t', ('l', 'g')), z='z') assert str(coords) == 'CoordSet: [x:t, y:[_1:l, _2:g], z:z]' coords.set_titles() # nothing happens assert str(coords) == 'CoordSet: [x:t, y:[_1:l, _2:g], z:z]' with pytest.raises(DimensionalityError): # because units doesn't match coords.set_units(('km/s', ('s', 'm')), z='radian') coords.set_units(('km/s', ('s', 'm')), z='radian', force=True) # force change assert str(coords) == 'CoordSet: [x:t, y:[_1:l, _2:wavelength], z:z]' assert coords.y_1.units == ur('s') # set item coords['z'] = coord2 assert str(coords) == 'CoordSet: [x:t, y:[_1:l, _2:wavelength], z:temperature]' coords['temperature'] = coord1 assert str(coords) == 'CoordSet: [x:t, y:[_1:l, _2:wavelength], z:time-on-stream]' coords['y_2'] = coord2 assert str(coords) == 'CoordSet: [x:t, y:[_1:l, _2:temperature], z:time-on-stream]' coords['_1'] = coord2 assert str(coords) == 'CoordSet: [x:t, y:[_1:temperature, _2:temperature], z:time-on-stream]' coords['t'] = coord2 assert str(coords) == 'CoordSet: [x:temperature, y:[_1:temperature, _2:temperature], z:time-on-stream]' coord2.title = 'zaza' coords['temperature'] = coord2 assert str(coords) == 'CoordSet: [x:zaza, y:[_1:temperature, _2:temperature], z:time-on-stream]' coords['temperature'] = coord2 assert str(coords) == 'CoordSet: [x:zaza, y:[_1:zaza, _2:temperature], z:time-on-stream]' coords.set(coord1, coord0, coord2) assert str(coords) == 'CoordSet: [x:zaza, y:wavenumber, z:time-on-stream]' coords.z = coord0 assert str(coords) == 'CoordSet: [x:zaza, y:wavenumber, z:wavenumber]' coords.zaza = coord0 assert str(coords) == 'CoordSet: [x:wavenumber, y:wavenumber, z:wavenumber]' coords.wavenumber = coord2 assert str(coords) == 'CoordSet: [x:zaza, y:wavenumber, z:wavenumber]' <file_sep>/spectrochempy/core/readers/readjdx.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module to extend NDDataset with the import methods. """ __all__ = ['read_jcamp', 'read_jdx', 'read_dx'] __dataset_methods__ = __all__ import io import re from datetime import datetime, timezone import numpy as np from spectrochempy.core import debug_ from spectrochempy.core.dataset.coord import Coord from spectrochempy.core.readers.importer import Importer, importermethod from spectrochempy.utils.exceptions import deprecated # ====================================================================================================================== # Public functions # ====================================================================================================================== def read_jcamp(*paths, **kwargs): """ Open Infrared JCAMP-DX files with extension ``.jdx`` or ``.dx``. Limited to AFFN encoding (see <NAME> and <NAME>, JCAMP-DX: A Standard Form for Exchange of Infrared Spectra in Computer Readable Form, Appl. Spec., 1988, 1, 151–162. doi:10.1366/0003702884428734.) Parameters ---------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read_jcamp |NDDataset| or list of |NDDataset|. Other Parameters ---------------- protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description: str, optional A Custom description. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True). recursive : bool, optional Read also in subfolders. (default=False). See Also --------- read : Generic read method. read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. """ kwargs['filetypes'] = ['JCAMP-DX files (*.jdx *.dx)'] kwargs['protocol'] = ['jcamp'] importer = Importer() return importer(*paths, **kwargs) @deprecated("read_jdx reading method is deprecated and may be removed in next versions " "- use read_jcamp instead") def read_jdx(*args, **kwargs): return read_jcamp(*args, **kwargs) @deprecated("read_dx reading method is deprecated and may be removed in next versions " "- use read_jcamp instead") def read_dx(*args, **kwargs): return read_jcamp(*args, **kwargs) # ====================================================================================================================== # private functions # ====================================================================================================================== @importermethod def _read_jdx(*args, **kwargs): debug_("reading a jcamp-dx file") # read jdx file dataset, filename = args content = kwargs.get('content', None) sortbydate = kwargs.pop("sortbydate", True) if content is not None: fid = io.StringIO(content.decode("utf-8")) else: fid = open(filename, 'r') # Read header of outer Block # .................................................................................................................. keyword = '' while keyword != '##TITLE': keyword, text = _readl(fid) if keyword != 'EOF': jdx_title = text else: raise ValueError('No ##TITLE LR in outer block header') while (keyword != '##DATA TYPE') and (keyword != '##DATATYPE'): keyword, text = _readl(fid) if keyword != 'EOF': jdx_data_type = text else: raise ValueError('No ##DATA TYPE LR in outer block header') if jdx_data_type == 'LINK': while keyword != '##BLOCKS': keyword, text = _readl(fid) nspec = int(text) elif jdx_data_type.replace(' ', '') == 'INFRAREDSPECTRUM': nspec = 1 else: raise ValueError('DATA TYPE must be LINK or INFRARED SPECTRUM') # Create variables # .................................................................................................................. xaxis = np.array([]) data = np.array([]) alltitles, alltimestamps, alldates, xunits, yunits = [], [], [], [], [] nx, firstx, lastx = np.zeros(nspec, 'int'), np.zeros(nspec, 'float'), np.zeros(nspec, 'float') # Read the spectra # .................................................................................................................. for i in range(nspec): # Reset variables keyword = '' # (year, month,...) must be reset at each spectrum because labels "time" # and "longdate" are not required in JDX file [year, month, day, hour, minute, second] = '', '', '', '', '', '' # Read JDX file for spectrum n° i while keyword != '##END': keyword, text = _readl(fid) if keyword in ['##ORIGIN', '##OWNER', '##JCAMP-DX']: continue elif keyword == '##TITLE': # Add the title of the spectrum in the list alltitles alltitles.append(text) elif keyword == '##LONGDATE': [year, month, day] = text.split('/') elif keyword == '##TIME': [hour, minute, second] = re.split(r'[:.]', text) elif keyword == '##XUNITS': xunits.append(text) elif keyword == '##YUNITS': yunits.append(text) elif keyword == '##FIRSTX': firstx[i] = float(text) elif keyword == '##LASTX': lastx[i] = float(text) elif keyword == '##XFACTOR': xfactor = float(text) elif keyword == '##YFACTOR': yfactor = float(text) elif keyword == '##NPOINTS': nx[i] = float(text) elif keyword == '##XYDATA': # Read the intensities allintensities = [] while keyword != '##END': keyword, text = _readl(fid) # for each line, get all the values exept the first one (first value = wavenumber) intensities = list(filter(None, text.split(' ')[1:])) if len(intensities) > 0: allintensities += intensities spectra = np.array([allintensities]) # convert allintensities into an array spectra[spectra == '?'] = 'nan' # deals with missing or out of range intensity values spectra = spectra.astype(np.float32) spectra *= yfactor # add spectra in "data" matrix if not data.size: data = spectra else: data = np.concatenate((data, spectra), 0) # Check "firstx", "lastx" and "nx" if firstx[i] != 0 and lastx[i] != 0 and nx[i] != 0: if not xaxis.size: # Creation of xaxis if it doesn't exist yet xaxis = np.linspace(firstx[0], lastx[0], nx[0]) xaxis = np.around((xaxis * xfactor), 3) else: # Check the consistency of xaxis if nx[i] - nx[i - 1] != 0: raise ValueError('Inconsistent data set: number of wavenumber per spectrum should be identical') elif firstx[i] - firstx[i - 1] != 0: raise ValueError('Inconsistent data set: the x axis should start at same value') elif lastx[i] - lastx[i - 1] != 0: raise ValueError('Inconsistent data set: the x axis should end at same value') else: raise ValueError('##FIRST, ##LASTX or ##NPOINTS are unusuable in the spectrum n°', i + 1) # Creation of the acquisition date if (year != '' and month != '' and day != '' and hour != '' and minute != '' and second != ''): date = datetime(int(year), int(month), int(day), int(hour), int(minute), int(second), tzinfo=timezone.utc) timestamp = date.timestamp() # Transform back to timestamp for storage in the Coord object # use datetime.fromtimestamp(d, timezone.utc)) # to transform back to datetime object else: timestamp = date = None # Todo: cases where incomplete date and/or time info alltimestamps.append(timestamp) alldates.append(date) # Check the consistency of xunits and yunits if i > 0: if yunits[i] != yunits[i - 1]: raise ValueError(f'##YUNITS should be the same for all spectra (check spectrum n°{i + 1}') elif xunits[i] != xunits[i - 1]: raise ValueError(f'##XUNITS should be the same for all spectra (check spectrum n°{i + 1}') # Determine xaxis name **************************************************** if xunits[0].strip() == '1/CM': axisname = 'wavenumbers' axisunit = 'cm^-1' elif xunits[0].strip() == 'MICROMETERS': axisname = 'wavelength' axisunit = 'um' elif xunits[0].strip() == 'NANOMETERS': axisname = 'wavelength' axisunit = 'nm' elif xunits[0].strip() == 'SECONDS': axisname = 'time' axisunit = 's' elif xunits[0].strip() == 'ARBITRARY UNITS': axisname = 'arbitrary unit' axisunit = None else: axisname = '' axisunit = '' fid.close() dataset.data = data dataset.name = jdx_title if yunits[0].strip() == 'ABSORBANCE': dataset.units = 'absorbance' dataset.title = 'absorbance' elif yunits[0].strip() == 'TRANSMITTANCE': # TODO: This units not in pint. Add this dataset.title = 'transmittance' # now add coordinates _x = Coord(xaxis, title=axisname, units=axisunit) if jdx_data_type == 'LINK': _y = Coord(alltimestamps, title='Acquisition timestamp (GMT)', units='s', labels=(alldates, alltitles)) dataset.set_coordset(y=_y, x=_x) else: _y = Coord() dataset.set_coordset(y=_y, x=_x) # Set origin, description and history dataset.origin = "omnic" dataset.description = "Dataset from jdx: '{0}'".format(jdx_title) dataset.history = str(datetime.now(timezone.utc)) + ':imported from jdx file \n' if sortbydate: dataset.sort(dim='x', inplace=True) dataset.history = str(datetime.now(timezone.utc)) + ':sorted by date\n' # Todo: make sure that the lowest index correspond to the largest wavenumber # for compatibility with dataset created by read_omnic: # Set the NDDataset date dataset._date = datetime.now(timezone.utc) dataset._modified = dataset.date return dataset # ...................................................................................................................... @importermethod def _read_dx(*args, **kwargs): return _read_jdx(*args, **kwargs) # ...................................................................................................................... def _readl(fid): line = fid.readline() if not line: return 'EOF', '' line = line.strip(' \n') # remove newline character if line[0:2] == '##': # if line starts with "##" if line[0:5] == '##END': # END KEYWORD, no text keyword = '##END' text = '' else: # keyword + text keyword, text = line.split('=') else: keyword = '' text = line.strip() return keyword, text # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/.ci/scripts/conda-upload.sh #!/usr/bin/env bash ## adapted on https://gist.github.com/zshaheen/fe76d1507839ed6fbfbccef6b9c13ed9 ## Show command and exit immediately if a command exits with a non-zero status. set -ex ## Settings (we build essentially a noarch package PKG_NAME=spectrochempy OS=noarch ## get version string from setuptools_scm PVS="$(python setup.py --version)" echo "Current version string = $PVS" ## Extract components IFS=$"+" read -ra arr <<< "$PVS" ## latest version string LATEST="${arr[0]}" IFS=$"." read -ra tag <<< "$LATEST"; DEVSTRING="${tag[3]}" VERSION="${tag[0]}.${tag[1]}.${tag[2]}" if [[ -z $DEVSTRING ]]; then DEVSTRING="stable" fi PKG_NAME_VERSION="$PKG_NAME-$VERSION-$DEVSTRING.tar.bz2" export VERSION=$VERSION export DEVSTRING=$DEVSTRING export CONDA_BLD_PATH="$HOME/conda-bld" mkdir -p "$CONDA_BLD_PATH" ## configure conda conda update -q -n base conda conda config -q --set anaconda_upload no conda config -q --set always_yes yes conda config -q --add channels conda-forge conda config -q --add channels spectrocat conda config -q --set channel_priority flexible PKG_FILE="$CONDA_BLD_PATH/$OS/$PKG_NAME_VERSION" echo "---> Building $PKG_FILE using mamba as a solver" conda mambabuild conda echo "---> Uploading $PKG_FILE" if [[ $TRAVIS_BRANCH == "master" ]]; then ## We build the current master branch (i.e.the latest development version) ## This is a "dev" version if [[ $TRAVIS_PULL_REQUEST == false ]]; then anaconda -t "$CONDA_UPLOAD_TOKEN" upload --force -u "$ANACONDA_USER" -l dev "$PKG_FILE"; fi; elif [[ $TRAVIS_BRANCH == "develop" ]]; then ## We build the a test version (i.e.the latest development version) ## This is a "test" version if [[ $TRAVIS_PULL_REQUEST == false ]]; then anaconda -t "$CONDA_UPLOAD_TOKEN" upload --force -u "$ANACONDA_USER" -l test "$PKG_FILE"; fi; elif [[ $TRAVIS_BRANCH == "$TRAVIS_TAG" ]]; then ## This is a "main" release if [[ $TRAVIS_PULL_REQUEST == false ]]; then anaconda -t "$CONDA_UPLOAD_TOKEN" upload --force -u "$ANACONDA_USER" "$PKG_FILE"; fi; fi # <file_sep>/tests/test_analysis/test_simplisma.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.analysis.simplisma import SIMPLISMA def test_simplisma(): print('') data = NDDataset.read_matlab(os.path.join('matlabdata', 'als2004dataset.MAT'), merge=False) print('Dataset (Jaumot et al., Chemometr. Intell. Lab. 76 (2005) 101-110)):') print('') for mat in data: print(' ' + mat.name, str(mat.shape)) ds = data[0] print('\n test simplisma on {}\n'.format(ds.name)) pure = SIMPLISMA(ds, n_pc=20, tol=0.2, noise=3, verbose=True) pure.C.T.plot() pure.St.plot() pure.plotmerit() assert '3 29 29.0 0.0072 0.9981' in pure.logs <file_sep>/docs/userguide/analysis/analysis.rst .. _userguide.analysis: Analysis ********** Below you will find some tutorials on analysis process. .. note:: this part is under work and for now very limited. We are working to improve this .. toctree:: :glob: :maxdepth: 2 peak_finding peak_integration mcr_als <file_sep>/spectrochempy/core/readers/readopus.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module extend NDDataset with the import method for OPUS generated data files. """ __all__ = ['read_opus'] __dataset_methods__ = __all__ import io import numpy as np from datetime import datetime, timezone, timedelta from brukeropusreader.opus_parser import parse_data, parse_meta from spectrochempy.core.dataset.coord import LinearCoord, Coord from spectrochempy.core.readers.importer import Importer, importermethod from spectrochempy.core import debug_ # ====================================================================================================================== # Public functions # ====================================================================================================================== def read_opus(*paths, **kwargs): """ Open Bruker OPUS file(s). Eventually group them in a single dataset. Only Absorbance spectra are extracted ("AB" field). Returns an error if dimensions are incompatibles. Parameters ----------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read_opus The dataset or a list of dataset corresponding to a (set of) OPUS file(s). Other Parameters ----------------- protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description: str, optional A Custom description. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True). recursive : bool, optional Read also in subfolders. (default=False). See Also -------- read : Generic read method. read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_labspec : Read Raman LABSPEC spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. Examples --------- Reading a single OPUS file (providing a windows type filename relative to the default ``Datadir``) >>> import spectrochempy as scp >>> scp.read_opus('irdata\\\\OPUS\\\\test.0000') NDDataset: [float64] a.u. (shape: (y:1, x:2567)) Reading a single OPUS file (providing a unix/python type filename relative to the default ``Datadir``) Note that here read_opus is called as a classmethod of the NDDataset class >>> scp.NDDataset.read_opus('irdata/OPUS/test.0000') NDDataset: [float64] a.u. (shape: (y:1, x:2567)) Single file specified with pathlib.Path object >>> from pathlib import Path >>> folder = Path('irdata/OPUS') >>> p = folder / 'test.0000' >>> scp.read_opus(p) NDDataset: [float64] a.u. (shape: (y:1, x:2567)) Multiple files not merged (return a list of datasets). Note that a directory is specified >>> le = scp.read_opus('test.0000', 'test.0001', 'test.0002', directory='irdata/OPUS') >>> len(le) 3 >>> le[0] NDDataset: [float64] a.u. (shape: (y:1, x:2567)) Multiple files merged as the `merge` keyword is set to true >>> scp.read_opus('test.0000', 'test.0001', 'test.0002', directory='irdata/OPUS', merge=True) NDDataset: [float64] a.u. (shape: (y:3, x:2567)) Multiple files to merge : they are passed as a list instead of using the keyword `merge` >>> scp.read_opus(['test.0000', 'test.0001', 'test.0002'], directory='irdata/OPUS') NDDataset: [float64] a.u. (shape: (y:3, x:2567)) Multiple files not merged : they are passed as a list but `merge` is set to false >>> le = scp.read_opus(['test.0000', 'test.0001', 'test.0002'], directory='irdata/OPUS', merge=False) >>> len(le) 3 Read without a filename. This has the effect of opening a dialog for file(s) selection >>> nd = scp.read_opus() Read in a directory (assume that only OPUS files are present in the directory (else we must use the generic `read` function instead) >>> le = scp.read_opus(directory='irdata/OPUS') >>> len(le) 4 Again we can use merge to stack all 4 spectra if thet have compatible dimensions. >>> scp.read_opus(directory='irdata/OPUS', merge=True) NDDataset: [float64] a.u. (shape: (y:4, x:2567)) """ kwargs['filetypes'] = ['Bruker OPUS files (*.[0-9]*)'] kwargs['protocol'] = ['opus'] importer = Importer() return importer(*paths, **kwargs) # ====================================================================================================================== # Private Functions # ====================================================================================================================== # ...................................................................................................................... @importermethod def _read_opus(*args, **kwargs): debug_('Bruker OPUS import') dataset, filename = args content = kwargs.get('content', None) if content: fid = io.BytesIO(content) else: fid = open(filename, 'rb') opus_data = _read_data(fid) # data try: npt = opus_data['AB Data Parameter']['NPT'] data = opus_data["AB"][:npt] dataset.data = np.array(data[np.newaxis], dtype='float32') except KeyError: raise IOError(f"{filename} is not an Absorbance spectrum. It cannot be read with the `read_opus` import method") # xaxis fxv = opus_data['AB Data Parameter']['FXV'] lxv = opus_data['AB Data Parameter']['LXV'] # xdata = linspace(fxv, lxv, npt) xaxis = LinearCoord.linspace(fxv, lxv, npt, title='Wavenumbers', units='cm^-1') # yaxis name = opus_data["Sample"]['SNM'] acqdate = opus_data["AB Data Parameter"]["DAT"] acqtime = opus_data["AB Data Parameter"]["TIM"] gmt_offset_hour = float(acqtime.split('GMT')[1].split(')')[0]) date_time = datetime.strptime(acqdate + '_' + acqtime.split()[0], '%d/%m/%Y_%H:%M:%S.%f') utc_dt = date_time - timedelta(hours=gmt_offset_hour) utc_dt = utc_dt.replace(tzinfo=timezone.utc) timestamp = utc_dt.timestamp() yaxis = Coord([timestamp], title='Acquisition timestamp (GMT)', units='s', labels=([utc_dt], [name])) # set dataset's Coordset dataset.set_coordset(y=yaxis, x=xaxis) dataset.units = 'absorbance' dataset.title = 'Absorbance' # Set name, origin, description and history dataset.name = filename.name dataset.origin = "opus" dataset.description = 'Dataset from opus files. \n' dataset.history = str(datetime.now(timezone.utc)) + ': import from opus files \n' dataset._date = datetime.now(timezone.utc) dataset._modified = dataset.date return dataset # ...................................................................................................................... def _read_data(fid): data = fid.read() meta_data = parse_meta(data) opus_data = parse_data(data, meta_data) return opus_data # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/spectrochempy/core/writers/writematlab.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Plugin module to extend NDDataset with a JCAMP-DX export method. """ from spectrochempy.core.writers.exporter import Exporter, exportermethod __all__ = ['write_matlab', 'write_mat'] __dataset_methods__ = __all__ # ....................................................................................................................... def write_matlab(*args, **kwargs): """ Writes a dataset in CSV format Parameters ---------- Returns ------- out : `pathlib` object path of the saved file Examples -------- The extension will be added automatically >>> X.write_matlab('myfile') """ exporter = Exporter() kwargs['filetypes'] = ['MATLAB files (*.mat)'] kwargs['suffix'] = '.mat' return exporter(*args, **kwargs) write_mat = write_matlab write_mat.__doc__ = 'This method is an alias of `write_matlab` ' @exportermethod def _write_matlab(*args, **kwargs): raise NotImplementedError <file_sep>/docs/userguide/processing/alignment.py # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Alignment of datasets # %% import spectrochempy as scp # %% [markdown] # ## Example # %% [markdown] # To allow some mathematical operations or dataset processing, it is often necessary that the datasets are aligned, # *i.e.,* that they have compatible coordinate for the dimensions. # # For sake of demonstration, let's take an experimental dataset that we will arbitrary split into four unaligned # datasets. Then will realign them and appy some binary mathematical operation such as addition or subtration that # required aligned coordinates. # %% dataset = scp.NDDataset.read_omnic('irdata/nh4y-activation.spg') dataset.y = dataset.y - dataset.y[0] # remove offset in the time dataset.y.title = 'Time' prefs = dataset.preferences prefs.reset() prefs.figure.figsize = (7, 3) prefs.figure.dpi = 100 _ = dataset.plot_map(colormap='viridis', colorbar=True) print('shape:', dataset.shape) # %% nd1 = dataset[0:30, 0:4000] nd2 = dataset[0:30, 2000:5549] nd3 = dataset[10:55, 0:4000] nd4 = dataset[10:55, 2000:5549] _ = scp.multiplot_map(datasets=[nd1, nd2, nd3, nd4], colormap='viridis', nrow=2, ncol=2, sharex=True, sharey=True, dpi=100) # %% [markdown] # The four datasets `nd1` to `nd4` have some overlapping in both dimensions. But it we want for example to add `nd2` # with `nd4`. This will fail because the dimension are not aligned. # %% try: nd2 + nd4 except Exception as e: scp.error_(str(e) + ' Cannot add unaligned datasets.') # %% [markdown] # Let try to align them, in the `y` dimension (*i.e.* the first) as this the one which differ in size. # (NOTE: to find the actual names of the dimensions, just get the `dims` attribute of the datasets. # %% nd2.dims, nd4.dims # %% [markdown] # To align we can use different methods, depending on the expected results (missing values in the aligned datasets # will be masked) # %% # `outer` method => union of the coordinates nd2a, nd4a = scp.align(nd2, nd4, dim='y', method='outer') # %% [markdown] # Now we can perform an addition without any problem # %% ndadd = nd2a + nd4a ndadd.shape # %% [markdown] # Let's plot both individual aligned arrays, and their sum. Note, that only the common region appears in the result # array, as the mathematical operation are aware of the masks. # %% _ = scp.multiplot_map(datasets=[nd2a, nd4a, ndadd], colormap='viridis', sharey=True, nrow=1, ncol=3, figsize=(8, 3), dpi=100) # %% [markdown] # Now, assume we want to align in the other dimension, or both # %% try: nd1 + nd2 except Exception as e: scp.error_(str(e) + ' Cannot add unaligned datasets.') # %% nd1a, nd2a = scp.align(nd1, nd2, dim='x', method='outer') ndadd = nd1a + nd2a _ = scp.multiplot_map(datasets=[nd1a, nd2a, ndadd], colormap='viridis', sharey=True, nrow=1, ncol=3, figsize=(8, 3), dpi=100) ndadd.shape # %% [markdown] # ## Methods for alignments # Method for alignments are: # # * **outer** which means that a union of the different coordinates is achieved (missing values are masked) # * **inner** which means that the intersection of the coordinates is used # * **first** which means that the first dataset is used as reference # * **last** which means that the last dataset is used as reference # * **interpolate** means that interpolation is performed to handle missing points whenever it is possible (Not yet # implemented) # %% [markdown] # ### `inner` method # %% # `inner` method => intersection of the coordinates nd2a, nd4a = scp.align(nd2, nd4, dim='y', method='inner') ndadd = nd2a + nd4a ndadd.shape # note the difference with the outer method above (the shape correspond to the intersection) # %% _ = scp.multiplot_map(datasets=[nd2a, nd4a, ndadd], colormap='viridis', sharey=True, nrow=1, ncol=3, figsize=(8, 3), dpi=100) # %% [markdown] # ### `first` method # %% # `inner` method => align on the first dataset nd2a, nd4a = scp.align(nd2, nd4, dim='y', method='first') ndadd = nd2a + nd4a ndadd.shape # note the difference with the outer method above # %% _ = scp.multiplot_map(datasets=[nd2a, nd4a, ndadd], colormap='viridis', sharey=True, nrow=1, ncol=3, figsize=(8, 3), dpi=100) # %% [markdown] # ### `last` method # %% # `last` method => align on the last dataset nd2a, nd4a = scp.align(nd2, nd4, dim='y', method='last') ndadd = nd2a + nd4a ndadd.shape # note the difference with the outer method above # %% _ = scp.multiplot_map(datasets=[nd2a, nd4a, ndadd], colormap='viridis', sharey=True, nrow=1, ncol=3, figsize=(8, 3), dpi=100) # %% [markdown] # ## Alignment along several dimensions # %% nd1a, nd4a = scp.align(nd1, nd4, dims=['y', 'x']) # by default the outer method is used ndadd = nd1a + nd4a # Comparison of the result array with the original (only the common region is visible, due to the masks) _ = scp.multiplot_map(datasets=[nd1a, nd4a, ndadd], colormap='viridis', sharex=0, sharey=True, nrow=1, ncol=3, figsize=(8, 3), dpi=100) nd1a.shape, nd4a.shape, ndadd.shape # %% nd1a, nd4a = scp.align(nd1, nd4, dims=['y', 'x'], method='inner') # by default the outer method is used ndadd = nd1a + nd4a # Comparison of the result array with the original (only the common region is visible, due to the masks) _ = scp.multiplot_map(datasets=[nd1a, nd4a, ndadd], colormap='viridis', sharex=0, sharey=True, nrow=1, ncol=3, figsize=(8, 3), dpi=100) # %% nd1a, nd4a = scp.align(nd1, nd4, dims=['y', 'x'], method='first') # by default the outer method is used ndadd = nd1a + nd4a # Comparison of the result array with the original (only the common region is visible, due to the masks) _ = scp.multiplot_map(datasets=[nd1a, nd4a, ndadd], colormap='viridis', sharex=0, sharey=True, nrow=1, ncol=3, figsize=(8, 3), dpi=100) # %% nd1a, nd4a = scp.align(nd1, nd4, dims=['y', 'x'], method='last') # by default the outer method is used ndadd = nd1a + nd4a # Comparison of the result array with the original (only the common region is visible, due to the masks) _ = scp.multiplot_map(datasets=[nd1a, nd4a, ndadd], colormap='viridis', sharex=0, sharey=True, nrow=1, ncol=3, figsize=(8, 3), dpi=100) <file_sep>/spectrochempy/utils/jsonutils.py # -*- coding: utf-8 -*- # # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ===================================================================================================================== # """ JSON utilities """ from datetime import datetime import pickle import base64 import pathlib import numpy as np from spectrochempy.units import Quantity, Unit __all__ = ['json_serialiser', 'json_decoder'] fromisoformat = lambda s: datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%f%Z") # ====================================================================================================================== # JSON UTILITIES # ====================================================================================================================== def json_decoder(dic): """Decode a serialised ison object """ if "__class__" in dic: klass = dic['__class__'] if klass == 'DATETIME': return fromisoformat(dic["isoformat"]) elif klass == 'NUMPY_ARRAY': if 'base64' in dic: return pickle.loads(base64.b64decode(dic['base64'])) elif 'tolist' in dic: return np.array(dic['tolist'], dtype=dic['dtype']) elif klass == 'PATH': return pathlib.Path(dic["str"]) elif klass == 'QUANTITY': return Quantity.from_tuple(dic["tuple"]) elif klass == 'UNIT': return Unit(dic['str']) elif klass == 'COMPLEX': if 'base64' in dic: return pickle.loads(base64.b64decode(dic['base64'])) elif 'tolist' in dic: return np.array(dic['tolist'], dtype=dic['dtype']).data[()] raise TypeError(dic['__class__']) return dic def json_serialiser(byte_obj, encoding=None): """ Return a serialised json object """ from spectrochempy.core import debug_ from spectrochempy.core.dataset.ndplot import Preferences debug_(str(byte_obj)) if byte_obj is None: return None elif hasattr(byte_obj, 'implements'): objnames = byte_obj.__dir__() # particular case of Linear Coordinates if byte_obj.implements('LinearCoord'): objnames.remove('data') dic = {} for name in objnames: if name in ['readonly'] or (name == 'dims' and 'datasets' in objnames) or [ name in ['parent', 'name'] and isinstance(byte_obj, Preferences)]: val = getattr(byte_obj, name) else: val = getattr(byte_obj, f'_{name}') # Warning with parent-> circular dependencies! if name != 'parent': dic[name] = json_serialiser(val, encoding=encoding) return dic elif isinstance(byte_obj, (str, int, float, bool)): return byte_obj elif isinstance(byte_obj, np.bool_): return bool(byte_obj) elif isinstance(byte_obj, (np.float64, np.float32, float)): return float(byte_obj) elif isinstance(byte_obj, (np.int64, np.int32, int)): return int(byte_obj) elif isinstance(byte_obj, tuple): return tuple([json_serialiser(v, encoding=encoding) for v in byte_obj]) elif isinstance(byte_obj, list): return [json_serialiser(v, encoding=encoding) for v in byte_obj] elif isinstance(byte_obj, dict): dic = {} for k, v in byte_obj.items(): dic[k] = json_serialiser(v, encoding=encoding) return dic elif isinstance(byte_obj, datetime): return {"isoformat": byte_obj.strftime("%Y-%m-%dT%H:%M:%S.%f%Z"), "__class__": 'DATETIME'} # .isoformat() elif isinstance(byte_obj, np.ndarray): if encoding is None: return {"tolist": json_serialiser(byte_obj.tolist(), encoding=encoding), "dtype": str(byte_obj.dtype), "__class__": 'NUMPY_ARRAY'} else: return {"base64": base64.b64encode(pickle.dumps(byte_obj)).decode(), "__class__": 'NUMPY_ARRAY'} elif isinstance(byte_obj, pathlib.PosixPath): return {"str": str(byte_obj), "__class__": 'PATH'} elif isinstance(byte_obj, Unit): return {"str": str(byte_obj), "__class__": 'UNIT'} elif isinstance(byte_obj, Quantity): return {"tuple": json_serialiser(byte_obj.to_tuple(), encoding=encoding), "__class__": 'QUANTITY'} elif isinstance(byte_obj, (np.complex128, np.complex64, np.complex)): if encoding is None: return {"tolist": json_serialiser([byte_obj.real, byte_obj.imag], encoding=encoding), "dtype": str(byte_obj.dtype), "__class__": 'COMPLEX'} else: return {"base64": base64.b64encode(pickle.dumps(byte_obj)).decode(), "__class__": 'COMPLEX'} raise ValueError(f'No encoding handler for data type {type(byte_obj)}') if __name__ == '__main__': pass <file_sep>/spectrochempy/core/analysis/efa.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implement the EFA (Evolving Factor Analysis) class. """ __all__ = ['EFA'] __dataset_methods__ = [] import numpy as np from datetime import datetime, timezone from traitlets import HasTraits, Instance, Float from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.coordset import CoordSet from spectrochempy.core.dataset.coord import Coord from spectrochempy.utils import MASKED from spectrochempy.core.analysis.svd import SVD # from spectrochempy.core.plotters.plot1d import plot_multiple # from spectrochempy.utils import show class EFA(HasTraits): """ Evolving Factor Analysis. Performs an Evolving Factor Analysis (forward and reverse) of the input |NDDataset|. """ _f_ev = Instance(NDDataset) _b_ev = Instance(NDDataset) _cutoff = Float(allow_none=True) def __init__(self, dataset): """ Parameters ---------- dataset : |NDDataset| object The input dataset has shape (M, N). M is the number of observations (for examples a series of IR spectra) while N is the number of features (for example the wavenumbers measured in each IR spectrum). """ # check if we have the correct input # ---------------------------------- X = dataset if isinstance(X, NDDataset): # As seen below, we cannot performs SVD on the masked array # so let's take the ndarray only self._X = X M, N = X.shape else: raise TypeError(f'An object of type NDDataset is expected as input, but an object of type' f' {type(X).__name__} has been provided') # max number of components K = min(M, N) # in case some row are masked, we need to take this into account if X.is_masked: masked_rows = np.all(X.mask, axis=-1) else: masked_rows = np.array([False] * M) K = min(K, len(np.where(~ masked_rows)[0])) # -------------------------------------------------------------------- # forward analysis # -------------------------------------------------------------------- f = NDDataset(np.zeros((M, K)), coordset=[X.y, Coord(range(K))], title='EigenValues', description='Forward EFA of ' + X.name, history=str(datetime.now(timezone.utc)) + ': created by spectrochempy ') # in case some row are masked, take this into account, by masking # the corresponding rows of f f[masked_rows] = MASKED # performs the analysis for i in range(M): # if some rows are masked, we must skip them if not masked_rows[i]: fsvd = SVD(X[:i + 1], compute_uv=False) k = fsvd.s.size # print(i, k) f[i, :k] = fsvd.s.data ** 2 f[i, k:] = MASKED else: f[i] = MASKED # -------------------------------------------------------------------- # backward analysis # -------------------------------------------------------------------- b = NDDataset(np.zeros((M, K)), coordset=[X.y, Coord(range(K))], title='EigenValues', name='Backward EFA of ' + X.name, history=str(datetime.now(timezone.utc)) + ': created by spectrochempy ') b[masked_rows] = MASKED for i in range(M - 1, -1, -1): # if some rows are masked, we must skip them if not masked_rows[i]: bsvd = SVD(X[i:M], compute_uv=False) k = bsvd.s.size b[i, :k] = bsvd.s.data ** 2 b[i, k:] = MASKED else: b[i] = MASKED self._f_ev = f self._b_ev = b @property def cutoff(self): """ float - cutoff value """ return self._cutoff @cutoff.setter def cutoff(self, val): self._cutoff = val @property def f_ev(self): """ |NDDataset| - Eigenvalues for the forward analysis """ f = self._f_ev if self._cutoff is not None: f.data = np.max((f.data, np.ones_like(f.data) * self._cutoff), axis=0) return f @property def b_ev(self): """ |NDDataset| - Eigenvalues for the backward analysis """ b = self._b_ev if self.cutoff is not None: b.data = np.max((b.data, np.ones_like(b.data) * self.cutoff), axis=0) return b def get_conc(self, n_pc=None): """ Computes abstract concentration profile (first in - first out) Parameters ---------- n_pc : int, optional, default:3 Number of pure species for which the concentration profile must be computed. Returns -------- concentrations Concentration profile. """ M, K = self.f_ev.shape if n_pc is None: n_pc = K n_pc = min(K, n_pc) f = self.f_ev b = self.b_ev xcoord = Coord(range(n_pc), title='PS#') c = NDDataset(np.zeros((M, n_pc)), coordset=CoordSet(y=self._X.y, x=xcoord), name='C_EFA[{}]'.format(self._X.name), title='relative concentration', description='Concentration profile from EFA', history=str(datetime.now(timezone.utc)) + ': created by spectrochempy') if self._X.is_masked: masked_rows = np.all(self._X.mask, axis=-1) else: masked_rows = np.array([False] * M) for i in range(M): if masked_rows[i]: c[i] = MASKED continue c[i] = np.min((f.data[i, :n_pc], b.data[i, :n_pc][::-1]), axis=0) return c # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/docs/gettingstarted/examples/processing/plot_proc_em.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Exponential window multiplication ===================================================== In this example, we exponential window multiplication to apodize a NMR signal in the time domain. """ import spectrochempy as scp Hz = scp.ur.Hz us = scp.ur.us path = scp.preferences.datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'topspin_1d' dataset1D = scp.read_topspin(path, expno=1, remove_digital_filter=True) ######################################################################################################################## # Normalize the dataset values and reduce the time domain dataset1D /= dataset1D.real.data.max() # normalize dataset1D = dataset1D[0.:15000.] ######################################################################################################################## # Apply exponential window apodization new1, curve1 = scp.em(dataset1D.copy(), lb=20 * Hz, retapod=True, inplace=False) ######################################################################################################################## # Apply a shifted exponential window apodization # defualt units are HZ for broadening and microseconds for shifting new2, curve2 = dataset1D.copy().em(lb=100 * Hz, shifted=10000 * us, retapod=True, inplace=False) ######################################################################################################################## # Plotting p = dataset1D.plot(zlim=(-2, 2), color='k') curve1.plot(color='r') new1.plot(color='r', clear=False, label=' em = 20 hz') curve2.plot(color='b', clear=False) new2.plot(dcolor='b', clear=False, label=' em = 30 HZ, shifted = ') # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/spectrochempy/widgets/fileselector.py # ---------------------------------------------------------------------------------------------------------------------- # Modified from intake.gui # # Copyright (c) 2012 - 2018, Anaconda, Inc. and Intake contributors # # BSD 2-Clause "Simplified" License # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------------------------------------------------- """ Widgets for the Jupyter notebook and Jupyter lab """ from contextlib import contextmanager from IPython.core.interactiveshell import InteractiveShell import IPython from ..utils import pathclean __all__ = ['FileSelector', 'URLSelector'] import ipywidgets as widgets @contextmanager def ignore(ob): try: ob.ignore = True yield finally: ob.ignore = False class Base(object): done_callback = None def stop(self, ok=False): done = self.done_callback is not None if ok and done: self.done_callback(ok) elif done: self.done_callback(None) def __repr__(self): return ("To get widget to display, you must " "install ipy/jupyter-widgets, run in a notebook and, in " "the case of jupyter-lab, install the jlab extension.") def _ipython_display_(self, **kwargs): # from IPython.Widget._ipython_display_ if InteractiveShell.initialized(): if self.widget._view_name is not None: plaintext = repr(self) data = {'text/plain': plaintext, 'application/vnd.jupyter.widget-view+json': {'version_major': 2, 'version_minor': 0, 'model_id': self.widget._model_id}} IPython.display.display(data, raw=True) self.widget._handle_displayed(**kwargs) class URLSelector(Base): def __init__(self, done_callback=None): self.done_callback = done_callback self.lurl = widgets.Label(value='URL:') self.url = widgets.Text(placeholder="Full URL with protocol", layout=widgets.Layout(flex='10 1 auto', width='auto')) self.x = widgets.Button(icon='close', tooltip='Close Selector', layout=widgets.Layout(flex='1 1 auto', width='auto')) self.x.on_click(lambda ev: self.stop()) self.ok = widgets.Button(icon='check', tooltip='OK', layout=widgets.Layout(flex='1 1 auto', width='auto')) self.ok.on_click(lambda ev: self.stop(ok=self.url.value)) self.widget = widgets.HBox(children=[self.lurl, self.url, self.ok, self.x]) class FileSelector(Base): """ ipywidgets interface for picking files The current path is stored in ``.path`` and the current selection is stored in ``.value``. """ def __init__(self, done_callback=None, path=None, filters=None): """ Parameters ---------- done_callback : function Called when the tick or cross buttons are clicked. Expects signature func(path, ok=True|False). filters : list of str or None Only show files ending in one of these strings. Normally used for picking file extensions. None is an alias for [''], passes all files. """ path = pathclean(path) self.startpath = path self.startname = path.name self.done_callback = done_callback if filters: if not isinstance(filters, (list, tuple)): filters = [filters] self.filters = list(filters) else: self.filters = [''] if not path or not path.exists(): self.path = path.cwd() else: self.path = path self.main = widgets.Select(rows=7) self.button = widgets.Button(icon='chevron-left', tooltip='Parent', layout=widgets.Layout(flex='1 1 auto', width='auto')) self.button.on_click(self.up) self.label = widgets.Label(layout=widgets.Layout(flex='100 1 auto', width='auto')) self.x = widgets.Button(icon='close', tooltip='Close Selector', layout=widgets.Layout(width='auto')) self.x.on_click(lambda ev: self.stop()) self.ok = widgets.Button(icon='check', tooltip='OK', layout=widgets.Layout(width='auto')) self.ok.on_click(lambda ev: self._ok()) self.make_options() self.main.observe(self.changed, 'value') self.upper = widgets.Box(children=[self.button, self.label]) self.right = widgets.VBox(children=[self.x, self.ok]) self.lower = widgets.HBox(children=[self.main, self.right]) self.widget = widgets.VBox(children=[self.upper, self.lower]) self.ignore = False def _ok(self): fn = self.path / self.main.value if fn.is_dir(): self.stop() else: self.stop(fn) def make_options(self): self.ignore = True self.label.value = str(self.path).replace(str(self.startpath.parent), '..') if str(self.startpath) in str( self.path) else str(self.path) out = [] for f in sorted(self.path.glob('[a-zA-Z0-9]*')): # os.listdir()): if f.is_dir() or any(ext in f.suffix for ext in self.filters + list(map(str.upper, self.filters))): out.append(f.name) self.main.value = self.value = None self.fullpath = self.path self.main.options = out self.ignore = False def up(self, *args): self.path = self.path.parent # os.path.dirname(self.path.rstrip('/')).rstrip('/') + '/' self.make_options() def changed(self, ev): if self.ignore: self.value = None self.fullpath = None return with ignore(self): fn = self.path / ev['new'] if fn.is_dir(): self.path = fn self.make_options() self.value = self.main.value self.fullpath = self.path / self.value <file_sep>/docs/gettingstarted/examples/analysis/plot_efa.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ EFA analysis example ====================== In this example, we perform the Evolving Factor Analysis """ ######################################################################################################################## # sphinx_gallery_thumbnail_number = 2 import spectrochempy as scp import os ######################################################################################################################## # Upload and preprocess a dataset datadir = scp.preferences.datadir dataset = scp.read_omnic(os.path.join(datadir, 'irdata', 'nh4y-activation.spg')) ######################################################################################################################## # columns masking dataset[:, 1230.0:920.0] = scp.MASKED # do not forget to use float in slicing dataset[:, 5997.0:5993.0] = scp.MASKED ######################################################################################################################## # difference spectra dataset -= dataset[-1] dataset.plot_stack(); ######################################################################################################################## # column masking for bad columns dataset[10:12] = scp.MASKED ######################################################################################################################## # Evolving Factor Analysis efa = scp.EFA(dataset) ######################################################################################################################## # Show results # npc = 4 c = efa.get_conc(npc) c.T.plot(); # scp.show() # Uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/docs/gettingstarted/examples/read/plot_read_IR_from_opus.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Loading Bruker OPUS files ============================================ Here we load an experimental Bruker OPUS files and plot it. """ import spectrochempy as scp Z = scp.read_opus(['test.0000', 'test.0001', 'test.0002', 'test.0003'], directory='irdata/OPUS') print(Z) # %% # plot it Z.plot(); scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/docs/userguide/processing/fourier.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # cell_metadata_filter: title,-all # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # One-dimensional (1D) Fourier transformation # %% [markdown] # In this notebook, we are going to transform time-domain data into 1D or 2D spectra using SpectroChemPy # processing tools # %% import spectrochempy as scp # %% [markdown] # ## FFT of 1D NMR spectra # %% [markdown] # First we open read some time domain data. Here is a NMD free induction decay (FID): # %% path = scp.preferences.datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'topspin_1d' fid = scp.read_topspin(path) fid # %% [markdown] # The type of the data is complex: # %% fid.dtype # %% [markdown] # We can represent both real and imaginary parts on the same plot using the `show_complex` parameter. # %% prefs = fid.preferences prefs.figure.figsize = (6, 3) _ = fid.plot(show_complex=True, xlim=(0, 15000)) print("td = ", fid.size) # %% [markdown] # Now we perform a Fast Fourier Fransform (FFT): # %% spec = scp.fft(fid) _ = spec.plot(xlim=(100, -100)) print("si = ", spec.size) spec # %% [markdown] # **Alternative notation** # %% k = 1024 spec = fid.fft(size=32 * k) _ = spec.plot(xlim=(100, -100)) print("si = ", spec.size) # %% newfid = spec.ifft() # x coordinateis in second (base units) so lets transform it _ = newfid.plot(show_complex=True, xlim=(0, 15000)) # %% [markdown] # Let's compare fid and newfid. There differs as a rephasing has been automatically applied after the first FFT (with # the parameters found in the original fid metadata: PHC0 and PHC1). # # First point in the time domain of the real part is at the maximum. # %% _ = newfid.real.plot(c='r', label='fft + ifft') ax = fid.real.plot(clear=False, xlim=(0, 5000), ls='--', label='original real part') _ = ax.legend() # %% [markdown] # First point in the time domain of the imaginary part is at the minimum. # %% _ = fid.imag.plot(ls='--', label='original imaginary part') ax = newfid.imag.plot(clear=False, xlim=(0, 5000), c='r', label='fft + ifft') _ = ax.legend(loc='lower right') # %% [markdown] # ## Preprocessing # # ### Line broadening # Often before applying a FFT, some exponential multiplication `em`or other broadening filters such as `gm` or `sp` # are applied. # See the dedicated [apodization tutorial](apodization.ipynb). # %% fid2 = fid.em(lb='50. Hz') spec2 = fid2.fft() _ = spec2.plot() _ = spec.plot(clear=False, xlim=(10, -5), c='r') # superpose the unbroadened spectrum in red and show expansion. # %% [markdown] # ### Zero-filling # %% print("td = ", fid.size) # %% td = 64 * 1024 # size: 64 K fid3 = fid.zf_size(size=td) print("new td = ", fid3.x.size) # %% spec3 = fid3.fft() _ = spec3.plot(xlim=(100, -100)) print("si = ", spec3.size) # %% [markdown] # ### Time domain baseline correction # See the dedicated [Time domain baseline correction tutorial](td_baseline.ipynb). # %% [markdown] # ### Magnitude calculation # %% ms = spec.mc() _ = ms.plot(xlim=(10, -10)) _ = spec.plot(clear=False, xlim=(10, -10), c='r') # %% [markdown] # ### Power spectrum # %% mp = spec.ps() _ = (mp / mp.max()).plot() _ = (spec / spec.max()).plot(clear=False, xlim=(10, -10), c='r') # Here we have normalized the spectra at their max value. # %% [markdown] # # Real Fourier transform # %% [markdown] # In some case, it might be interesting to perform real Fourier transform . For instance, as a demontration, # we will independently transform real and imaginary part of the previous fid, and recombine them to obtain the same # result as when performing complex Fourier transform on the complex dataset. # %% lim = (-20, 20) _ = spec3.plot(xlim=lim) _ = spec3.imag.plot(xlim=lim) # %% Re = fid3.real.astype('complex64') fR = Re.fft() _ = fR.plot(xlim=lim, show_complex=True) Im = fid3.imag.astype('complex64') fI = Im.fft() _ = fI.plot(xlim=lim, show_complex=True) # %% [markdown] # Recombinaison: # %% _ = (fR - fI.imag).plot(xlim=lim) _ = (fR.imag + fI).plot(xlim=lim) <file_sep>/spectrochempy/core/plotters/multiplot.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Module containing multiplot function(s) """ __all__ = ['multiplot', 'multiplot_map', 'multiplot_stack', 'multiplot_image', 'multiplot_lines', 'multiplot_scatter', 'multiplot_with_transposed', 'plot_with_transposed'] __dataset_methods__ = [] import numpy as np import matplotlib.pyplot as plt from matplotlib.tight_layout import ( get_renderer, get_tight_layout_figure, get_subplotspec_list, ) import matplotlib as mpl from spectrochempy.utils import is_sequence # from spectrochempy.core import preferences, project_preferences # ............................................................................. def multiplot_scatter(datasets, **kwargs): """ Plot a multiplot with 1D scatter type plots. Alias of multiplot (with `method` argument set to ``scatter``. """ kwargs['method'] = 'scatter' return multiplot(datasets, **kwargs) # ............................................................................. def multiplot_lines(datasets, **kwargs): """ Plot a multiplot with 1D linetype plots. Alias of multiplot (with `method` argument set to ``lines``. """ kwargs['method'] = 'lines' return multiplot(datasets, **kwargs) # ............................................................................. def multiplot_stack(datasets, **kwargs): """ Plot a multiplot with 2D stack type plots. Alias of multiplot (with `method` argument set to ``stack``. """ kwargs['method'] = 'stack' return multiplot(datasets, **kwargs) # ............................................................................. def multiplot_map(datasets, **kwargs): """ Plot a multiplot with 2D map type plots. Alias of multiplot (with `method` argument set to ``map``. """ kwargs['method'] = 'map' return multiplot(datasets, **kwargs) # ............................................................................. def multiplot_image(datasets, **kwargs): """ Plot a multiplot with 2D image type plots. Alias of multiplot (with `method` argument set to ``image``. """ kwargs['method'] = 'image' return multiplot(datasets, **kwargs) # with transpose plot ----------------------------------------------------------------- def plot_with_transposed(dataset, **kwargs): """ Plot a 2D dataset as a stacked plot with its transposition in a second axe. Alias of plot_2D (with `method` argument set to ``with_transposed``). """ kwargs['method'] = 'with_transposed' axes = multiplot(dataset, **kwargs) return axes multiplot_with_transposed = plot_with_transposed # ............................................................................. def multiplot(datasets=[], labels=[], nrow=1, ncol=1, method='stack', sharex=False, sharey=False, sharez=False, colorbar=False, suptitle=None, suptitle_color='k', **kwargs): """ Generate a figure with multiple axes arranged in array (n rows, n columns) Parameters ---------- datasets : nddataset or list of nddataset labels : list of str. The labels that will be used as title of each axes. method : str, default to `map` for 2D and `lines` for 1D data Type of plot to draw in all axes (`lines` , `scatter` , `stack` , `map` ,`image` or `with_transposed`). nrows, ncols : int, default=1 Number of rows/cols of the subplot grid. ncol*nrow must be equal to the number of datasets to plot sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default=False Controls sharing of properties among x (`sharex`) or y (`sharey`) axes:: - True or 'all' : x- or y-axis will be shared among all subplots. - False or 'none' : each subplot x- or y-axis will be independent. - 'row' : each subplot row will share an x- or y-axis. - 'col' : each subplot column will share an x- or y-axis. When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are visible. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are visible. sharez : bool or {'none', 'all', 'row', 'col'}, default=False equivalent to sharey for 1D plot. for 2D plot, z is the intensity axis (i.e., contour levels for maps or the vertical axis for stack plot), y is the third axis. figsize : 2-tuple of floats ``(width, height)`` tuple in inches dpi : float Dots per inch facecolor : color The figure patch facecolor; defaults to rc ``figure.facecolor`` edgecolor : color The figure patch edge color; defaults to rc ``figure.edgecolor`` linewidth : float The figure patch edge linewidth; the default linewidth of the frame frameon : bool If `False` , suppress drawing the figure frame left : float in the [0-1] interval The left side of the subplots of the figure right : float in the [0-1] interval The right side of the subplots of the figure bottom : float in the [0-1] interval The bottom of the subplots of the figure top : float in the [0-1] interval The top of the subplots of the figure wspace : float in the [0-1] interval The amount of width reserved for blank space between subplots, expressed as a fraction of the average axis width hspace : float in the [0-1] interval The amount of height reserved for white space between subplots, expressed as a fraction of the average axis height suptitle : str title of the figure to display on top suptitle_color : color """ # some basic checking # ------------------------------------------------------------------------------------------------------------------ show_transposed = False if method in 'with_transposed': show_transposed = True method = 'stack' nrow = 2 ncol = 1 datasets = [datasets, datasets] # we need to datasets sharez = True single = False if not is_sequence(datasets): single = True datasets = list([datasets]) # make a list if len(datasets) < nrow * ncol and not show_transposed: # not enough datasets given in this list. raise ValueError('Not enough datasets given in this list') # if labels and len(labels) != len(datasets): # # not enough labels given in this list. # raise ValueError('Not enough labels given in this list') if nrow == ncol and nrow == 1 and not show_transposed and single: # obviously a single plot, return it return datasets[0].plot(**kwargs) elif nrow * ncol < len(datasets): nrow = ncol = len(datasets) // 2 if nrow * ncol < len(datasets): ncol += 1 ndims = set([dataset.ndim for dataset in datasets]) if len(ndims) > 1: raise NotImplementedError('mixed dataset shape.') ndim = list(ndims)[0] # create the subplots and plot the ndarrays # ------------------------------------------------------------------------------------------------------------------ mpl.rcParams['figure.autolayout'] = False figsize = kwargs.pop('figsize', None) dpi = kwargs.pop('dpi', 150) fig = kwargs.pop('fig', plt.figure(figsize=figsize, dpi=dpi)) fig.rcParams = plt.rcParams.copy() # save params used for this figure if suptitle is not None: fig.suptitle(suptitle, color=suptitle_color) # axes is dictionary with keys such as 'axe12', where the fist number # is the row and the second the column axes = {} # limits xlims = [] ylims = [] zlims = [] if sharex not in [None, True, False, 'all', 'col']: raise ValueError("invalid option for sharex. Should be" " among (None, False, True, 'all' or 'col')") if sharex: sharex = 'all' if ndim == 1: sharez = False textsharey = "sharey" textsharez = "sharez" if method in ['stack']: sharez, sharey = sharey, sharez # we echange them zlims, ylims = ylims, zlims # for our internal needs as only sharex and sharey are recognized by # matplotlib subplots textsharey = "sharez" textsharez = "sharey" if sharey not in [None, False, True, 'all', 'col']: raise ValueError("invalid option for {}. Should be" " among (None, False, True, 'all' or 'row')".format(textsharey)) if sharez not in [None, False, True, 'all', 'col', 'row']: raise ValueError("invalid option for {}. Should be" " among (None, False, True, " "'all', 'row' or 'col')".format(textsharez)) if sharey: sharey = 'all' if sharez: sharez = 'all' for irow in range(nrow): for icol in range(ncol): idx = irow * ncol + icol dataset = datasets[idx] try: label = labels[idx] except Exception: label = '' _sharex = None _sharey = None _sharez = None # on the type of the plot and if ((irow == icol and irow == 0) or (sharex == 'col' and irow == 0) or (sharey == 'row' and icol == 0)): ax = fig.add_subplot(nrow, ncol, irow * ncol + icol + 1) else: if sharex == 'all': _sharex = axes['axe11'] elif sharex == 'col': _sharex = axes['axe1{}'.format(icol + 1)] if sharey == 'all': _sharey = axes['axe11'] elif sharey == 'row': _sharey = axes['axe{}1'.format(irow + 1)] # in the last dimension if sharez == 'all': _sharez = axes['axe11'] elif sharez == 'row': _sharez = axes['axe{}1'.format(irow + 1)] elif sharez == 'col': _sharez = axes['axe1{}'.format(icol + 1)] ax = fig.add_subplot(nrow, ncol, idx + 1, sharex=_sharex, sharey=_sharey) ax._sharez = _sharez # we add a new share info to the ax. # wich will be useful for the interactive masks ax.name = 'axe{}{}'.format(irow + 1, icol + 1) axes[ax.name] = ax if icol > 0 and sharey: # hide the redondant ticklabels on left side of interior figures plt.setp(axes[ax.name].get_yticklabels(), visible=False) axes[ax.name].yaxis.set_tick_params(which='both', labelleft=False, labelright=False) axes[ax.name].yaxis.offsetText.set_visible(False) if irow < nrow - 1 and sharex: # hide the bottom ticklabels of interior rows plt.setp(axes[ax.name].get_xticklabels(), visible=False) axes[ax.name].xaxis.set_tick_params(which='both', labelbottom=False, labeltop=False) axes[ax.name].xaxis.offsetText.set_visible(False) if show_transposed and irow == 1: transposed = True else: transposed = False dataset.plot(method=method, ax=ax, clear=False, autolayout=False, colorbar=colorbar, data_transposed=transposed, **kwargs) ax.set_title(label, fontsize=8) if sharex and irow < nrow - 1: ax.xaxis.label.set_visible(False) if sharey and icol > 0: ax.yaxis.label.set_visible(False) xlims.append(ax.get_xlim()) ylims.append(ax.get_ylim()) xrev = (ax.get_xlim()[1] - ax.get_xlim()[0]) < 0 # yrev = (ax.get_ylim()[1] - ax.get_ylim()[0]) < 0 # TODO: add a common color bar (set vmin and vmax using zlims) amp = np.ptp(np.array(ylims)) ylim = [np.min(np.array(ylims) - amp * 0.01), np.max(np.array(ylims)) + amp * 0.01] for ax in axes.values(): ax.set_ylim(ylim) # if yrev: # ylim = ylim[::-1] # amp = np.ptp(np.array(xlims)) if not show_transposed: xlim = [np.min(np.array(xlims)), np.max(np.array(xlims))] if xrev: xlim = xlim[::-1] for ax in axes.values(): ax.set_xlim(xlim) def do_tight_layout(fig, axes, suptitle, **kwargs): # tight_layout renderer = get_renderer(fig) axeslist = list(axes.values()) subplots_list = list(get_subplotspec_list(axeslist)) kw = get_tight_layout_figure(fig, axeslist, subplots_list, renderer, pad=1.08, h_pad=0, w_pad=0, rect=None) left = kwargs.get('left', kw['left']) bottom = kwargs.get('bottom', kw['bottom']) right = kwargs.get('right', kw['right']) top = kw['top'] if suptitle: top = top * .95 top = kwargs.get('top', top) ws = kwargs.get('wspace', kw.get('wspace', 0) * 1.1) hs = kwargs.get('hspace', kw.get('hspace', 0) * 1.1) plt.subplots_adjust(left=left, bottom=bottom, right=right, top=top, wspace=ws, hspace=hs) do_tight_layout(fig, axes, suptitle, **kwargs) # make an event that will trigger subplot adjust each time the mouse leave # or enter the axes or figure def _onenter(event): do_tight_layout(fig, axes, suptitle, **kwargs) fig.canvas.draw() fig.canvas.mpl_connect('axes_enter_event', _onenter) fig.canvas.mpl_connect('axes_leave_event', _onenter) fig.canvas.mpl_connect('figure_enter_event', _onenter) fig.canvas.mpl_connect('figure_leave_event', _onenter) return axes if __name__ == '__main__': pass <file_sep>/docs/gettingstarted/examples/processing/readme.txt .. _processing_examples-index: Processing dataset examples ---------------------------- Example of how to process NDDataset (or more generally NDPanels in SpectroChemPy)<file_sep>/spectrochempy/core/readers/readdir.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module provides methods for reading data in a directory """ __all__ = ['read_dir', 'read_carroucell'] __dataset_methods__ = __all__ import os import warnings import datetime import re import scipy.interpolate import numpy as np import xlrd from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.coord import Coord from spectrochempy.utils import get_filename, readdirname from spectrochempy.core import info_, print_ from spectrochempy.core.readers.importer import importermethod, Importer # ====================================================================================================================== # Public functions # ====================================================================================================================== def read_dir(directory=None, **kwargs): """ Read an entire directory. Open a list of readable files in a and store data/metadata in a dataset or a list of datasets according to the following rules : * 2D spectroscopic data (e.g. valid *.spg files or matlab arrays, etc...) from distinct files are stored in distinct NDdatasets. * 1D spectroscopic data (e.g., *.spa files) in a given directory are grouped into single NDDataset, providing their unique dimension are compatible. If not, an error is generated. Parameters ---------- directory : str or pathlib Folder where are located the files to read. Returns -------- read_dir |NDDataset| or list of |NDDataset|. Depending on the python version, the order of the datasets in the list may change. See Also -------- read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. Examples -------- >>> import spectrochempy as scp >>> A = scp.read_dir('irdata') >>> len(A) 4 >>> B = scp.NDDataset.read_dir() """ kwargs['listdir'] = True importer = Importer() return importer(directory, **kwargs) # TODO: make an importer function, when a test directory will be provided. # ...................................................................................................................... def read_carroucell(dataset=None, directory=None, **kwargs): """ Open .spa files in a directory after a carroucell experiment. The files for a given sample are grouped in NDDatasets (sorted by acquisition date). The NDDatasets are returned in a list sorted by sample number. When the file containing the temperature data is present, the temperature is read and assigned as a label to each spectrum. Parameters ---------- dataset : `NDDataset` The dataset to store the data and metadata. If None, a NDDataset is created. directory : str, optional If not specified, opens a dialog box. spectra : arraylike of 2 int (min, max), optional, default=None The first and last spectrum to be loaded as determined by their number. If None all spectra are loaded. discardbg : bool, optional, default=True If True : do not load background (sample #9). delta_clocks : int, optional, default=0 Difference in seconds between the clocks used for spectra and temperature acquisition. Defined as t(thermocouple clock) - t(spectrometer clock). Returns -------- nddataset |NDDataset| or list of |NDDataset|. See Also -------- read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. Notes ------ All files are expected to be present in the same directory and their filenames are expected to be in the format : X_samplename_YYY.spa and for the backround files : X_BCKG_YYYBG.spa where X is the sample holder number and YYY the spectrum number. Examples -------- """ # debug_("starting reading in a folder") # check if the first parameter is a dataset # because we allow not to pass it if not isinstance(dataset, NDDataset): # probably did not specify a dataset # so the first parameter must be the directory if isinstance(dataset, str) and dataset != '': directory = dataset directory = readdirname(directory) if not directory: # probably cancel has been chosen in the open dialog info_("No directory was selected.") return spectra = kwargs.get('spectra', None) discardbg = kwargs.get('discardbg', True) delta_clocks = datetime.timedelta(seconds=kwargs.get('delta_clocks', 0)) datasets = [] # get the sorted list of spa files in the directory spafiles = sorted([f for f in os.listdir(directory) if (os.path.isfile(os.path.join(directory, f)) and f[-4:].lower() == '.spa')]) # discard BKG files if discardbg: spafiles = sorted([f for f in spafiles if 'BCKG' not in f]) # select files if spectra is not None: [min, max] = spectra if discardbg: spafiles = sorted([f for f in spafiles if min <= int(f.split('_')[2][:-4]) <= max and 'BCKG' not in f]) if not discardbg: spafilespec = sorted([f for f in spafiles if min <= int(f.split('_')[2][:-4]) <= max and 'BCKG' not in f]) spafileback = sorted([f for f in spafiles if min <= int(f.split('_')[2][:-6]) <= max and 'BCKG' in f]) spafiles = spafilespec + spafileback curfilelist = [spafiles[0]] curprefix = spafiles[0][::-1].split("_", 1)[1][::-1] for f in spafiles[1:]: if f[::-1].split("_", 1)[1][::-1] != curprefix: datasets.append(NDDataset.read_omnic(curfilelist, sortbydate=True, directory=directory)) datasets[-1].name = os.path.basename(curprefix) curfilelist = [f] curprefix = f[::-1].split("_", 1)[1][::-1] else: curfilelist.append(f) datasets.append(NDDataset.read_omnic(curfilelist, sortbydate=True, directory=directory)) datasets[-1].name = os.path.basename(curprefix) # Now manage temperature Tfile = sorted([f for f in os.listdir(directory) if f[-4:].lower() == '.xls']) if len(Tfile) == 0: print_("no temperature file") elif len(Tfile) > 1: warnings.warn("several .xls/.csv files. The temperature will not be read") else: Tfile = Tfile[0] if Tfile[-4:].lower() == '.xls': book = xlrd.open_workbook(os.path.join(directory, Tfile)) # determine experiment start and end time (thermocouple clock) ti = datasets[0].y.labels[0][0] + delta_clocks tf = datasets[-1].y.labels[-1][0] + delta_clocks # get thermocouple time and T information during the experiment t = [] T = [] sheet = book.sheet_by_index(0) for i in range(9, sheet.nrows): try: time = datetime.datetime.strptime(sheet.cell(i, 0).value, '%d/%m/%y %H:%M:%S').replace( tzinfo=datetime.timezone.utc) if ti <= time <= tf: t.append(time) T.append(sheet.cell(i, 4).value) except ValueError: # debug_('incorrect date or temperature format in row {}'.format(i)) pass except TypeError: # debug_('incorrect date or temperature format in row {}'.format(i)) pass # interpolate T = f(timestamp) tstamp = [time.timestamp() for time in t] # interpolate, except for the first and last points that are extrapolated interpolator = scipy.interpolate.interp1d(tstamp, T, fill_value='extrapolate', assume_sorted=True) for ds in datasets: # timestamp of spectra for the thermocouple clock tstamp_ds = [(label[0] + delta_clocks).timestamp() for label in ds.y.labels] T_ds = interpolator(tstamp_ds) newlabels = np.hstack((ds.y.labels, T_ds.reshape((50, 1)))) ds.y = Coord(title=ds.y.title, data=ds.y.data, labels=newlabels) if len(datasets) == 1: # debug_("finished read_dir()") return datasets[0] # a single dataset is returned # debug_("finished read_dir()") # several datasets returned, sorted by sample # return sorted(datasets, key=lambda ds: int(re.split('-|_', ds.name)[0])) # ====================================================================================================================== # Private functions # ====================================================================================================================== @importermethod def _read_dir(*args, **kwargs): _, directory = args directory = readdirname(directory) files = get_filename(directory, **kwargs) datasets = [] for key in files.keys(): if key: importer = Importer() nd = importer(files[key], **kwargs) if not isinstance(nd, list): nd = [nd] datasets.extend(nd) return datasets if __name__ == '__main__': pass <file_sep>/spectrochempy/utils/traitlets.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from pathlib import Path from matplotlib import cycler from traitlets.config.configurable import Configurable from traitlets import All, List, TraitError, observe __all__ = ["MetaConfigurable", "Range"] class MetaConfigurable(Configurable): def __init__(self, jsonfile=None, **kwargs): # lgtm [py/missing-call-to-init] super().__init__(**kwargs) self.cfg = self.parent.config_manager self.jsonfile = self.parent.config_file_name if jsonfile is not None: self.jsonfile = jsonfile def to_dict(self): """Return config value in a dict form Returns ------- dict A regular dictionary """ d = {} for k, v in self.traits(config=True).items(): d[k] = v.default_value return d @observe(All) def _anytrait_changed(self, change): # update configuration if not hasattr(self, 'cfg'): # not yet initialized return if change.name in self.traits(config=True): value = change.new if isinstance(value, (type(cycler), Path)): value = str(value) self.cfg.update(self.jsonfile, {self.__class__.__name__: {change.name: value, }}) self.updated = True # ====================================================================================================================== # Range trait type # ====================================================================================================================== class Range(List): """ The trait-type Range. Create a trait with two values defining an ordered range of values """ klass = list _cast_types = (tuple,) # Describe the trait type info_text = 'an ordered interval trait' allow_none = True def __init__(self, trait=None, default_value=None, **kwargs): """ Parameters ---------- trait : TraitType [ optional ] The type for restricting the contents of the Container. If unspecified, types are not checked. default_value : SequenceType [ optional ] The default value for the Trait. Must be list/tuple/set, and will be cast to the container type. """ super(Range, self).__init__(trait=None, default_value=default_value, **kwargs) def length_error(self, obj, value): e = "The '%s' trait of '%s' instance must be of length 2 exactly," \ " but a value of %s was specified." \ % (self.name, type(obj), value) raise TraitError(e) def validate_elements(self, obj, value): if value is None or len(value) == 0: return length = len(value) if length != 2: self.length_error(obj, value) value.sort() value = super(Range, self).validate_elements(obj, value) return value def validate(self, obj, value): value = super(Range, self).validate(object, value) value = self.validate_elements(obj, value) return value # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/docs/_templates/changelog.rst What's new =========== .. START CHANGELOG {{ history }} <file_sep>/tests/test_plotters/test_plot.py # # -*- coding: utf-8 -*- # # # # ====================================================================================================================== # # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # = # # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # = # # # ====================================================================================================================== # # import matplotlib.pyplot as mpl # # # from spectrochempy.utils.testing import image_comparison # from spectrochempy import set_loglevel, INFO, WARNING, MASKED, show, multiplot, plot_multiple # # set_loglevel(INFO) # # # To regenerate the reference figures, set FORCE to True # FORCE = True # # # # for this regeneration it is advised to set non parallel testing. # # (remove option -nauto in pytest.ini) # # # # @image_comparison(reference=['IR_dataset_2D_stack', 'IR_dataset_2D_map', # # 'IR_dataset_2D_image'], force_creation=FORCE) # # def test_plot_generic_2D(IR_dataset_2D): # # for method in ['stack', 'map', 'image']: # # dataset = IR_dataset_2D.copy() # # dataset.plot(method=method) # # # # # # @image_comparison(reference=['IR_dataset_1D', 'IR_dataset_1D_sans'], # # force_creation=FORCE) # # def test_plot_generic_1D(IR_dataset_1D): # # dataset = IR_dataset_1D.copy() # # dataset.plot() # # assert mpl.rcParams['figure.figsize'] == [6.8, 4.4] # # dataset.plot(style='sans') # # assert mpl.rcParams['font.family'] == ['sans-serif'] # # # # # # @image_comparison(reference=['IR_dataset_2D_stack']) # # def test_plot_stack(IR_dataset_2D): # # dataset = IR_dataset_2D.copy() # # dataset.plot_stack() # plot_stack is an alias of plot(method='stack') # # # # # # @image_comparison(reference=['IR_dataset_2D_map']) # # def test_plot_map(IR_dataset_2D): # # dataset = IR_dataset_2D.copy() # # dataset.plot_map() # plot_map is an alias of plot(method='map') # # # # # # @image_comparison(reference=['IR_dataset_2D_image', # # 'IR_dataset_2D_image_sanspaper'], # # force_creation=FORCE) # # def test_plot_image(IR_dataset_2D): # # dataset = IR_dataset_2D.copy() # # dataset.plot_image() # plot_image is an alias of plot(method='image') # # dataset.plot_image(style=['sans', 'paper'], fontsize=9) # # # # # # @image_comparison(reference=['IR_dataset_2D_image', # # 'IR_dataset_2D_image_sanspaper'], # # min_similarity=85.0) # # def test_plot_image_offset(IR_dataset_2D): # # dataset = IR_dataset_2D.copy() + .0001 # # dataset.plot_image() # plot_image with offset # # dataset.plot_image(style=['sans', 'paper']) # # # # # # @image_comparison(reference=['IR_dataset_2D_stack']) # # def test_plot_stack_generic(IR_dataset_2D): # # dataset = IR_dataset_2D.copy() # # dataset.plot() # generic plot default to stack # # # def test_plot_stack_masked(IR_dataset_2D): # # just to see if masked area do not apppear on the figure # dataset = IR_dataset_2D.copy() * 2. # dataset[1300.:900.] = MASKED # dataset.plot_stack(colorbar=False) # dataset.plot_map(colorbar=False) # show() # # # def test_plot_stack_multiple(IR_dataset_2D): # dataset = IR_dataset_2D.copy() # s1 = dataset[-10:] # s2 = dataset[0:5] # row = s1[-1] # row.plot() # # two on the same plot # s1.plot_stack() # s2.plot_stack(data_only=True, clear=False) # show() # # # # BUG FIXES IN PLOTS # # # def test_successive_plot_bug_1a3_28(IR_dataset_2D): # dataset = IR_dataset_2D.copy() * 2. # dataset[:, 1300.:900.] = MASKED # dataset.plot_stack(colorbar=False) # dataset.plot() # in 0.1a3.28 bug because key colorbar is missing. # show() # # # def test_successive_plot_bug_with_colorbars(IR_dataset_2D): # dataset = IR_dataset_2D.copy() * 2. # dataset[1300.:900.] = MASKED # dataset.plot_stack() # dataset.plot() # dataset.plot() # bug colorbars stacked on the first plot # dataset.plot(method='map') # bug: no colorbar # show() # # # @image_comparison(reference=['multiplot1', 'multiplot2'], force_creation=FORCE) # def test_multiplot(IR_dataset_2D): # dataset = IR_dataset_2D.copy() # # datasets = [dataset, dataset * 1.1, dataset * 1.2, dataset * 1.3] # labels = ['sample {}'.format(label) for label in # ["1", "2", "3", "4"]] # # multiplot(datasets=datasets, method='stack', labels=labels, nrow=2, ncol=2, # figsize=(9, 5), sharex=True, sharey=True) # # multiplot(datasets=datasets, method='map', labels=labels, nrow=2, ncol=2, # figsize=(9, 5), sharex=True, sharey=True) # # # @image_comparison(reference=['IR_dataset_1D', # 'IR_dataset_1D_sans', # 'IR_dataset_1D', # 'multiple_IR_dataset_1D_scatter', # 'multiple_IR_dataset_1D_scatter_sans', # 'multiple_IR_dataset_1D_scatter', # ], force_creation=FORCE) # def tests_multipleplots_and_styles(IR_dataset_1D, IR_dataset_2D): # dataset = IR_dataset_1D # # # plot generic # dataset.copy().plot() # # # plot generic style # dataset.copy().plot(style='sans') # # # check that style reinit to default # dataset.copy().plot() # # dataset = IR_dataset_2D # # datasets = [dataset[0], dataset[10], dataset[20], dataset[50], dataset[53]] # labels = ['sample {}'.format(label) for label in # ["S1", "S10", "S20", "S50", "S53"]] # # # plot multiple # plot_multiple(method='scatter', # datasets=datasets, labels=labels, legend='best') # # # plot mupltiple with style # plot_multiple(method='scatter', style='sans', # datasets=datasets, labels=labels, legend='best') # # # check that style reinit to default # plot_multiple(method='scatter', # datasets=datasets, labels=labels, legend='best') # # # # #### debugging #### # set_loglevel(WARNING) <file_sep>/spectrochempy/utils/system.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ['get_user_and_node', 'get_user', 'get_node', 'is_kernel', 'sh', 'is_windows', ] import getpass import platform import sys from subprocess import run, PIPE, STDOUT def is_windows(): win = 'Windows' in platform.platform() return win def get_user(): return getpass.getuser() def get_node(): return platform.node() def get_user_and_node(): return f"{get_user()}@{get_node()}" def is_kernel(): """ Check if we are running from IPython """ # from http://stackoverflow.com # /questions/34091701/determine-if-were-in-an-ipython-notebook-session if 'IPython' not in sys.modules: # IPython hasn't been imported return False from IPython import get_ipython # pragma: no cover # check for `kernel` attribute on the IPython instance return getattr(get_ipython(), 'kernel', None) is not None # pragma: no cover class _ExecCommand: def __init__(self, command): """ Parameters ---------- command: shell command to execute """ self.commands = [command] def __call__(self, *args, **kwargs): self.commands.extend(args) silent = kwargs.pop("silent", False) proc = run(self.commands, text=True, stdout=PIPE, stderr=STDOUT) # capture_output=True) # TODO: handle error codes if not silent and proc.stdout: print(proc.stdout) return proc.stdout # noinspection PyPep8Naming class sh(object): """ Utility to run subprocess run command as if they were functions """ def __getattr__(self, command): return _ExecCommand(command) def __call__(self, script, silent=False): # use to run shell script proc = run(script, text=True, shell=True, stdout=PIPE, stderr=STDOUT) if not silent: print(proc.stdout) return proc.stdout sh = sh() <file_sep>/tests/test_readers_writers/test_topspin.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import pytest from pathlib import Path import spectrochempy as scp nmrdir = Path('nmrdata/bruker/tests/nmr') def test_deprecated(): with pytest.deprecated_call(): scp.read_bruker_nmr(nmrdir / 'topspin_2d', expno=1, remove_digital_filter=True) def test_read_topspin(): # Open a dialog for selecting a Topspin directory A = scp.read_topspin(directory=nmrdir) assert A.name == 'topspin_2d expno:1 procno:1 (SER)' # A.plot() A = scp.read_topspin(nmrdir / 'exam2d_HC/3/pdata/1/2rr') A.plot_map() # Select a TOPSPIN spectra using the full name B = scp.read_topspin(nmrdir / 'topspin_1d/1/fid') assert str(B) == 'NDDataset: [complex128] unitless (size: 12411)' C = scp.read_topspin(nmrdir / 'topspin_1d/1/pdata/1/1r') assert str(C) == 'NDDataset: [complex128] unitless (size: 16384)' C.plot_map() # Select a TOPSPIN spectra using the full name B = scp.read_topspin(nmrdir / 'topspin_2d/1/ser') assert str(B) == 'NDDataset: [quaternion] unitless (shape: (y:96, x:948))' B.plot_surface() C = scp.read_topspin(nmrdir / 'topspin_2d/1/pdata/1/2rr') assert str(C) == 'NDDataset: [quaternion] unitless (shape: (y:1024, x:2048))' C.plot_image() # alternative syntax D = scp.read_topspin(nmrdir / 'topspin_2d', expno=1, procno=1) assert D == C scp.show() def test_read_topspin_glob(): D = scp.read_topspin(nmrdir, glob='topspin*/*/pdata/*/*') print(D) # EOF <file_sep>/tests/test_processors/test_nmr.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os import numpy as np import pytest from spectrochempy.core import preferences as prefs from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.units import ur from spectrochempy.utils import show from spectrochempy.utils.testing import (assert_equal, assert_array_equal, assert_array_almost_equal) pytestmark = pytest.mark.skip("all tests still WIP") # 1D # Reader def test_nmr_reader_1D(): path = os.path.join(prefs.datadir, 'nmrdata', 'bruker', 'tests', 'nmr', 'topspin_1d') # load the data in a new dataset ndd = NDDataset() ndd.read_topspin(path, expno=1, remove_digital_filter=True) assert ndd.__str__() == 'NDDataset: [complex128] unitless (size: 12411)' assert "<tr><td style='padding-right:5px; padding-bottom:0px; padding-top:0px; width:124px'><font color='green'> " \ " coordinates</font> </td><td style='text-align:left; padding-bottom:0px; padding-top:0px; border:.5px " \ "solid lightgray; '> <div><font color='blue'>[ 0 4 ... 4.964e+04 4.964e+04] us</font></div>" \ "</td><tr>" in ndd._repr_html_() # plot def test_nmr_1D_show(NMR_dataset_1D): # test simple plot dataset = NMR_dataset_1D.copy() dataset.plot() def test_nmr_1D_show_complex(NMR_dataset_1D): dataset = NMR_dataset_1D.copy() dataset.plot(xlim=(0., 25000.)) dataset.plot(imag=True, color='r', data_only=True, clear=False) # display the real and complex at the same time dataset.plot(show_complex=True, color='green', xlim=(0., 30000.), zlim=(-200., 200.)) show() # apodization def test_nmr_1D_apodization(NMR_dataset_1D): dataset = NMR_dataset_1D.copy() dataset /= dataset.real.data.max() # normalize lb = 0 arr, apod = dataset.em(lb=lb, retapod=True) # arr and dataset should be equal as no em was applied assert_equal(dataset.data, arr.data) lb = 0. gb = 0. arr, apod = dataset.gm(lb=lb, gb=gb, retapod=True) # arr and dataset should be equal as no em was applied assert_equal(dataset.data, arr.data) lb = 100 arr, apod = dataset.em(lb=lb, retapod=True) # arr and dataset should not be equal as inplace=False assert not np.array_equal(dataset.data, arr.data) assert_array_almost_equal(apod[1], 0.9987, decimal=4) # inplace=True dataset.plot(xlim=(0., 6000.)) dataset.em(lb=100. * ur.Hz, inplace=True) dataset.plot(c='r', data_only=True, clear=False) # successive call dataset.em(lb=200. * ur.Hz, inplace=True) dataset.plot(c='g', data_only=True, clear=False) dataset = NMR_dataset_1D.copy() dataset.plot() dataset.em(100. * ur.Hz, inplace=True) dataset.plot(c='r', data_only=True, clear=False) # first test gm dataset = NMR_dataset_1D.copy() dataset /= dataset.real.data.max() # normalize dataset.plot(xlim=(0., 6000.)) dataset, apod = dataset.gm(lb=-100. * ur.Hz, gb=100. * ur.Hz, retapod=True) dataset.plot(c='b', data_only=True, clear=False) apod.plot(c='r', data_only=True, clear=False) show() # FFT def test_nmr_fft_1D(NMR_dataset_1D): dataset1D = NMR_dataset_1D.copy() dataset1D /= dataset1D.real.data.max() # normalize dataset1D.x.ito('s') new = dataset1D.fft(tdeff=8192, size=2 ** 15) new.plot() new2 = new.ifft() dataset1D.plot() (new2 - 1.).plot(color='r', clear=False) show() def test_nmr_fft_1D_our_Hz(NMR_dataset_1D): dataset1D = NMR_dataset_1D.copy() dataset1D /= dataset1D.real.data.max() # normalize LB = 10. * ur.Hz GB = 50. * ur.Hz dataset1D.gm(gb=GB, lb=LB) new = dataset1D.fft(size=32000, ppm=False) new.plot(xlim=[5000, -5000]) show() def test_nmr_manual_1D_phasing(NMR_dataset_1D): dataset1D = NMR_dataset_1D.copy() dataset1D /= dataset1D.real.data.max() # normalize dataset1D.em(10. * ur.Hz) # inplace broadening transf = dataset1D.fft(tdeff=8192, size=2 ** 15) # fft transf.plot() # plot) # manual phasing transfph = transf.pk(verbose=True) # by default pivot = 'auto' transfph.plot(xlim=(20, -20), clear=False, color='r') assert_array_equal(transfph.data, transf.data) # because phc0 already applied transfph3 = transf.pk(pivot=50, verbose=True) transfph3.plot(clear=False, color='r') not assert_array_equal(transfph3.data, transfph.data) # because phc0 already applied # transfph4 = transf.pk(pivot=100, phc0=40., verbose=True) transfph4.plot(xlim=(20, -20), clear=False, color='g') assert transfph4 != transfph transfph4 = transf.pk(pivot=100, verbose=True, inplace=True) (transfph4 - 10).plot(xlim=(20, -20), clear=False, color='r') show() def test_nmr_auto_1D_phasing(): path = os.path.join(prefs.datadir, 'nmrdata', 'bruker', 'tests', 'nmr', 'topspin_1d') ndd = NDDataset.read_topspin(path, expno=1, remove_digital_filter=True) ndd /= ndd.real.data.max() # normalize ndd.em(10. * ur.Hz, inplace=True) transf = ndd.fft(tdeff=8192, size=2 ** 15) transf.plot(xlim=(20, -20), ls=':', color='k') transfph2 = transf.pk(verbose=True) transfph2.plot(xlim=(20, -20), clear=False, color='r') # automatic phasing transfph3 = transf.apk(verbose=True) (transfph3 - 1).plot(xlim=(20, -20), clear=False, color='b') transfph4 = transf.apk(algorithm='acme', verbose=True) (transfph4 - 2).plot(xlim=(20, -20), clear=False, color='g') transfph5 = transf.apk(algorithm='neg_peak', verbose=True) (transfph5 - 3).plot(xlim=(20, -20), clear=False, ls='-', color='r') transfph6 = transf.apk(algorithm='neg_area', verbose=True) (transfph6 - 4).plot(xlim=(20, -20), clear=False, ls='-.', color='m') transfph4 = transfph6.apk(algorithm='acme', verbose=True) (transfph4 - 6).plot(xlim=(20, -20), clear=False, color='b') show() def test_nmr_multiple_manual_1D_phasing(): path = os.path.join(prefs.datadir, 'nmrdata', 'bruker', 'tests', 'nmr', 'topspin_1d') ndd = NDDataset.read_topspin(path, expno=1, remove_digital_filter=True) ndd /= ndd.real.data.max() # normalize ndd.em(10. * ur.Hz) # inplace broadening transf = ndd.fft(tdeff=8192, size=2 ** 15) transfph1 = transf.pk(verbose=True) transfph1.plot(xlim=(20, -20), color='k') transfph2 = transf.pk(verbose=True) transfph2.plot(xlim=(20, -20), clear=False, color='r') transfph3 = transf.pk(52.43836, -16.8366, verbose=True) transfph3.plot(xlim=(20, -20), clear=False, color='b') show() def test_nmr_multiple_auto_1D_phasing(): path = os.path.join(prefs.datadir, 'nmrdata', 'bruker', 'tests', 'nmr', 'topspin_1d') ndd = NDDataset.read_topspin(path, expno=1, remove_digital_filter=True) ndd /= ndd.real.data.max() # normalize ndd.em(10. * ur.Hz) # inplace broadening transf = ndd.fft(tdeff=8192, size=2 ** 15) transf.plot(xlim=(20, -20), ls=':', color='k') t1 = transf.apk(algorithm='neg_peak', verbose=True) (t1 - 5.).plot(xlim=(20, -20), clear=False, color='b') t2 = t1.apk(algorithm='neg_area', verbose=True) (t2 - 10).plot(xlim=(20, -20), clear=False, ls='-.', color='m') t3 = t2.apk(algorithm='acme', verbose=True) (t3 - 15).plot(xlim=(20, -20), clear=False, color='r') show() # #### 2D NMR ######## def test_nmr_reader_2D(): path = os.path.join(prefs.datadir, 'nmrdata', 'bruker', 'tests', 'nmr', 'topspin_2d') # load the data in a new dataset ndd = NDDataset() ndd.read_topspin(path, expno=1, remove_digital_filter=True) assert ndd.__str__() == "NDDataset: [quaternion] unitless (shape: (y:96, x:948))" assert "<tr><td style='padding-right:5px; padding-bottom:0px; padding-top:0px;" in ndd._repr_html_() def test_nmr_2D_imag(NMR_dataset_2D): # plt.ion() dataset = NMR_dataset_2D.copy() dataset.plot(imag=True) show() pass def test_nmr_2D_imag_compare(NMR_dataset_2D): # plt.ion() dataset = NMR_dataset_2D.copy() dataset.plot() dataset.plot(imag=True, cmap='jet', data_only=True, alpha=.3, clear=False) # better not to replot a second colorbar show() pass def test_nmr_2D_hold(NMR_dataset_2D): dataset = NMR_dataset_2D dataset.plot() dataset.imag.plot(cmap='jet', data_only=True, clear=False) show() pass # apodization def test_nmr_2D_em_x(NMR_dataset_2D): dataset = NMR_dataset_2D.copy() assert dataset.shape == (96, 948) dataset.plot_map() # plot original dataset = NMR_dataset_2D.copy() dataset.plot_map() dataset.em(lb=50. * ur.Hz, axis=-1) assert dataset.shape == (96, 948) dataset.plot_map(cmap='copper', data_only=True, clear=False) # em on dim=x dataset = NMR_dataset_2D.copy() dataset.plot_map() dataset.em(lb=50. * ur.Hz, dim='x') assert dataset.shape == (96, 948) dataset.plot_map(cmap='copper', data_only=True, clear=False) # em on dim=x show() pass def test_nmr_2D_em_y(NMR_dataset_2D): dataset = NMR_dataset_2D.copy() assert dataset.shape == (96, 948) dataset.plot_map() # plot original dataset = NMR_dataset_2D.copy() dataset.plot_map() dataset.em(lb=50. * ur.Hz, dim=0) assert dataset.shape == (96, 948) dataset.plot_map(cmap='copper', data_only=True, clear=False) # em on dim=x dataset = NMR_dataset_2D.copy() dataset.plot_map() dataset.em(lb=50. * ur.Hz, dim='y') assert dataset.shape == (96, 948) dataset.plot_map(cmap='copper', data_only=True, clear=False) # em on dim=x show() def test_nmr_2D(NMR_dataset_2D): dataset = NMR_dataset_2D dataset.plot(nlevels=20) # , start=0.15) show() pass <file_sep>/spectrochempy/core/analysis/peakfinding.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ['find_peaks'] __dataset_methods__ = ['find_peaks'] import scipy.signal import numpy as np from datetime import datetime, timezone """wrappers of scipy.signal peak finding functions""" # Todo: # find_peaks_cwt(vector, widths[, wavelet, ...]) Attempt to find the peaks in a 1-D array. # argrelmin(data[, axis, order, mode]) Calculate the relative minima of data. # argrelmax(data[, axis, order, mode]) Calculate the relative maxima of data. # argrelextrema(data, comparator[, axis, ...]) Calculate the relative extrema of data. def find_peaks(dataset, height=None, window_length=3, threshold=None, distance=None, prominence=None, width=None, wlen=None, rel_height=0.5, plateau_size=None, use_coord=True): """ Wrapper and extension of scpy.signal.find_peaks(). Find peaks inside a 1D NDDataset based on peak properties. This function finds all local maxima by simple comparison of neighbouring values. Optionally, a subset of these peaks can be selected by specifying conditions for a peak's properties. Parameters ---------- dataset : |NDDataset| A 1D NDDataset or a 2D NDdataset with `len(X.y) == 1` height : number or ndarray or sequence, optional Required height of peaks. Either a number, ``None``, an array matching `x` or a 2-element sequence of the former. The first element is always interpreted as the minimal and the second, if supplied, as the maximal required height. window_length: int, default: 5 The length of the filter window used to interpolate the maximum. window_length must be a positive odd integer. If set to one, the actual maximum is returned. threshold : number or ndarray or sequence, optional Required threshold of peaks, the vertical distance to its neighbouring samples. Either a number, ``None``, an array matching `x` or a 2-element sequence of the former. The first element is always interpreted as the minimal and the second, if supplied, as the maximal required threshold. distance : number, optional Required minimal horizontal distance (>= 1) in samples between neighbouring peaks. Smaller peaks are removed first until the condition is fulfilled for all remaining peaks. prominence : number or ndarray or sequence, optional Required prominence of peaks. Either a number, ``None``, an array matching `x` or a 2-element sequence of the former. The first element is always interpreted as the minimal and the second, if supplied, as the maximal required prominence. width : number or ndarray or sequence, optional Required width of peaks in samples. Either a number, ``None``, an array matching `x` or a 2-element sequence of the former. The first element is always interpreted as the minimal and the second, if supplied, as the maximal required width. Floats are interpreted as width measured along the 'x' Coord; ints are interpreted as a number of points wlen : int or float, optional Used for calculation of the peaks prominences, thus it is only used if one of the arguments `prominence` or `width` is given. Floats are interpreted as measured along the 'x' Coord; ints are interpreted as a number of points. See argument len` in `peak_prominences` of the scipy documentation for a full description of its effects. rel_height : float, optional, Used for calculation of the peaks width, thus it is only used if `width` is given. See argument `rel_height` in `peak_widths` of the scipy documentation for a full description of its effects. plateau_size : number or ndarray or sequence, optional Required size of the flat top of peaks in samples. Either a number, ``None``, an array matching `x` or a 2-element sequence of the former. The first element is always interpreted as the minimal and the second, if supplied as the maximal required plateau size. Floats are interpreted as measured along the 'x' Coord; ints are interpreted as a number of points. interp: bool, optional locate maximum by quadratic interpolation use_coord : bool, optional Set whether the x Coord (when it exists) should be used instead of indices for the positions and width Returns ------- peaks : ndarray Indices of peaks in `x` that satisfy all given conditions. properties : dict A dictionary containing properties of the returned peaks which were calculated as intermediate results during evaluation of the specified conditions: * peak_heights If `height` is given, the height of each peak in `x`. * left_thresholds, right_thresholds If `threshold` is given, these keys contain a peaks vertical distance to its neighbouring samples. * prominences, right_bases, left_bases If `prominence` is given, these keys are accessible. See `peak_prominences` for a description of their content. * width_heights, left_ips, right_ips If `width` is given, these keys are accessible. See `peak_widths` for a description of their content. * plateau_sizes, left_edges', 'right_edges' If `plateau_size` is given, these keys are accessible and contain the indices of a peak's edges (edges are still part of the plateau) and the calculated plateau sizes. To calculate and return properties without excluding peaks, provide the open interval ``(None, None)`` as a value to the appropriate argument (excluding `distance`). Warns ----- PeakPropertyWarning Raised if a peak's properties have unexpected values (see `peak_prominences` and `peak_widths`). Warnings -------- This function may return unexpected results for data containing NaNs. To avoid this, NaNs should either be removed or replaced. See Also -------- find_peaks_cwt: in scipy.signal: Find peaks using the wavelet transformation. peak_prominences: in scipy.signal: Directly calculate the prominence of peaks. peak_widths: in scipy.signal: Directly calculate the width of peaks. Notes ----- In the context of this function, a peak or local maximum is defined as any sample whose two direct neighbours have a smaller amplitude. For flat peaks (more than one sample of equal amplitude wide) the index of the middle sample is returned (rounded down in case the number of samples is even). For noisy signals the peak locations can be off because the noise might change the position of local maxima. In those cases consider smoothing the signal before searching for peaks or use other peak finding and fitting methods (like `find_peaks_cwt`). Some additional comments on specifying conditions: * Almost all conditions (excluding `distance`) can be given as half-open or closed intervals, e.g ``1`` or ``(1, None)`` defines the half-open interval :math:`[1, \\infty]` while ``(None, 1)`` defines the interval :math:`[-\\infty, 1]`. The open interval ``(None, None)`` can be specified as well, which returns the matching properties without exclusion of peaks. * The border is always included in the interval used to select valid peaks. * For several conditions the interval borders can be specified with arrays matching `x` in shape which enables dynamic constrains based on the sample position. * The conditions are evaluated in the following order: `plateau_size`, `height`, `threshold`, `distance`, `prominence`, `width`. In most cases this order is the fastest one because faster operations are applied first to reduce the number of peaks that need to be evaluated later. * While indices in `peaks` are guaranteed to be at least `distance` samples apart, edges of flat peaks may be closer than the allowed `distance`. * Use `wlen` to reduce the time it takes to evaluate the conditions for `prominence` or `width` if `x` is large or has many local maxima (see `peak_prominences`). """ X = dataset.squeeze() if X.ndim > 1: raise ValueError("Works only for 1D NDDataset or a 2D NDdataset with `len(X.y) <= 1`") if window_length % 2 == 0: raise ValueError("window_length must be an odd integer") # if the following parameters are entered as floats, the coordinates are used. Else, they will # be treated as indices as in scipy.signal.find_peak() # transform coord (if exists) to index if use_coord and X.coordset is not None: step = np.abs(X.x.data[-1] - X.x.data[0]) / (len(X.x) - 1) if distance is not None: distance = int(round(distance / step)) if width is not None: width = int(round(width / step)) if wlen is not None: wlen = int(round(wlen / step)) if plateau_size is not None: plateau_size = int(round(plateau_size / step)) data = X.data peaks, properties = scipy.signal.find_peaks(data, height=height, threshold=threshold, distance=distance, prominence=prominence, width=width, wlen=wlen, rel_height=rel_height, plateau_size=plateau_size) # if dataset.ndim == 1: out = X[peaks] # else: # ndim == 2 # out = dataset[:, peaks] if window_length > 1: # quadratic interpolation to find the maximum for i, peak in enumerate(peaks): y = data[peak - window_length // 2:peak + window_length // 2 + 1] if use_coord and X.coordset is not None: x = X.x.data[peak - window_length // 2:peak + window_length // 2 + 1] else: x = range(peak - window_length // 2, peak + window_length // 2 + 1) coef = np.polyfit(x, y, 2) x_at_max = - coef[1] / (2 * coef[0]) y_at_max = np.poly1d(coef)(x_at_max) if out.ndim == 1: out[i] = y_at_max else: out[:, i] = y_at_max out.x.data[i] = x_at_max # transform back index to coord if use_coord and X.coordset is not None: for key in ('left_bases', 'right_bases', 'left_edges', 'right_edges'): # values are int type if key in properties: properties[key] = properties[key].astype('float64') for i, index in enumerate(properties[key]): properties[key][i] = X.x.data[int(index)] for key in ('left_ips', 'right_ips'): # values are float type if key in properties: for i, ips in enumerate(properties[key]): # interpolate coord floor = int(np.floor(ips)) properties[key][i] = X.x.data[floor] + (ips - floor) * (X.x.data[floor + 1] - X.x.data[floor]) if 'widths' in properties: for i in range(len(properties['widths'])): properties['widths'][i] = np.abs(properties['left_ips'][i] - properties['right_ips'][i]) if 'plateau_sizes' in properties: properties['plateau_sizes'] = properties['plateau_sizes'].astype('float64') for i in range(len(properties['plateau_sizes'])): properties['plateau_sizes'][i] = np.abs(properties['left_edges'][i] - properties['right_edges'][i]) out.name = 'peaks of ' + X.name out.history[-1] = str(datetime.now(timezone.utc)) + f': find_peaks(): {len(peaks)} peak(s) found' return out, properties <file_sep>/docs/gettingstarted/examples/analysis/plot_2D_iris.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ 2D-IRIS analysis example ========================= In this example, we perform the 2D IRIS analysis of CO adsorption on a sulfide catalyst. """ import spectrochempy as scp ######################################################################################################################## # ## Uploading dataset X = scp.read('irdata/CO@Mo_Al2O3.SPG') ######################################################################################################################## # ``X`` has two coordinates: # * `wavenumbers` named "x" # * and `timestamps` (*i.e.,* the time of recording) named "y". print(X.coordset) ######################################################################################################################## # ## Setting new coordinates # # Each experiments corresponding to a timestamp correspond to a given pressure of CO in the intrared cell. # # Hence it would be interesting to replace the "useless" timestamps (``y``) by a pressure coordinates: pressures = [0.00300, 0.00400, 0.00900, 0.01400, 0.02100, 0.02600, 0.03600, 0.05100, 0.09300, 0.15000, 0.20300, 0.30000, 0.40400, 0.50300, 0.60200, 0.70200, 0.80100, 0.90500, 1.00400] "" c_pressures = scp.Coord(pressures, title='pressure', units='torr') ############################################################################### # Now we can set multiple coordinates: c_times = X.y.copy() # the original coordinate X.y = [c_times, c_pressures] print(X.y) ############################################################################### # By default, the current coordinate is the first one (here `c_times`). For example, it will be used for plotting: prefs = X.preferences prefs.figure.figsize = (7,3) _ = X.plot(colorbar=True) _ = X.plot_map(colorbar=True) ############################################################################### # To seamlessly work with the second coordinates (pressures), we can change the default coordinate: X.y.select(2) # to select coordinate ``_2`` X.y.default ######################################################################################################################## # Let's now plot the spectral range of interest. The default coordinate is now used: X_ = X[:, 2250.:1950.] print(X_.y.default) _ = X_.plot() _ = X_.plot_map() ############################################################################### # ## IRIS analysis without regularization ######################################################################################################################## # Perform IRIS without regularization (the verbose flag can be set to True to have information on the running process) param = { 'epsRange': [-8, -1, 50], 'kernel': 'langmuir' } iris = scp.IRIS(X_, param, verbose=False) ######################################################################################################################## # Plots the results iris.plotdistribution() _ = iris.plotmerit() ############################################################################### # ## With regularization and a manual seach ######################################################################################################################## # Perform IRIS with regularization, manual search param = { 'epsRange': [-8, -1, 50], 'lambdaRange': [-10, 1, 12], 'kernel': 'langmuir' } iris = scp.IRIS(X_, param, verbose=False) iris.plotlcurve() iris.plotdistribution(-7) _ = iris.plotmerit(-7) ############################################################################### # ## Automatic search ######################################################################################################################## # Now try an automatic search of the regularization parameter: param = { 'epsRange': [-8, -1, 50], 'lambdaRange': [-10, 1], 'kernel': 'langmuir' } iris = scp.IRIS(X_, param, verbose=False) iris.plotlcurve() iris.plotdistribution(-1) _ = iris.plotmerit(-1) "" # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/docs/userguide/project/project.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # Project management # # from pathlib import Path # %% from spectrochempy import NDDataset, Project, preferences as prefs, pathclean # %% [markdown] # ## Project creation # We can easily create a new project to store various datasets # %% proj = Project() # %% [markdown] # As we did not specify a name, a name has been attributed automatically: # %% proj.name # %% [markdown] # ------ # To get the signature of the object, one can use the usual '?'. Uncomment the following line to check # %% # Project? # %% [markdown] # ---- # Let's change this name # %% proj.name = 'myNMRdata' proj # %% [markdown] # Now we will add a dataset to the project. # # First we read the dataset (here some NMR data) and we give it some name (e.g. 'nmr n°1') # %% datadir = pathclean(prefs.datadir) path = datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' nd1 = NDDataset.read_topspin(path / 'topspin_1d', expno=1, remove_digital_filter=True, name="NMR_1D") nd2 = NDDataset.read_topspin(path / 'topspin_2d', expno=1, remove_digital_filter=True, name='NMR_2D') # %% [markdown] # To add it to the project, we use the `add_dataset` function for a single dataset: # %% proj.add_datasets(nd1) # %% [markdown] # or `add_datasets` for several datasets. # %% proj.add_datasets(nd1, nd2) # %% [markdown] # Display its structure # %% proj # %% [markdown] # It is also possible to add other projects as sub-project (using the `add_project`) # %% [markdown] # ## Remove an element from a project # %% proj.remove_dataset('NMR_1D') proj # %% [markdown] # ## Get project's elements # %% proj.add_datasets(nd1, nd2) proj # %% [markdown] # We can just use the name of the element as a project attribute. # %% proj.NMR_1D # %% _ = proj.NMR_1D.plot() # %% [markdown] # However this work only if the name contains no space, dot, comma, colon, etc. The only special character allowed is # the underscore `_`. If the name is not respecting this, then it is possible to use the following syntax (as a # project behave as a dictionary). For example: # %% proj['NMR_1D'].data # %% proj.NMR_2D # %% [markdown] # ## Saving and loading projects # %% proj # %% [markdown] # #### Saving # %% proj.save_as('NMR') # %% [markdown] # #### Loading # %% proj2 = Project.load('NMR') # %% proj2 # %% _ = proj2.NMR_1D.plot() # %% proj2.NMR_2D # %% proj.NMR_2D.plot() # %% <file_sep>/spectrochempy/databases/isotopes.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, # Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in # the root directory = # ====================================================================================================================== """ Database isotopes for NMR This module essentially define a class :class:`Isotopes` which handle all necessary features of NMR nuclei, such as their spin, larmor frequency and so on. """ __all__ = ['Isotopes'] import pathlib import re from fractions import Fraction import numpy as np from spectrochempy.units import ur from spectrochempy.core import preferences as prefs from spectrochempy.core.dataset.meta import Meta # ====================================================================================================================== # Isotopes class # ====================================================================================================================== class Isotopes(Meta): # lgtm [py/missing-call-to-init] """ This class defines useful properties of nuclei. [#]_ Parameters ---------- nucleus : String, optional, default='1H' In the AX form where A is the atomic mass and X the atom symbol References ---------- .. [#] Nuclear magnetic moments are taken from Stone, Table of Nuclear Magnetic Dipole and Electric Quadrupole Moments, Atomic Data and Nuclear Data Tables 90, 75-176 (2005). Nuclear quadrupole moments are taken from P.Pyykko, Mol.Phys. 99, 1617-1629 (2001) and the 2002 edition of the CRC Handbook of Physics and Chemistry (which took it from Pyykko and others). Examples -------- How to use it? after the |scpy| has been loaded : >>> from spectrochempy import * one can use : >>> isotope = Isotopes('129Xe') >>> isotope.name 'xenon' >>> isotope.spin Fraction(1, 2) >>> isotope.symbol 'Xe' >>> isotope.nucleus = '27Al' # we change the isotope`inplace` >>> isotope.name 'aluminium' >>> isotope.spin Fraction(5, 2) >>> isotope.symbol 'Al' >>> isotope.nucleus = 'Al27' >>> isotope.name 'aluminium' """ _nucleus = '' # ------------------------------------------------------------------------------------------------------------------ # isotope / alias of nucleus # ------------------------------------------------------------------------------------------------------------------ @property def isotope(self): """The current isotope (alias for nucleus)""" return self.nucleus.strip() # ------------------------------------------------------------------------------------------------------------------ # spin # ------------------------------------------------------------------------------------------------------------------ @property def spin(self): """Spin quantum number of the current nucleus""" return Fraction(self[self.nucleus]['spin']) # =========================================================================== # Z # =========================================================================== @property def Z(self): """Atomic number of the current nucleus""" return self[self.nucleus]['Z'] # =========================================================================== # A # =========================================================================== @property def A(self): """Atomic mass of the current nucleus""" return self[self.nucleus]['A'] # =========================================================================== # full name # =========================================================================== @property def name(self): """the name of the nucleus""" return self[self.nucleus]['name'].strip() # =========================================================================== # gamma # =========================================================================== @property def gamma(self): """gyromagnetic ratio of the current nucleus""" muN = ur.elementary_charge / ur.proton_mass / 2. / (2. * np.pi) return (self[self.nucleus]['gamma'] * muN).to('MHz/T') # =========================================================================== # _get_abundance # =========================================================================== @property def abundance(self): """natural abundance in percent of the current nucleus""" return self[self.nucleus]['abundance'] # =========================================================================== # _get_Q # =========================================================================== @property def Q(self): """ Electric quadrupole moment in barn ' 'of the current nucleus """ try: return float(self[self.nucleus]['Q']) * 1000. * ur.mbarn except Exception: return 0. * ur.barn # ------------------------------------------------------------------------------------------------------------------ # symbol # ------------------------------------------------------------------------------------------------------------------ @property def symbol(self): """Symbol of the current nucleus""" return self[self.nucleus]['symbol'].strip() # ------------------------------------------------------------------------------------------------------------------ # Stability # ------------------------------------------------------------------------------------------------------------------ @property def stability(self): """ The stability of the current nucleus """ return self[self.nucleus]['stability'].strip() @property def nucleus(self): return self._get_nucleus(self._nucleus) def _get_nucleus(self, nuc): if nuc in list(self.keys()): return nuc p = re.compile(r'^([A-Z,a-z]+)[_-]*([0-9]+$)') m = re.match(p, nuc).groups() nuc = m[1] + m[0] # transform "e.g., Al27->27Al, ou AL-27 to 27Al" if nuc in list(self.keys()): return nuc else: raise KeyError(f'Unknown isotope symbol : {nuc}') # ------------------------------------------------------------------------------------------------------------------ # initializer # ------------------------------------------------------------------------------------------------------------------ def __init__(self, nucleus='1H'): # filename = resource_filename(PKG, 'isotopes.csv') DATABASES = pathlib.Path(prefs.databases) filename = DATABASES / 'isotopes.csv' txt = filename.read_text() arr = txt.replace(" ", "").split('\n') keys = arr[0].split(',') dic = {} for line in arr[1:]: vals = line.split(',') dic[vals[0]] = dict(zip(keys[1:], vals[1:])) self._data = self._isotopes_validate(dic) self.nucleus = nucleus # ------------------------------------------------------------------------------------------------------------------ # Private interface # ------------------------------------------------------------------------------------------------------------------ def __str__(self): return self.nucleus.strip() def __repr__(self): return "Isotopes < " + self.nucleus.strip() + " >" def _repr_html_(self): return "<sup>%s</sup>%s [%s]" % (self.A, self.symbol, self.spin) def __getattr__(self, key): key = self._get_nucleus(key) if key != self.nucleus: return Isotopes(key) else: return self[key] def __setattr__(self, key, value): if key not in ['nucleus', 'readonly', '_data', '_trait_notifiers', '_trait_values', '_trait_validators', '_cross_validation_lock']: self[key] = value elif key == 'nucleus': self.__dict__['_nucleus'] = value else: self.__dict__[key] = value # to avoid a recursive call # we can not use # self._readonly = value! def _isotopes_validate(self, pv): for key, item in pv.items(): if not key or not item: continue pv[key] = {'name': item['name'], 'symbol': item['symbol'], 'A': int(item['A']), 'Q': float(item['quadrupole']), 'Z': int(item['Z']), 'gamma': float(item['gn']), 'spin': float(item['spin']), 'abundance': float(item['abundance']), 'stablity': item['stability'], } return pv def __eq__(self, other): raise NotImplementedError # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/docs/devguide/examples.rst .. _contributing.examples: Adding new tutorials --------------------- Adding your examples to the gallery ------------------------------------ If you have any nice examples to add to the SpectroChemPy gallery, they are more than welcome. They will allow other users to see the API in operation. There are two ways to do this: * Use the discussion forums and attach your files, which we will take into account after revisions, mentioning of course the origin and the possible copyright. * Create a pull request: For this operation, if you are a newcomer with the `git` version system, please refer to the :ref:`develguide` section . <file_sep>/docs/devguide/be_prepared.rst .. _be_prepared: Be prepared to work on the code ================================ To contribute further to the code and documentation, you will need learning how to work with GitHub and the |scpy| code base. .. _contributing.version_control: Version control, Git, and GitHub --------------------------------- The code of |scpy| is hosted on `GitHub <https://www.github.com/spectrochempy/spectrochempy>`__. To contribute, you will need to register for a `free GitHub account <https://github.com/signup/free>`__. Actually, you may have already done this while submitting issues, so you are also almost ready to contribute to the code. The reason we use `Git <https://git-scm.com/>`__ to version controlling our code is to allow several people to work on this project simultaneously. However, working with `Git <https://git-scm.com/>`__ is unfortunately not the easiest step for a newcomer when trying to contribute to an open-source software. But learning this versioning system at the same time as developing with Python can be very rewarding for your daily work. To learn `Git <https://git-scm.com/>`__, you may want to check out the `GitHub help pages <https://help.github.com/>`_ or the `NumPy's documentation <https://numpy.org/doc/stable/dev/index.html>`__. There is no shortage of resources on the web on this subject and many tutorials are available. Below we give some essential information to get you started with **Git**, but of course if you encounter difficulties, don't hesitate to ask for help. This may help to solve your problems faster, but it also allows us to improve this part of our documentation based on your feedback. Installing git --------------- `GitHub <https://help.github.com/set-up-git-redirect>`__ has instructions for installing and configuring git. All these steps need to be completed before you can work seamlessly between your local repository and GitHub. Git is a free and open source distributed control system used in well-known software repositories, such as `GitHub <https://github.com>`__ or `Bitbucket <https://bitbucket.org>`__. For this project, we use a GitHub repository: `spectrochempy repository <https://github.com/spectrochempy/spectrochempy>`__. Depending on your operating system, you may refer to these pages for installation instructions: - `Download Git for macOS <https://git-scm.com/download/mac>`__ (One trivial option is to install `XCode <https://developer.apple.com/xcode/>`__ which is shipped with the git system). - `Download Git for Windows <https://git-scm.com/download/win>`__. - `Download for Linux and Unix <https://git-scm.com/download/linux>`__. For the common Debian/Ubuntu distribution, it is as simple as typing in the Terminal: .. sourcecode:: bash sudo apt-get install git - Alternatively, once miniconda or anaconda is installed (see :ref:`contributing.dev_env`), one can use conda to install git: .. sourcecode:: bash conda install git To check whether or not *git* is correctly installed, use .. sourcecode:: bash git --version Optional: installing a GUI git client ------------------------------------- Once your installation of git is complete, it may be useful to install a GUI client for the git version system. We have been using `SourceTree client <https://www.sourcetreeapp.com>`__ (which can be installed on both Windows and Mac operating systems). To configure and learn how to use the sourcetree GUI application, you can consult this `tutorial <https://confluence.atlassian.com/bitbucket/tutorial-learn-bitbucket-with-sourcetree-760120235.html>`__ However, any other GUI can be interesting such as `Github-desktop <https://desktop.github.com>`__, or if you prefer, you can stay using the command line in a terminal. .. note:: Many IDE such as `PyCharm <https://www.jetbrains.com/fr-fr/pycharm/>`__ have an integrated GUI git client which can be used in place of an external application. This is an option that we use a lot (in combination to the more visual SourceTree application) .. _contributing.forking: Forking the spectrochempy repository ------------------------------------ You will need your own fork to work on the code. Go to the `SpectroChemPy project page <https://github.com/spectrochempy/spectrochempy>`__ and hit the ``Fork`` button to create an exact copy of the project on your account. Then you will need to clone your fork to your machine. The fastest way is to type these commands in a terminal on your machine: .. sourcecode:: bash git clone https://github.com/your-user-name/spectrochempy.git localfolder cd localfolder git remote add upstream https://github.com/spectrochempy/spectrochempy.git This creates the directory ``localfolder`` and connects your repository to the upstream (main project) |scpy| repository. .. _contributing.dev_env: Creating a Python development environment ------------------------------------------ To test out code and documentation changes, you'll need to build |scpy| from source, which requires a Python environment. * Install either `Anaconda <https://www.anaconda.com/download/>`_, `miniconda <https://conda.io/miniconda.html>`_, or `miniforge <https://github.com/conda-forge/miniforge>`_ * Make sure your conda is up to date (``conda update conda``) * Make sure that you have :ref:`cloned the repository <contributing.forking>` * ``cd`` to the |scpy| source directory (*i.e.,* ``localfolder`` created previously) We'll now install |scpy| in development mode following 2 steps: 1. Create and activate the environment. This will create a new environment and will not touch any of your other existing environments, nor any existing Python installation. (conda installer is somewhat very slow, this is why we prefer to replace it by `mamba <https://https://github.com/mamba-org/mamba>`__. .. sourcecode:: bash conda update conda -y conda config --add channels conda-forge conda config --add channels cantera conda config --add channels spectrocat conda config --set channel_priority flexible conda install mamba jinja2 Here we will create un environment using python in its version 3.9 but it is up to you to install any version from 3.6.9 to 3.9. Just change the relevant information in the code below (the first line use a script to create the necessary yaml file containing all information about the packages to install): .. sourcecode:: bash python .ci/env/env_create.py -v 3.9 --dev scpy3.9.yml mamba env create -f .ci/env/scpy3.9.yml conda activate scpy3.9 2. Install |scpy| Once your environment is created and activated, we must install SpectroChemPy in development mode. .. sourcecode:: bash (scpy3.9) $ cd <spectrochempy folder> (scpy3.9) $ python setup.py develop At this point you should be able to import spectrochempy from your local development version: .. sourcecode:: bash (scpy3.9) $ python This start an interpreter in which you can check your installation .. sourcecode:: python >>> import spectrochempy as scp >>> print(scp.version) SpectroChemPy's API ... >>> exit() Controling the environments --------------------------- You can create as many environment you want, using the method above (for example with different versions of python) To view your environments: .. sourcecode:: bash conda info -e To return to your root environment: .. sourcecode:: bash conda deactivate See the full conda docs `here <https://conda.pydata.org/docs>`__. Creating a branch ----------------- Generally we want the master branch to reflect only production-ready code, so you will have create a feature branch for making your changes. For example: .. sourcecode:: bash git branch my_new_feature git checkout my_new_feature The above can be simplified to: .. sourcecode:: bash git checkout -b my_new_feature This changes your working directory to the ``my-new-feature`` branch. Keep any changes in this branch specific to one bug or feature so it is clear what the branch brings to spectrochempy. You can have many ``my-other-new-feature`` branches and switch in between them using the: .. sourcecode:: bash git checkout command. When creating this branch, make sure your master branch is up to date with the latest upstream master version. To update your local master branch, you can do: .. sourcecode:: bash git checkout master git pull upstream master --ff-only When you want to update the feature branch with changes in master after you created the branch, check the section on :ref:`updating a PR <contributing.update-pr>`. <file_sep>/tests/test_processors/test_smooth.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import pytest from spectrochempy import show, np pytestmark = pytest.mark.skip("WIP with NMR data") def test_smooth(NMR_dataset_1D): dataset = NMR_dataset_1D.copy() dataset /= dataset.real.data.max() # nromalize dataset = dataset.fft(tdeff=8192, size=2 ** 15) + np.random.random(2 ** 15) * 5. dataset.plot() s = dataset.smooth() s.plot(clear=False, color='r', xlim=[20, -20]) show() def test_smooth_2D(IR_dataset_2D): dataset = IR_dataset_2D.copy() dataset /= dataset.real.data.max() # nromalize dataset += np.random.random(dataset.shape[-1]) * 0.02 s = dataset.smooth(length=21) (dataset + 0.25).plot(xlim=[4000, 3000]) s.plot(cmap='copper', clear=False, xlim=[4000, 3000]) s2 = s.smooth(length=21, dim='y') (s2 - 0.25).plot(cmap='jet', clear=False, xlim=[4000, 3000]) show() <file_sep>/tests/test_dataset/test_dataset.py import numpy as np import pytest from pint.errors import (UndefinedUnitError) from quaternion import quaternion import spectrochempy as scp from spectrochempy.units import ur from spectrochempy.utils import get_user_and_node, SpectroChemPyException from spectrochempy.utils.testing import (assert_dataset_equal, assert_dataset_almost_equal, assert_equal, assert_array_almost_equal, assert_array_equal, raises, RandomSeedContext, ) typequaternion = np.dtype(np.quaternion) # test minimal constructeur and dtypes adata = ([], [None, 1.], [np.nan, np.inf], [0, 1, 2], [0., 1., 3.], [0. + 1j, 10. + 3.j], [0. + 1j, np.nan + 3.j],) @pytest.mark.parametrize("a", adata) def test_1D_NDDataset(a): # 1D for arr in [a, np.array(a)]: ds = scp.NDDataset(arr) assert ds.size == len(arr) assert ds.shape == (ds.size,) if ds.size == 0: assert ds.dtype is None assert ds.dims == [] else: assert ds.dtype in [np.float64, np.complex128] assert ds.dims == ['x'] # force dtype ds = scp.NDDataset(arr, dtype=np.float32) if ds.size == 0: assert ds.dtype is None else: assert ds.dtype == np.float32 assert ds.title == "<untitled>" assert ds.mask == scp.NOMASK assert ds.meta == {} assert ds.name.startswith("NDDataset") assert ds.author == get_user_and_node() assert ds.description == "" assert ds.history == [] arrdata = (np.array([[1, 1.], [0, np.nan]]), np.random.rand(2, 3).astype('int64'), np.random.rand(2, 4),) @pytest.mark.parametrize("arr", arrdata) def test_2D_NDDataset(arr): # 2D ds = scp.NDDataset(arr) assert ds.size == arr.size assert ds.shape == arr.shape if ds.size == 0: assert ds.dtype is None assert ds.dims == [] else: assert ds.dtype == np.float64 assert ds.dims == ['y', 'x'][-ds.ndim:] assert ds.title == "<untitled>" assert ds.mask == scp.NOMASK assert ds.meta == {} assert ds.name.startswith("NDDataset") assert ds.author == get_user_and_node() assert not ds.history assert ds.description == "" # force dtype ds = scp.NDDataset(arr, dtype=np.float32) if ds.size == 0: assert ds.dtype is None else: assert ds.dtype == np.float32 if ds.shape[-1] % 2 == 0: # must be even ds = scp.NDDataset(arr, dtype=np.complex) if ds.size == 0: assert ds.dtype is None else: assert ds.dtype == np.complex128 else: with pytest.raises(ValueError): ds = scp.NDDataset(arr, dtype=np.complex) if (arr.shape[-1] % 2) == 0 and (arr.shape[-2] % 2) == 0 and arr.ndim == 2: ds = scp.NDDataset(arr, dtype=np.quaternion) if ds.size == 0: assert ds.dtype is None else: assert ds.dtype == np.quaternion else: with pytest.raises(ValueError): ds = scp.NDDataset(arr, dtype=np.quaternion) # test units ds1 = scp.NDDataset(arr * scp.ur.km) ds2 = scp.NDDataset(arr, units=scp.ur.km) assert ds1.units == scp.ur.km assert ds2.units == scp.ur.km assert_dataset_equal(ds1, ds2) # masking ds1[0] = scp.MASKED assert ds1.is_masked # init with another dataset ds2 = scp.NDDataset(ds1) assert_dataset_equal(ds1, ds2) # check no coordinates assert not ds2.is_complex assert ds2.coordset is None # no coordinates assert ds2.x is None # no coordinates with pytest.raises(AttributeError): ds2.t # dim attributes ds2 = scp.NDDataset(arr, dims=['u', 'w']) assert ds2.ndim == 2 assert ds2.dims == ['u', 'w'] def test_nddataset_coordset(): # init coordinates set at NDDataset initialization dx = np.random.random((10, 7, 3)) coord0 = np.arange(10) coord1 = np.arange(7) coord2 = np.arange(3) * 100. da = scp.NDDataset(dx, coordset=(coord0, coord1, coord2), title='absorbance', coordtitles=['wavelength', 'time-on-stream', 'temperature'], coordunits=['cm^-1', 's', 'K'], ) assert da.shape == (10, 7, 3) assert da.coordset.titles == ['temperature', 'time-on-stream', 'wavelength'] assert da.coordset.names == ['x', 'y', 'z'] assert da.coordunits == [ur.Unit('K'), ur.Unit('s'), ur.Unit('cm^-1')] # order of dims follow data shape, but not necessarily the coord list ( # which is ordered by name) assert da.dims == ['z', 'y', 'x'] assert da.coordset.names == sorted(da.dims) # transpose dat = da.T assert dat.dims == ['x', 'y', 'z'] # dims changed but did not change coords order ! assert dat.coordset.names == sorted(dat.dims) assert dat.coordtitles == da.coordset.titles assert dat.coordunits == da.coordset.units # too many coordinates cadd = scp.Coord(labels=['d%d' % i for i in range(6)]) coordtitles = ['wavelength', 'time-on-stream', 'temperature'] coordunits = ['cm^-1', 's', None] daa = scp.NDDataset(dx, coordset=[coord0, coord1, coord2, cadd, coord2.copy()], title='absorbance', coordtitles=coordtitles, coordunits=coordunits, ) assert daa.coordset.titles == coordtitles[::-1] assert daa.dims == ['z', 'y', 'x'] # with a CoordSet c0, c1 = scp.Coord(labels=['d%d' % i for i in range(6)]), scp.Coord(data=[1, 2, 3, 4, 5, 6]) cc = scp.CoordSet(c0, c1) cd = scp.CoordSet(x=cc, y=c1) ds = scp.NDDataset([1, 2, 3, 6, 8, 0], coordset=cd, units='m') assert ds.dims == ['x'] assert ds.x == cc ds.history = 'essai: 1' ds.history = 'try:2' # wrong type with pytest.raises(TypeError): ds.coord[1.3] # extra coordinates with pytest.raises(AttributeError): ds.y # invalid_length coord1 = scp.Coord(np.arange(9), title='wavelengths') # , units='m') coord2 = scp.Coord(np.arange(20), title='time') # , units='s') with pytest.raises(ValueError): scp.NDDataset(np.random.random((10, 20)), coordset=(coord1, coord2)) def test_nddataset_coords_indexer(): dx = np.random.random((10, 100, 10)) coord0 = np.linspace(4000, 1000, 10) coord1 = np.linspace(0, 60, 10) # wrong length coord2 = np.linspace(20, 30, 10) with pytest.raises(ValueError): # wrong lenth da = scp.NDDataset(dx, coordset=[coord0, coord1, coord2], title='absorbance', coordtitles=['wavelength', 'time-on-stream', 'temperature'], coordunits=['cm^-1', 's', 'K'], ) coord1 = np.linspace(0, 60, 100) da = scp.NDDataset(dx, coordset=[coord0, coord1, coord2], title='absorbance', coordtitles=['wavelength', 'time-on-stream', 'temperature'], coordunits=['cm^-1', 's', 'K'], ) assert da.shape == (10, 100, 10) coords = da.coordset assert len(coords) == 3 assert_array_almost_equal(da.coordset[2].data, coord0, decimal=2, err_msg="get axis by index " "failed") # we use almost as SpectroChemPy round the coordinate numbers assert_array_almost_equal(da.coordset['wavelength'].data, coord0, decimal=2, err_msg="get axis by title failed") assert_array_almost_equal(da.coordset['time-on-stream'].data, coord1, decimal=4, err_msg="get axis by title failed") assert_array_almost_equal(da.coordset['temperature'].data, coord2, decimal=3) da.coordset['temperature'] += 273.15 * ur.K assert_array_almost_equal(da.coordset['temperature'].data, coord2 + 273.15, decimal=3) # ====================================================================================================================== # Methods # ====================================================================================================================== def test_nddataset_str(): arr1d = scp.NDDataset([1, 2, 3]) assert '[float64]' in str(arr1d) arr2d = scp.NDDataset(np.array([[1, 2], [3, 4]])) assert str(arr2d) == 'NDDataset: [float64] unitless (shape: (y:2, x:2))' def test_nddataset_str_repr(ds1): arr1d = scp.NDDataset(np.array([1, 2, 3])) assert repr(arr1d).startswith('NDDataset') arr2d = scp.NDDataset(np.array([[1, 2], [3, 4]])) assert repr(arr2d).startswith('NDDataset') def test_nddataset_mask_valid(): scp.NDDataset(np.random.random((10, 10)), mask=np.random.random((10, 10)) > 0.5) def test_nddataset_copy_ref(): """ Tests to ensure that creating a new NDDataset object copies by *reference*. """ a = np.ones((10, 10)) nd_ref = scp.NDDataset(a) a[0, 0] = 0 assert nd_ref.data[0, 0] == 0 def test_nddataset_conversion(): nd = scp.NDDataset(np.array([[1, 2, 3], [4, 5, 6]])) assert nd.data.size == 6 assert nd.data.dtype == np.dtype('float64') def test_nddataset_invalid_units(): with pytest.raises(UndefinedUnitError): scp.NDDataset(np.ones((5, 5)), units="NotAValidUnit") def test_nddataset_units(nd1d): nd = nd1d.copy() nd = np.fabs(nd) nd.units = 'm' nd2 = np.sqrt(nd) assert isinstance(nd2, type(nd)) assert nd2.data[1] == np.sqrt(nd.data[1]) assert nd2.units == ur.m ** .5 nd.units = 'cm' nd2 = np.sqrt(nd) nd.ito('m') nd2 = np.sqrt(nd) assert isinstance(nd2, type(nd)) assert nd2.data[1] == np.sqrt(nd.data[1]) assert nd2.units == ur.m ** .5 def test_nddataset_masked_array_input(): a = np.random.randn(100) marr = np.ma.masked_where(a > 0, a) nd = scp.NDDataset(marr) # check that masks and data match assert_array_equal(nd.mask, marr.mask) assert_array_equal(nd.data, marr.data) # check that they are both by reference marr.mask[10] = ~marr.mask[10] marr.data[11] = 123456789 assert_array_equal(nd.mask, marr.mask) assert_array_equal(nd.data, marr.data) def test_nddataset_swapdims(nd1d, nd2d, ref_ds, ds1): nd1 = nd1d.copy() nd2 = nd2d.copy() nd3 = ds1.copy() # swapdims needs 2D at least assert nd1.shape == (10,) nd1s = nd1.swapdims(1, 0) assert_equal(nd1s.data, nd1.data) nd2s = nd2.swapdims(1, 0) assert nd2s.dims == nd2.dims[::-1] assert nd3.shape == ref_ds.shape nd3s = nd3.swapdims(1, 0) ref = ref_ds refs = np.swapaxes(ref, 1, 0) assert nd3.shape == ref.shape # original unchanged assert nd3s.shape == refs.shape assert nd3s is not nd3 assert nd3s.dims[:2] == nd3.dims[:2][::-1] nd3s = nd3.swapdims(1, 0, inplace=True) assert nd3.shape == refs.shape # original changed assert nd3s is nd3 # objects should be the same # use of the numpy method nd3s = np.swapaxes(nd3, 1, 0) assert nd3.shape == refs.shape # original unchanged (but was already # swapped) assert nd3s.shape == ref.shape assert nd3s is not nd3 # TODO: add check for swapdims of all elements # of a dataset such as meta # ################################## TEST # SLICING################################ def test_nddataset_loc2index(ref_ds, ds1): da = ds1 ref = ref_ds assert da.shape == ref.shape coords = da.coordset assert len(coords) == 3 assert da._loc2index(3990.0, dim=0) == 0 assert da._loc2index('j', dim=0) == 9 with pytest.raises(IndexError): da._loc2index('z', 0) # labels doesn't exist da._loc2index(5000, 0) assert da._loc2index(5000, 0) == (0, 'out_of_limits') # return the low limit assert da._loc2index(0, 0) == (9, 'out_of_limits') # return the high limit index def test_nddataset_slicing_by_index(ref_ds, ds1): da = ds1 ref = ref_ds # case where the index is an integer: the selection is by index starting # at zero assert da.shape == ref.shape coords = da.coordset plane0 = da[0] # should return a dataset of with dimension x of size 1 assert type(plane0) == type(da) assert plane0.ndim == 3 assert plane0.shape == (1, 100, 3) assert plane0.size == 300 assert plane0.dims == ['z', 'y', 'x'] assert_dataset_equal(plane0.z, da.z[0]) da1 = plane0.squeeze() assert da1.shape == (100, 3) assert da1.dims == ['y', 'x'] plane1 = da[:, 0] assert type(plane1) == type(da) assert plane1.ndim == 3 assert plane1.shape == (10, 1, 3) assert plane1.size == 30 assert plane1.dims == ['z', 'y', 'x'] da2 = plane1.squeeze() assert da2.dims == ['z', 'x'] assert_dataset_almost_equal(da2.z, coords[-1], decimal=2) # remember # coordinates # are ordered by name! assert_dataset_almost_equal(da2.x, coords[0]) # another selection row0 = plane0[:, 0] assert type(row0) == type(da) assert row0.shape == (1, 1, 3) # and again selection element = row0[..., 0] assert type(element) == type(da) assert element.dims == ['z', 'y', 'x'] # squeeze row1 = row0.squeeze() assert row1.mask == scp.NOMASK row1[0] = scp.MASKED assert row1.dims == ['x'] assert row1.shape == (3,) assert row1.mask.shape == (3,) element = row1[..., 0] assert element.x == coords[0][0] # now a slicing in multi direction da[1:4, 10:40:2, :2] # now again a slicing in multi direction (full selection) da[:, :, -2] # now again a slicing in multi direction (ellipsis) da[..., -1] da[-1, ...] def test_nddataset_slicing_by_label(ds1): da = ds1 # selection planeb = da['b'] assert type(planeb) == type(da) plane1 = da[1] assert_equal(planeb.data, plane1.data) assert planeb.ndim == 3 assert planeb.size == 300 bd = da['b':'f'] # the last index is included assert bd.shape == (5, 100, 3) b1 = da[1:6] assert_equal(bd.data, b1.data) bc = da['b':'f', :, "hot"] assert bc.shape == (5, 100, 1) assert bc.z.labels[0] == 'b' da[..., "hot"] # TODO: find a way to use such syntax # hot2 = da[ # # "x.hot"] # assert hot == hot2 def test_nddataset_slicing_by_values(ds1): da = ds1 x = da[3000.] assert x.shape == (1, 100, 3) y = da[3000.0:2000.0, :, 210.] assert y.shape == (4, 100, 1) # slicing by values should also work using reverse order da[2000.0:3000.0, :, 210.] def test_nddataset_slicing_out_limits(caplog, ds1): import logging logger = logging.getLogger('SpectroChemPy') logger.propagate = True caplog.set_level(logging.DEBUG) da = ds1 y1 = da[2000.] assert str(y1) == 'NDDataset: [float64] a.u. (shape: (z:1, y:100, x:3))' y2 = da[2000] assert y2 is None # as we are out of limits assert caplog.records[-1].levelname == 'ERROR' assert caplog.records[-1].message.startswith('Empty array of shape (0, 100, 3) resulted from slicing.') y3 = da[:, 95:105] assert str(y3) == 'NDDataset: [float64] a.u. (shape: (z:10, y:5, x:3))' da[5000.:4001.] assert y2 is None # as we are out of limits assert caplog.records[-1].levelname == 'ERROR' assert caplog.records[-1].message.startswith('Empty array of shape (0, 100, 3) resulted from slicing.') y5 = da[5000.:3000.] assert str(y5) == 'NDDataset: [float64] a.u. (shape: (z:4, y:100, x:3))' @raises(IndexError) def test_nddataset_slicing_toomanyindex(ds1): da = ds1 da[:, 3000.:2000., :, 210.] def test_nddataset_slicing_by_index_nocoords(ds1): da = ds1 # case where the index is an integer: # the selection is by index starting at zero da.delete_coordset() # clear coords plane0 = da[1] assert type(plane0) == type(da) # should return a dataset assert plane0.ndim == 3 assert plane0.size == 300 def test_nddataset_slicing_by_location_but_nocoords(ref_ds, ds1): da = ds1 # case where the index is an integer: # the selection is by index starting at zero da.delete_coordset() # clear coords # this cannot work (no coords for location) with pytest.raises(SpectroChemPyException): da[3666.7] # slicing tests def test_nddataset_simple_slicing(): d1 = scp.NDDataset(np.ones((5, 5))) assert d1.data.shape == (5, 5) assert d1.shape == (5, 5) d2 = d1[2:3, 2:3] assert d2.shape == (1, 1) assert (d1 is not d2) d3 = d1[2, 2] assert d3.shape == (1, 1) assert d3.squeeze().shape == () d3 = d1[0] assert d3.shape == (1, 5) def test_nddataset_slicing_with_mask(): mask = np.zeros((5, 5)).astype(bool) mask[1, 1] = True d1 = scp.NDDataset(np.ones((5, 5)), mask=mask) assert d1[1].shape == (1, 5) assert d1[1, 1].mask def test_nddataset_slicing_with_mask_units(): mask = np.zeros((5, 5)).astype(bool) mask[1, 1] = True d1 = scp.NDDataset(np.ones((5, 5)), mask=mask, units='m') assert d1[0].shape == (1, 5) def test_nddataset_slicing_with_coords(ds1): da = ds1.copy() da00 = da[0, 0] assert da00.shape == (1, 1, 3) assert da00.coordset['x'] == da00.coordset[0] assert da00.coordset['x'] == da.coordset[0] def test_nddataset_mask_array_input(): marr = np.ma.array([1., 2., 5.]) # Masked array with no masked entries nd = scp.NDDataset(marr) assert not nd.is_masked marr = np.ma.array([1., 2., 5.], mask=[True, False, False]) # Masked array nd = scp.NDDataset(marr) assert nd.is_masked def test_nddataset_unmasked_in_operation_with_masked_numpy_array(): ndd = scp.NDDataset(np.array([1, 2, 3])) np_data = -np.ones_like(ndd) np_mask = np.array([True, False, True]) np_arr_masked = np.ma.array(np_data, mask=np_mask) result1 = ndd * np_arr_masked assert result1.is_masked assert np.all(result1.mask == np_mask) # TODO: IndexError: in the future, 0-d boolean arrays will be # interpreted as a valid boolean index # assert np.all(result1[~result1.mask].data == -ndd.data[~np_mask]) result2 = np_arr_masked * ndd # Numpy masked array return a masked array in this case # assert result2.is_masked assert np.all(result2.mask == np_mask) # assert np.all(result2[ # # ~result2.mask].data == -ndd.data[~np_mask]) @pytest.mark.parametrize('shape', [(10,), (5, 5), (3, 10, 10)]) def test_nddataset_mask_invalid_shape(shape): with pytest.raises(ValueError) as exc: with RandomSeedContext(789): scp.NDDataset(np.random.random((10, 10)), mask=np.random.random(shape) > 0.5) assert exc.value.args[0] == 'mask {} and data (10, 10) shape mismatch!'.format(shape) @pytest.mark.parametrize('mask_in', [np.array([True, False]), np.array([1, 0]), [True, False], [1, 0]]) def test_nddataset_mask_init_without_np_array(mask_in): ndd = scp.NDDataset(np.array([1, 1]), mask=mask_in) assert (ndd.mask == mask_in).all() def test_nddataset_with_mask_acts_like_masked_array(): # test for #2414 input_mask = np.array([True, False, False]) input_data = np.array([1., 2., 3.]) ndd_masked = scp.NDDataset(input_data.copy(), mask=input_mask.copy()) # ndd_masked = np.sqrt(ndd_masked) other = - np.ones_like(input_data) result1 = np.multiply(ndd_masked, other) result2 = ndd_masked * other result3 = other * ndd_masked result4 = other / ndd_masked # Test for both orders of multiplication for result in [result1, result2, result3, result4]: assert result.is_masked # Result mask should match input mask because other has no mask assert np.all( result.mask == input_mask) # TODO:IndexError: in the # # future, 0-d boolean arrays will be # # interpreted # as a # valid # boolean index # assert np.all(result[~result.mask].data == - # # # # input_data[~input_mask]) def test_nddataset_creationdate(): ndd = scp.NDDataset([1., 2., 3.]) ndd2 = np.sqrt(ndd) assert ndd2._date is not None def test_nddataset_title(): ndd = scp.NDDataset([1., 2., 3.], title='xxxx') assert ndd.title == 'xxxx' ndd2 = scp.NDDataset(ndd, title='yyyy') assert ndd2.title == 'yyyy' ndd2.title = 'zzzz' assert ndd2.title == 'zzzz' def test_nddataset_real_imag(): na = np.array([[1. + 2.j, 2. + 0j], [1.3 + 2.j, 2. + 0.5j], [1. + 4.2j, 2. + 3j]]) nd = scp.NDDataset(na) # in the last dimension assert_array_equal(nd.real, na.real) assert_array_equal(nd.imag, na.imag) def test_nddataset_comparison(): ndd = scp.NDDataset([1., 2. + 1j, 3.]) val = ndd * 1.2 - 10. val = np.abs(val) assert np.all(val >= 6.) def test_nddataset_repr_html(): dx = np.random.random((10, 100, 3)) coord0 = scp.Coord(data=np.linspace(4000., 1000., 10), labels='a b c d e f g h i j'.split(), mask=None, units="cm^-1", title='wavelength') coord1 = scp.Coord(data=np.linspace(0., 60., 100), labels=None, mask=None, units="s", title='time-on-stream') coord2 = scp.Coord(data=np.linspace(200., 300., 3), labels=['cold', 'normal', 'hot'], mask=None, units="K", title='temperature') da = scp.NDDataset(dx, coordset=[coord0, coord1, coord2], title='absorbance', units='absorbance') da._repr_html_() # ### Metadata ################################################################ def test_nddataset_with_meta(ds1): da = ds1.copy() meta = scp.Meta() meta.essai = ['try_metadata', 10] da.meta = meta # check copy of meta dac = da.copy() assert dac.meta == da.meta # ### sorting ################################################################# def test_nddataset_sorting(ds1): # ds1 is defined in conftest dataset = ds1[:3, :3, 0].copy() dataset.sort(inplace=True, dim='z') labels = np.array(list('abc')) assert_array_equal(dataset.coordset['z'].labels, labels) # nochange because the axis is naturally iversed to force it # we need to specify descend dataset.sort(inplace=True, descend=False, dim='z') # order value in increasing order labels = np.array(list('cba')) assert_array_equal(dataset.coordset['z'].labels, labels) dataset.sort(inplace=True, dim='z') new = dataset.copy() new = new.sort(descend=False, inplace=False, dim='z') assert_array_equal(new.data, dataset.data[::-1]) assert (new[0, 0] == dataset[-1, 0]) assert_array_equal(new.coordset['z'].labels, labels) assert_array_equal(new.coordset["z"].data, dataset.coordset['z'].data[::-1]) # check for another dimension dataset = ds1.copy() new = ds1.copy() new.sort(dim='y', inplace=True, descend=False) assert_array_equal(new.data, dataset.data) assert (new[0, 0, 0] == dataset[0, 0, 0]) new = dataset.copy() new.sort(dim='y', inplace=True, descend=True) assert_array_equal(new.data, dataset.data[:, ::-1, :]) assert (new[0, -1, 0] == dataset[0, 0, 0]) # ### multiple axis # ############################################################# def test_nddataset_multiple_axis(ref_ds, coord0, coord1, coord2, coord2b, dsm): # dsm is defined in conftest ref = ref_ds da = dsm.copy() coordm = scp.CoordSet(coord2, coord2b) # check indexing assert da.shape == ref.shape coords = da.coordset assert len(coords) == 3 assert coords['z'] == coord0 assert da.z == coord0 assert da.coordset['wavenumber'] == coord0 assert da.wavenumber == coord0 assert da['wavenumber'] == coord0 # for multiple coordinates assert da.coordset['x'] == coordm assert da['x'] == coordm assert da.x == coordm # but we can also specify, which axis should be returned explicitely # by an index or a label assert da.coordset['x_1'] == coord2b assert da.coordset['x_2'] == coord2 assert da.coordset['x'][1] == coord2 assert da.coordset['x']._1 == coord2b assert da.x['_1'] == coord2b assert da['x_1'] == coord2b assert da.x_1 == coord2b x = da.coordset['x'] assert x['temperature'] == coord2 assert da.coordset['x']['temperature'] == coord2 # even simpler we can specify any of the axis title and get it ... assert da.coordset['time-on-stream'] == coord1 assert da.coordset['temperature'] == coord2 da.coordset['magnetic field'] += 100 * ur.millitesla assert da.coordset['magnetic field'] == coord2b + 100 * ur.millitesla def test_nddataset_coords_manipulation(dsm): dataset = dsm.copy() coord0 = dataset.coordset['y'] coord0 -= coord0[0] # remove first element def test_nddataset_square_dataset_with_identical_coordinates(): a = np.random.rand(3, 3) c = scp.Coord(np.arange(3) * .25, title='time', units='us') nd = scp.NDDataset(a, coordset=scp.CoordSet(x=c, y='x')) assert nd.x == nd.y # ### Test masks ###### def test_nddataset_use_of_mask(dsm): nd = dsm nd[950.:1260.] = scp.MASKED # ---------------------------------------------------------------------------------------------------------------------- # additional tests made following some bug fixes # ---------------------------------------------------------------------------------------------------------------------- def test_nddataset_repr_html_bug_undesired_display_complex(): da = scp.NDDataset([1, 2, 3]) da.title = 'intensity' da.description = 'Some experimental measurements' da.units = 'dimensionless' assert "(complex)" not in da._repr_html_() pass def test_nddataset_bug_fixe_figopeninnotebookwithoutplot(): da = scp.NDDataset([1, 2, 3]) da2 = np.sqrt(da ** 3) assert da2._fig is None # no figure should open def test_nddataset_bug_par_arnaud(): import spectrochempy as scp import numpy as np x = scp.Coord(data=np.linspace(1000., 4000., num=6000), title='x') y = scp.Coord(data=np.linspace(0., 10, num=5), title='y') data = np.random.rand(x.size, y.size) ds = scp.NDDataset(data, coordset=[x, y]) ds2 = ds[2000.0:3200.0, :] assert ds2.coordset.y.data.shape[0] == 2400, 'taille axe 0 doit être 2400' assert ds2.data.shape[0] == 2400, "taille dimension 0 doit être 2400" # ################ Complex and Quaternion, and NMR ################## def test_nddataset_create_from_complex_data(): # 1D (complex) nd = scp.NDDataset([1. + 2.j, 2. + 0j]) assert nd.data.size == 2 assert nd.size == 2 assert nd.data.shape == (2,) assert nd.shape == (2,) # 2D (complex in the last dimension - automatic detection) nd = scp.NDDataset([[1. + 2.j, 2. + 0j], [1.3 + 2.j, 2. + 0.5j], [1. + 4.2j, 2. + 3j]]) assert nd.data.size == 6 assert nd.size == 6 assert nd.data.shape == (3, 2) assert nd.shape == (3, 2) # 2D quaternion nd = scp.NDDataset([[1., 2.], [1.3, 2.], [1., 2.], [1., 2.], ], dtype=typequaternion) assert nd.data.size == 2 assert nd.size == 2 assert nd.data.shape == (2, 1) assert nd.shape == (2, 1) # take real part ndr = nd.real assert ndr.shape == (2, 1) assert not ndr.is_quaternion def test_nddataset_set_complex_1D_during_math_op(): nd = scp.NDDataset([1., 2.], coordset=[scp.Coord([10, 20])], units='meter') assert nd.data.size == 2 assert nd.size == 2 assert nd.shape == (2,) assert nd.units == ur.meter assert not nd.is_complex ndj = nd * 1j assert ndj.data.size == 2 assert ndj.is_complex def test_nddataset_create_from_complex_data_with_units(): # 1D nd = scp.NDDataset([1. + 2.j, 2. + 0j]) assert nd.data.size == 2 assert nd.size == 2 assert nd.data.shape == (2,) assert nd.shape == (2,) # add units nd.units = 'm**-1' nd.ito('cm^-1') # 2D nd2 = scp.NDDataset([[1. + 2.j, 2. + 0j], [1.3 + 2.j, 2. + 0.5j], [1. + 4.2j, 2. + 3j]]) assert nd2.data.size == 6 assert nd2.size == 6 assert nd2.data.shape == (3, 2) assert nd2.shape == (3, 2) # add units nd2.units = 'm**-1' nd2.ito('cm^-1') def test_nddataset_real_imag_quaternion(): na = np.array([[1. + 2.j, 2. + 0j, 1.3 + 2.j], [2. + 0.5j, 1. + 4.2j, 2. + 3j]]) nd = scp.NDDataset(na) # in the last dimension assert_array_equal(nd.real, na.real) assert_array_equal(nd.imag, na.imag) # in another dimension nd.set_quaternion(inplace=True) assert nd.is_quaternion assert nd.shape == (1, 3) na = np.array([[1. + 2.j, 2. + 0j], [1.3 + 2.j, 2. + 0.5j], [1. + 4.2j, 2. + 3j], [5. + 4.2j, 2. + 3j]]) nd = scp.NDDataset(na) nd.set_quaternion(inplace=True) assert nd.is_quaternion assert_array_equal(nd.real.data, na[::2, :].real) nb = np.array([[0. + 2.j, 0. + 0j], [1.3 + 2.j, 2. + 0.5j], [0. + 4.2j, 0. + 3j], [5. + 4.2j, 2. + 3j]]) ndj = scp.NDDataset(nb, dtype=quaternion) assert nd.imag == ndj def test_nddataset_quaternion(): na0 = np.array([[1., 2., 2., 0., 0., 0.], [1.3, 2., 2., 0.5, 1., 1.], [1, 4.2, 2., 3., 2., 2.], [5., 4.2, 2., 3., 3., 3.]]) nd = scp.NDDataset(na0) assert nd.shape == (4, 6) nd.dims = ['v', 'u'] nd.set_coordset(v=np.linspace(-1, 1, 4), u=np.linspace(-10., 10., 6)) nd.set_quaternion() # test swapdims nds = nd.swapdims(0, 1) assert_array_equal(nd.data.T, nds.data) assert nd.coordset[0] == nds.coordset[0] # we do not swap the coords # test transpose nds = nd.T assert_array_equal(nd.data.T, nds.data) assert nd.coordset[0] == nds.coordset[0] def test_nddataset_max_with_2D_quaternion(NMR_dataset_2D): # test on a 2D NDDataset nd2 = NMR_dataset_2D assert nd2.is_quaternion nd = nd2.RR nd.max() nd2.max() # no axis specified nd2.max(dim=0) # axis selected def test_nddataset_max_min_with_1D(NMR_dataset_1D): # test on a 1D NDDataset nd1 = NMR_dataset_1D nd1[4] = scp.MASKED assert nd1.is_masked mx = nd1.max() assert (mx.real, mx.imag) == pytest.approx((2283.5096153847107, -2200.383064516033)) # check if it works for real mx1 = nd1.real.max() assert mx1 == pytest.approx(2283.5096153847107) mi = nd1.min() assert (mi.real, mi.imag) == pytest.approx((-408.29714640199626, 261.1864143920416)) def test_nddataset_comparison_of_dataset(NMR_dataset_1D): # bug in notebook nd1 = NMR_dataset_1D.copy() nd2 = NMR_dataset_1D.copy() lb1 = nd1.em(lb=100. * ur.Hz) lb2 = nd2.em(lb=100. * ur.Hz) assert nd1 is not nd2 assert nd1 == nd2 assert lb1 is not lb2 assert lb1 == lb2 def test_nddataset_complex_dataset_slicing_by_index(): na0 = np.array([1. + 2.j, 2., 0., 0., -1.j, 1j] * 4) nd = scp.NDDataset(na0) assert nd.shape == (24,) assert nd.data.shape == (24,) coords = (np.linspace(-10., 10., 24),) nd.set_coordset(coords) x1 = nd.x.copy() nd.coordset = coords x2 = nd.x.copy() assert x1 == x2 # slicing nd1 = nd[0] assert nd1.shape == (1,) assert nd1.data.shape == (1,) # slicing range nd2 = nd[1:6] assert nd2.shape == (5,) assert nd2.data.shape == (5,) na0 = na0.reshape(6, 4) nd = scp.NDDataset(na0) coords = scp.CoordSet(np.linspace(-10., 10., 6), np.linspace(-1., 1., 4)) nd.set_coordset(**coords) assert nd.shape == (6, 4) assert nd.data.shape == (6, 4) nd.coordset = coords # slicing 2D nd1 = nd[0] assert nd1.shape == (1, 4) assert nd1.data.shape == (1, 4) # slicing range nd1 = nd[1:3] assert nd1.shape == (2, 4) assert nd1.data.shape == (2, 4) # slicing range nd1 = nd[1:3, 0:2] assert nd1.shape == (2, 2) assert nd1.data.shape == (2, 2) nd.set_complex() assert nd.shape == (6, 4) assert nd.data.shape == (6, 4) def test_nddataset_init_complex_1D_with_mask(): # test with complex with mask and units np.random.seed(12345) d = np.random.random((5)) * np.exp(.1j) d1 = scp.NDDataset(d, units=ur.Hz) # with units d1[1] = scp.MASKED assert d1.shape == (5,) assert d1._data.shape == (5,) assert d1.size == 5 assert d1.dtype == np.complex assert d1.has_complex_dims assert d1.mask.shape[-1] == 5 assert d1[2].data == d[2] d1R = d1.real assert not d1R.has_complex_dims assert d1R._data.shape == (5,) assert d1R._mask.shape == (5,) def test_nddataset_transpose_swapdims(ds1): nd = ds1.copy() ndt = nd.T assert nd[1] == ndt[..., 1].T # fix a bug with loc indexation nd1 = nd[4000.:3000.] assert str(nd1) == 'NDDataset: [float64] a.u. (shape: (z:4, y:100, x:3))' nd2 = ndt[..., 4000.:3000.] assert str(nd2) == 'NDDataset: [float64] a.u. (shape: (x:3, y:100, z:4))' assert nd1 == nd2.T def test_nddataset_set_coordinates(nd2d, ds1): # set coordinates all together nd = nd2d.copy() ny, nx = nd.shape nd.set_coordset(x=np.arange(nx), y=np.arange(ny)) assert nd.dims == ['y', 'x'] assert nd.x == np.arange(nx) nd.transpose(inplace=True) assert nd.dims == ['x', 'y'] assert nd.x == np.arange(nx) # set coordinates from tuple nd = nd2d.copy() ny, nx = nd.shape nd.set_coordset(np.arange(ny), np.arange(nx)) assert nd.dims == ['y', 'x'] assert nd.x == np.arange(nx) nd.transpose(inplace=True) assert nd.dims == ['x', 'y'] assert nd.x == np.arange(nx) # set coordinate with one set to None: should work! # set coordinates from tuple nd = nd2d.copy() ny, nx = nd.shape nd.set_coordset(np.arange(ny), None) assert nd.dims == ['y', 'x'] assert nd.y == np.arange(ny) assert nd.x.is_empty nd.transpose(inplace=True) assert nd.dims == ['x', 'y'] assert nd.y == np.arange(ny) assert nd.x.is_empty assert nd.coordset == scp.CoordSet(np.arange(ny), None) nd = nd2d.copy() ny, nx = nd.shape nd.set_coordset(None, np.arange(nx)) assert nd.dims == ['y', 'x'] assert nd.x == np.arange(nx) assert nd.y.is_empty nd.set_coordset(y=np.arange(ny), x=None) # set up a single coordinates nd = nd2d.copy() ny, nx = nd.shape nd.x = np.arange(nx) nd.x = np.arange(nx) # do it again - fix a bug nd.set_coordtitles(y='intensity', x='time') assert repr(nd.coordset) == 'CoordSet: [x:time, y:intensity]' # validation with pytest.raises(ValueError): nd.x = np.arange(nx + 5) with pytest.raises(AttributeError): nd.z = None # set coordinates all together nd = nd2d.copy() ny, nx = nd.shape nd.coordset = scp.CoordSet(u=np.arange(nx), v=np.arange(ny)) assert nd.dims != ['u', 'v'] # dims = ['y','x'] # set dim names nd.dims = ['u', 'v'] nd.set_coordset(**scp.CoordSet(u=np.arange(ny), v=np.arange(nx))) assert nd.dims == ['u', 'v'] # ## issue 29 def test_nddataset_issue_29_mulitlabels(): DS = scp.NDDataset(np.random.rand(3, 4)) with pytest.raises(ValueError): # shape data and label mismatch DS.set_coordset(DS.y, scp.Coord(title='xaxis', units='s', data=[1, 2, 3, 4], labels=['a', 'b', 'c'])) c = scp.Coord(title='xaxis', units='s', data=[1, 2, 3, 4], labels=['a', 'b', 'c', 'd']) DS.set_coordset(x=c) c = scp.Coord(title='xaxis', units='s', data=[1, 2, 3, 4], labels=[['a', 'c', 'b', 'd'], ['e', 'f', 'g', 'h']]) d = DS.y DS.set_coordset(d, c) DS.x.labels = ['alpha', 'beta', 'omega', 'gamma'] assert DS.x.labels.shape == (4, 3) # sort DS1 = DS.sort(axis=1, by='value', descend=True) assert_array_equal(DS1.x, [4, 3, 2, 1]) # sort assert DS.dims == ['y', 'x'] DS1 = DS.sort(dim='x', by='label', descend=False) assert_array_equal(DS1.x, [1, 3, 2, 4]) DS1 = DS.sort(dim='x', by='label', pos=2, descend=False) assert_array_equal(DS1.x, [1, 2, 4, 3]) DS.sort(dim='y') DS.y.labels = ['alpha', 'omega', 'gamma'] DS2 = DS.sort(dim='y') assert_array_equal(DS2.y.labels, ['alpha', 'gamma', 'omega']) def test_nddataset_apply_funcs(dsm): # convert to masked array np.ma.array(dsm) dsm[1] = scp.MASKED np.ma.array(dsm) np.array(dsm) def test_take(dsm): pass <file_sep>/tests/test_analysis/test_mcrals.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os import numpy as np from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.analysis.efa import EFA from spectrochempy.core.analysis.mcrals import MCRALS from spectrochempy.utils import show def test_MCRALS_no_coords(): print('') data = NDDataset.read_matlab(os.path.join('matlabdata', 'als2004dataset.MAT')) print('Dataset (Jaumot et al., Chemometr. Intell. Lab. 76 (2005) 101-110)):') print('') for mat in data: print(' ' + mat.name, str(mat.shape)) print('\n test on single experiment (m1) with given estimate of pure species (spure)...\n') X = data[0] guess = data[1] mcr = MCRALS(X, guess, verbose=True) mcr.C.T.plot() mcr.St.plot() mcr.plotmerit() print('\n test on single experiment (m1) with EFA estimate of pure species (verbose off)...\n') guess = EFA(X).get_conc(4) param = { 'normSpec': 'euclid', 'maxit': 100 } mcr2 = MCRALS(X, guess, param=param, verbose=False) mcr2.plotmerit() assert 'converged !' in mcr2.logs[-15:] def test_MCRALS(): data = NDDataset.read_matlab(os.path.join('matlabdata', 'als2004dataset.MAT'), transposed=True) X = data[0] # m1 X.set_coordset(y=np.arange(51), x=np.arange(96)) X.title = 'concentration' X.coordset.set_titles(y='spec coord.', x='elution time') X.plot(title='M1') guess = data[1] # spure guess.set_coordset(y=np.arange(4), x=np.arange(96)) guess.title = 'concentration' guess.coordset.set_titles(y='#components', x='elution time') guess.plot(title='spure') mcr = MCRALS(X, guess, verbose=True) mcr.C.T.plot(title='Concentration') mcr.St.plot(title='spectra') mcr.plotmerit() guess = EFA(X).get_conc(4) guess.plot(title='EFA guess') param = { 'normSpec': 'euclid', 'maxit': 100 } mcr2 = MCRALS(X, guess, param=param, verbose=False) mcr.plotmerit() assert 'converged !' in mcr2.logs[-15:] show() # ============================================================================= if __name__ == '__main__': pass <file_sep>/tests/test_analysis/test_integrate.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Tests integration """ def test_integrate(IR_dataset_2D): dataset = IR_dataset_2D[:, 1250.:1800.] # default dim='x', compare trapz and simps area_trap = dataset.trapz() area_simp = dataset.simps() diff = area_trap - area_simp assert (diff.shape == (55,)) assert ((diff / area_trap).max() < 1e-4) area_trap_x = dataset.trapz(dim='x') diff = area_trap - area_trap_x assert (diff.max() == 0.0) area_trap_y = dataset.trapz(dim='y') assert (area_trap_y.shape == (572,)) <file_sep>/spectrochempy/core/analysis/__init__.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Package with modules related to the analysis of |NDDataset|'s or |Project|'s. """ <file_sep>/docs/userguide/fitting/fitting.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Fitting # # %% import numpy as np import spectrochempy as scp from spectrochempy import ur # %% [markdown] # ## Solving a linear equation using least square method (LSTSQ) # In the first example, we find the least square solution of a simple linear equation. # # Let's first create a NDDataset with some data. We have for instance some noisy data that represent the distance `d` # traveled by some objects versus time `t`: # %% def func(t, v, var): d = v * t + (np.random.rand(len(t)) - 0.5) * var d[0].data = 0. return d time = scp.LinearCoord.linspace(0, 10, 20, title='time', units='hour') d = scp.NDDataset.fromfunction(func, v=100. * ur('km/hr'), var=60. * ur('km'), # extra arguments passed to the function v, var coordset=scp.CoordSet(t=time), name='mydataset', title='distance travelled') # %% [markdown] # Here is a plot of these data-points: # %% prefs = d.preferences prefs.figure.figsize = (7, 3) d.plot_scatter(markersize=7, mfc='red'); # %% [markdown] # We want to fit a line through these data-points of equation # # $d = v.t + d_0$ # # By construction, we know already that the line should have a # gradient of roughly 100 km/h and cut the y-axis at, more or less, 0 km. # # Using LSTSQ, the solution is found very easily: # %% lst = scp.LSTSQ(time, d) v, d0 = lst.transform() print('speed : {:.3fK}, distance at time 0 : {:.3fK}'.format(v, d0)) # %% [markdown] # <div class="alert alert-info"> # <b>Note</b> # # In the particular case where the variation is proportional to the x dataset coordinate, the same result can be # obtained directly using `d` as a single # parameter on LSTSQ (as `t` is the `x` coordinate axis!) # </div> # %% lst = scp.LSTSQ(d) v, d0 = lst.transform() print('speed : {:.3fK}, distance at time 0 : {:.3fK}'.format(v, d0)) # %% [markdown] # and the final plot # %% d.plot_scatter(markersize=7, mfc='red', mec='black', label='Original data', title='Least-square fitting ' 'example') dfit = lst.inverse_transform() dfit.plot_pen(clear=False, color='g', lw=2, label=' Fitted line', legend="best"); # %% [markdown] # Let's try now with a quadratic increase of the speed: # %% def func(t, a, var): d = a * (t / 3.) ** 2 + (np.random.rand(len(t)) - 0.8) * var for i in range(t.size): if d[i].magnitude < 0: d[i] = 0. * d.units return d time = scp.Coord.linspace(0, 10, 20, title='time', units='hour') d2 = scp.NDDataset.fromfunction(func, a=100. * ur('km/hr^2'), var=60. * ur('km'), # extra arguments passed to the function v, var coordset=scp.CoordSet(t=time), name='mydataset', title='distance travelled') d2.plot_scatter(markersize=7, mfc='red'); # %% [markdown] # Now we must use the first syntax LSTQ(X, Y) as the variation is not proportional to time, but to its square. # %% X = (time ** 2) lst = scp.LSTSQ(X, d2) v, d0 = lst.transform() print('acceleration : {:.3fK}, distance at time 0 : {:.3fK}'.format(v, d0)) # %% d2.plot_scatter(markersize=7, mfc='red', mec='black', label='Original data', title='Least-square fitting ' 'example on quadratic data') dfit = lst.inverse_transform() dfit.plot_pen(clear=False, color='g', lw=2, label=' Fitted line', legend="best"); # %% [markdown] # ## Least square with non-negativity constrainst (NNLS) # %% [markdown] # When fitting data with LSTSQ, it happens that we get some negative values were it should not, for instance having a # negative distance at time 0. # # In this case, we can use the NNLS method of fitting. It operates as ``LSTSQ`` but keep the Y values always positive. # %% X = (time ** 2) lst = scp.NNLS(X, d2) v, d0 = lst.transform() print('acceleration : {:.3fK}, distance at time 0 : {:.3fK}'.format(v, d0)) # %% d2.plot_scatter(markersize=7, mfc='red', mec='black', label='Original data', title='Non-negative Least-square fitting ' 'example') dfit = lst.inverse_transform() dfit.plot_pen(clear=False, color='g', lw=2, label=' Fitted line', legend="best"); # %% [markdown] # ## NDDataset modelling using the Fit method # %% [markdown] # First we will load an IR dataset # %% nd = scp.read('irdata/nh4y-activation.spg"') # %% [markdown] # As we want to start with a single 1D spectra, we select the last one (index -1) # %% nd = nd[-1].squeeze() # nd[-1] returns a nddataset with shape (1,5549) # this is why we squeeze it to get a pure 1D dataset with shape (5549,) # %% [markdown] # Now we slice it to keep only the OH vibration region: # %% ndOH = nd[3700.:3300.] ndOH.plot(); # %% [markdown] # ### Baseline correction # %% [markdown] # We can perform a linear baseline correction to start with this data (see the [baseline tutorial]( # ../processing/baseline.ipynb)). For removing a linear baseline, the fastest method is however to use the ``abc`` ( # automatic baseline correction) # %% ndOHcorr = scp.abc(ndOH) ndOHcorr.plot(); # %% [markdown] # ### Peak finding # # Below we will need to start with some guess of the peak position and width. For this we can use the `find_peaks()` # method (see [Peak findind tutorial](../analysis/peak_finding.ipynb)) # %% peaks, _ = ndOHcorr.find_peaks() peaks.x.values # %% ax = ndOHcorr.plot_pen() # output the spectrum on ax. ax will receive next plot too pks = peaks + 0.01 # add a small offset on the y positiion of the markers pks.plot_scatter(ax=ax, marker='v', color='black', clear=False, # we need to keep the previous outpout on ax data_only=True, # we dont need to redraw all things like labels, etc... ylim=(-0.05, 1.3)); # %% [markdown] # The maximum of the two major peaks are thus exactly at 3624.61 and 3541.68 cm$^{-1}$ # %% [markdown] # ### Fitting script # Now we will define the fitting procedure as a script # %% script = """ #----------------------------------------------------------- # syntax for parameters definition : # name : value, low_bound, high_bound # * for fixed parameters # $ for variable parameters # > for reference to a parameter in the COMMON block # (> is forbidden in the COMMON block) # common block parameters should not have a _ in their names #----------------------------------------------------------- # COMMON: # common parameters ex. # $ gwidth: 1.0, 0.0, none $ gratio: 0.1, 0.0, 1.0 $ gassym: 0.1, 0, 1 MODEL: LINE_1 shape: assymvoigtmodel * ampl: 1.0, 0.0, none $ pos: 3624.61, 3520.0, 3570.0 > ratio: gratio > assym: gassym $ width: 200, 0, 1000 MODEL: LINE_2 shape: assymvoigtmodel $ ampl: 0.2, 0.0, none $ pos: 3541.68, 3400.0, 3700.0 > ratio: gratio > assym: gassym $ width: 200, 0, 1000 """ # %% [markdown] # #### Syntax for parameters definition # # In such script, the char `#` at the begining of a line denote that the whole line is a comment. Comments are # obviously optional but may be usefull to explain # # Each individual model component is identified by the keyword `MODEL` # # A `MODEL` have a name, *e.g.*, `MODEL: LINE_1`. # # Then come for each model components its `shape`, *i.e.,* the shape of the line. # # Come after the definition of the model parameters depending on the shape, e.g., for a `gaussianmodel` we have three # parameters: `amplitude` (`ampl`), `width` and `position` (`pos`) of the line. # # To define a given parameter, we have to write its `name` and a set of 3 values: the expected `value` and 2 limits # for the allowed variations : `low_bound`, `high_bound` # ``` # name : value, low_bound, high_bound # ```` # These parameters are preceded by a mark saying what kind of parameter it will behave in the fit procedure: # # * `$` is the default and denote a variable parameters # * `*` denotes fixed parameters # * `>` say that the given parameters is actualy defined in a COMMON block # # `COMMON`is the common block containing parameters to which a parmeter in the MODEL blocks can make reference using # the `>` markers. (`>` obviously is forbidden in the COMMON block) # common block parameters should not have a `_`(underscore) in their names # # With this parameter script definition, you can thus make rather complex search for modelling, as you can make # pareters dependents or fixed. # # The line shape can be (up to now) in the following list of shape (for 1D models - see below for 2D): # # * PolynomialBaseline -> `polynomialbaseline`: # # Arbitrary-degree polynomial (degree limited to 10, however). As a linear baseline is automatically calculated # during fittin, this polynom is always of # greater or equal to order 2 (parabolic function at the minimum). # # $f(x) = ampl * \sum_{i=2}^{max} c_i*x^i$ # # ``` # MODEL: baseline # shape: polynomialbaseline # # This polynom starts at the order 2 # $ ampl: val, 0.0, None # $ c_2: 1.0, None, None # * c_3: 0.0, None, None # * c_4: 0.0, None, None # # etc # ``` # # # * Gaussian Model -> `gaussianmodel`: # # Normalized 1D gaussian function. # # $f(x) = \frac{ampl}{\sqrt{2 \pi \sigma^2}} \exp({\frac{-(x-pos)^2}{2 \sigma^2}})$ # # where $\sigma = \frac{width}{2.3548}$ # # ``` # MODEL: Linex # shape: gaussianmodel # $ ampl: val, 0.0, None # $ width: val, 0.0, None # $ pos: val, lob, upb # ``` # # # * Lorentzian Model -> `lorentzianmodel`: # # A standard Lorentzian function (also known as the Cauchy distribution). # # $f(x) = \frac{ampl * \lambda}{\pi [(x-pos)^2+ \lambda^2]}$ # # where $\lambda = \frac{width}{2}$ # # ``` # MODEL: liney: # shape: lorentzianmodel # $ ampl:val, 0.0, None # $ width: val, 0.0, None # $ pos: val, lob, upb # ``` # # # * Voigt Model -> `voigtmodel`: # # A Voigt model constructed as the convolution of a `GaussianModel` and # a `LorentzianModel` -- commonly used for spectral line fitting. # # ``` # MODEL: linez # shape: voigtmodel # $ ampl: val, 0.0, None # $ width: val, 0.0, None # $ pos: val, lob, upb # $ ratio: val, 0.0, 1.0 # ``` # # # * Assymetric Voigt Model -> `assymvoigtmodel`: # # An assymetric Voigt model (<NAME> and <NAME>, Vibrational Spectroscopy, 2008, 47, 66-69) # # ``` # MODEL: linez # shape: voigtmodel # $ ampl: val, 0.0, None # $ width: val, 0.0, None # $ pos: val, lob, upb # $ ratio: val, 0.0, 1.0 # $ assym: val, 0.0, 1.0 # ``` # %% f1 = scp.Fit(ndOHcorr, script, silent=False) f1.run(maxiter=10000, every=100) ndOHcorr.plot(plot_model=True, lw=2); # %% [markdown] # <div class='alert alert-warning'> # <b>Todo</b> # # Tutorial to be continued with other methods of optimization and fitting (2D...) # </div> <file_sep>/spectrochempy/core/readers/readmatlab.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """Plugin module to extend NDDataset with the import methods method. """ __all__ = ['read_matlab', 'read_mat'] __dataset_methods__ = __all__ import io from warnings import warn from datetime import datetime, timezone import numpy as np import scipy.io as sio from spectrochempy.core.dataset.nddataset import NDDataset, Coord from spectrochempy.core.readers.importer import Importer, importermethod # ====================================================================================================================== # Public functions # ====================================================================================================================== def read_matlab(*paths, **kwargs): """ Read a matlab file with extension ``.mat`` and return its content as a list. The array of numbers (i.e. matlab matrices) and Eigenvector's DataSet Object (DSO, see `DSO <https://www.eigenvector.com/software/dataset.htm>`_ ) are returned as NDDatasets. The content not recognized by SpectroChemPy is returned as a tuple (name, object). Parameters ----------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read_matlab |NDDataset| or list of |NDDataset|. Other Parameters ---------------- protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False) description: str, optional A Custom description. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True) recursive : bool, optional Read also in subfolders. (default=False) Examples --------- >>> import spectrochempy as scp >>> scp.read_matlab('matlabdata/dso.mat') NDDataset: [float64] unitless (shape: (y:20, x:426)) See ``read_omnic`` for more examples of use See Also -------- read : Read generic files. read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_labspec : Read Raman LABSPEC spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. """ kwargs['filetypes'] = ['MATLAB files (*.mat *.dso)'] kwargs['protocol'] = ['matlab', 'mat', 'dso'] importer = Importer() return importer(*paths, **kwargs) # ...................................................................................................................... read_mat = read_matlab # ---------------------------------------------------------------------------------------------------------------------- # Private methods # ---------------------------------------------------------------------------------------------------------------------- @importermethod def _read_mat(*args, **kwargs): _, filename = args content = kwargs.get('content', False) if content: fid = io.BytesIO(content) else: fid = open(filename, 'rb') dic = sio.loadmat(fid) datasets = [] for name, data in dic.items(): dataset = NDDataset() if name == '__header__': dataset.description = str(data, 'utf-8', 'ignore') continue if name.startswith('__'): continue if data.dtype in [np.dtype('float64'), np.dtype('float32'), np.dtype('int8'), np.dtype('int16'), np.dtype('int32'), np.dtype('int64'), np.dtype('uint8'), np.dtype('uint16'), np.dtype('uint32'), np.dtype('uint64')]: # this is an array of numbers dataset.data = data dataset.name = name dataset.history = str(datetime.now(timezone.utc)) + ':imported from .mat file \n' # TODO: reshape from fortran/Matlab order to C opder # for 3D or higher datasets ? datasets.append(dataset) elif all(name in data.dtype.names for name in ['moddate', 'axisscale', 'imageaxisscale']): # this is probably a DSO object dataset = _read_dso(dataset, name, data) datasets.append(dataset) else: warn(f'unsupported data type : {data.dtype}') # TODO: implement DSO reader datasets.append([name, data]) return datasets @importermethod def _read_dso(dataset, name, data): name_mat = data['name'][0][0] if len(name_mat) == 0: name = '' else: name = name_mat[0] typedata_mat = data['type'][0][0] if len(typedata_mat) == 0: typedata = '' else: typedata = typedata_mat[0] if typedata != 'data': return ((name, data)) else: author_mat = data['author'][0][0] if len(author_mat) == 0: author = '*unknown*' else: author = author_mat[0] date_mat = data['date'][0][0] if len(date_mat) == 0: date = datetime(1, 1, 1, 0, 0) else: date = datetime(int(date_mat[0][0]), int(date_mat[0][1]), int(date_mat[0][2]), int(date_mat[0][3]), int(date_mat[0][4]), int(date_mat[0][5])) dat = data['data'][0][0] # look at coords and labels # only the first label and axisscale are taken into account # the axisscale title is used as the coordinate title coords = [] for i in range(len(dat.shape)): coord = datac = None # labels = title = None labelsarray = data['label'][0][0][i][0] if len(labelsarray): # some labels might be present if isinstance(labelsarray[0], np.ndarray): labels = data['label'][0][0][i][0][0] else: labels = data['label'][0][0][i][0] if len(labels): coord = (Coord(labels=[str(label) for label in labels])) if len(data['label'][0][0][i][1]): if isinstance(data['label'][0][0][i][1][0], np.ndarray): if len(data['label'][0][0][i][1][0]): coord.name = data['label'][0][0][i][1][0][0] elif isinstance(data['label'][0][0][i][1][0], str): coord.name = data['label'][0][0][i][1][0] axisdataarray = data['axisscale'][0][0][i][0] if len(axisdataarray): # some axiscale might be present if isinstance(axisdataarray[0], np.ndarray): if len(axisdataarray[0]) == dat.shape[i]: datac = axisdataarray[0] # take the first axiscale data elif axisdataarray[0].size == dat.shape[i]: datac = axisdataarray[0][0] if datac is not None: if isinstance(coord, Coord): coord.data = datac else: coord = Coord(data=datac) if len(data['axisscale'][0][0][i][1]): # some titles might be present try: coord.title = data['axisscale'][0][0][i][1][0] except Exception: try: coord.title = data['axisscale'][0][0][i][1][0][0] except Exception: pass if not isinstance(coord, Coord): coord = Coord(data=[j for j in range(dat.shape[i])], title='index') coords.append(coord) dataset.data = dat dataset.set_coordset(*[coord for coord in coords]) dataset.author = author dataset.name = name dataset.date = date # TODO: reshape from fortran/Matlab order to C order # for 3D or higher datasets ? for i in data['description'][0][0]: dataset.description += i for i in data['history'][0][0][0][0]: dataset.history.append(i) dataset.history = (str(datetime.now(timezone.utc)) + ': Imported by spectrochempy ') return dataset # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/docs/gettingstarted/examples/fitting/plot_lstsq_single_equation.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Solve a linear equation using LSTSQ ----------------------------------- In this example, we find the least square solution of a simple linear equation. """ # sphinx_gallery_thumbnail_number = 2 import spectrochempy as scp ############################################################################## # Let's take a similar example to the one given in the `numpy.linalg` # documentation # # We have some noisy data that represent the distance `d` traveled by some # objects versus time `t`: t = scp.NDDataset(data=[0, 1, 2, 3], title='time', units='hour') d = scp.NDDataset(data=[-1, 0.2, 0.9, 2.1], coordset=[t], title='distance', units='kilometer') ############################################################################## # Here is a plot of these data-points: d.plot_scatter(markersize=7, mfc='red') ############################################################################## # We want to fit a line through these data-points of equation # # .. math:: # # d = v.t + d_0 # # By examining the coefficients, we see that the line should have a # gradient of roughly 1 km/h and cut the y-axis at, more or less, -1 km. # # Using LSTSQ, the solution is found very easily: lst = scp.LSTSQ(t, d) v, d0 = lst.transform() print('speed : {:.3fK}, d0 : {:.3fK}'.format(v, d0)) ############################################################################## # Final plot d.plot_scatter(markersize=10, mfc='red', mec='black', label='Original data', suptitle='Least-square fitting ' 'example') dfit = lst.inverse_transform() dfit.plot_pen(clear=False, color='g', label='Fitted line', legend=True) ############################################################################## # Note: The same result can be obtained directly using `d` as a single # parameter on LSTSQ (as `t` is the `x` coordinate axis!) lst = scp.LSTSQ(d) v, d0 = lst.transform() print('speed : {:.3fK}, d0 : {:.3fK}'.format(v, d0)) # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/docs/userguide/processing/math_operations.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # Mathematical operations # %% from spectrochempy import * import numpy as np # %% [markdown] # ## Ufuncs (Universal Numpy's functions) # A universal function (or `ufunc` in short) is a function that operates on numpy arrays in an element-by-element # fashion, supporting array broadcasting, type casting, and several other standard features. That is, a `ufunc` is a # “vectorized” wrapper for a function that takes a fixed number of specific inputs and produces a fixed number of # specific outputs. # # For instance, in numpy to calculate the square root of each element of a given nd-array, we can write something # like this using the `np.sqrt` functions : # %% x = np.array([1., 2., 3., 4., 6.]) np.sqrt(x) # %% [markdown] # As seen above, `np.sqrt(x)` return a numpy array. # # The interesting thing, it that `ufunc`'s can also work with `NDDataset`. # %% dx = NDDataset(x) np.sqrt(dx) # %% [markdown] # It is worth to note, that in spectrochempy, when can use internal equivalent of these `ufunc`'s. # # For instance, the square root can be calculated using the following syntax: # %% sqrt(dx) # %% [markdown] # ## List of UFuncs working on `NDDataset`: # # ### Functions affecting magnitudes of the number but keeping units # * [negative](#negative)(x, \*\*kwargs): Numerical negative, element-wise. # * [absolute](#abs)(x, \*\*kwargs): Calculate the absolute value, element-wise. Alias: [abs](#abs) # * [fabs](#abs)(x, \*\*kwargs): Calculate the absolute value, element-wise. Complex values are not handled, # use [absolute](#absolute) to find the absolute values of complex data. # * [conj](#)(x, \*\*kwargs): Return the complex conjugate, element-wise. # * [rint](#rint)(x, \*\*kwargs) :Round to the nearest integer, element-wise. # * [floor](#floor)(x, \*\*kwargs): Return the floor of the input, element-wise. # * [ceil](#ceil)(x, \*\*kwargs): Return the ceiling of the input, element-wise. # * [trunc](#trunc)(x, \*\*kwargs): Return the truncated value of the input, element-wise. # # ### Functions affecting magnitudes of the number but also units # * [sqrt](#sqrt)(x, \*\*kwargs): Return the non-negative square-root of an array, element-wise. # * [square](#square)(x, \*\*kwargs): Return the element-wise square of the input. # * [cbrt](#cbrt)(x, \*\*kwargs): Return the cube-root of an array, element-wise. # * [reciprocal](#reciprocal)(x, \*\*kwargs): Return the reciprocal of the argument, element-wise. # # ### Functions that require no units or dimensionless units for inputs. Returns dimensionless objects. # * [exp](#exp)(x, \*\*kwargs): Calculate the exponential of all elements in the input array. # * [exp2](#exp)(x, \*\*kwargs): Calculate 2\*\*p for all p in the input array. # * [expm1](#exp)(x, \*\*kwargs): Calculate `exp(x) - 1` for all elements in the array. # * [log](#log)(x, \*\*kwargs): Natural logarithm, element-wise. # * [log2](#log)(x, \*\*kwargs): Base-2 logarithm of x. # * [log10](#log)(x, \*\*kwargs): Return the base 10 logarithm of the input array, element-wise. # * [log1p](#log)(x, \*\*kwargs): Return `log(x + 1)`, element-wise. # # ### Functions that return numpy arrays (*Work only for NDDataset*) # * [sign](#sign)(x): Returns an element-wise indication of the sign of a number. # * [logical_not](#logical_not)(x): Compute the truth value of NOT x element-wise. # * [isfinite](#isfinite)(x): Test element-wise for finiteness. # * [isinf](#isinf)(x): Test element-wise for positive or negative infinity. # * [isnan](#isnan)(x): Test element-wise for `NaN` and return result as a boolean array. # * [signbit](#signbit)(x): Returns element-wise `True` where signbit is set. # # ### Trigonometric functions. Require unitless data or radian units. # * [sin](#sin)(x, \*\*kwargs): Trigonometric sine, element-wise. # * [cos](#cos)(x, \*\*kwargs): Trigonometric cosine element-wise. # * [tan](#tan)(x, \*\*kwargs): Compute tangent element-wise. # * [arcsin](#arcsin)(x, \*\*kwargs): Inverse sine, element-wise. # * [arccos](#arccos)(x, \*\*kwargs): Trigonometric inverse cosine, element-wise. # * [arctan](#arctan)(x, \*\*kwargs): Trigonometric inverse tangent, element-wise. # # ### Hyperbolic functions # * [sinh](#sinh)(x, \*\*kwargs): Hyperbolic sine, element-wise. # * [cosh](#cosh)(x, \*\*kwargs): Hyperbolic cosine, element-wise. # * [tanh](#tanh)(x, \*\*kwargs): Compute hyperbolic tangent element-wise. # * [arcsinh](#arcsinh)(x, \*\*kwargs): Inverse hyperbolic sine element-wise. # * [arccosh](#arccosh)(x, \*\*kwargs): Inverse hyperbolic cosine, element-wise. # * [arctanh](#arctanh)(x, \*\*kwargs): Inverse hyperbolic tangent element-wise. # # ### Unit conversions # * [deg2rad](#deg2rad)(x, \*\*kwargs): Convert angles from degrees to radians. # * [rad2deg](#rad2deg)(x, \*\*kwargs): Convert angles from radians to degrees. # # ### Binary Ufuncs # # * [add](#add)(x1, x2, \*\*kwargs): Add arguments élement-wise. # * [subtract](#subtract)(x1, x2, \*\*kwargs): Subtract arguments, element-wise. # * [multiply](#multiply)(x1, x2, \*\*kwargs): Multiply arguments element-wise. # * [divide](#divide) or [true_divide](#true_divide)(x1, x2, \*\*kwargs): Returns a true division of the inputs, # element-wise. # * [floor_divide](#floor_divide)(x1, x2, \*\*kwargs): Return the largest integer smaller or equal to the division of # the inputs. # * [mod](#mod) or [remainder](#remainder)(x1, x2,\*\*kwargs): Return element-wise remainder of division. # * [fmod](#fmod)(x1, x2, \*\*kwargs): Return the element-wise remainder of division. # %% [markdown] # ## Usage # To demonstrate the use of mathematical operations on spectrochempy object, we will first load an experimental 2D # dataset. # %% d2D = NDDataset.read_omnic('irdata/nh4y-activation.spg') prefs = d2D.preferences prefs.colormap = 'magma' prefs.colorbar = False prefs.figure.figsize = (6, 3) _ = d2D.plot() # %% [markdown] # Let's select only the first row of the 2D dataset ( the `squeeze` method is used to remove # the residual size 1 dimension). In addition we mask the saturated region. # %% dataset = d2D[0].squeeze() _ = dataset.plot() # %% [markdown] # This dataset will be artificially modified already using some mathematical operation (subtraction with a scalar) to # present negative values and we will also mask some data # %% dataset = dataset - 2. # add an offset to make that some of the values become negative dataset[1290.:890.] = MASKED # additionally we mask some data _ = dataset.plot() # %% [markdown] # ### Unary functions # %% [markdown] # #### Functions affecting magnitudes of the number but keeping units # %% [markdown] # ##### negative # Numerical negative, element-wise, keep units # %% out = np.negative(dataset) # the same results is obtained using out=-dataset _ = out.plot(figsize=(6, 2.5), show_mask=True) # %% [markdown] # ##### abs # ##### absolute (alias of abs) # ##### fabs (absolute for float arrays) # Numerical absolute value element-wise, element-wise, keep units # %% out = np.abs(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### rint # Round elements of the array to the nearest integer, element-wise, keep units # %% out = np.rint(dataset) _ = out.plot(figsize=(6, 2.5)) # not that title is not modified for this ufunc # %% [markdown] # ##### floor # Return the floor of the input, element-wise. # %% out = np.floor(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### ceil # Return the ceiling of the input, element-wise. # %% out = np.ceil(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### trunc # Return the truncated value of the input, element-wise. # %% out = np.trunc(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # #### Functions affecting magnitudes of the number but also units # ##### sqrt # Return the non-negative square-root of an array, element-wise. # %% out = np.sqrt(dataset) # as they are some negative elements, return dataset has complex dtype. _ = out.plot_1D(show_complex=True, figsize=(6, 2.5)) # %% [markdown] # ##### square # Return the element-wise square of the input. # %% out = np.square(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### cbrt # Return the cube-root of an array, element-wise. # %% out = np.cbrt(dataset) _ = out.plot_1D(figsize=(6, 2.5)) # %% [markdown] # ##### reciprocal # Return the reciprocal of the argument, element-wise. # %% out = np.reciprocal(dataset + 3.) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # #### Functions that require no units or dimensionless units for inputs. Returns dimensionless objects. # %% [markdown] # ##### exp # Exponential of all elements in the input array, element-wise # %% out = np.exp(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # Obviously numpy exponential functions applies only to dimensionless array. Else an error is generated. # %% x = NDDataset(np.arange(5), units='m') try: np.exp(x) # A dimensionality error will be generated except DimensionalityError as e: error_(e) # %% [markdown] # ##### exp2 # Calculate 2\*\*p for all p in the input array. # %% out = np.exp2(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### expm1 # Calculate `exp(x) - 1` for all elements in the array. # %% out = np.expm1(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### log # Natural logarithm, element-wise. # # This doesn't generate un error for negative numbrs, but the output is masked for those values # %% out = np.log(dataset) ax = out.plot(figsize=(6, 2.5), show_mask=True) # %% out = np.log(dataset - dataset.min()) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### log2 # Base-2 logarithm of x. # %% out = np.log2(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### log10 # Return the base 10 logarithm of the input array, element-wise. # %% out = np.log10(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### log1p # Return `log(x + 1)`, element-wise. # %% out = np.log1p(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # #### Functions that return numpy arrays (*Work only for NDDataset*) # %% [markdown] # ##### sign # Returns an element-wise indication of the sign of a number. Returned object is a ndarray # %% np.sign(dataset) # %% np.logical_not(dataset < 0) # %% [markdown] # ##### isfinite # Test element-wise for finiteness. # %% np.isfinite(dataset) # %% [markdown] # ##### isinf # Test element-wise for positive or negative infinity. # %% np.isinf(dataset) # %% [markdown] # ##### isnan # Test element-wise for `NaN` and return result as a boolean array. # %% np.isnan(dataset) # %% [markdown] # ##### signbit # Returns element-wise `True` where signbit is set. # %% np.signbit(dataset) # %% [markdown] # #### Trigonometric functions. Require dimensionless/unitless dataset or radians. # # In the below examples, unit of data in dataset is absorbance (then dimensionless) # %% [markdown] # ##### sin # Trigonometric sine, element-wise. # %% out = np.sin(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### cos # Trigonometric cosine element-wise. # %% out = np.cos(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### tan # Compute tangent element-wise. # %% out = np.tan(dataset / np.max(dataset)) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### arcsin # Inverse sine, element-wise. # %% out = np.arcsin(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### arccos # Trigonometric inverse cosine, element-wise. # %% out = np.arccos(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### arctan # Trigonometric inverse tangent, element-wise. # %% out = np.arctan(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # #### Angle units conversion # %% [markdown] # ##### rad2deg # Convert angles from radians to degrees (warning: unitless or dimensionless are assumed to be radians, so no error # will be issued). # %% [markdown] # for instance, if we take the z axis (the data magintude) in the figure above, it's expressed in radians. We can # change to degrees easily. # %% out = np.rad2deg(dataset) out.title = 'data' # just to avoid a too long title _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### deg2rad # Convert angles from degrees to radians. # %% out = np.deg2rad(out) out.title = 'data' _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # #### Hyperbolic functions # %% [markdown] # ##### sinh # Hyperbolic sine, element-wise. # %% out = np.sinh(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### cosh # Hyperbolic cosine, element-wise. # %% out = np.cosh(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### tanh # Compute hyperbolic tangent element-wise. # %% out = np.tanh(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### arcsinh # Inverse hyperbolic sine element-wise. # %% out = np.arcsinh(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### arccosh # Inverse hyperbolic cosine, element-wise. # %% out = np.arccosh(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### arctanh # Inverse hyperbolic tangent element-wise. # %% out = np.arctanh(dataset) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ### Binary functions # %% dataset2 = np.reciprocal(dataset + 3) # create a second dataset dataset2[5000.:4000.] = MASKED _ = dataset.plot(figsize=(6, 2.5)) _ = dataset2.plot(figsize=(6, 2.5)) # %% [markdown] # #### Arithmetics # %% [markdown] # ##### add # Add arguments element-wise. # %% out = np.add(dataset, dataset2) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### subtract # Subtract arguments, element-wise. # %% out = np.subtract(dataset, dataset2) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### multiply # Multiply arguments element-wise. # %% out = np.multiply(dataset, dataset2) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### divide # or # ##### true_divide # Returns a true division of the inputs, element-wise. # %% out = np.divide(dataset, dataset2) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### floor_divide # Return the largest integer smaller or equal to the division of the inputs. # %% out = np.floor_divide(dataset, dataset2) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### mod # or # ##### remainder # Return element-wise remainder of division. # %% out = np.mod(dataset, dataset2) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ##### fmod # Return element-wise remainder of division. # # **Note**: For `fmod`, the sign of result is the sign of the dividend, while for remainder the sign of the result is # the sign of the divisor. # %% out = np.fmod(dataset, dataset2) _ = out.plot(figsize=(6, 2.5)) # %% [markdown] # ## Complex or hypercomplex NDDatasets # # # NDDataset objects with complex data are handled differently than in # `numpy.ndarray`. # # Instead, complex data are stored by interlacing the real and imaginary part. # This allows the definition of data that can be complex in several axis, and *e # .g.,* allows 2D-hypercomplex array that can be transposed (useful for NMR data). # %% da = NDDataset([[1. + 2.j, 2. + 0j], [1.3 + 2.j, 2. + 0.5j], [1. + 4.2j, 2. + 3j], [5. + 4.2j, 2. + 3j]]) da # %% [markdown] # A dataset of type float can be transformed into a complex dataset (using two cionsecutive rows to create a complex # row) # %% da = NDDataset(np.arange(40).reshape(10, 4)) da # %% dac = da.set_complex() dac # %% [markdown] # Note the `x`dimension size is divided by a factor of two # %% [markdown] # A dataset which is complex in two dimensions is called hypercomplex (it's datatype in SpectroChemPy is set to # quaternion). # %% daq = da.set_quaternion() # equivalently one can use the set_hypercomplex method daq # %% pycharm={"name": "#%%\n"} daq.dtype <file_sep>/tests/test_dataset/test_npy.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import numpy as np import pytest from spectrochempy.core.dataset.npy import dot from spectrochempy import diag def test_npy(ds1): # functions that keep units # DIAG with pytest.raises(ValueError): df = diag(ds1) # work only for 1d or 2D dataset ds = ds1[0].squeeze() assert ds.ndim == 2 df = diag(ds) assert df.units == ds1.units assert df.ndim == 1 assert df.size == ds.x.size d = ds[0].squeeze() assert d.ndim == 1 df = diag(d) assert df.units == ds1.units assert df.ndim == 2 assert df.size == d.x.size ** 2 df = diag(ds.data) assert df.implements('NDDataset') # DOT a = ds # 2D dataset b = ds1[3].squeeze() # second 2D dataset b.ito('km', force=True) # put some units to b x = dot(a.T, b) assert x.units == a.units * b.units assert x.shape == (a.x.size, b.x.size) # allow mixing numpy object with dataset x = dot(a.T, b.data) assert x.units == a.units # if no dataset then is it equivalent to np.dot x = dot(a.data.T, b.data) assert isinstance(x, np.ndarray) # ============================================================================ if __name__ == '__main__': pass # end of module <file_sep>/spectrochempy/core/readers/readlabspec.py # -*- coding: utf-8 -*- # # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ===================================================================================================================== # # author: <NAME> (LCS) # """This module extend NDDataset with the import method for Labspec *.txt generated data files. """ __all__ = ['read_labspec'] __dataset_methods__ = __all__ import io import datetime import numpy as np from spectrochempy.core.dataset.coord import Coord, LinearCoord from spectrochempy.core.readers.importer import importermethod, Importer from spectrochempy.core.dataset.meta import Meta # ====================================================================================================================== # Public functions # ====================================================================================================================== def read_labspec(*paths, **kwargs): """ Read a single Raman spectrum or a series of Raman spectra. Files to open are *.txt file created by Labspec software. Parameters ---------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read |NDDataset| or list of |NDDataset|. Other Parameters ---------------- protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False) sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True) description: str, optional A Custom description. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True) recursive : bool, optional Read also in subfolders. (default=False). See Also -------- read : Generic read method. read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. Examples -------- >>> import spectrochempy as scp >>> A = scp.read_labspec('ramandata/Activation.txt') """ kwargs['filetypes'] = ['LABSPEC exported files (*.txt)'] kwargs['protocol'] = ['labspec', 'txt'] importer = Importer() return importer(*paths, **kwargs) read_txt = read_labspec # ====================================================================================================================== # Private functions # ====================================================================================================================== # ...................................................................................................................... @importermethod def _read_txt(*args, **kwargs): # read Labspec *txt files or series dataset, filename = args content = kwargs.get('content', False) if content: fid = io.StringIO(content) # TODO: get the l list of string else: fid = open(filename, 'r', encoding='utf-8') try: lines = fid.readlines() except UnicodeDecodeError: fid = open(filename, 'r', encoding='latin-1') lines = fid.readlines() fid.close() # Metadata meta = Meta() i = 0 while lines[i].startswith('#'): key, val = lines[i].split('=') key = key[1:] if key in meta.keys(): key = f'{key} {i}' meta[key] = val.strip() i += 1 # read spec rawdata = np.genfromtxt(lines[i:], delimiter='\t') # populate the dataset if rawdata.shape[1] == 2: data = rawdata[:, 1][np.newaxis] _x = Coord(rawdata[:, 0], title='Raman shift', units='1/cm') _y = Coord(None, title='Time', units='s') date_acq, _y = _transf_meta(_y, meta) else: data = rawdata[1:, 1:] _x = Coord(rawdata[0, 1:], title='Raman shift', units='1/cm') _y = Coord(rawdata[1:, 0], title='Time', units='s') date_acq, _y = _transf_meta(_y, meta) _x = LinearCoord(_x) # set dataset metadata dataset.data = data dataset.set_coordset(y=_y, x=_x) dataset.title = 'Raman Intensity' dataset.units = 'absorbance' dataset.name = filename.stem dataset.meta = meta # date_acq is Acquisition date at start (first moment of acquisition) dataset.description = 'Spectrum acquisition : ' + str(date_acq) # Set the NDDataset date dataset._date = datetime.datetime.now(datetime.timezone.utc) dataset._modified = dataset.date # Set origin, description and history dataset.history = f'{dataset.date}:imported from LabSpec6 text file {filename}' return dataset def _transf_meta(y, meta): # Reformats some of the metadata from Labspec6 informations # such as the acquisition date of the spectra and returns a list with the acquisition in datetime format, # the list of effective dates for each spectrum # def val_from_key_wo_time_units(k): # for key in meta: # h, m, s = 0, 0, 0 # if k in key: # _, units = key.split(k) # units = units.strip()[1:-1] # if units == 's': # s = meta[key] # elif units == 'mm:ss': # m, s = meta[key].split(':') # elif units == 'hh:mm': # h, m = meta[key].split(':') # break # return datetime.timedelta(seconds=int(s), minutes=int(m), hours=int(h)) if meta: try: dateacq = datetime.datetime.strptime(meta['Acquired'], '%d.%m.%Y %H:%M:%S') except TypeError: dateacq = datetime.datetime.strptime(meta['Date'], '%d/%m/%y %H:%M:%S') acq = int(meta.get('Acq. time (s)', meta['Exposition'])) accu = int(meta.get('Accumulations', meta.get('Accumulation'))) delay = int(meta.get('Delay time (s)', 0)) # total = val_from_key_wo_time_units('Full time') else: dateacq = datetime.datetime(2000, 1, 1, 0, 0, 0) # datestr = '01/01/2000 00:00:00' acq = 0 accu = 0 delay = 0 # total = datetime.timedelta(0) # delay between spectra delayspectra = datetime.timedelta(seconds=acq * accu + delay) # Date d'acquisition : le temps indiqué est celui où l'on démarre l'acquisition dateacq = dateacq - delayspectra # Dates effectives de chacun des spectres de la série : le temps indiqué est celui où l'on démarre l'acquisition # Labels for time : dates with the initial time for each spectrum try: y.labels = [dateacq + delayspectra * i for i in range(len(y))] except Exception as e: print(e) return dateacq, y # def rgp_series(lsdatasets, sortbydate=True): # """ # Concatenation of individual spectra to an integrated series # # :type lsdatasets: list # list of datasets (usually created after opening several spectra at once) # # :type sortbydate: bool # to sort data by date order (default=True) # # :type out: NDDataset # single dataset after grouping # """ # # # Test and initialize # if (type(lsdatasets) != list): # print('Error : A list of valid NDDatasets is expected') # return # # lsfile = list(lsdatasets[i].name for i in range(len(lsdatasets))) # # out = stack(lsdatasets) # # lstime = out.y.labels # out.y.data = lstime # # # Orders by date and calculates relative times # if sortbydate: # out = out.sort(dim='y') # # lstime = [] # ref = out[0].y.labels[0] # for i in range(out.shape[0]): # time = (out[i].y.labels[0] - ref).seconds # lstime.append((time)) # # # Formats the concatenated dataset # labels = out.y.labels # out.y = lstime # out.y.labels = labels, lsfile # out.y.title = 'Time' # out.y.units = 's' # out.name = 'Series concatenated' # # return out # # # ## Saving data # # def reconstruct_data(dataset): # """ # Recreates raw data matrix from the values of X,Y and data of a NDDataset # """ # dim0, dim1 = dataset.shape # rawdata = np.zeros((dim0 + 1, dim1 + 1)) # rawdata[0, 0] = None # rawdata[1::, 0] = dataset.y # rawdata[0, 1::] = dataset.x # rawdata[1::, 1::] = np.copy(dataset.data) # # metalist = [] # metakeysmod = {} # for ky in dataset.meta.keys(): # writes metadata in the same order as Labspec6 # if ky != 'ordre Labspec6': # ind = dataset.meta['ordre Labspec6'][ky] # kymod = str(ind) + ky # metakeysmod[kymod] = dataset.meta[ky] # for ky2 in sorted(metakeysmod.keys()): # metalist.append(ky2[ky2.find('#'):] + '=' + metakeysmod[ky2]) # # return rawdata, metalist # # # def save_txt(dataset, filename=''): # """ Exports dataset to txt format, aiming to be readable by Labspec software # Only partially efficient. Loss of metadata # """ # # if no filename is provided, opens a dialog box to create txt file # if filename == '': # root = tk.Tk() # root.withdraw() # root.overrideredirect(True) # root.geometry('0x0+0+0') # root.deiconify() # root.lift() # root.focus_force() # f = filedialog.asksaveasfile(initialfile='dataset', # defaultextension=".txt", # filetypes=[("Text", "*.txt"), ("All Files", "*.*")], # confirmoverwrite=True) # if f is None: # asksaveasfile return `None` if dialog closed with "cancel". # return # root.destroy() # else: # f = filename # # rawdata, metalist = reconstruct_data(dataset) # # with open('savetxt.txt', 'w') as f: # # After leaving the above block of code, the file is closed # f.writelines(metalist) # np.savetxt(f, rawdata, delimiter='\t') # # return # # # # Data treatment # # def elimspikes(self, seuil=0.03): # """Spikes removal tool # # :seuil: float : minimal threshold for the detection(fraction)""" # # out = self.copy() # self.plot(reverse=False) # for k in range(3): # outmd = out.data[:, 1:-1:] # median point # out1 = out.data[:, 0:-2:] # previous point # out2 = out.data[:, 2::] # next point # # test1 = (outmd > (1 + seuil) * out1) # test2 = (outmd > (1 + seuil) * out2) # test = (test1 & test2) # outmd[test] = (out1[test] + out2[test]) / 2 # out.data[:, 1:-1:] = outmd # out.name = '*' + self.name # out.history = 'Spikes removed by elimspikes(), with a fraction threshold value=' + str(seuil) # out.plot(reverse=False) # return out <file_sep>/docs/index.rst :orphan: .. _home: ##################################################################### Processing, analysing and modelling spectroscopic data ##################################################################### .. toctree:: :hidden: :caption: Table of Content .. toctree:: :hidden: :caption: Summary |scpy| is a framework for processing, analyzing and modeling **Spectro**\ scopic data for **Chem**\ istry with **Py**\ thon. It is a cross platform software, running on Linux, Windows or OS X. Among its major features: #. Import data from experiments or modeling programs with their *metatdata* (title, units, coordinates, ...) #. Preprocess these data: baseline correction, (automatic) subtraction, smoothing, apodization... #. Manipulate single or multiple datasets: concatenation, splitting, alignment along given dimensions, ... #. Explore data with exploratory analyses methods such as ``SVD``, ``PCA``, ``EFA`` and visualization capabilities ... #. Modelling single or multiple datasets with curve fitting / curve modelling (``MCR-ALS``) methods... #. Export data and analyses to various formats: ``csv``, ``xls``, ``JCAMP-DX``, ... #. Embed the complete workflow from raw data import to final analyses in a Project Manager .. only:: html .. image:: https://anaconda.org/spectrocat/spectrochempy/badges/version.svg :target: https://anaconda.org/spectrocat/spectrochempy .. image:: https://anaconda.org/spectrocat/spectrochempy/badges/platforms.svg :target: https://anaconda.org/spectrocat/spectrochempy .. image:: https://anaconda.org/spectrocat/spectrochempy/badges/latest_release_date.svg :target: https://anaconda.org/spectrocat/spectrochempy .. warning:: |scpy| is still experimental and under active development. Its current design is subject to major changes, reorganizations, bugs and crashes!!! Please report any issues to the `Issue Tracker <https://github.com/spectrochempy/spectrochempy/issues>`__ .. toctree:: :hidden: Home <self> **************** Getting Started **************** * :doc:`gettingstarted/whyscpy` * :doc:`gettingstarted/overview` * :doc:`gettingstarted/gallery/auto_examples/index` * :doc:`gettingstarted/install/index` .. toctree:: :maxdepth: 1 :hidden: :caption: Getting Started gettingstarted/whyscpy gettingstarted/overview Examples <gettingstarted/gallery/auto_examples/index> Installation <gettingstarted/install/index> .. _userguide: *********************** User's Guide *********************** * :doc:`userguide/introduction/introduction` * :doc:`userguide/objects` * :doc:`userguide/units/units` * :doc:`userguide/importexport/importexport` * :doc:`userguide/plotting/plotting` * :doc:`userguide/processing/processing` * :doc:`userguide/fitting/fitting` * :doc:`userguide/analysis/analysis` * :doc:`userguide/databases/databases` .. toctree:: :maxdepth: 1 :hidden: :caption: User's Guide userguide/introduction/introduction userguide/objects userguide/units/units userguide/importexport/importexport userguide/plotting/plotting userguide/processing/processing userguide/fitting/fitting userguide/analysis/analysis userguide/databases/databases *********************** Reference & Help *********************** * :doc:`userguide/reference/changelog` * :doc:`userguide/reference/index` * :doc:`userguide/reference/faq` * :doc:`devguide/issues` * :doc:`devguide/examples` * :doc:`devguide/contributing` .. toctree:: :maxdepth: 1 :hidden: :caption: Reference & Help userguide/reference/changelog userguide/reference/index userguide/reference/faq Bug reports & feature request <devguide/issues> Sharing examples & tutorials <devguide/examples> devguide/contributing ******** Credits ******** * :doc:`credits/credits` * :doc:`credits/citing` * :doc:`credits/license` * :doc:`credits/seealso` .. toctree:: :maxdepth: 1 :hidden: :caption: Credits credits/credits credits/citing credits/license credits/seealso <file_sep>/tests/test_analysis/test_iris.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os from spectrochempy.core.analysis.iris import IRIS from spectrochempy.core.dataset.coord import Coord from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.utils import show def test_IRIS(): X = NDDataset.read_omnic(os.path.join('irdata', 'CO@Mo_Al2O3.SPG')) p = [0.00300, 0.00400, 0.00900, 0.01400, 0.02100, 0.02600, 0.03600, 0.05100, 0.09300, 0.15000, 0.20300, 0.30000, 0.40400, 0.50300, 0.60200, 0.70200, 0.80100, 0.90500, 1.00400] X.coordset.update(y=Coord(p, title='pressure', units='torr')) # Using the `update` method is mandatory because it will preserve the name. # Indeed, setting using X.coordset[0] = Coord(...) fails unless name is specified: Coord(..., name='y') # set the optimization parameters, perform the analysis # and plot the results param = { 'epsRange': [-8, -1, 20], 'lambdaRange': [-7, -5, 3], 'kernel': 'langmuir' } X_ = X[:, 2250.:1950.] X_.plot() iris = IRIS(X_, param, verbose=True) f = iris.f X_hat = iris.reconstruct() iris.plotlcurve(scale='ln') f[0].plot(method='map', plottitle=True) X_hat[0].plot(plottitle=True) show() <file_sep>/tests/test_readers_writers/test_read_csv.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from pathlib import Path import spectrochempy as scp from spectrochempy.core import preferences as prefs from spectrochempy.core.dataset.nddataset import NDDataset def test_read_csv(): datadir = prefs.datadir A = NDDataset.read_csv('agirdata/P350/TGA/tg.csv', directory=datadir, origin='tga') assert A.shape == (1, 3247) B = NDDataset.read_csv('irdata/IR.CSV', origin='omnic', csv_delimiter=',') assert B.shape == (1, 3736) # without directory C = NDDataset.read_csv('irdata/IR.CSV') assert C.shape == (1, 3736) # pathlib.Path objects can be used instead of string for filenames p = Path(datadir) / 'irdata' / 'IR.CSV' D = scp.read_csv(p) assert D == C # Read CSV content content = p.read_bytes() E = scp.read_csv({ 'somename.csv': content }) assert E == C <file_sep>/spectrochempy/core/dataset/ndplot.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module defines the class |NDPlot| in which generic plot methods for a |NDDataset| are defined. """ __all__ = ['NDPlot', 'plot'] import re import textwrap from cycler import cycler import matplotlib as mpl from matplotlib.colors import to_rgba # from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt import plotly.graph_objects as go from mpl_toolkits.axes_grid1 import make_axes_locatable from traitlets import Dict, HasTraits, Instance, Union, default, TraitError from spectrochempy.utils import get_figure, pathclean from spectrochempy.core.dataset.meta import Meta from spectrochempy.core import preferences, dataset_preferences, project_preferences, matplotlib_preferences, error_ from spectrochempy.core.plotters.plot1d import plot_1D from spectrochempy.core.plotters.plot3d import plot_3D from spectrochempy.core.plotters.plot2d import plot_2D # from spectrochempy.utils import deprecated # ====================================================================================================================== # Management of the preferences for datasets # ====================================================================================================================== class Preferences(Meta): """ Preferences management """ def __init__(self, **data): super().__init__(**data) def __getitem__(self, key): # search on the preferences if self.parent is not None: res = getattr(self.parent, f'{self.name}_{key}') elif hasattr(matplotlib_preferences, key): res = getattr(matplotlib_preferences, key) elif hasattr(dataset_preferences, key): res = getattr(dataset_preferences, key) elif hasattr(project_preferences, key): res = getattr(project_preferences, key) elif hasattr(preferences, key): res = getattr(preferences, key) else: alias = self._get_alias(key) if alias: if isinstance(alias, list): res = Preferences(parent=self, name=key, **dict([(n, getattr(self, f'{key}_{n}')) for n in alias])) else: res = getattr(self, alias) else: res = super().__getitem__(key) if res is None: error_( f'not found {key}') # key = key.replace('_','.').replace('...', '_').replace('..', # '-') # # res = mpl.rcParams[key] return res def __setitem__(self, key, value): # also change the corresponding preferences if hasattr(matplotlib_preferences, key): try: setattr(matplotlib_preferences, key, value) except TraitError: value = type(matplotlib_preferences.traits()[key].default_value)(value) setattr(matplotlib_preferences, key, value) elif hasattr(dataset_preferences, key): setattr(dataset_preferences, key, value) elif hasattr(project_preferences, key): setattr(project_preferences, key, value) elif hasattr(preferences, key): setattr(preferences, key, value) elif key in self.keys(): newkey = f'{self.name}_{key}' setattr(matplotlib_preferences, newkey, value) self.parent[newkey] = value return else: # try to find an alias for matplotlib values alias = self._get_alias(key) if alias: newkey = f'{alias}_{key}' setattr(matplotlib_preferences, newkey, value) self.parent[newkey] = value else: error_(f'not found {key}') return super().__setitem__(key, value) # # ........................ TO WORK ON ## from spectrochempy.core import preferences, # config_manager # # read json files in the pscp file (obj[f]) # # then write it in the main config # # # directory # f = # 'ProjectPreferences.json' # if f in obj.files: # TODO: work on this # prefjsonfile # = # # # os.path.join(config_dir, f) # with open(prefjsonfile, 'w') as fd: # json.dump(obj[f], fd, # indent=4) # # we must also reinit preferences # app.init_all_preferences() # # # # # # # app.load_config_file(prefjsonfile) # app.project_preferences = ProjectPreferences(config=app.config, # parent=app) # ------------------------------------------------------------------------------------------------------------------ # Private methods # ------------------------------------------------------------------------------------------------------------------ def _get_alias(self, key): alias = [] lkeyp = (len(key) + 1) regex = r"[a-zA-Z0-9_]*(?:\b|_)" + key + "(?:\b|_)[a-zA-Z0-9_]*" for item in matplotlib_preferences.trait_names(): matches = re.match(regex, item) if matches is not None: alias.append(item) if alias: starts = any([par.startswith(key) for par in alias]) # ends = any([par.endswith(key) for par in alias]) if len(alias) > 1: if alias[0].endswith(key) and (not starts and self.parent is not None): # it is a member of a group but we don't know which one: raise KeyError( f'Found several keys for {key}: {alias}, so it is ambigous. Please choose on one of them') else: if any([par.startswith(key) for par in alias]): # we return the group of parameters pars = [] for par in alias: if par.startswith(key): pars.append(par[lkeyp:]) return pars else: return alias[0][:-lkeyp] raise KeyError(f'{key} not found in matplolib preferences') # ------------------------------------------------------------------------------------------------------------------ # Public methods # ------------------------------------------------------------------------------------------------------------------ def reset(self): # remove the matplotlib_user json file to reset to defaults config_dir = pathclean(preferences.cfg.config_dir) f = config_dir / 'MatplotlibPreferences.json' if f.exists(): f.unlink() matplotlib_preferences._apply_style('scpy') self.style = 'scpy' # reset also non-matplolib preferences nonmplpars = ['method_1D', 'method_2D', 'method_3D', 'colorbar', 'show_projections', 'show_projection_x', 'show_projection_y', 'colormap', 'max_lines_in_stack', 'simplify', 'number_of_x_labels', 'number_of_y_labels', 'number_of_z_labels', 'number_of_contours', 'contour_alpha', 'contour_start', 'antialiased', 'rcount', 'ccount'] for par in nonmplpars: setattr(self, par, matplotlib_preferences.traits()[par].default_value) self._data = {} def all(self): """ List all parameters with their current and default value """ for key in matplotlib_preferences.trait_names(config=True): self.help(key) def help(self, key): """ Display information on a given parameter Parameters ---------- key: str name of the parameter for which we want information """ from spectrochempy.utils import colored, TBold value = self[key] trait = matplotlib_preferences.traits()[key] default = trait.default_value thelp = trait.help.replace('\n', ' ').replace('\t', ' ') sav = '' while thelp != sav: sav = thelp thelp = thelp.replace(' ', ' ') help = '\n'.join(textwrap.wrap(thelp, 100, initial_indent=' ' * 20, subsequent_indent=' ' * 20)) value = colored(value, 'GREEN') default = colored(default, 'BLUE') print(TBold(f"{key} = {value} \t[default: {default}]")) print(f"{help}\n") def makestyle(self, filename='mydefault', to_mpl=False): if filename.startswith('scpy'): error_('`scpy` is READ-ONLY. Please use an another style name.') return txt = "" sline = "" for key in mpl.rcParams.keys(): if key in ['animation.avconv_args', 'animation.avconv_path', 'animation.html_args', 'keymap.all_axes', 'mathtext.fallback_to_cm', 'validate_bool_maybe_none', 'savefig.jpeg_quality', 'text.latex.preview', 'backend', 'backend_fallback', 'date.epoch', 'docstring.hardcopy', 'figure.max_open_warning', 'figure.raise_window', 'interactive', 'savefig.directory', 'timezone', 'tk.window_focus', 'toolbar', 'webagg.address', 'webagg.open_in_browser', 'webagg.port', 'webagg.port_retries']: continue val = str(mpl.rcParams[key]) sav = '' while val != sav: sav = val val = val.replace(' ', ' ') line = f'{key:40s} : {val}\n' if line[0] != sline: txt += '\n' sline = line[0] if key not in ['axes.prop_cycle']: line = line.replace('[', '').replace(']', "").replace('\'', '').replace('"', '') if key == 'savefig.bbox': line = f'{key:40s} : standard\n' txt += line.replace("#", '') # Non matplotlib parameters, # some parameters are not saved in matplotlib style sheets so we willa dd them here nonmplpars = ['method_1D', 'method_2D', 'method_3D', 'colorbar', 'show_projections', 'show_projection_x', 'show_projection_y', 'colormap', 'max_lines_in_stack', 'simplify', 'number_of_x_labels', 'number_of_y_labels', 'number_of_z_labels', 'number_of_contours', 'contour_alpha', 'contour_start', 'antialiased', 'rcount', 'ccount'] txt += '\n\n##\n## ADDITIONAL PARAMETERS FOR SPECTROCHEMPY\n##\n' for par in nonmplpars: txt += f"##@{par:37s} : {getattr(self, par)}\n" stylesheet = (pathclean(self.stylesheets) / filename).with_suffix('.mplstyle') stylesheet.write_text(txt) if to_mpl: # make it also accessible to pyplot stylelib = (pathclean(mpl.get_configdir()) / 'stylelib' / filename).with_suffix('.mplstyle') stylelib.write_text(txt) # matplotlib_preferences.traits()['style'].trait_types = matplotlib_preferences.traits()['style'].trait_types +\ # (Unicode(filename),) self.style = filename return self.style # ====================================================================================================================== # Class NDPlot to handle plotting of datasets # ====================================================================================================================== class NDPlot(HasTraits): """ Plotting interface for |NDDataset| This class is used as basic plotting interface of the |NDDataset|. """ # variable containing the matplotlib axis defined for a NDArray object _ax = Instance(plt.Axes, allow_none=True) # The figure on which this NDArray can be plotted _fig = Union((Instance(plt.Figure), Instance(go.Figure)), allow_none=True) # The axes on which this dataset and other elements such as projections # and colorbar can be plotted _ndaxes = Dict(Instance(plt.Axes)) # add metadata to store plot parameters _preferences = Instance(Preferences, allow_none=True) # ------------------------------------------------------------------------------------------------------------------ # generic plotter and plot related methods or properties # ------------------------------------------------------------------------------------------------------------------ def plot(self, **kwargs): """ Generic plot function. This apply to a |NDDataset| but actually delegate the work to a plotter defined by the parameter ``method``. """ # -------------------------------------------------------------------- # select plotter depending on the dimension of the data # -------------------------------------------------------------------- method = 'generic' method = kwargs.pop('method', method) # Find or guess the adequate plotter # ----------------------------------- _plotter = getattr(self, f"plot_{method.replace('+', '_')}", None) if _plotter is None: # no plotter found error_('The specified plotter for method ' '`{}` was not found!'.format(method)) raise IOError # Execute the plotter # -------------------- return _plotter(**kwargs) # ------------------------------------------------------------------------------------------------------------------ # plotter: plot_generic # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def plot_generic(self, **kwargs): """ The generic plotter. It try to guess an adequate basic plot for the data. Other method of plotters are defined explicitely in the ``plotters`` package. Parameters ---------- ax : :class:`matplotlib.axe` the viewplot where to plot. kwargs : optional additional arguments Returns ------- ax Return the handler to ax where the main plot was done """ if self._squeeze_ndim == 1: ax = plot_1D(self, **kwargs) elif self._squeeze_ndim == 2: ax = plot_2D(self, **kwargs) elif self._squeeze_ndim == 3: ax = plot_3D(self, **kwargs) else: error_('Cannot guess an adequate plotter, nothing done!') return False return ax def close_figure(self): """Close a Matplotlib figure associated to this dataset""" if self._fig is not None: plt.close(self._fig) # ------------------------------------------------------------------------------------------------------------------ # setup figure properties # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def _figure_setup(self, ndim=1, **kwargs): prefs = self.preferences method = prefs.method_2D if ndim == 2 else prefs.method_1D method = kwargs.get('method', method) ax3d = '3d' if method in ['surface'] else None # Get current figure information # ------------------------------ # should we use the previous figure? clear = kwargs.get('clear', True) # is ax in the keywords ? ax = kwargs.pop('ax', None) # is it a twin figure? In such case if ax and hold are also provided, # they will be ignored tax = kwargs.get('twinx', None) if tax is not None: if isinstance(tax, plt.Axes): clear = False ax = tax.twinx() ax.name = 'main' tax.name = 'twin' # the previous main is renamed! self.ndaxes['main'] = ax self.ndaxes['twin'] = tax else: raise ValueError(f'{tax} is not recognized as a valid Axe') self._fig = get_figure(preferences=prefs, **kwargs) if clear: self._ndaxes = {} # reset ndaxes self._divider = None if ax is not None: # ax given in the plot parameters, # in this case we will plot on this ax if isinstance(ax, (plt.Axes)): ax.name = 'main' self.ndaxes['main'] = ax else: raise ValueError('{} is not recognized as a valid Axe'.format(ax)) elif self._fig.get_axes(): # no ax parameters in keywords, so we need to get those existing # We assume that the existing axes have a name self.ndaxes = self._fig.get_axes() else: # or create a new subplot ax = self._fig.gca(projection=ax3d) ax.name = 'main' self.ndaxes['main'] = ax # set the prop_cycle according to preference prop_cycle = eval(prefs.axes.prop_cycle) if isinstance(prop_cycle, str): # not yet evaluated prop_cycle = eval(prop_cycle) colors = prop_cycle.by_key()['color'] for i, c in enumerate(colors): try: c = to_rgba(c) colors[i] = c except ValueError: try: c = to_rgba(f'#{c}') colors[i] = c except ValueError as e: raise e linestyles = ['-', '--', ':', '-.'] markers = ['o', 's', '^'] if ax is not None and (kwargs.pop('scatter', False) or kwargs.pop('scatterpen', False)): ax.set_prop_cycle(cycler('color', colors * len(linestyles) * len(markers)) + cycler('linestyle', linestyles * len( colors) * len( markers)) + cycler( 'marker', markers * len(colors) * len(linestyles))) elif ax is not None and kwargs.pop('pen', False): ax.set_prop_cycle(cycler('color', colors * len(linestyles)) + cycler('linestyle', linestyles * len(colors))) # Get the number of the present figure self._fignum = self._fig.number # for generic plot, we assume only a single axe # with possible projections # and an optional colobar. # other plot class may take care of other needs ax = self.ndaxes['main'] if ndim == 2: # TODO: also the case of 3D # show projections (only useful for map or image) # ------------------------------------------------ self.colorbar = colorbar = kwargs.get('colorbar', prefs.colorbar) proj = kwargs.get('proj', prefs.show_projections) # TODO: tell the axis by title. xproj = kwargs.get('xproj', prefs.show_projection_x) yproj = kwargs.get('yproj', prefs.show_projection_y) SHOWXPROJ = (proj or xproj) and method in ['map', 'image'] SHOWYPROJ = (proj or yproj) and method in ['map', 'image'] # Create the various axes # ------------------------- # create new axes on the right and on the top of the current axes # The first argument of the new_vertical(new_horizontal) method is # the height (width) of the axes to be created in inches. # # This is necessary for projections and colorbar self._divider = None if (SHOWXPROJ or SHOWYPROJ or colorbar) and self._divider is None: self._divider = make_axes_locatable(ax) divider = self._divider if SHOWXPROJ: axex = divider.append_axes("top", 1.01, pad=0.01, sharex=ax, frameon=0, yticks=[]) axex.tick_params(bottom='off', top='off') plt.setp(axex.get_xticklabels() + axex.get_yticklabels(), visible=False) axex.name = 'xproj' self.ndaxes['xproj'] = axex if SHOWYPROJ: axey = divider.append_axes("right", 1.01, pad=0.01, sharey=ax, frameon=0, xticks=[]) axey.tick_params(right='off', left='off') plt.setp(axey.get_xticklabels() + axey.get_yticklabels(), visible=False) axey.name = 'yproj' self.ndaxes['yproj'] = axey if colorbar and not ax3d: axec = divider.append_axes("right", .15, pad=0.1, frameon=0, xticks=[], yticks=[]) axec.tick_params(right='off', left='off') # plt.setp(axec.get_xticklabels(), visible=False) axec.name = 'colorbar' self.ndaxes['colorbar'] = axec # ------------------------------------------------------------------------------------------------------------------ # resume a figure plot # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def _plot_resume(self, origin, **kwargs): # debug_('resume plot') # put back the axes in the original dataset # (we have worked on a copy in plot) if not kwargs.get('data_transposed', False): origin.ndaxes = self.ndaxes if not hasattr(self, '_ax_lines'): self._ax_lines = None origin._ax_lines = self._ax_lines if not hasattr(self, "_axcb"): self._axcb = None origin._axcb = self._axcb else: nda = {} for k, v in self.ndaxes.items(): nda[k + 'T'] = v origin.ndaxes = nda origin._axT_lines = self._ax_lines if hasattr(self, "_axcb"): origin._axcbT = self._axcb origin._fig = self._fig loc = kwargs.get("legend", None) if loc: origin.ndaxes['main'].legend(loc=loc) # Additional matplotlib commands on the current plot # --------------------------------------------------------------------- commands = kwargs.get('commands', []) if commands: for command in commands: com, val = command.split('(') val = val.split(')')[0].split(',') ags = [] kws = {} for item in val: if '=' in item: k, v = item.split('=') kws[k.strip()] = eval(v) else: ags.append(eval(item)) getattr(self.ndaxes['main'], com)(*ags, **kws) # TODO: improve this # output command should be after all plot commands savename = kwargs.get('output', None) if savename is not None: # we save the figure with options found in kwargs # starting with `save` # debug_('save plot to {}'.format(savename)) kw = {} for key, value in kwargs.items(): if key.startswith('save'): key = key[4:] kw[key] = value self._fig.savefig(savename, **kw) # ------------------------------------------------------------------------------------------------------------------ # Special attributes # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def __dir__(self): return ['fignum', 'ndaxes', 'divider'] # ------------------------------------------------------------------------------------------------------------------ # Properties # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @default('_preferences') def _preferences_default(self): # Reset all preferences prefs = Preferences() return prefs # .................................................................................................................. @property def preferences(self): """ |Meta| instance object - Additional metadata. """ return self._preferences # .................................................................................................................. @preferences.setter def preferences(self, preferences): # property.setter for preferences if preferences is not None: self._preferences.update(preferences) # .................................................................................................................. @property def fig(self): """ Matplotlib figure associated to this dataset """ return self._fig # .................................................................................................................. @property def fignum(self): """ Matplotlib figure associated to this dataset """ return self._fignum # .................................................................................................................. @property def ndaxes(self): """ A dictionary containing all the axes of the current figures """ return self._ndaxes # .................................................................................................................. @ndaxes.setter def ndaxes(self, axes): # we assume that the axes have a name if isinstance(axes, list): # a list a axes have been passed for ax in axes: # debug_('add axe: {}'.format(ax.name)) self._ndaxes[ax.name] = ax elif isinstance(axes, dict): self._ndaxes.update(axes) elif isinstance(axes, plt.Axes): # it's an axe! add it to our list self._ndaxes[axes.name] = axes # .................................................................................................................. @property def ax(self): """ the main matplotlib axe associated to this dataset """ return self._ndaxes['main'] # .................................................................................................................. @property def axT(self): """ the matplotlib axe associated to the transposed dataset """ return self._ndaxes['mainT'] # .................................................................................................................. @property def axec(self): """ Matplotlib colorbar axe associated to this dataset """ return self._ndaxes['colorbar'] # .................................................................................................................. @property def axecT(self): """ Matplotlib colorbar axe associated to the transposed dataset """ return self._ndaxes['colorbarT'] # .................................................................................................................. @property def axex(self): """ Matplotlib projection x axe associated to this dataset """ return self._ndaxes['xproj'] # .................................................................................................................. @property def axey(self): """ Matplotlib projection y axe associated to this dataset """ return self._ndaxes['yproj'] # .................................................................................................................. @property def divider(self): """ Matplotlib plot divider """ return self._divider # ............................................................................. plot = NDPlot.plot # make plot accessible directly from the scp API # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/tests/test_readers_writers/test_read_zip.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from pathlib import Path from spectrochempy.core import preferences as prefs from spectrochempy.core.dataset.nddataset import NDDataset def test_read_zip(): datadir = prefs.datadir # with pytest.raises(NotImplementedError): # NDDataset.read_zip('agirdata/P350/FTIR/FTIR.zip') A = NDDataset.read_zip('agirdata/P350/FTIR/FTIR.zip', origin='omnic', only=10, csv_delimiter=';', merge=True) assert A.shape == (10, 2843) # Test bytes contents for ZIP files z = Path(datadir) / 'agirdata' / 'P350' / 'FTIR' / 'FTIR.zip' content2 = z.read_bytes() B = NDDataset.read_zip({ 'name.zip': content2 }, origin='omnic', only=10, csv_delimiter=';', merge=True) assert B.shape == (10, 2843) # Test read_zip with several contents C = NDDataset.read_zip({ 'name1.zip': content2, 'name2.zip': content2 }, origin='omnic', only=10, csv_delimiter=';', merge=True) assert C.shape == (2, 10, 2843) <file_sep>/spectrochempy/utils/exceptions.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import warnings __all__ = ['SpectroChemPyWarning', 'SpectroChemPyException', 'UnitsCompatibilityError', 'DimensionsCompatibilityError', 'CoordinateMismatchError', 'ProtocolError', 'deprecated', ] # ====================================================================================================================== # Exception and warning subclass # ====================================================================================================================== # ---------------------------------------------------------------------------------------------------------------------- class SpectroChemPyWarning(Warning): """ The base warning class for SpectroChemPy warnings. """ # ---------------------------------------------------------------------------------------------------------------------- class SpectroChemPyException(Exception): """ The base exception class for SpectroChemPy """ # ---------------------------------------------------------------------------------------------------------------------- class UnitsCompatibilityError(SpectroChemPyException): """ Exception raised when units are not compatible, preventing some mathematical operations """ # ---------------------------------------------------------------------------------------------------------------------- class DimensionsCompatibilityError(SpectroChemPyException): """ Exception raised when dimensions are not compatible for concatenation for instance """ # ---------------------------------------------------------------------------------------------------------------------- class CoordinateMismatchError(SpectroChemPyException): """ Exception raised when object coordinates differ """ class ProtocolError(SpectroChemPyException): def __init__(self, protocol, available_protocols): print(f'The `{protocol}` protocol is unknown or not yet implemented:\n' f'it is expected to be one of {tuple(available_protocols)}') # ---------------------------------------------------------------------------------------------------------------------- def deprecated(message): """ Deprecation decorator Parameters ---------- message : str, the deprecation message """ def deprecation_decorator(func): def wrapper(*args, **kwargs): warnings.warn("The function `{} is deprecated : {}".format(func.__name__, message), DeprecationWarning) return func(*args, **kwargs) return wrapper return deprecation_decorator # ====================================================================================================================== # EOF <file_sep>/tests/test_analysis/test_efa.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy.core.analysis.efa import EFA from spectrochempy.utils import MASKED, show def test_EFA(IR_dataset_2D): ds = IR_dataset_2D.copy() # columns masking ds[:, 1230.0:920.0] = MASKED # do not forget to use float in slicing ds[:, 5900.0:5890.0] = MASKED # difference spectra ds -= ds[-1] # column masking for bad columns ds[10:12] = MASKED efa = EFA(ds) n_pc = 4 c = efa.get_conc(n_pc) c.T.plot() show() <file_sep>/spectrochempy/core/__init__.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Package defining the *core* methods of the |scpy| API. Most the API methods such as plotting, processing, analysis, etc... """ # warnings.simplefilter('ignore', (DeprecationWarning, # FutureWarning, UserWarning)) import os from os import environ import sys import warnings import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import scipy from tqdm import tqdm warnings.filterwarnings("ignore") # ====================================================================================================================== # Tells here the methods or object we allow to import from this library # ====================================================================================================================== __all__ = [ # Useful librairies alias for the end user avoiding to load them when wild card import is used # -------------------------------------------------------------------------------------------- 'np', 'plt', 'scipy', 'os', 'sys', 'mpl', # methods and objects from other packages will be added # later on this module (see below) ] # ====================================================================================================================== # logging functions # ====================================================================================================================== from spectrochempy.utils import pstr # noqa: E402 def print_(*args, **kwargs): """ Formatted printing """ s = "" for a in args: s += pstr(a, **kwargs) + ' ' s = s.replace('\0', '').strip() print(s) # ---------------------------------------------------------------------------------------------------------------------- def info_(*args, **kwargs): s = "" for a in args: s += pstr(a, **kwargs) + ' ' s = s.replace('\0', '').strip() app.logs.info(s) # ---------------------------------------------------------------------------------------------------------------------- def debug_(*args, **kwargs): s = "" for a in args: s += pstr(a, **kwargs) + ' ' s = s.replace('\0', '').strip() try: app.logs.debug(s) except NameError: # works only if app if already loaded pass # ---------------------------------------------------------------------------------------------------------------------- def error_(*args, **kwargs): s = '' if not isinstance(args[0], str): s += type(args[0]).__name__ + ": " for a in args: s += pstr(a, **kwargs) + ' ' s = s.replace('\0', '').strip() app.logs.error(s) # ---------------------------------------------------------------------------------------------------------------------- def warning_(*args, **kwargs): s = "" for a in args: s += pstr(a, **kwargs) + ' ' s = s.replace('\0', '').strip() app.logs.warning(s) __all__ += ['info_', 'debug_', 'error_', 'warning_', 'print_'] # ====================================================================================================================== # Progress bar # ====================================================================================================================== pbar_count = 0 USE_TQDM = environ.get('USE_TQDM', 'Yes') == 'Yes' and 'DOC_BUILDING' not in environ and "/bin/scpy" not in sys.argv[0] if USE_TQDM: pbar = tqdm(total=1211) pbar.set_description('Loading SpectroChemPy API') val_tqdm = [1, 39, 52, 83, 83, 89, 92, 93, 94, 95, 96, 97, 98, 99, 100] def _pbar_update(close=None): global pbar_count if USE_TQDM: if close: pbar.clear() pbar.close() pbar_count = 0 else: pbar.update(val_tqdm[pbar_count]) pbar_count += 1 else: pass # ====================================================================================================================== # loading module libraries # here we also construct the __all__ list automatically # ====================================================================================================================== _pbar_update() from spectrochempy.application import SpectroChemPy # noqa: E402 app = SpectroChemPy() __all__ += ['app'] from spectrochempy.application import ( # noqa: E402 __version__ as version, __release__ as release, __copyright__ as copyright, __license__ as license, __release_date__ as release_date, __author__ as authors, __contributor__ as contributors, __url__ as url, DEBUG, WARNING, ERROR, CRITICAL, INFO, ) preferences = app.preferences project_preferences = app.project_preferences dataset_preferences = app.dataset_preferences matplotlib_preferences = app.matplotlib_preferences description = app.description long_description = app.long_description config_manager = app.config_manager config_dir = app.config_dir # datadir = app.datadir def set_loglevel(level=WARNING): preferences.log_level = level def get_loglevel(): return preferences.log_level __all__ += [ # Helpers 'DEBUG', 'WARNING', 'ERROR', 'CRITICAL', 'INFO', 'project_preferences', 'dataset_preferences', 'preferences', 'matplotlib_preferences', 'config_manager', 'config_dir', 'set_loglevel', 'get_loglevel', # Info 'copyright', 'version', 'release', 'license', 'url', 'release_date', 'authors', 'contributors', 'description', 'long_description' ] # IPython methods # ---------------------------------------------------------------------------------------------------------------------- # we put them before so that we can eventually overwrite them _pbar_update() # constants # ---------------------------------------------------------------------------------------------------------------------- from spectrochempy.utils import show, MASKED, NOMASK, EPSILON, INPLACE # noqa: E402 __all__ += ['show', 'MASKED', 'NOMASK', 'EPSILON', 'INPLACE'] # dataset # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.core.dataset.api import * # noqa: E402,F403,F401 from spectrochempy.core.dataset import api # noqa: E402 __all__ += api.__all__ # plotters # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.core.plotters.api import * # noqa: E402,F403,F401 from spectrochempy.core.plotters import api # noqa: E402 __all__ += api.__all__ # processors # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.core.processors.api import * # noqa: E402,F403,F401 from spectrochempy.core.processors import api # noqa: E402 __all__ += api.__all__ # readers # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.core.readers.api import * # noqa: E402,F403,F401 from spectrochempy.core.readers import api # noqa: E402 __all__ += api.__all__ # writers # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.core.writers.api import * # noqa: E402,F403,F401 from spectrochempy.core.writers import api # noqa: E402 __all__ += api.__all__ # units # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.units.units import * # noqa: E402,F403,F401 from spectrochempy.units import units # noqa: E402 __all__ += units.__all__ # databases # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.databases.api import * # noqa: E402,F403,F401 from spectrochempy.databases import api # noqa: E402 __all__ += api.__all__ # analysis # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.core.analysis.api import * # noqa: E402,F403,F401 from spectrochempy.core.analysis import api # noqa: E402 __all__ += api.__all__ # fitting # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.core.fitting.api import * # noqa: E402,F403,F401 from spectrochempy.core.fitting import api # noqa: E402 __all__ += api.__all__ # project # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.core.project.api import * # noqa: E402,F403,F401 from spectrochempy.core.project import api # noqa: E402 __all__ += api.__all__ # script # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.core.scripts.api import * # noqa: E402,F403,F401 from spectrochempy.core.scripts import api # noqa: E402 __all__ += api.__all__ # widgets # ---------------------------------------------------------------------------------------------------------------------- _pbar_update() from spectrochempy.widgets.api import * # noqa: E402,F403,F401 from spectrochempy.widgets import api # noqa: E402 __all__ += api.__all__ # Helpers # ---------------------------------------------------------------------------------------------------------------------- def APIref(): """ Helper to display public objects and methods from the API """ a = __all__[:] a = sorted(a) return a APIref = APIref() __all__.append('APIref') # START THE app _pbar_update() _pbar_update(close=True) _started = app.start() warnings.filterwarnings(action='ignore', module='matplotlib', category=UserWarning) # ---------------------------------------------------------------------------------------------------------------------- # File Dialogs # ---------------------------------------------------------------------------------------------------------------------- # can not be in utils due to circular imports __all__ += ['open_dialog', 'save_dialog'] USE_QT = preferences.use_qt if USE_QT: try: from PyQt5 import QtWidgets GUI = QtWidgets.QApplication(sys.argv) FileDialog = QtWidgets.QFileDialog except ImportError: # Qt not found - use Tkinter USE_QT = False if not USE_QT: from tkinter import filedialog # ------------------------------------------------------------------------------------------------------------------ # Private functions # ------------------------------------------------------------------------------------------------------------------ class _QTFileDialogs: @classmethod def _open_existing_directory(cls, parent=None, caption='Select a folder', directory=''): options = FileDialog.DontResolveSymlinks | FileDialog.ShowDirsOnly | FileDialog.DontUseNativeDialog directory = FileDialog.getExistingDirectory(parent, caption=caption, directory=directory, options=options) if directory: return directory # noinspection PyRedundantParentheses @classmethod def _open_filename(cls, parent=None, directory='', caption='Select file', filters=None): options = FileDialog.DontUseNativeDialog filename, _ = FileDialog.getOpenFileName(parent, caption=caption, directory=directory, filter=';;'.join(filters), options=options) if filename: return filename # noinspection PyRedundantParentheses @classmethod def _open_multiple_filenames( cls, parent=None, directory='', caption='Select file(s)', filters=None): """ Return one or several files to open """ options = FileDialog.DontUseNativeDialog files, _ = FileDialog.getOpenFileNames(parent, caption=caption, directory=directory, filter=';;'.join(filters), options=options) if files: return files @classmethod def _save_filename(cls, filename='', caption='Save as...', selected_filter='', filters=None): options = FileDialog.DontUseNativeDialog options |= FileDialog.DontConfirmOverwrite # bug : this seems to work only with DontUseNativeDialog on OSX. # TODO: Check on windows and Linux # second problems: if we confirm overwrite here a new dialog is opened, # and thus the main one do not close on exit! filename, _ = FileDialog.getSaveFileName(parent=None, caption=caption, directory=str(filename), initialFilter=selected_filter, filter=';;'.join(filters), options=options) if filename: return filename class _TKFileDialogs: def __init__(self): import tkinter as tk root = tk.Tk() root.withdraw() root.overrideredirect(True) root.geometry('0x0+0+0') root.deiconify() root.lift() root.focus_force() self.root = root # self.root.mainloop() def _open_existing_directory(self, caption='Select a folder', directory=''): directory = filedialog.askdirectory(parent=self.root, initialdir=directory, title=caption) if directory: return directory @staticmethod def filetypes(filters): # convert QT filters to TK import re regex = r"(.*)\((.*)\)" filetypes = [] for filter in filters: matches = re.finditer(regex, filter) match = list(matches)[0] g = list(match.groups()) g[1] = g[1].replace('[0-9]', '') g[1] = g[1].replace('1[r|i]', '*.*') g[1] = g[1].replace('2[r|i]*', '*.*') g[1] = g[1].replace('3[r|i]*', '*.*') g[1] = g[1].replace(' ', ',') g[1] = tuple(set(g[1].split(','))) filetypes.append((g[0], (g[1]))) return filetypes # noinspection PyRedundantParentheses def _open_filename(self, filters=None): filename = filedialog.askopenfilename( parent=self.root, filetypes=self.filetypes(filters), title='Select file to open') self.root.destroy() if filename: return filename # noinspection PyRedundantParentheses def _open_multiple_filenames( self, filters=None): """ Return one or several files to open """ filename = filedialog.askopenfilenames( parent=self.root, filetypes=self.filetypes(filters) + [("all files", ('*'))], title='Select file(s) to open') self.root.destroy() if filename: return filename def _save_filename(self, filename='', caption='Save as...', selected_filter='', filters=None): from spectrochempy.utils import pathclean dftext = '' directory = '.' if filename: filename = pathclean(filename) directory = filename.parent dftext = filename.suffix if not dftext and selected_filter: raise Exception("Save error") if not dftext: dftext = '.scp' # -defaultextension, -filetypes, -initialdir, -initialfile, -message, -parent, -title, -typevariable, # -command, or -confirmoverwrite filename = filedialog.asksaveasfilename(parent=self.root, title=caption, initialdir=str(directory), initialfile=filename.name, defaultextension=dftext, filetypes=self.filetypes(filters)) if filename: return pathclean(filename) # ------------------------------------------------------------------------------------------------------------------ # Public functions # ------------------------------------------------------------------------------------------------------------------ # noinspection PyRedundantParentheses def save_dialog(filename='', caption='Save as...', selected_filter='', filters=("All Files (*)")): """ Return a file where to save """ if USE_QT: f = _QTFileDialogs._save_filename(filename, caption, selected_filter, filters) else: f = _TKFileDialogs()._save_filename(filename, caption, selected_filter, filters) from spectrochempy.utils.file import pathclean return pathclean(f) # noinspection PyRedundantParentheses def open_dialog(single=True, directory='', filters=("All Files (*)") ): """ Return one or several files to open """ if USE_QT: klass = _QTFileDialogs else: klass = _TKFileDialogs() if directory is None: directory = '' if filters == 'directory': caption = 'Select a folder' f = klass._open_existing_directory(caption=caption, directory=str(directory)) elif single: f = klass._open_filename(filters=filters) else: f = klass._open_multiple_filenames(filters=filters) from spectrochempy.utils.file import pathclean return pathclean(f) # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/spectrochempy/utils/fake.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Fake data for testing This module implements routines to generate fake data that can be used for testing our various |scpy| analysis methods """ __all__ = ['generate_fake'] import numpy as np def _make_spectra_matrix(pos, width, ampl): from spectrochempy.core.dataset.coord import Coord from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.fitting.models import gaussianmodel x = Coord(np.linspace(6000.0, 1000.0, 4000), units='cm^-1', title='wavenumbers') s = [] for args in zip(ampl, width, pos): s.append(gaussianmodel().f(x.data, *args)) st = np.vstack(s) st = NDDataset(data=st, units='absorbance', title='absorbance', coordset=[range(len(st)), x]) return st def _make_concentrations_matrix(*profiles): from spectrochempy.core.dataset.coord import Coord from spectrochempy.core.dataset.nddataset import NDDataset t = Coord(np.linspace(0, 10, 50), units='hour', title='time') c = [] for p in profiles: c.append(p(t.data)) ct = np.vstack(c) ct = ct - ct.min() ct = ct / np.sum(ct, axis=0) ct = NDDataset(data=ct, title='concentration', coordset=[range(len(ct)), t]) return ct def _generate_2D_spectra(concentrations, spectra): """ Generate a fake 2D experimental spectra Parameters ---------- concentrations : |NDDataset| spectra : |NDDataset| Returns ------- |NDDataset| """ from spectrochempy.core.dataset.npy import dot return dot(concentrations.T, spectra) def generate_fake(): from spectrochempy.utils import show # define properties of the spectra and concentration profiles # ---------------------------------------------------------------------------------------------------------------------- POS = (6000., 4000., 2000., 2500.) WIDTH = (6000., 1000., 600., 800.) AMPL = (100., 100., 20., 50.) def C1(t): return t * .05 + .01 # linear evolution of the baseline def C2(t): return np.exp(-t / .5) * .3 + .1 def C3(t): return np.exp(-t / 3.) * .7 def C4(t): return 1. - C2(t) - C3(t) spec = _make_spectra_matrix(POS, WIDTH, AMPL) spec.plot_stack(colorbar=False) conc = _make_concentrations_matrix(C1, C2, C3, C4) conc.plot_stack(colorbar=False) d = _generate_2D_spectra(conc, spec) # add some noise d.data = np.random.normal(d.data, .007 * d.data.max()) d.plot_stack() show() d.save('test_full2D') spec.save('test_spectra') conc.save('test_concentration') # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/tests/test_plotters/test_plot2D.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy import NDDataset, show, preferences as prefs def test_plot2D(): A = NDDataset.read_omnic('irdata/nh4y-activation.spg') A.y -= A.y[0] A.y.to('hour', inplace=True) A.y.title = u'Aquisition time' A.copy().plot_stack() A.copy().plot_stack(data_transposed=True) A.copy().plot_image(style=['sans', 'paper'], fontsize=9) # use preferences prefs = A.preferences prefs.reset() prefs.image.cmap = 'magma' prefs.font.size = 10 prefs.font.weight = 'bold' prefs.axes.grid = True A.plot() A.plot(style=['sans', 'paper', 'grayscale'], colorbar=False) show() pass def test_plotly2D(): A = NDDataset.read_omnic('irdata/nh4y-activation.spg', directory=prefs.datadir) A.y -= A.y[0] A.y.to('hour', inplace=True) A.y.title = u'Aquisition time' # TODO: A.copy().plot(use_plotly=True) # ====================================================================================================================== if __name__ == '__main__': pass # EOF <file_sep>/docs/gettingstarted/install/install_colab.rst .. _install_colab: **************************************** Install in Google Colaboratory (Colab) **************************************** May be you want to try or run SpectroChemPy without installing python and all the necessary packages on your computer. To do this you can use `Colaboratory <https://colab.research.google.com/notebooks/intro.ipynb?hl=en#>`__, in short `Colab`, which allows you to run python notebooks in your browser without any installation. The Colab Notebooks are very similar to Jupyter Notebook (from which they derive). To start with Colab, go to the `Colab website <https://colab.research.google.com/notebooks/intro.ipynb#recent=true>`_ and create a new notebook. In the first cell, you must enter the following block of instructions to load SpectroChemPy and the tests/examples files in Colab. .. sourcecode:: ipython3 !wget -c "https://www.spectrochempy.fr/downloads/set_colab.sh" &> /dev/null !bash set_colab.sh Then as usual you can start using SpectroChemPy. .. image:: images/colab.png :alt: Colab windows .. warning:: Colab notebooks are isolated and thus you need to perform the above operation for all notebook you create. Example of a Colab session -------------------------- .. raw:: html <video width="696" controls> <source src="../../_static/video/capsule_colab.mp4" type="video/mp4"> Your browser does not support the video tag. </video> <file_sep>/spectrochempy/core/processors/filter.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ['savgol_filter', 'detrend'] __dataset_methods__ = __all__ import scipy.signal """wrappers of scipy.signal filters, """ # Todo: # find_peaks_cwt(vector, widths[, wavelet, ...]) Attempt to find the peaks in a 1-D array. # argrelmin(data[, axis, order, mode]) Calculate the relative minima of data. # argrelmax(data[, axis, order, mode]) Calculate the relative maxima of data. # argrelextrema(data, comparator[, axis, ...]) Calculate the relative extrema of data. def savgol_filter(dataset, window_length=5, polyorder=0, deriv=0, delta=1.0, mode='interp', cval=0.0, **kwargs): """ Apply a Savitzky-Golay filter to a NDDataset. Wrapper of scpy.signal.savgol(). If dataset has dimension greater than 1, dim determines the axis along which the filter is applied. Parameters ---------- dataset : |NDDataset| The data to be filtered. If dataset.data is not a single or double precision floating point array, it will be converted to type numpy.float64 before filtering. window_length : int The length of the filter window (i.e. the number of coefficients). window_length must be a positive odd integer. polyorder : int The order of the polynomial used to fit the NDDataset. polyorder must be less than window_length. deriv : int, optional The order of the derivative to compute. This must be a nonnegative integer. The default is 0, which means to filter the data without differentiating. delta : float, optional The spacing of the samples to which the filter will be applied. This is only used if deriv > 0. Default is 1.0. mode : str, optional Must be ‘mirror’, ‘constant’, ‘nearest’, ‘wrap’ or ‘interp’. This determines the type of extension to use for the padded signal to which the filter is applied. When mode is ‘constant’, the padding value is given by cval. See :py:scipy.signal.savgol_filter: for more details on ‘mirror’, ‘constant’, ‘wrap’, and ‘nearest’. When the ‘interp’ mode is selected (the default), no extension is used. Instead, a degree polyorder polynomial is fit to the last window_length values of the edges, and this polynomial is used to evaluate the last window_length // 2 output values. cval : scalar, optional Value to fill past the edges of the input if mode is ‘constant’. Default is 0.0. **kwargs : dict See other parameters. Returns ------- NDDataset: same shape as x. data units are removed when deriv > 1 The filtered data. Other Parameters ---------------- dim : str or int, optional, default='x'. Specify on which dimension to apply this method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, optional, default=False. True if we make the transform inplace. If False, the function return a new object Notes ----- Even spacing of the axis coordinates is NOT checked. Be aware that Savitzky-Golay algorithm is based on indexes, not on coordinates. Details on the `mode` options: 'mirror': Repeats the values at the edges in reverse order. The value closest to the edge is not included. 'nearest': The extension contains the nearest input value. 'constant': The extension contains the value given by the `cval` argument. 'wrap': The extension contains the values from the other end of the array. For example, if the input is [1, 2, 3, 4, 5, 6, 7, 8], and `window_length` is 7, the following shows the extended data for the various `mode` options (assuming `cval` is 0):: mode | Ext | Input | Ext -----------+---------+------------------------+--------- 'mirror' | 4 3 2 | 1 2 3 4 5 6 7 8 | 7 6 5 'nearest' | 1 1 1 | 1 2 3 4 5 6 7 8 | 8 8 8 'constant' | 0 0 0 | 1 2 3 4 5 6 7 8 | 0 0 0 'wrap' | 6 7 8 | 1 2 3 4 5 6 7 8 | 1 2 3 See Also --------- smooth : Smooth the data using a window with requested size. Examples -------- >>> import spectrochempy as scp >>> dataset = scp.read('irdata/nh4y-activation.spg') >>> dataset.savgol_filter(window_length=5, polyorder=0) NDDataset: [float64] a.u. (shape: (y:55, x:5549)) """ if not kwargs.pop('inplace', False): # default new = dataset.copy() else: new = dataset is_ndarray = False axis = kwargs.pop('dim', kwargs.pop('axis', -1)) if hasattr(new, 'get_axis'): axis, dim = new.get_axis(axis, negative_axis=True) data = new.data else: is_ndarray = True data = new data = scipy.signal.savgol_filter(data, window_length, polyorder, deriv, delta, axis, mode, cval) if not is_ndarray: if deriv != 0 and dataset.coord(dim).reversed: data = data * (-1) ** deriv new.data = data else: new = data if not is_ndarray: new.history = f'savgol_filter applied (window_length={window_length}, polyorder={polyorder}, ' \ f'deriv={deriv}, delta={delta}, mode={mode}, cval={cval}' return new def detrend(dataset, type='linear', bp=0, **kwargs): """ Remove linear trend along dim from dataset. Wrapper of scpy.signal.detrend(). Parameters ---------- dataset : |NDDataset| The input data. type : str among ['linear', 'constant'}, optional, default='linear' The type of detrending. If ``type == 'linear'`` (default), the result of a linear least-squares fit to `data` is subtracted from `data`. If ``type == 'constant'``, only the mean of `data` is subtracted. bp : array_like of ints, optional A sequence of break points. If given, an individual linear fit is performed for each part of `data` between two break points. Break points are specified as indices into `data`. **kwargs : dict See other parameters. Returns ------- detrended The detrended |NDDataset|. Other Parameters ---------------- dim : str or int, optional, default='x'. Specify on which dimension to apply this method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, optional, default=False. True if we make the transform inplace. If False, the function return a new object See Also -------- BaselineCorrection : Manual baseline correction. abs : Automatic baseline correction. autosub : Subtraction of reference. Examples -------- >>> import spectrochempy as scp >>> dataset = scp.read("irdata/nh4y-activation.spg") >>> dataset.detrend(type='constant') NDDataset: [float64] a.u. (shape: (y:55, x:5549)) """ if not kwargs.pop('inplace', False): # default new = dataset.copy() else: new = dataset is_ndarray = False axis = kwargs.pop('dim', kwargs.pop('axis', -1)) if hasattr(new, 'get_axis'): axis, dim = new.get_axis(axis, negative_axis=True) data = new.data else: is_ndarray = True data = new data = scipy.signal.detrend(data, axis=axis, type=type, bp=bp) if is_ndarray: return data new.data = data return new <file_sep>/spectrochempy/core/dataset/coordset.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements class |CoordSet|. """ __all__ = ['CoordSet'] import copy as cpy import warnings import uuid import numpy as np from traitlets import HasTraits, List, Bool, Unicode, observe, All, validate, \ default, Dict, Int from spectrochempy.core.dataset.ndarray import NDArray, DEFAULT_DIM_NAME from spectrochempy.core.dataset.coord import Coord, LinearCoord from spectrochempy.utils import is_sequence, colored_output, convert_to_html # ====================================================================================================================== # CoordSet # ====================================================================================================================== class CoordSet(HasTraits): # Hidden attributes containing the collection of objects _id = Unicode() _coords = List(allow_none=True) _references = Dict({}) _updated = Bool(False) # Hidden id and name of the object _id = Unicode() _name = Unicode() # Hidden attribute to specify if the collection is for a single dimension _is_same_dim = Bool(False) # other settings _copy = Bool(False) _sorted = Bool(True) _html_output = Bool(False) # default coord index _default = Int(0) # ------------------------------------------------------------------------------------------------------------------ # initialization # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def __init__(self, *coords, **kwargs): """ A collection of Coord objects for a NDArray object with validation. This object is an iterable containing a collection of Coord objects. Parameters ---------- *coords : |NDarray|, |NDArray| subclass or |CoordSet| sequence of objects. If an instance of CoordSet is found, instead of an array, this means that all coordinates in this coords describe the same axis. It is assumed that the coordinates are passed in the order of the dimensions of a nD numpy array ( `row-major <https://docs.scipy.org/doc/numpy-1.14.1/glossary.html#term-row-major>`_ order), i.e., for a 3d object : 'z', 'y', 'x'. **kwargs: dict See other parameters. Other Parameters ---------------- x : |NDarray|, |NDArray| subclass or |CoordSet| A single coordinate associated to the 'x'-dimension. If a coord was already passed in the argument, this will overwrite the previous. It is thus not recommended to simultaneously use both way to initialize the coordinates to avoid such conflicts. y, z, u, ... : |NDarray|, |NDArray| subclass or |CoordSet| Same as `x` for the others dimensions. dims : list of string, optional Names of the dims to use corresponding to the coordinates. If not given, standard names are used: x, y, ... See Also -------- Coord : Explicit coordinates object. LinearCoord : Implicit coordinates object. NDDataset: The main object of SpectroChempy which makes use of CoordSet. Examples -------- >>> from spectrochempy import Coord, CoordSet Define 4 coordinates, with two for the same dimension >>> coord0 = Coord.linspace(10., 100., 5, units='m', title='distance') >>> coord1 = Coord.linspace(20., 25., 4, units='K', title='temperature') >>> coord1b = Coord.linspace(1., 10., 4, units='millitesla', title='magnetic field') >>> coord2 = Coord.linspace(0., 1000., 6, units='hour', title='elapsed time') Now create a coordset >>> cs = CoordSet(t=coord0, u=coord2, v=[coord1, coord1b]) Display some coordinates >>> cs.u Coord: [float64] hr (size: 6) >>> cs.v CoordSet: [_1:temperature, _2:magnetic field] >>> cs.v_1 Coord: [float64] K (size: 4) """ self._copy = kwargs.pop('copy', True) self._sorted = kwargs.pop('sorted', True) keepnames = kwargs.pop('keepnames', False) # if keepnames is false and the names of the dimensions are not passed in kwargs, then use dims if not none dims = kwargs.pop('dims', None) self.name = kwargs.pop('name', None) # initialise the coordinate list self._coords = [] # First evaluate passed args # -------------------------- # some cleaning if coords: if all([(isinstance(coords[i], (np.ndarray, NDArray, list, CoordSet)) or coords[i] is None) for i in range(len(coords))]): # Any instance of a NDArray can be accepted as coordinates for a dimension. # If an instance of CoordSet is found, this means that all # coordinates in this set describe the same axis coords = tuple(coords) elif is_sequence(coords) and len(coords) == 1: # if isinstance(coords[0], list): # coords = (CoordSet(*coords[0], sorted=False),) # else: coords = coords[0] if isinstance(coords, dict): # we have passed a dict, postpone to the kwargs evaluation process kwargs.update(coords) coords = None else: raise ValueError('Did not understand the inputs') # now store the args coordinates in self._coords (validation is fired when this attribute is set) if coords: for coord in coords[::-1]: # we fill from the end of the list # (in reverse order) because by convention when the # names are not specified, the order of the # coords follow the order of dims. if not isinstance(coord, CoordSet): if isinstance(coord, list): coord = CoordSet(*coord, sorted=False) elif not isinstance(coord, LinearCoord): # else coord = Coord(coord, copy=True) else: coord = cpy.deepcopy(coord) if not keepnames: if dims is None: # take the last available name of available names list coord.name = self.available_names.pop(-1) else: # use the provided list of dims coord.name = dims.pop(-1) self._append(coord) # append the coord (but instead of append, # use assignation -in _append - to fire the validation process ) # now evaluate keywords argument # ------------------------------ for key, coord in list(kwargs.items())[:]: # remove the already used kwargs (Fix: deprecation warning in Traitlets - all args, kwargs must be used) del kwargs[key] # prepare values to be either Coord, LinearCoord or CoordSet if isinstance(coord, (list, tuple)): coord = CoordSet(*coord, sorted=False) # make sure in this case it becomes a CoordSet instance elif isinstance(coord, np.ndarray) or coord is None: coord = Coord(coord, copy=True) # make sure it's a Coord # (even if it is None -> Coord(None) elif isinstance(coord, str) and coord in DEFAULT_DIM_NAME: # may be a reference to another coordinates (e.g. same coordinates for various dimensions) self._references[key] = coord # store this reference continue # Populate the coords with coord and coord's name. if isinstance(coord, (NDArray, Coord, LinearCoord, CoordSet)): # NDArray, if key in self.available_names or ( len(key) == 2 and key.startswith('_') and key[1] in list("123456789")): # ok we can find it as a canonical name: # this will overwrite any already defined coord value # which means also that kwargs have priority over args coord.name = key self._append(coord) elif not self.is_empty and key in self.names: # append when a coordinate with this name is already set in passed arg. # replace it idx = self.names.index(key) coord.name = key self._coords[idx] = coord else: raise KeyError(f'Probably an invalid key (`{key}`) for coordinates has been passed. ' f'Valid keys are among:{DEFAULT_DIM_NAME}') else: raise ValueError(f'Probably an invalid type of coordinates has been passed: {key}:{coord} ') # store the item (validation will be performed) # self._coords = _coords # inform the parent about the update self._updated = True # set a notifier on the name traits name of each coordinates for coord in self._coords: if coord is not None: HasTraits.observe(coord, self._coords_update, '_name') # initialize the base class with the eventual remaining arguments super().__init__(**kwargs) # .................................................................................................................. def implements(self, name=None): """ Utility to check if the current object implement `CoordSet`. Rather than isinstance(obj, CoordSet) use object.implements('CoordSet'). This is useful to check type without importing the module """ if name is None: return 'CoordSet' else: return name == 'CoordSet' # ------------------------------------------------------------------------------------------------------------------ # Validation methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @validate('_coords') def _coords_validate(self, proposal): coords = proposal['value'] if not coords: return None for id, coord in enumerate(coords): if coord and not isinstance(coord, (Coord, LinearCoord, CoordSet)): raise TypeError( 'At this point all passed coordinates should be of type Coord or CoordSet!') # coord = # # Coord(coord) coords[id] = coord for coord in coords: if isinstance(coord, CoordSet): # it must be a single dimension axis # in this case we must have same length for all coordinates coord._is_same_dim = True # check this is valid in term of size try: coord.sizes except ValueError: raise # change the internal names n = len(coord) coord._set_names([f"_{i + 1}" for i in range(n)]) # we must have _1 for the first coordinates, # _2 the second, etc... coord._set_parent_dim(coord.name) # last check and sorting names = [] for coord in coords: if coord.has_defined_name: names.append(coord.name) else: raise ValueError('At this point all passed coordinates should have a valid name!') if coords: if self._sorted: _sortedtuples = sorted((coord.name, coord) for coord in coords) # Final sort coords = list(zip(*_sortedtuples))[1] return list(coords) # be sure its a list not a tuple else: return None # .................................................................................................................. @default('_id') def _id_default(self): # a unique id return f"{type(self).__name__}_{str(uuid.uuid1()).split('-')[0]}" # ------------------------------------------------------------------------------------------------------------------ # Readonly Properties # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @property def available_names(self): """ Chars that can be used for dimension name (DEFAULT_DIM_NAMES less those already in use) """ _available_names = DEFAULT_DIM_NAME.copy() for item in self.names: if item in _available_names: _available_names.remove(item) return _available_names # .................................................................................................................. @property def coords(self): """ list -Coordinates in the coordset """ return self._coords # .................................................................................................................. @property def has_defined_name(self): """ bool - True is the name has been defined """ return not (self.name == self.id) # .................................................................................................................. @property def id(self): """ str - Object identifier (Readonly property). """ return self._id # .................................................................................................................. @property def is_empty(self): """ bool - True if there is no coords defined. """ if self._coords: return len(self._coords) == 0 else: return False # .................................................................................................................. @property def is_same_dim(self): """ bool - True if the coords define a single dimension """ return self._is_same_dim # .................................................................................................................. @property def references(self): return self._references # .................................................................................................................. @property def sizes(self): """int or tuple of int - Sizes of the coord object for each dimension (readonly property). If the set is for a single dimension return a single size as all coordinates must have the same. """ _sizes = [] for i, item in enumerate(self._coords): _sizes.append(item.size) # recurrence if item is a CoordSet if self.is_same_dim: _sizes = list(set(_sizes)) if len(_sizes) > 1: raise ValueError('Coordinates must be of the same size for a dimension with multiple coordinates') return _sizes[0] return _sizes # alias size = sizes # .................................................................................................................. # @property # def coords(self): #TODO: replace with itertiems, items etc ... to simulate a dict # """list - list of the Coord objects in the current coords (readonly # property). # """ # return self._coords # .................................................................................................................. @property def names(self): """list - Names of the coords in the current coords (read only property) """ _names = [] if self._coords: for item in self._coords: if item.has_defined_name: _names.append(item.name) return _names # ------------------------------------------------------------------------------------------------------------------ # Mutable Properties # ------------------------------------------------------------------------------------------------------------------ @property def default(self): """ Coord - default coordinates """ return self[self._default] @property def data(self): # in case data is called on a coordset for dimension with multiple coordinates # return the first coordinates return self.default.data # .................................................................................................................. @property def name(self): if self._name: return self._name else: return self._id @name.setter def name(self, value): if value is not None: self._name = value # .................................................................................................................. @property def titles(self): """list - Titles of the coords in the current coords """ _titles = [] for item in self._coords: if isinstance(item, NDArray): _titles.append(item.title if item.title else item.name) # TODO:name elif isinstance(item, CoordSet): _titles.append([el.title if el.title else el.name for el in item]) # TODO:name else: raise ValueError('Something wrong with the titles!') return _titles # .................................................................................................................. @property def labels(self): """list - Labels of the coordinates in the current coordset """ return [item.labels for item in self] # .................................................................................................................. @property def units(self): """ list - Units of the coords in the current coords """ return [item.units for item in self] # ------------------------------------------------------------------------------------------------------------------ # public methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def copy(self, keepname=False): """ Make a disconnected copy of the current coords. Returns ------- object an exact copy of the current object """ return self.__copy__() # .................................................................................................................. def keys(self): """ Alias for names Returns ------- out : list list of all coordinates names (including reference to other coordinates) """ keys = [] if self.names: keys.extend(self.names) if self._references: keys.extend(list(self.references.keys())) return keys # .................................................................................................................. def select(self, val): """ Select the default coord index """ self._default = min(max(0, int(val) - 1), len(self.names)) # ................................................................................................................. def set(self, *args, **kwargs): """ Set one or more coordinates in the current CoordSet Parameters ---------- args kwargs Returns ------- """ if not args and not kwargs: return if len(args) == 1 and (is_sequence(args[0]) or isinstance(args[0], CoordSet)): args = args[0] if isinstance(args, CoordSet): kwargs.update(args.to_dict()) args = () if args: self._coords = [] # reset for i, item in enumerate(args[::-1]): item.name = self.available_names.pop() self._append(item) for k, item in kwargs.items(): if isinstance(item, CoordSet): # try to keep this parameter to True! item._is_same_dim = True self[k] = item # .................................................................................................................. def set_titles(self, *args, **kwargs): """ Set one or more coord title at once Notes ----- If the args are not named, then the attributions are made in coordinate's name alhabetical order : e.g, the first title will be for the `x` coordinates, the second for the `y`, etc. Parameters ---------- args : str(s) The list of titles to apply to the set of coordinates (they must be given according to the coordinate's name alphabetical order kwargs : str keyword attribution of the titles. The keys must be valid names among the coordinate's name list. This is the recommended way to set titles as this will be less prone to errors. """ if len(args) == 1 and (is_sequence(args[0]) or isinstance(args[0], CoordSet)): args = args[0] for i, item in enumerate(args): if not isinstance(self[i], CoordSet): self[i].title = item else: if is_sequence(item): for j, v in enumerate(self[i]): v.title = item[j] for k, item in kwargs.items(): self[k].title = item # .................................................................................................................. def set_units(self, *args, **kwargs): """ Set one or more coord units at once. Notes ----- If the args are not named, then the attributions are made in coordinate's name alhabetical order : e.g, the first units will be for the `x` coordinates, the second for the `y`, etc. Parameters ---------- args : str(s) The list of units to apply to the set of coordinates (they must be given according to the coordinate's name alphabetical order kwargs : str keyword attribution of the units. The keys must be valid names among the coordinate's name list. This is the recommended way to set units as this will be less prone to errors. force : bool, optional, default=False whether or not the new units must be compatible with the current units. See the `Coord`.`to` method. """ force = kwargs.pop('force', False) if len(args) == 1 and is_sequence(args[0]): args = args[0] for i, item in enumerate(args): if not isinstance(self[i], CoordSet): self[i].to(item, force=force, inplace=True) else: if is_sequence(item): for j, v in enumerate(self[i]): v.to(item[j], force=force, inplace=True) for k, item in kwargs.items(): self[k].to(item, force=force, inplace=True) # .................................................................................................................. def to_dict(self): """ Return a dict of the coordinates from the coordset Returns ------- out : dict A dictionary where keys are the names of the coordinates, and the values the coordinates themselves """ return dict(zip(self.names, self._coords)) # .................................................................................................................. def update(self, **kwargs): """ Update a specific coordinates in the CoordSet. Parameters ---------- kwarg : Only keywords among the CoordSet.names are allowed - they denotes the name of a dimension. """ dims = kwargs.keys() for dim in list(dims)[:]: if dim in self.names: # we can replace the given coordinates idx = self.names.index(dim) self[idx] = Coord(kwargs.pop(dim), name=dim) # ------------------------------------------------------------------------------------------------------------------ # private methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def _append(self, coord): # utility function to append coordinate with full validation if not isinstance(coord, tuple): coord = (coord,) if self._coords: # some coordinates already present, prepend the new one self._coords = (*coord,) + tuple(self._coords) # instead of append, fire the validation process else: # no coordinates yet, start a new tuple of coordinate self._coords = (*coord,) # .................................................................................................................. def _loc2index(self, loc): # Return the index of a location for coord in self.coords: try: return coord._loc2index(loc) except IndexError: continue # not found! raise IndexError # .................................................................................................................. def _set_names(self, names): # utility function to change names of coordinates (in batch) # useful when a coordinate is a CoordSet itself for coord, name in zip(self._coords, names): coord.name = name # .................................................................................................................. def _set_parent_dim(self, name): # utility function to set the paretn name for sub coordset for coord in self._coords: coord._parent_dim = name # ------------------------------------------------------------------------------------------------------------------ # special methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @staticmethod def __dir__(): return ['coords', 'references', 'is_same_dim', 'name'] # .................................................................................................................. def __call__(self, *args, **kwargs): # allow the following syntax: coords(), coords(0,2) or coords = [] axis = kwargs.get('axis', None) if args: for idx in args: coords.append(self[idx]) elif axis is not None: if not is_sequence(axis): axis = [axis] for i in axis: coords.append(self[i]) else: coords = self._coords if len(coords) == 1: return coords[0] else: return CoordSet(*coords) # .................................................................................................................. def __hash__(self): # all instance of this class has same hash, so they can be compared return hash(tuple(self._coords)) # .................................................................................................................. def __len__(self): return len(self._coords) def __delattr__(self, item): if 'notify_change' in item: pass else: try: return self.__delitem__(item) except (IndexError, KeyError): raise AttributeError # .................................................................................................................. def __getattr__(self, item): # when the attribute was not found if '_validate' in item or '_changed' in item: raise AttributeError try: return self.__getitem__(item) except (IndexError, KeyError): raise AttributeError # .................................................................................................................. def __getitem__(self, index): if isinstance(index, str): # find by name if index in self.names: idx = self.names.index(index) return self._coords.__getitem__(idx) # ok we did not find it! # let's try in references if index in self._references.keys(): return self._references[index] # let's try in the title if index in self.titles: # selection by coord titles if self.titles.count(index) > 1: warnings.warn(f"Getting a coordinate from its title. However `{index}` occurs several time. Only" f" the first occurence is returned!") return self._coords.__getitem__(self.titles.index(index)) # may be it is a title or a name in a sub-coords for item in self._coords: if isinstance(item, CoordSet) and index in item.titles: # selection by subcoord title return item.__getitem__(item.titles.index(index)) for item in self._coords: if isinstance(item, CoordSet) and index in item.names: # selection by subcoord name return item.__getitem__(item.names.index(index)) try: # let try with the canonical dimension names if index[0] in self.names: # ok we can find it a a canonical name: c = self._coords.__getitem__(self.names.index(index[0])) if len(index) > 1 and index[1] == '_': if isinstance(c, CoordSet): c = c.__getitem__(index[1:]) else: c = c.__getitem__(index[2:]) # try on labels return c except IndexError: pass raise KeyError(f"Could not find `{index}` in coordinates names or titles") try: self._coords.__getitem__(index) except TypeError: print() res = self._coords.__getitem__(index) if isinstance(index, slice): if isinstance(res, CoordSet): res = (res,) return CoordSet(*res, keepnames=True) else: return res # .................................................................................................................. def __setattr__(self, key, value): keyb = key[1:] if key.startswith('_') else key if keyb in ['parent', 'copy', 'sorted', 'coords', 'updated', 'name', 'html_output', 'is_same_dim', 'parent_dim', 'trait_values', 'trait_notifiers', 'trait_validators', 'cross_validation_lock', 'notify_change']: super().__setattr__(key, value) return try: self.__setitem__(key, value) except Exception: super().__setattr__(key, value) # .................................................................................................................. def __setitem__(self, index, coord): try: coord = coord.copy(keepname=True) # to avoid modifying the original except TypeError as e: if isinstance(coord, list): coord = [c.copy(keepname=True) for c in coord[:]] else: raise e if isinstance(index, str): # find by name if index in self.names: idx = self.names.index(index) coord.name = index self._coords.__setitem__(idx, coord) return # ok we did not find it! # let's try in the title if index in self.titles: # selection by coord titles if self.titles.count(index) > 1: warnings.warn(f"Getting a coordinate from its title. However `{index}` occurs several time. Only" f" the first occurence is returned!") index = self.titles.index(index) coord.name = self.names[index] self._coords.__setitem__(index, coord) return # may be it is a title or a name in a sub-coords for item in self._coords: if isinstance(item, CoordSet) and index in item.titles: # selection by subcoord title index = item.titles.index(index) coord.name = item.names[index] item.__setitem__(index, coord) return for item in self._coords: if isinstance(item, CoordSet) and index in item.names: # selection by subcoord title index = item.names.index(index) coord.name = item.names[index] item.__setitem__(index, coord) return try: # let try with the canonical dimension names if index[0] in self.names: # ok we can find it a a canonical name: c = self._coords.__getitem__(self.names.index(index[0])) if len(index) > 1 and index[1] == '_': c.__setitem__(index[1:], coord) return except KeyError: pass # add the new coordinates if index in self.available_names or ( len(index) == 2 and index.startswith('_') and index[1] in list("123456789")): coord.name = index self._coords.append(coord) return else: raise KeyError(f"Could not find `{index}` in coordinates names or titles") self._coords[index] = coord # .................................................................................................................. def __delitem__(self, index): if isinstance(index, str): # find by name if index in self.names: idx = self.names.index(index) del self._coords[idx] return # let's try in the title if index in self.titles: # selection by coord titles index = self.titles.index(index) self._coords.__delitem__(index) return # may be it is a title in a sub-coords for item in self._coords: if isinstance(item, CoordSet) and index in item.titles: # selection by subcoord title return item.__delitem__(index) # let try with the canonical dimension names if index[0] in self.names: # ok we can find it a a canonical name: c = self._coords.__getitem__(self.names.index(index[0])) if len(index) > 1 and index[1] == '_': if isinstance(c, CoordSet): return c.__delitem__(index[1:]) raise KeyError(f"Could not find `{index}` in coordinates names or titles") # .................................................................................................................. # def __iter__(self): # for item in self._coords: # yield item # .................................................................................................................. def __repr__(self): out = "CoordSet: [" + ', '.join(['{}'] * len(self._coords)) + "]" s = [] for item in self._coords: if isinstance(item, CoordSet): s.append(f"{item.name}:" + repr(item).replace('CoordSet: ', '')) else: s.append(f"{item.name}:{item.title}") out = out.format(*s) return out # .................................................................................................................. def __str__(self): return repr(self) # .................................................................................................................. def _cstr(self, header=' coordinates: ... \n', print_size=True): txt = '' for idx, dim in enumerate(self.names): coord = getattr(self, dim) if coord: dimension = f' DIMENSION `{dim}`' for k, v in self.references.items(): if dim == v: # reference to this dimension dimension += f'=`{k}`' txt += dimension + '\n' if isinstance(coord, CoordSet): # txt += ' index: {}\n'.format(idx) if not coord.is_empty: if print_size: txt += f'{coord[0]._str_shape().rstrip()}\n' coord._html_output = self._html_output for idx_s, dim_s in enumerate(coord.names): c = getattr(coord, dim_s) txt += f' ({dim_s}) ...\n' c._html_output = self._html_output sub = c._cstr(header=' coordinates: ... \n', print_size=False) # , indent=4, first_indent=-6) txt += f"{sub}\n" elif not coord.is_empty: # coordinates if available # txt += ' index: {}\n'.format(idx) coord._html_output = self._html_output txt += '{}\n'.format(coord._cstr(header=header, print_size=print_size)) txt = txt.rstrip() # remove the trailing '\n' if not self._html_output: return colored_output(txt.rstrip()) else: return txt.rstrip() # .................................................................................................................. def _repr_html_(self): return convert_to_html(self) # .................................................................................................................. def __deepcopy__(self, memo): coords = self.__class__(tuple(cpy.deepcopy(ax, memo=memo) for ax in self), keepnames=True) coords.name = self.name coords._is_same_dim = self._is_same_dim coords._default = self._default return coords # .................................................................................................................. def __copy__(self): coords = self.__class__(tuple(cpy.copy(ax) for ax in self), keepnames=True) # name must be changed coords.name = self.name # and is_same_dim and default for coordset coords._is_same_dim = self._is_same_dim coords._default = self._default return coords # .................................................................................................................. def __eq__(self, other): if other is None: return False try: return self._coords == other._coords except Exception: return False # .................................................................................................................. def __ne__(self, other): return not self.__eq__(other) # ------------------------------------------------------------------------------------------------------------------ # Events # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def _coords_update(self, change): # when notified that a coord name have been updated self._updated = True # .................................................................................................................. @observe(All) def _anytrait_changed(self, change): # ex: change { # 'owner': object, # The HasTraits instance # 'new': 6, # The new value # 'old': 5, # The old value # 'name': "foo", # The name of the changed trait # 'type': 'change', # The event type of the notification, usually 'change' # } # debug_('changes in CoordSet: %s to %s' % (change.name, change.new)) if change.name == '_updated' and change.new: self._updated = False # reset # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/docs/gettingstarted/video/presentation.py # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] slideshow={"slide_type": "slide"} # # Overview # %% [markdown] # In this presentation, we will shortly present some of the **SpectroChemPy** features. # %% [markdown] slideshow={"slide_type": "notes"} # ## Using the Jupyter Lab environment # %% [markdown] # PRobably the most easiet way to start experiencing SpectroChemPy # # <img src='images/enter_md.png' /> # %% [markdown] slideshow={"slide_type": "subslide"} # We first need to load the API # %% slideshow={"slide_type": "fragment"} tags=["hide-output"] import spectrochempy as scp # %% [markdown] slideshow={"slide_type": "subslide"} # ## NDDataset, the main object # %% [markdown] slideshow={"slide_type": "subslide"} # NDDataset is a python object, actually a container, which can represent most of your multidimensional spectroscopic # data. # %% [markdown] slideshow={"slide_type": "subslide"} # For instance, in the following we read data from a series of FTIR experiments, # provided by the OMNIC software, and create a **NDDataset** from these data # %% ds = scp.read('irdata/nh4y-activation.spg') print(ds) # %% [markdown] slideshow={"slide_type": "subslide"} # ### Display dataset information # %% ds # %% [markdown] slideshow={"slide_type": "subslide"} # ### Plotting a dataset # %% slideshow={"slide_type": "fragment"} _ = ds.plot() # %% [markdown] slideshow={"slide_type": "subslide"} # #### Modifying the figure # %% [markdown] slideshow={"slide_type": "subslide"} # ### Slicing a dataset # %% slideshow={"slide_type": "fragment"} region = ds[:, 4000.0:2000.0] _ = region.plot() # %% [markdown] slideshow={"slide_type": "subslide"} # ### Maths on datasets # %% slideshow={"slide_type": "fragment"} region.y -= region.y[0] # make y coordinate reative to the first point region.y.title = 'time of dehydratatioin' region -= region[-1] # suppress the last spectra to all _ = region.plot(colorbar=True) # %% [markdown] slideshow={"slide_type": "subslide"} # ## Processing a dataset # %% [markdown] slideshow={"slide_type": "subslide"} # We just give here few examples # %% [markdown] slideshow={"slide_type": "subslide"} # #### Smoothing # %% slideshow={"slide_type": "fragment"} smoothed = region.smooth(window_length=51, window='hanning') _ = smoothed.plot(colormap='magma') # %% [markdown] slideshow={"slide_type": "subslide"} # #### Baseline correction # %% slideshow={"slide_type": "fragment"} region = ds[:, 4000.0:2000.0] smoothed = region.smooth(window_length=51, window='hanning') blc = scp.BaselineCorrection(smoothed) basc = blc.compute([2000., 2300.], [3800., 3900.], method='multivariate', interpolation='pchip', npc=5) _ = basc.plot() # %% [markdown] slideshow={"slide_type": "subslide"} # ## IRIS processing # %% slideshow={"slide_type": "subslide"} ds = scp.read('irdata/CO@Mo_Al2O3.SPG')[:, 2250.:1950.] pressure = [0.00300, 0.00400, 0.00900, 0.01400, 0.02100, 0.02600, 0.03600, 0.05100, 0.09300, 0.15000, 0.20300, 0.30000, 0.40400, 0.50300, 0.60200, 0.70200, 0.80100, 0.90500, 1.00400] ds.y = scp.Coord(pressure, title='Pressure', units='torr') _ = ds.plot(colormap='magma') # %% slideshow={"slide_type": "subslide"} param = {'epsRange': [-8, -1, 50], 'lambdaRange': [-10, 1, 12], 'kernel': 'langmuir'} iris = scp.IRIS(ds, param, verbose=False) _ = iris.plotdistribution(-7, colormap='magma') <file_sep>/spectrochempy/units/units.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ The core interface to the Pint library """ __all__ = ['Unit', 'Quantity', 'ur', 'set_nmr_context', 'DimensionalityError'] from warnings import warn from pint import set_application_registry, UnitRegistry, DimensionalityError, formatting, Context # from pint.measurement import _Measurement as Measure from pint.unit import UnitsContainer, _Unit as Unit, UnitDefinition from pint.quantity import _Quantity as Quantity from pint.formatting import siunitx_format_unit from pint.converters import ScaleConverter # ====================================================================================================================== # Modify the pint behaviour # ====================================================================================================================== # TODO: better ways ?? _PRETTY_EXPONENTS = '⁰¹²³⁴⁵⁶⁷⁸⁹' # ---------------------------------------------------------------------------------------------------------------------- def _pretty_fmt_exponent(num): """Format an number into a pretty printed exponent using unicode. """ # work badly for decimals as superscript dot do not exist in unicode # (as far as we know) ret = '{0:n}'.format(num).replace('-', '⁻').replace('.', "\u22C5") for n in range(10): ret = ret.replace(str(n), _PRETTY_EXPONENTS[n]) return ret formats = {'P': { # Pretty format. 'as_ratio': False, # True in pint 'single_denominator': False, 'product_fmt': '·', 'division_fmt': '/', 'power_fmt': '{}{}', 'parentheses_fmt': '({})', 'exp_call': _pretty_fmt_exponent, }, 'L': { # spectrochempy Latex format. 'as_ratio': False, # True in pint 'single_denominator': True, 'product_fmt': r' \cdot ', 'division_fmt': r'\frac[{}][{}]', 'power_fmt': '{}^[{}]', 'parentheses_fmt': r'\left({}\right)', }, 'H': { # spectrochempy HTML format. 'as_ratio': False, # True in pint 'single_denominator': False, 'product_fmt': r'.', 'division_fmt': r'{}/{}', 'power_fmt': '{}<sup>{}</sup>', 'parentheses_fmt': r'{}', }, 'K': { # spectrochempy Compact format. 'as_ratio': False, 'single_denominator': False, 'product_fmt': '.', 'division_fmt': '/', 'power_fmt': '{}^{}', 'parentheses_fmt': r'({})', }, } formatting._FORMATS.update(formats) formatting._KNOWN_TYPES = frozenset(list(formatting._FORMATS.keys()) + ['~']) def _repr_html_(cls): p = cls.__format__('~H') # attempt to solve a display problem in notebook (recent version of pint # have a strange way to handle HTML. For me it doen't work p = p.replace(r'\[', '').replace(r'\]', '').replace(r'\ ', ' ') return p setattr(Quantity, '_repr_html_', _repr_html_) setattr(Quantity, '_repr_latex_', lambda cls: "$" + cls.__format__('~L') + "$") # TODO: work on this latex format setattr(Unit, 'scaling', property(lambda u: u._REGISTRY.Quantity(1., u._units).to_base_units().magnitude)) # ---------------------------------------------------------------------------------------------------------------------- def __format__(self, spec): # modify Pint unit __format__ spec = spec or self.default_format # special cases if "Lx" in spec: # the LaTeX siunitx code return r"\si[]{%s}" % siunitx_format_unit(self) if '~' in spec or 'K' in spec or 'T' in spec or 'L' in spec: # spectrochempy modified if self.dimensionless and 'absorbance' not in self._units: if self._units == 'ppm': units = UnitsContainer({'ppm': 1}) elif self._units in ['percent', 'transmittance']: units = UnitsContainer({'%': 1}) elif self._units == 'weight_percent': units = UnitsContainer({'wt.%': 1}) elif self._units == 'radian': units = UnitsContainer({'rad': 1}) elif self._units == 'degree': units = UnitsContainer({'deg': 1}) # elif self._units == 'absorbance': # units = UnitsContainer({'a.u.': 1}) elif abs(self.scaling - 1.) < 1.e-10: units = UnitsContainer({'': 1}) else: units = UnitsContainer({'scaled-dimensionless (%.2g)' % self.scaling: 1}) else: units = UnitsContainer( dict((self._REGISTRY._get_symbol(key), value) for key, value in list(self._units.items()))) spec = spec.replace('~', '') else: units = self._units if "H" in spec: # HTML / Jupyter Notebook ( return r"\[" + format(units, spec).replace(" ", r"\ ") + r"\]" return '%s' % (format(units, spec)) setattr(Unit, '__format__', __format__) if globals().get('U_', None) is None: # filename = resource_filename(PKG, 'spectrochempy.txt') U_ = UnitRegistry(on_redefinition='ignore') # filename) U_.define('__wrapped__ = 1') # <- hack to avoid an error with pytest (doctest activated) U_.define('@alias point = count') U_.define('transmittance = 1. / 100.') U_.define('absolute_transmittance = 1.') U_.define('absorbance = 1. = a.u.') U_.define('Kubelka_Munk = 1. = K.M.') U_.define('ppm = 1. = ppm') U_.define(UnitDefinition('percent', 'pct', (), ScaleConverter(1 / 100.0))) U_.define(UnitDefinition('weight_percent', 'wt_pct', (), ScaleConverter(1 / 100.0))) U_.default_format = '' # .2fK' Q_ = U_.Quantity Q_.default_format = '' # .2fK' set_application_registry(U_) del UnitRegistry # to avoid importing it else: warn('Unit registry was already set up. Bypassed the new loading') U_.enable_contexts('spectroscopy', 'boltzmann', 'chemistry') # Context for NMR # ---------------------------------------------------------------------------------------------------------------------- def set_nmr_context(larmor): """ Set a NMR context relative to the given Larmor frequency Parameters ---------- larmor : Quantity or float The Larmor frequency of the current nucleus. If it is not a quantity it is assumed to be given in MHz Examples -------- First we set the NMR context, >>> set_nmr_context(104.3 * U_.MHz) then, we can use the context as follow : >>> fhz = 10000 * U_.Hz >>> with U_.context('nmr'): ... fppm = fhz.to('ppm') >>> print("{:~.3f}".format(fppm)) 95.877 ppm or in the opposite direction >>> with U_.context('nmr'): ... fhz = fppm.to('kHz') >>> print("{:~.3f}".format(fhz)) 10.000 kHz Now we update the context : >>> with U_.context('nmr', larmor=100. * U_.MHz): ... fppm = fhz.to('ppm') >>> print("{:~.3f}".format(fppm)) 100.000 ppm >>> set_nmr_context(75 * U_.MHz) >>> fhz = 10000 * U_.Hz >>> with U_.context('nmr'): ... fppm = fhz.to('ppm') >>> print("{:~.3f}".format(fppm)) 133.333 ppm """ if not isinstance(larmor, U_.Quantity): larmor = larmor * U_.MHz if 'nmr' not in list(U_._contexts.keys()): c = Context('nmr', defaults={'larmor': larmor}) c.add_transformation('[]', '[frequency]', lambda U_, x, **kwargs: x * kwargs.get('larmor') / 1.e6) c.add_transformation('[frequency]', '[]', lambda U_, x, **kwargs: x * 1.e6 / kwargs.get('larmor')) U_.add_context(c) else: c = U_._contexts['nmr'] c.defaults['larmor'] = larmor # set alias for units and uncertainties # ---------------------------------------------------------------------------------------------------------------------- ur = U_ Quantity = Q_ # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/tests/test_plotters/test_styles.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import pytest from spectrochempy import preferences, plt, os prefs = preferences styles = ['poster', 'talk', 'scpy', 'sans', 'serif', 'grayscale', 'notebook', 'paper'] @pytest.mark.parametrize('style', styles) def test_styles(style): try: plt.style.use(style) except OSError: plt.style.use(os.path.join(prefs.stylesheets, style + '.mplstyle')) <file_sep>/spectrochempy/core/dataset/coordrange.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements the class |CoordRange|. """ __all__ = __slots__ = ['trim_ranges'] from traitlets import HasTraits, List, Bool from spectrochempy.utils.traitlets import Range # ====================================================================================================================== # _CoordRange # ====================================================================================================================== class _CoordRange(HasTraits): # TODO: May use also units ??? ranges = List(Range()) reversed = Bool() # .................................................................................................................. def __init__(self, *ranges, reversed=False): self.reversed = reversed if len(ranges) == 0: # first case: no argument passed, returns an empty range self.ranges = [] elif len(ranges) == 2 and all(isinstance(elt, (int, float)) for elt in ranges): # second case: a pair of scalars has been passed # using the Interval class, we have autochecking of the interval # validity self.ranges = [list(map(float, ranges))] else: # third case: a set of pairs of scalars has been passed self._clean_ranges(ranges) if self.ranges: self._clean_ranges(self.ranges) # ------------------------------------------------------------------------------------------------------------------ # private methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def _clean_ranges(self, ranges): """Sort and merge overlapping ranges It works as follows:: 1. orders each interval 2. sorts intervals 3. merge overlapping intervals 4. reverse the orders if required """ # transforms each pairs into valid interval # should generate an error if a pair is not valid ranges = [list(range) for range in ranges] # order the ranges ranges = sorted(ranges, key=lambda r: min(r[0], r[1])) cleaned_ranges = [ranges[0]] for range in ranges[1:]: if range[0] <= cleaned_ranges[-1][1]: if range[1] >= cleaned_ranges[-1][1]: cleaned_ranges[-1][1] = range[1] else: cleaned_ranges.append(range) self.ranges = cleaned_ranges if self.reversed: for range in self.ranges: range.reverse() self.ranges.reverse() def trim_ranges(*ranges, reversed=False): """ Set of ordered, non intersecting intervals. An ordered set of ranges is contructed from the inputs and returned. *e.g.,* [[a, b], [c, d]] with a < b < c < d or a > b > c > d. Parameters ----------- *ranges : iterable An interval or a set of intervals. set of intervals. If none is given, the range will be a set of an empty interval [[]]. The interval limits do not need to be ordered, and the intervals do not need to be distincts. reversed : bool, optional The intervals are ranked by decreasing order if True or increasing order if False. Returns ------- ordered list of ranges. Examples -------- >>> import spectrochempy as scp >>> scp.trim_ranges([1, 4], [7, 5], [6, 10]) [[1, 4], [5, 10]] """ return _CoordRange(*ranges, reversed=reversed).ranges # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/spectrochempy/core/dataset/meta.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, # Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in # the root directory = # ====================================================================================================================== """ This module mainly contains the definition of a Meta class object Such object is particularly used in `SpectrochemPy` by the |NDDataset| object to store metadata. Like a regular dictionary, the elements can be accessed by key, but also by attributes, *e.g.* ``a = meta['key']`` give the same results as ``a = meta.key``. """ # from traitlets import HasTraits, Dict, Bool, default # import sys import copy import json import numpy as np # constants # ---------------------------------------------------------------------------------------------------------------------- __all__ = ['Meta'] # ====================================================================================================================== # Class Meta # ====================================================================================================================== class Meta(object): # HasTraits): """A dictionary to store metadata. The metadata are accessible by item or by attributes, and the dictionary can be made read-only if necessary. Examples -------- First we initialise a metadata object >>> m = Meta() then, metadata can be set by attribute (or by key like in a regular dictionary), and further accessed by attribute (or key): >>> m.chaine = "a string" >>> m["entier"] = 123456 >>> print(m.entier) 123456 >>> print(m.chaine) a string One can make the dictionary read-only >>> m.readonly = True >>> m.chaine = "a modified string" Traceback (most recent call last): ... ValueError : 'the metadata `chaine` is read only' >>> print(m.chaine) a string .. rubric:: Methods """ # ------------------------------------------------------------------------------------------------------------------ # private attributes # ------------------------------------------------------------------------------------------------------------------ _data = {} # ------------------------------------------------------------------------------------------------------------------ # public attributes # ------------------------------------------------------------------------------------------------------------------ readonly = False # Bool(False) parent = None name = None # ------------------------------------------------------------------------------------------------------------------ # special methods # ------------------------------------------------------------------------------------------------------------------ def __init__(self, **data): """ Parameters ---------- **data : keywords The dictionary can be already inited with some keywords. """ self.parent = data.pop('parent', None) self.name = data.pop('name', None) self._data = data def __dir__(self): return ['data', 'readonly', 'parent', 'name'] def __setattr__(self, key, value): if key not in ['readonly', 'parent', 'name', '_data', '_trait_values', '_trait_notifiers', '_trait_validators', '_cross_validation_lock', '__wrapped__']: self[key] = value else: self.__dict__[key] = value # to avoid a recursive call # we can not use # self._readonly = value! def __getattr__(self, key): if key.startswith('_ipython') or key.startswith('_repr'): raise AttributeError if key in ['__wrapped__']: return False return self[key] def __setitem__(self, key, value): if key in self.__dir__() or key.startswith('_'): raise KeyError('`{}` can not be used as a metadata key'.format(key)) elif not self.readonly: self._data.update({key: value}) else: raise ValueError('the metadata `{}` is read only'.format(key)) def __getitem__(self, key): return self._data.get(key, None) def __len__(self): return len(self._data) def __copy__(self): ret = self.__class__() ret.update(copy.deepcopy(self._data)) ret.readonly = self.readonly ret.parent = self.parent ret.name = self.name return ret def __deepcopy__(self, memo=None): return self.__copy__() def __eq__(self, other): m1 = self._data if hasattr(other, "_data"): m2 = other._data elif isinstance(other, dict): m2 = other else: return False eq = True for k, v in m1.items(): if isinstance(v, list): for i, ve in enumerate(v): eq &= np.all(ve == m2[k][i]) else: eq &= np.all(v == m2[k]) return eq def __ne__(self, other): return not self.__eq__(other) def __iter__(self): for item in sorted(self._data.keys()): yield item def __str__(self): return str(self._data) def _repr_html_(self): s = json.dumps(self._data, sort_keys=True, indent=4) return s.replace('\n', '<br/>').replace(' ', '&nbsp;') # ------------------------------------------------------------------------------------------------------------------ # public methods # ------------------------------------------------------------------------------------------------------------------ def implements(self, name=None): if name is None: return 'Meta' else: return name == 'Meta' def to_dict(self): """Transform a metadata dictionary to a regular one. Returns ------- dict A regular dictionary """ return self._data def get(self, key, default=None): """ Parameters ---------- :param key: :return: """ return self._data.get(key, default) def update(self, d): """Feed a metadata dictionary with the content of an another dictionary Parameters ---------- d : dict-like object Any dict-like object can be used, such as `dict`, traits `Dict` or another `Meta` object. """ if isinstance(d, Meta) or hasattr(d, '_data'): d = d.to_dict() if d: self._data.update(d) def copy(self): """ Return a disconnected copy of self. Returns ------- meta A disconnected meta object identical to the original object """ return self.__copy__() def keys(self): """A list of metadata contained in the object. Returns ------- list A sorted key's list Examples -------- >>> m = Meta() >>> m.td = 10 >>> m.si = 20 >>> print(m.keys()) ['si', 'td'] Notes ----- Alternatively, it is possible to iter directly on the Meta object >>> m = Meta() >>> m.td = 10 >>> m.si = 20 >>> for key in m : ... print(key) si td """ return [key for key in self] def items(self): """A list of metadata items contained in the object. Returns ------- list An item list sorted by key Examples -------- >>> m = Meta() >>> m.td = 10 >>> m.si = 20 >>> print(m.items()) [('si', 20), ('td', 10)] """ return [(key, self[key]) for key in self] def swap(self, dim1, dim2, inplace=True): """ Permute meta corresponding to distinct axis to reflect swapping on the corresponding data array Parameters ---------- dim1 dim2 inplace Returns ------- """ newmeta = self.copy() newmeta.readonly = False newmeta.parent = None newmeta.name = None for key in self: if isinstance(self[key], list) and len(self[key]) > 1: # print (newmeta[key], len(self[key])) X = newmeta[key] X[dim1], X[dim2] = X[dim2], X[dim1] else: newmeta[key] = self[key] newmeta.readonly = self.readonly newmeta.parent = self.parent newmeta.name = self.name if not inplace: return newmeta else: self._data = newmeta._data def permute(self, *dims, inplace=True): """ Parameters ---------- dims inplace Returns ------- """ newmeta = self.copy() newmeta.readonly = False newmeta.parent = None newmeta.name = None for key in self: if isinstance(self[key], list) and len(self[key]) > 1: newmeta[key] = type(self[key])() for dim in dims: newmeta[key].append(self[key][dim]) else: newmeta[key] = self[key] newmeta.readonly = self.readonly newmeta.parent = self.parent newmeta.name = self.name if not inplace: return newmeta else: self._data = newmeta._data @property def data(self): return self._data <file_sep>/tests/test_readers_writers/test_read_carroucell.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os import pytest from spectrochempy.core import info_ from spectrochempy.core.dataset.nddataset import NDDataset # uncomment the next line to test it manually @pytest.mark.skip('interactive so cannot be used with full testing') def test_read_carroucell_without_dirname(): NDDataset.read_carroucell() def test_read_carroucell_with_dirname(): A = NDDataset.read_carroucell(os.path.join('irdata', 'carroucell_samp')) for x in A: info_(' ' + x.name + ': ' + str(x.shape)) assert len(A) == 11 assert A[3].shape == (6, 11098) <file_sep>/docs/userguide/analysis/mcr_als.py # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # MCR ALS # %% import spectrochempy as scp # %% [markdown] # ## Introduction # # MCR-ALS (standing for Multivariate Curve Resolution - Alternating Least Squares) is a popular method for resolving a # set (or several sets) of spectra $X$ of an evolving mixture (or a set of mixtures) into the spectra $S^t$ of 'pure' # species and their concentration profiles $C$. In term of matrix equation: # $$ X = C S^t + E $$ # The ALS algorithm allows applying soft or hard constraints (e.g. non negativity, unimodality, equality to a given # profile) to the spectra or concentration profiles of pure species. This property makes MCR-ALS an extremely flexible # and powerful method. Its current implementation in Scpy is limited to soft constraints but is exected to cover more # advanced features in further releases. # # In, this tutorial the application of MCS-ALS as implemented in Scpy to a 'classical' dataset form the literature is # presented. # # ## The (minimal) dataset # # In this example, we perform the MCR ALS optimization of a dataset corresponding to a HPLC-DAD run, from Jaumot et al. # Chemolab, 76 (2005), # pp. 101-110 and Jaumot et al. Chemolab, 140 (2015) pp. 1-12. This dataset (and others) can be loaded from the # "Multivariate Curve Resolution Homepage" # at https://mcrals.wordpress.com/download/example-data-sets. For the user convenience, this dataset is present in the # 'datadir' of spectrochempy in 'als2004dataset.MAT' and can be read as follows in Scpy: # %% A = scp.read_matlab("matlabdata/als2004dataset.MAT") # %% [markdown] # The .mat file contains 6 matrices which are thus returned in A as a list of 6 NDdatasets. We print the names and # dimensions of these datasets: # %% for a in A: print(a.name + ': ' + str(a.shape)) # %% [markdown] # In this tutorial, we are first interested in the dataset named ('m1') that contains a singleHPLC-DAD run(s). # As usual, the rows correspond to the 'time axis' of the HPLC run(s), and the columns to the 'wavelength' axis # of the UV spectra. # # Let's name it 'X' (as in the matrix equation above), display its content and plot it: # %% X = A[0] X # %% _ = X.plot() # %% [markdown] # The original dataset is the 'm1' matrix and does not contain information as to the actual elution time, wavelength, # and data units. Hence the resulting NDDataset has no coordinates and on the plot, only the matrix line and row # indexes are indicated. For the clarity of the tutorial, we add: (i) a proper title to the data, (ii) # the default coordinates (index) do the NDDataset and (iii) a proper name for these coordinates: # %% X.title = 'absorbance' X.set_coordset(None, None) X.set_coordtitles(y='elution time', x='wavelength') X # %% [markdown] # From now on, these names will be taken into account by Scpy in the plottings as well as in the analysis treatments # (PCA, EFA, MCR-ALs, ...). For instance to plot X as a surface: # %% surf = X.plot_surface(colorbar=True, linewidth=.2, ccount=100, figsize=(10, 5)) # %% [markdown] # ## Initial guess and MCR ALS optimization # # The ALS optimization of the MCR equation above requires the input of a guess for either the concentration matrix # $C_0$ or the spectra matrix $S^t_0$. Given the data matrix $X$, the lacking initial matrix ($S^t_0$ or $C_0$, # respectively) is computed by: # $$ S^t_0 = \left( C_0^tC_0 \right)^{-1} C_0^t X $$ # # or # # $$ C_0 = X {S^t_0}^t \left( S_0^t {S_0^t}^t \right)^{-1} $$ # # ### Case of initial spectral profiles # The matrix spure provided in the initial dataset is a guess for the spectral profiles. Let's name it 'St0', # and plot it: # %% St0 = A[1] _ = St0.plot() # %% [markdown] # Note that, again, no information has been given as to the ordinate and abscissa data. We could add them as previously # but this is not very important. The key point is that the 'wavelength' dimension is compatible with the data 'X', # which is indeed the case (both have a legth of 95). If it was not, an error would be generated in the following. # # #### ALS Optimization # With this guess 'St0' and the dataset 'X' we can create a MCRALS object. At this point of the tutorial, we will use # all the default parameters except for the 'verbose' option which is swiched on to have a summary # of the ALS iterations: # %% mcr = scp.MCRALS(X, St0, verbose='True') # %% [markdown] # The optimization has converged within few iterations. The figures reported for each iteration are defined as follows: # # - 'Error/PCA' is the standard deviation of the residuals with respect to data reconstructed by a PCA with as many # components as pure species (4 in this example), # # - 'Error/exp': is the standard deviation of the residuals with respect to the experimental data X, # # - '%change': is the percent change of 'Error/exp' between 2 iterations # # The default is to stop when this %change between two iteration is negative (so that the solution is improving), # but with an absolute value lower than 0.1% (so that the improvement is considered negligible). This parameter - # as well as several other parameters affecting the ALS optimization can be changed by the setting the 'tol' value # in a python dictionary using the key 'tol'. For instance: # %% mcr = scp.MCRALS(X, St0, param={'tol': 0.01}, verbose='True') # %% [markdown] # As could be expected more iterations have been necessary to reach this stricter convergence criterion. The other # convergence criterion that can be fixed by the user is 'maxdiv', the maximum number of successive diverging # iterations. It is set to 5 by default and allows for stopping the ALS algorithm when it is no converging. # If for instance the 'tol' is set very low, the optimization will be stopped when either the maximum number # of iterations is reached (maxit, 50 by default) or when no improvement is during 5 successive iterations (maxdiv). # %% mcr = scp.MCRALS(X, St0, param={'tol': 0.001}, verbose='True') # %% [markdown] # Now if 'maxit' is set to 10: # %% mcr = scp.MCRALS(X, St0, param={'tol': 0.001, 'maxit': 10}, verbose='True') # %% [markdown] # #### Solutions # # The solutions of the MCR ALS optimization are the optimized concentration and pure spectra matrices. They can be # obtained by the MCRALS.transform() method. let's remake an MCRALS object with the default settings, # ('tol' = 0.1 and verbose = False), and get C and St. # %% mcr1 = scp.MCRALS(X, St0) # %% [markdown] # As the dimensions of C are such that the rows direction (C.y) corresponds to the elution time and the columns # direction (C.x) correspond to the four pure species, it is necessary to transpose it before plotting in order # to plot the concentration vs. the elution time. # %% _ = mcr1.C.T.plot() # %% [markdown] # On the other hand, the spectra of the pure species can be plot directly: # %% _ = mcr1.St.plot() # %% [markdown] # #### A basic illustration of the rotational ambiguity # We have thus obtained the elution profiles of the four pure species. Note that the 'concentration' values are very # low. This results from the fact that the absorbance values in X are on the order of 0-1 while the absorbances of # the initial pure spectra are of the order of 10^4. As can be seen above, the absorbance of the final spectra is of # the same order of magnitude. # # It is possible to normalize the intensity of the spectral profiles by setting the 'normSpec' parameter to True. # With this option, the specra are normalized such that their euclidian norm is 1. The other normalization option is # normspec = 'max', whereby the maximum intyensity of tyhe spectra is 1. Let's look at the effect of # both normalizations: # %% mcr2 = scp.MCRALS(X, St0, param={'normSpec': 'euclid'}) mcr3 = scp.MCRALS(X, St0, param={'normSpec': 'max'}) _ = mcr1.St.plot() _ = mcr2.St.plot() _ = mcr3.St.plot() # %% _ = mcr1.C.T.plot() _ = mcr2.C.T.plot() _ = mcr3.C.T.plot() # %% [markdown] # It is clear that the normalization affects the relative intensity of the spectra and of the concentration. # This is a basic example of the well known rotational ambiguity of the MCS ALS solutions. # %% [markdown] # ### Guessing the concentration profile with PCA + EFA # # Generally, in MCR ALS, the initial guess cannot be obtained independently of the experimental data 'x'. # In such a case, one has to rely on 'X' to obtained (i) the number of pure species and (ii) their initial # concentrations or spectral profiles. The number of of pure species can be assessed by carrying out a PCA on the # data while the concentrations or spectral profiles can be estimated using procedures such EFA of SIMPLISMA. # The following will illustrate the use of PCA followed by EFA # # #### Use of PCA to assess the number of pure species # # Let's first analyse our dataset using PCA and plot a screeplot: # %% pca = scp.PCA(X) pca.printev(n_pc=10) _ = pca.screeplot(n_pc=8) # %% [markdown] # The number of significant PC's is clearly larger or equal to 2. It is, however, difficult tto determine whether # it should be set to 3 or 4... Let's look at the score and loading matrices: # # %% S, LT = pca.reduce(n_pc=8) _ = S.T.plot() _ = LT.plot() # %% [markdown] # Examination of the scores and loadings indicate that the 4th component has structured, non random scores and loadings. # Hence we will fix the number of pure species to 4. # # NB: The PCA.transform() can also be used with n_pc='auto' to determine automatically the number of components using # the method of <NAME> (Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604). This type of methods, # however, often lead to too many PC's for the chemist because they recover all contributions to the data variance: # chemical AND non-chemical, thus including non-gaussian noise, baseline changes, background absorption... # # 32 in the present case: # %% S3, LT3 = pca.reduce(n_pc='auto') S3.shape # %% [markdown] # #### Determination of initial concentrations using EFA # # Once the number of components has been determined, the initial concentration matrix is obtained very easily using EFA: # # %% efa = scp.EFA(X) C0 = efa.get_conc(n_pc=4) _ = C0.T.plot() # %% [markdown] # The MCR ALS can then be launched using this new guess: # %% mcr4 = scp.MCRALS(X, guess=C0, param={'maxit': 100, 'normSpec': 'euclid'}, verbose=True) # %% _ = mcr4.C.T.plot() _ = mcr4.St.plot() # %% [markdown] # ## Augmented datasets # %% [markdown] # The 'MATRIX' dataset is a columnwise augmented dataset consisting into 5 successive runs: # %% A[3] # %% [markdown] # Let's plot it as a map, and as a surface: # %% X2 = A[3] X2.title = 'absorbance' X2.set_coordset(None, None) X2.set_coordtitles(y='elution time', x='wavelength') surf = X2.plot_surface(colorbar=True, linewidth=.2, ccount=100, figsize=(10, 5)) _ = X2.plot(method='map') # %% mcr5 = scp.MCRALS(X2, guess=St0, param={'unimodConc': [0] * 4}, verbose=True) # %% _ = mcr5.C.T.plot() # %% _ = mcr5.St.plot() # %% [markdown] # [To be continued...] <file_sep>/docs/userguide/reference/faq.rst .. _faq: Frequently asked questions (FAQ) ================================ .. contents:: Table of Contents :depth: 2 General ------- Where are the preference's files saved? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Typically, the main application preference file is saved in a hidden directory located in your home user directory: ``$HOME/.spectrochempy/config`` under the name ``spectrochempy_cfg.py`` But if the `SCP_CONFIG_HOME` environment variable is set and the `$SCP_CONFIG_HOME/spectrochempy` directory exists, it will be that directory. In principle you should not need to access files in this directory, but if you wants to do it, you can use one of these solutions : On Mac OSX system you access to this file by typing in the terminal: .. sourcecode:: bash $ cd ~/.spectrochempy/config $ open spectrochempy_cfg.py On Linux system, the second command can be replaced by: .. sourcecode:: bash $ nano spectrochempy_cfg.py or whatever you prefer to read and edit a text file. Uncomment the line where you want to make a change, for instance change the following line if you want to modify the default directory where the data are saved: .. sourcecode:: python #c.GeneralPreferences.datadir = '' to .. sourcecode:: python c.GeneralPreferences.datadir = 'mydatadir/irdata' Code usage ---------- How to get the index from a coordinate? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The index of a wavelength (or any other type of coord) can be obtained by the `loc2index()` method which will return the index corresponding to the closest value: .. sourcecode:: python >>> X.x.loc2index(2000.0) 2074 The exact value of the coordinate can the be obtained by: .. sourcecode:: python >>> X.x[2074].values 1999.53 How to specify a plot with abscissa in ascending or descending order? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default NDDataset with wavenumbers (infrared) or ppm units (NMR) are plotted with coords in descending order. This can be prevented by passing `reverse=False`: .. sourcecode:: python X.plot(reverse=False) Conversely, other plots use by default the ascending order, but this can also be changed: .. sourcecode:: python X.plot(reverse=True) <file_sep>/spectrochempy/core/analysis/nnmf.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implement the NNMF (Non Negative Matrix Factorization) class """ # TODO: create tests __all__ = ['NNMF'] __dataset_methods__ = [] import numpy as np from numpy.linalg import norm from time import time from sys import stdout from traitlets import HasTraits from spectrochempy.core import info_ class NNMF(HasTraits): """ Performs a Non Negative Matrix Factorization of a |NDDataset|. Algorithm based on : <NAME>. Projected gradient methods for non-negative matrix factorization. Neural Computation, 19(2007), 2756-2779. If you find this tool useful, please cite the above work. Author : <NAME>, National Taiwan University Copyright (c) 2005-2008 <NAME> All rights reserved. Python/numpy translation : Anthony Di Franco ; """ def __init__(self, X, Ci, Sti, **kwargs): """ Parameters ========== self.C, self.St = nnmf(X, Ci, Sti,**kwargs) C,St : output solution Ci,Sti : initial solution Other Parameters ================ tol : float, optional Tolerance for a relative stopping condition. maxtime : float, optional Time limit. maxit : float Limit for iterations """ super().__init__() tol = kwargs.get('tol', 0.1) maxtime = kwargs.get('maxtime', 60) maxit = kwargs.get('maxit', 100) self.C = Ci.copy() self.C.name = 'Conc profile optimized by nnmf' self.C.history = '' self.St = Sti.copy() self.St.name = 'Spectral profile optimized by nnmf' self.St.history = '' self.C.data, self.St.data = self.nmf(X.data, Ci.data, Sti.data, tol, maxtime, maxit) @staticmethod def nmf(V, Winit, Hinit, tol, timelimit, maxiter): """ (W,H) = nmf(V,Winit,Hinit,tol,timelimit,maxiter) W,H : output solution Winit,Hinit : initial solution tol : tolerance for a relative stopping condition timelimit, maxiter : limit of time and iterations """ def nlssubprob(V, W, Hinit, tol, maxiter): """ H, grad : output solution and gradient iter : #iterations used V, W : constant matrices Hinit : initial solution tol : stopping tolerance maxiter : limit of iterations """ H = Hinit WtV = np.dot(W.T, V) WtW = np.dot(W.T, W) alpha = 1 beta = 0.1 for n_iter in range(1, maxiter + 1): grad = np.dot(WtW, H) - WtV if norm(grad * np.logical_or(grad < 0, H > 0)) < tol: break Hp = H # search step size for inner_iter in range(20): # gradient step Hn = H - alpha * grad # gradient step Hn *= Hn > 0 d = Hn - H gradd = np.dot(grad.ravel(), d.ravel()) dQd = np.dot(np.dot(WtW, d).ravel(), d.ravel()) suff_decr = 0.99 * gradd + 0.5 * dQd < 0 if inner_iter == 0: decr_alpha = not suff_decr Hp = H if decr_alpha: if suff_decr: H = Hn break else: alpha = alpha * beta else: if not suff_decr or (Hp == Hn).all(): H = Hp break else: alpha = alpha / beta Hp = Hn if n_iter == maxiter: info_('Max iter in nlssubprob') return H, grad, n_iter W = Winit H = Hinit initt = time() gradW = np.dot(W, np.dot(H, H.T)) - np.dot(V, H.T) gradH = np.dot(np.dot(W.T, W), H) - np.dot(W.T, V) initgrad = norm(np.r_[gradW, gradH.T]) info_('Init gradient norm {:.3f}'.format(initgrad)) tolW = max(0.001, tol) * initgrad tolH = tolW for myiter in range(1, maxiter): # stopping condition projnorm = norm(np.r_[gradW[np.logical_or(gradW < 0, W > 0)], gradH[np.logical_or(gradH < 0, H > 0)]]) if projnorm < tol * initgrad or time() - initt > timelimit: break (W, gradW, iterW) = nlssubprob(V.T, H.T, W.T, tolW, 10000) W = W.T gradW = gradW.T if iterW == 1: tolW = 0.1 * tolW (H, gradH, iterH) = nlssubprob(V, W, H, tolH, 10000) if iterH == 1: tolH = 0.1 * tolH if myiter % 10 == 0: stdout.write('.') info_( '\nIter = {} Final proj-grad norm {:.3f}'.format(myiter, projnorm)) return W, H <file_sep>/spectrochempy/gui/assets/redraw.js function redraw() { var figs = document.getElementsByClassName("js-plotly-plot") for (var i = 0; i < figs.length; i++) { Plotly.redraw(figs[i]) } } setTimeout(function () { redraw(); }, 1000); <file_sep>/docs/userguide/processing/apodization.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Apodization # %% import spectrochempy as scp from spectrochempy.units import ur # %% [markdown] # ## Introduction # # As an example, apodization is a transformation particularly useful for preprocessing NMR time domain data before # Fourier transformation. It generally help for signal to noise improvement. # %% # reead an experimental spectra path = scp.pathclean('nmrdata/bruker/tests/nmr/topspin_1d') # the method pathclean allow to write pth in linux or window style indifferently dataset = scp.NDDataset.read_topspin(path, expno=1, remove_digital_filter=True) dataset = dataset / dataset.max() # normalization # store original data nd = dataset.copy() # show data nd # %% [markdown] # ### Plot of the Real and Imaginary original data # %% _ = nd.plot(xlim=(0., 15000.)) _ = nd.plot(imag=True, data_only=True, clear=False, color='r') # %% [markdown] # ### Exponential multiplication # %% _ = nd.plot(xlim=(0., 15000.)) _ = nd.em(lb=300. * ur.Hz) _ = nd.plot(data_only=True, clear=False, color='g') # %% [markdown] # **Warning:** processing function are most of the time applied inplace. Use `inplace=False` option to avoid this if # necessary # %% nd = dataset.copy() # to go back to the original data _ = nd.plot(xlim=(0., 5000.)) ndlb = nd.em(lb=300. * ur.Hz, inplace=False) # ndlb contain the processed data _ = nd.plot(data_only=True, clear=False, color='g') # nd dataset remain unchanged _ = ndlb.plot(data_only=True, clear=False, color='b') # %% [markdown] # Of course, imaginary data are also transformed at the same time # %% _ = nd.plot(imag=True, xlim=(0, 5000), color='r') _ = ndlb.plot(imag=True, data_only=True, clear=False, color='b') # %% [markdown] # If we want to display the apodization function, we can use the `retapod=True` parameter. # %% nd = dataset.copy() _ = nd.plot(xlim=(0., 5000.)) ndlb, apod = nd.em(lb=300. * ur.Hz, inplace=False, retapod=True) # ndlb contain the processed data and apod the # apodization function _ = ndlb.plot(data_only=True, clear=False, color='b') _ = apod.plot(data_only=True, clear=False, color='m', linestyle='--') # %% [markdown] # #### Shifted apodization # %% nd = dataset.copy() _ = nd.plot(xlim=(0., 5000.)) ndlb, apod = nd.em(lb=300. * ur.Hz, shifted=1000 * ur.us, inplace=False, retapod=True) # ndlb contain the processed data and apod the apodization function _ = ndlb.plot(data_only=True, clear=False, color='b') _ = apod.plot(data_only=True, clear=False, color='m', linestyle='--') # %% [markdown] # ### Other apodization functions # %% [markdown] # #### Gaussian-Lorentzian appodization # %% nd = dataset.copy() lb = 10. gb = 200. ndlg, apod = nd.gm(lb=lb, gb=gb, inplace=False, retapod=True) _ = nd.plot(xlim=(0., 5000.)) _ = ndlg.plot(data_only=True, clear=False, color='b') _ = apod.plot(data_only=True, clear=False, color='m', linestyle='--') # %% [markdown] # #### Shifted Gaussian-Lorentzian apodization # %% nd = dataset.copy() lb = 10. gb = 200. ndlg, apod = nd.gm(lb=lb, gb=gb, shifted=2000 * ur.us, inplace=False, retapod=True) _ = nd.plot(xlim=(0., 5000.)) _ = ndlg.plot(data_only=True, clear=False, color='b') _ = apod.plot(data_only=True, clear=False, color='m', linestyle='--') # %% [markdown] # #### Apodization using sine window multiplication # # The`sp` apodization is by default performed on the last dimension. # # Functional form of apodization window (cfBruker TOPSPIN manual): $sp(t) = \sin(\frac{(\pi - \phi) t }{\text{aq}} + # \phi)^{pow}$ # # where # * $0 < t < \text{aq}$ and $\phi = \pi ⁄ \text{sbb}$ when $\text{ssb} \ge 2$ # # or # * $\phi = 0$ when $\text{ssb} < 2$ # # $\text{aq}$ is an acquisition status parameter and $\text{ssb}$ is a processing parameter (see below) and $\text{ # pow}$ is an exponent equal to 1 for a sine bell window or 2 for a squared sine bell window. # # The $\text{ssb}$ parameter mimics the behaviour of the `SSB` parameter on bruker TOPSPIN software: # * Typical values are 1 for a pure sine function and 2 for a pure cosine function. # * Values greater than 2 give a mixed sine/cosine function. Note that all values smaller than 2, for example 0, # have the same effect as $\text{ssb}=1$, namely a pure sine function. # # **Shortcuts**: # * `sine` is strictly a alias of `sp` # * `sinm` is equivalent to `sp` with $\text{pow}=1$ # * `qsin` is equivalent to `sp` with $\text{pow}=2$ # # Below are several examples of `sinm` and `qsin` apodization functions. # %% nd = dataset.copy() _ = nd.plot() new, curve = nd.qsin(ssb=3, retapod=True) _ = curve.plot(color='r', clear=False) _ = new.plot(xlim=(0, 25000), zlim=(-2, 2), data_only=True, color='r', clear=False) # %% nd = dataset.copy() _ = nd.plot() new, curve = nd.sinm(ssb=1, retapod=True) _ = curve.plot(color='b', clear=False) _ = new.plot(xlim=(0, 25000), zlim=(-2, 2), data_only=True, color='b', clear=False) # %% nd = dataset.copy() _ = nd.plot() new, curve = nd.sinm(ssb=3, retapod=True) _ = curve.plot(color='b', ls='--', clear=False) _ = new.plot(xlim=(0, 25000), zlim=(-2, 2), data_only=True, color='b', clear=False) # %% nd = dataset.copy() _ = nd.plot() new, curve = nd.qsin(ssb=2, retapod=True) _ = curve.plot(color='m', clear=False) _ = new.plot(xlim=(0, 25000), zlim=(-2, 2), data_only=True, color='m', clear=False) # %% nd = dataset.copy() _ = nd.plot() new, curve = nd.qsin(ssb=1, retapod=True) _ = curve.plot(color='g', clear=False) _ = new.plot(xlim=(0, 25000), zlim=(-2, 2), data_only=True, color='g', clear=False) <file_sep>/tests/test_analysis/test_svd.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Tests for the SVD class """ from numpy.testing import assert_allclose from spectrochempy.core.analysis.svd import SVD from spectrochempy.utils import MASKED # test svd # ----------- def test_svd(IR_dataset_2D): dataset = IR_dataset_2D svd = SVD(dataset) assert_allclose(svd.ev_ratio[0].data, 94.539, rtol=1e-5, atol=0.0001) # with masks dataset[:, 1240.0:920.0] = MASKED # do not forget to use float in slicing dataset[10:12] = MASKED dataset.plot_stack() svd = SVD(dataset) assert_allclose(svd.ev_ratio.data[0], 93.8, rtol=1e-4, atol=0.01) # with masks dataset[:, 1240.0:920.0] = MASKED # do not forget to use float in slicing dataset[10:12] = MASKED dataset.plot_stack() svd = SVD(dataset, full_matrices=True) assert_allclose(svd.ev_ratio.data[0], 93.8, rtol=1e-4, atol=0.01) <file_sep>/spectrochempy/core/readers/readtopspin.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Bruker file (single dimension FID or multidimensional SER) importers """ __all__ = ['read_topspin', 'read_bruker_nmr'] __dataset_methods__ = __all__ import re import numpy as np from quaternion import as_quat_array from nmrglue.fileio.bruker import read as read_fid, read_pdata, read_lowmem from spectrochempy.core import debug_ from spectrochempy.core.dataset.meta import Meta from spectrochempy.core.dataset.coord import LinearCoord from spectrochempy.units import ur from spectrochempy.utils.exceptions import deprecated from spectrochempy.core.readers.importer import Importer, importermethod # ====================================================================================================================== # Constants # ====================================================================================================================== FnMODE = ["undefined", "QF", "QSEQ", "TPPI", "STATES", "STATES-TPPI", "ECHO-ANTIECHO"] AQ_mod = ["QF", "QSIM", "QSEQ", "DQD"] nmr_valid_meta = [ # ACQU # ('amp', ''), ('aq_mod', ''), ('aqseq', ''), # ('aunm', ''), # ('autopos', ''), ('bf1', 'MHz'), ('bf2', 'MHz'), ('bf3', 'MHz'), ('bf4', 'MHz'), # ('bf5', 'MHz'), # ('bf6', 'MHz'), # ('bf7', 'MHz'), # ('bf8', 'MHz'), # ('bytorda', ''), # ('cfdgtyp', ''), # ('cfrgtyp', ''), # ('chemstr', ''), ('cnst', ''), # ('cpdprg', ''), # ('cpdprg1', ''), # ('cpdprg2', ''), # ('cpdprg3', ''), # ('cpdprg4', ''), # ('cpdprg5', ''), # ('cpdprg6', ''), # ('cpdprg7', ''), # ('cpdprg8', ''), # ('cpdprgb', ''), # ('cpdprgt', ''), ('d', 's'), ('date', ''), # ('dbl', ''), # ('dbp', ''), # ('dbp07', ''), # ('dbpnam0', ''), # ('dbpnam1', ''), # ('dbpnam2', ''), # ('dbpnam3', ''), # ('dbpnam4', ''), # ('dbpnam5', ''), # ('dbpnam6', ''), # ('dbpnam7', ''), # ('dbpoal', ''), # ('dbpoffs', ''), ('de', 'us'), # ('decbnuc', ''), # ('decim', ''), # ('decnuc', ''), # ('decstat', ''), ('digmod', ''), # ('digtyp', ''), # ('dl', ''), # ('dp', ''), # ('dp07', ''), # ('dpname0', ''), # ('dpname1', ''), # ('dpname2', ''), # ('dpname3', ''), # ('dpname4', ''), # ('dpname5', ''), # ('dpname6', ''), # ('dpname7', ''), # ('dpoal', ''), # ('dpoffs', ''), # ('dqdmode', ''), # ('dr', ''), # ('ds', ''), # ('dslist', ''), # ('dspfirm', ''), # ('dspfvs', ''), # ('dtypa', ''), # ('exp', ''), # ('f1list', ''), # ('f2list', ''), # ('f3list', ''), # ('fcuchan', ''), # ('file_size', ''), # ('fl1', ''), # ('fl2', ''), # ('fl3', ''), # ('fl4', ''), ('fnmode', ''), # ('fov', ''), # ('fq1list', ''), # ('fq2list', ''), # ('fq3list', ''), # ('fq4list', ''), # ('fq5list', ''), # ('fq6list', ''), # ('fq7list', ''), # ('fq8list', ''), # ('fs', ''), # ('ftlpgn', ''), # ('fw', ''), # ('gp031', ''), # ('gpnam0', ''), # ('gpnam1', ''), # ('gpnam10', ''), # ('gpnam11', ''), # ('gpnam12', ''), # ('gpnam13', ''), # ('gpnam14', ''), # ('gpnam15', ''), # ('gpnam16', ''), # ('gpnam17', ''), # ('gpnam18', ''), # ('gpnam19', ''), # ('gpnam2', ''), # ('gpnam20', ''), # ('gpnam21', ''), # ('gpnam22', ''), # ('gpnam23', ''), # ('gpnam24', ''), # ('gpnam25', ''), # ('gpnam26', ''), # ('gpnam27', ''), # ('gpnam28', ''), # ('gpnam29', ''), # ('gpnam3', ''), # ('gpnam30', ''), # ('gpnam31', ''), # ('gpnam4', ''), # ('gpnam5', ''), # ('gpnam6', ''), # ('gpnam7', ''), # ('gpnam8', ''), # ('gpnam9', ''), # ('gpx', ''), # ('gpy', ''), # ('gpz', ''), # ('grdprog', ''), # ('hdduty', ''), # ('hdrate', ''), # ('hgain', ''), # ('hl1', ''), # ('hl2', ''), # ('hl3', ''), # ('hl4', ''), # ('holder', ''), # ('hpmod', ''), # ('hpprgn', ''), # ('in', 's'), # ('inp', 's'), # ('instrum', ''), # ('l', ''), # ('lfilter', ''), # ('lgain', ''), # ('locked', ''), # ('lockfld', ''), # ('lockgn', ''), # ('lockpow', ''), # ('lockppm', ''), # ('locnuc', ''), # ('locphas', ''), # ('locshft', ''), # ('ltime', ''), ('masr', 'Hz'), # ('masrlst', ''), # ('nbl', ''), ('nc', ''), ('ns', ''), ('nuc1', ''), ('nuc2', ''), ('nuc3', ''), ('nuc4', ''), # ('nuc5', ''), # ('nuc6', ''), # ('nuc7', ''), # ('nuc8', ''), ('nuclei', ''), ('nucleus', ''), ('o1', 'Hz'), ('o2', 'Hz'), ('o3', 'Hz'), ('o4', 'Hz'), # ('o5', 'Hz'), # ('o6', 'Hz'), # ('o7', 'Hz'), # ('o8', 'Hz'), # ('obschan', ''), # ('overflw', ''), ('p', 'us'), # ('paps', ''), ('parmode', ''), # ('pcpd', ''), ('ph_ref', ''), ('phcor', ''), # ('php', ''), ('pl', ''), # ('powmod', ''), # ('pr', ''), # ('prechan', ''), # ('prgain', ''), # ('probhd', ''), # ('prosol', ''), ('pulprog', ''), ('pw', 'W'), # ('qnp', ''), # ('qs', ''), # ('qsb', ''), # ('rd', ''), # ('recchan', ''), # ('recph', ''), ('rg', ''), # ('ro', ''), # ('routwd1', ''), # ('routwd2', ''), # ('rpuused', ''), # ('rsel', ''), # ('s', ''), # ('seout', ''), ('sfo1', 'MHz'), ('sfo2', 'MHz'), ('sfo3', 'MHz'), ('sfo4', 'MHz'), # ('sfo5', 'MHz'), # ('sfo6', 'MHz'), # ('sfo7', 'MHz'), # ('sfo8', 'MHz'), # ('solvent', ''), # ('sp', ''), # ('sp07', ''), # ('spectr', ''), # ('spnam0', ''), # ('spnam1', ''), # ('spnam10', ''), # ('spnam11', ''), # ('spnam12', ''), # ('spnam13', ''), # ('spnam14', ''), # ('spnam15', ''), # ('spnam16', ''), # ('spnam17', ''), # ('spnam18', ''), # ('spnam19', ''), # ('spnam2', ''), # ('spnam20', ''), # ('spnam21', ''), # ('spnam22', ''), # ('spnam23', ''), # ('spnam24', ''), # ('spnam25', ''), # ('spnam26', ''), # ('spnam27', ''), # ('spnam28', ''), # ('spnam29', ''), # ('spnam3', ''), # ('spnam30', ''), # ('spnam31', ''), # ('spnam4', ''), # ('spnam5', ''), # ('spnam6', ''), # ('spnam7', ''), # ('spnam8', ''), # ('spnam9', ''), # ('spoal', ''), # ('spoffs', ''), # ('subnam0', ''), # ('subnam1', ''), # ('subnam2', ''), # ('subnam3', ''), # ('subnam4', ''), # ('subnam5', ''), # ('subnam6', ''), # ('subnam7', ''), # ('subnam8', ''), # ('subnam9', ''), ('sw', 'ppm'), # ('sw_h', 'Hz'), # ('swibox', ''), ('td', ''), # ('td0', ''), ('te', 'K'), # ('te2', ''), # ('te3', ''), # ('teg', ''), # ('tl', ''), # ('tp', ''), # ('tp07', ''), # ('tpname0', ''), # ('tpname1', ''), # ('tpname2', ''), # ('tpname3', ''), # ('tpname4', ''), # ('tpname5', ''), # ('tpname6', ''), # ('tpname7', ''), # ('tpoal', ''), # ('tpoffs', ''), # ('tunhin', ''), # ('tunhout', ''), # ('tunxout', ''), # ('usera1', ''), # ('usera2', ''), # ('usera3', ''), # ('usera4', ''), # ('usera5', ''), # ('v9', ''), ('valist', ''), ('vclist', ''), ('vd', ''), ('vdlist', ''), ('vplist', ''), ('vtlist', ''), # ('wbst', ''), # ('wbsw', ''), # ('ws', ''), # ('xgain', ''), # ('xl', ''), # ('yl', ''), # ('ymax_a', ''), # ('ymin_a', ''), # ('zgoptns', ''), # ('zl1', ''), # ('zl2', ''), # ('zl3', ''), # ('zl4', ''), # PROCS # ('absf1', ''), # ('absf2', ''), # ('absg', ''), # ('absl', ''), # ('acqt0', ''), # ('alpha', ''), # ('ampcoil', ''), # ('anavpt', ''), ('aqorder', ''), # ('assfac', ''), # ('assfaci', ''), # ('assfacx', ''), # ('asswid', ''), # ('aunmp', ''), # ('axleft', ''), # ('axname', ''), # ('axnuc', ''), # ('axright', ''), # ('axtype', ''), # ('axunit', ''), # ('azfe', ''), # ('azfw', ''), # ('bc_mod', ''), # ('bcfw', ''), # ('bytordp', ''), # ('cagpars', ''), # ('coroffs', ''), # ('cy', ''), # ('datmod', ''), # ('dc', ''), # ('dfilt', ''), # ('dtypp', ''), # ('eretic', ''), # ('f1p', ''), # ('f2p', ''), # ('fcor', ''), # ('fntype', ''), # ('frqlo3', ''), # ('frqlo3n', ''), # ('ft_mod', ''), # ('ftsize', ''), # ('gamma', ''), # ('gb', 'Hz' ), # ('gpnam', ''), # ('grpdly', ''), ('inf', 'us'), # ('intbc', ''), # ('intscl', ''), # ('isen', ''), # ('lb', 'Hz' ), # ('lev0', ''), # ('linpstp', ''), # ('locsw', ''), # ('lpbin', ''), # ('maxi', ''), ('mc2', ''), # ('mdd_csalg', ''), # ('mdd_cslambda', ''), # ('mdd_csniter', ''), # ('mdd_csnorm', ''), # ('mdd_cszf', ''), # ('mdd_mod', ''), # ('mddcexp', ''), # ('mddct_sp', ''), # ('mddf180', ''), # ('mddlambda', ''), # ('mddmemory', ''), # ('mddmerge', ''), # ('mddncomp', ''), # ('mddniter', ''), # ('mddnoise', ''), # ('mddphase', ''), # ('mddseed', ''), # ('mddsrsize', ''), # ('me_mod', ''), # ('mean', ''), # ('mi', ''), # ('mulexpno', ''), # ('nc_proc', ''), # ('ncoef', ''), # ('nlev', ''), # ('nlogch', ''), # ('noisf1', ''), # ('noisf2', ''), # ('novflw', ''), # ('nsp', ''), # ('nth_pi', ''), # ('nusamount', ''), # ('nusfpnz', ''), # ('nusjsp', ''), # ('nuslist', ''), # ('nusseed', ''), # ('nust2', ''), # ('nustd', ''), # ('nzp', ''), # ('offset', ''), # ('pacoil', ''), # ('pc', ''), # ('pexsel', ''), # ('ph_mod', ''), ('phc0', 'deg'), ('phc1', 'deg'), # ('phlist', ''), # ('pknl', ''), # ('plstep', ''), # ('plstrt', ''), # ('plw', ''), # ('plwmax', ''), # ('pparmod', ''), # ('ppdiag', ''), # ('ppiptyp', ''), # ('ppmpnum', ''), # ('ppresol', ''), # ('pqphase', ''), # ('pqscale', ''), # ('pscal', ''), # ('psign', ''), # ('pynm', ''), # ('pynmp', ''), # ('recpre', ''), # ('recprfx', ''), # ('recsel', ''), ('reverse', ''), # ('s_dev', ''), # ('selrec', ''), ('sf', 'MHz'), # ('si', ''), # ('sigf1', ''), # ('sigf2', ''), # ('sino', ''), # ('siold', ''), # ('solvold', ''), # ('spectyp', ''), # ('spincnt', ''), # ('spnam', ''), # ('sppex', ''), # ('spw', ''), # ('sreglst', ''), # ('ssb', ''), # ('stsi', ''), # ('stsr', ''), # ('subnam', ''), ('sw_p', ''), # ('swfinal', ''), # ('symm', ''), # ('tdeff', ''), # ('tdoff', ''), # ('te1', ''), # ('te4', ''), # ('te_pidx', ''), # ('te_stab', ''), # ('ti', ''), # ('tilt', ''), # ('tm1', ''), # ('tm2', ''), # ('toplev', ''), # ('userp1', ''), # ('userp2', ''), # ('userp3', ''), # ('userp4', ''), # ('userp5', ''), # ('wdw', ''), # ('xdim', ''), # ('ymax_p', ''), # ('ymin_p', ''), ] # ====================================================================================================================== # Digital filter functions # ====================================================================================================================== # Extracted from nmrglue.fileio.bruker.py (BSD License) # Table of points to frequency shift Bruker data to remove digital filter # (Phase is 360 degrees * num_pts) # This table is an 'un-rounded' version base on the table by # <NAME> and <NAME>'s offline processing note, online at: # http://www.boc.chem.uu.nl/static/local/prospectnd/dmx_digital_filters.html # and the updated table with additional entries at: # http://sbtools.uchc.edu/help/nmr/nmr_toolkit/bruker_dsp_table.asp # The rounding in the above tables appear to be based on k / (2*DECIM) # for example 2: 44.75 = 44 + 3/4 # 4: 66.625 = 66 + 5/8 # 8: 68.563 ~= 68 + 9/16 = 68.5625 # Using this the un-rounded table was created by checking possible unrounded # fracions which would round to those in the original table. bruker_dsp_table = {10: {2: 44.75, 3: 33.5, 4: 66.625, 6: 59.083333333333333, 8: 68.5625, 12: 60.375, 16: 69.53125, 24: 61.020833333333333, 32: 70.015625, 48: 61.34375, 64: 70.2578125, 96: 61.505208333333333, 128: 70.37890625, 192: 61.5859375, 256: 70.439453125, 384: 61.626302083333333, 512: 70.4697265625, 768: 61.646484375, 1024: 70.48486328125, 1536: 61.656575520833333, 2048: 70.492431640625, }, 11: {2: 46., 3: 36.5, 4: 48., 6: 50.166666666666667, 8: 53.25, 12: 69.5, 16: 72.25, 24: 70.166666666666667, 32: 72.75, 48: 70.5, 64: 73., 96: 70.666666666666667, 128: 72.5, 192: 71.333333333333333, 256: 72.25, 384: 71.666666666666667, 512: 72.125, 768: 71.833333333333333, 1024: 72.0625, 1536: 71.916666666666667, 2048: 72.03125}, 12: {2: 46., 3: 36.5, 4: 48., 6: 50.166666666666667, 8: 53.25, 12: 69.5, 16: 71.625, 24: 70.166666666666667, 32: 72.125, 48: 70.5, 64: 72.375, 96: 70.666666666666667, 128: 72.5, 192: 71.333333333333333, 256: 72.25, 384: 71.666666666666667, 512: 72.125, 768: 71.833333333333333, 1024: 72.0625, 1536: 71.916666666666667, 2048: 72.03125}, 13: {2: 2.75, 3: 2.8333333333333333, 4: 2.875, 6: 2.9166666666666667, 8: 2.9375, 12: 2.9583333333333333, 16: 2.96875, 24: 2.9791666666666667, 32: 2.984375, 48: 2.9895833333333333, 64: 2.9921875, 96: 2.9947916666666667}} def _remove_digital_filter(dic, data): """ Remove the digital filter from Bruker data. nmrglue modified Digital Filter Processing """ if 'acqus' not in dic: raise KeyError("dictionary does not contain acqus parameters") if 'DECIM' not in dic['acqus']: raise KeyError("dictionary does not contain DECIM parameter") decim = dic['acqus']['DECIM'] if 'DSPFVS' not in dic['acqus']: raise KeyError("dictionary does not contain DSPFVS parameter") dspfvs = dic['acqus']['DSPFVS'] if 'GRPDLY' not in dic['acqus']: grpdly = 0 else: grpdly = dic['acqus']['GRPDLY'] if grpdly > 0: # use group delay value if provided (not 0 or -1) phase = grpdly # Determine the phase correction else: if dspfvs >= 14: # DSPFVS greater than 14 give no phase correction. phase = 0. else: if dspfvs < 11: dspfvs = 11 # default for DQD # loop up the phase in the table if dspfvs not in bruker_dsp_table: raise KeyError("dspfvs not in lookup table") if decim not in bruker_dsp_table[dspfvs]: raise KeyError("decim not in lookup table") phase = bruker_dsp_table[dspfvs][decim] # fft si = data.shape[-1] pdata = np.fft.fftshift(np.fft.fft(data, si, axis=-1), -1) / float(si / 2) pdata = (pdata.T - pdata.T[0]).T # TODO: this allow generally to # TODO: remove Bruker smiles, not so sure actually # Phasing si = float(pdata.shape[-1]) ph = 2.0j * np.pi * phase * np.arange(si) / si pdata = pdata * np.exp(ph) # ifft data = np.fft.ifft(np.fft.ifftshift(pdata, -1), si, axis=-1) * float(si / 2) # remove last points * 2 rp = 2 * (phase // 2) td = dic['acqus']['TD'] // 2 td = int(td) - int(rp) dic['acqus']['TD'] = td * 2 data = data[..., :td] # debug_('Bruker digital filter : removed %s points' % rp) return data # def _scale(meta, dim=-1, reverse=None): # """ # private function: Compute scale for a given axis. # """ # # # import parameter to convert units # sw = float(meta.sw_h[dim]) # sfo1 = float(meta.sfo1[dim]) # bf1 = float(meta.bf1[dim]) # sf = float(meta.sf[dim]) # si = max(float(meta.si[dim])-1, 1) # td = float(meta.td[dim]) # # sr = (sf - bf1) * 1.0e6 # o1 = (sfo1 - bf1) * 1.0e6 # # # set the spectral parameters # # (si, sw_h, bf1, -sr + o1) # # size, sw, obs, car) (correspondance with nmrglue udic) # # # derived units (these are in ppm) # # fact = 2.0 if meta.fnmode[dim] in [3, 4, 5, 6] or else 1.0 # if meta.isfreq[dim]: # delta = -sw * fact / (si * bf1) # first = (-sr + o1)/ bf1 - delta * si / 2. # # if reverse is None: # reverse = meta.reverse # # if reverse: # return scal()[::-1] # else: # return scal() # ====================================================================================================================== # Bruker topspin import function # ====================================================================================================================== def read_topspin(*paths, **kwargs): """ Open Bruker TOPSPIN (NMR) dataset. Parameters ---------- *paths : str, optional Paths of the Bruker directories to read. **kwargs : dict See other parameters. Returns -------- read_topspin |NDDataset| or list of |NDDataset|. Other Parameters ---------------- expno : int, optional experiment number. procno : int processing number. protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description : str, optional A Custom description. origin : {'omnic', 'tga'}, optional In order to properly interpret CSV file it can be necessary to set the origin of the spectra. Up to now only 'omnic' and 'tga' have been implemented. csv_delimiter : str, optional Set the column delimiter in CSV file. By default it is the one set in SpectroChemPy ``Preferences``. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True) recursive : bool, optional Read also in subfolders. (default=False) See Also -------- read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_labspec : Read Raman LABSPEC spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. """ kwargs['filetypes'] = ['Bruker TOPSPIN fid\'s or processed data files (fid ser 1[r|i] 2[r|i]* 3[r|i]*)', 'Compressed TOPSPIN data directories (*.zip)'] kwargs['protocol'] = ['topspin'] importer = Importer() return importer(*paths, **kwargs) @deprecated("read_bruker_nmr reading method is deprecated and may be removed in next versions " "- use read_topspin instead") def read_bruker_nmr(*args, **kwargs): return read_topspin(*args, **kwargs) # ...................................................................................................................... def _get_files(path, typ='acqu'): files = [] for i in ['', 2, 3]: f = path / f'{typ}{i}' if f.exists(): files.append(f) f = path / f'{typ}{i}s' if f.exists(): files.append(f) return files @importermethod def _read_topspin(*args, **kwargs): debug_('Bruker TOPSPIN import') dataset, path = args # content = kwargs.get('content', None) # is-it a processed dataset (1r, 2rr .... processed = True if path.match('pdata/*/*') else False # low memory handling (lowmem) ? lowmem = kwargs.get('lowmem', False) # load all in numero by default # ------------------------------------------------------------------------------------------------------------------ # start reading .... # ------------------------------------------------------------------------------------------------------------------ parents = path.parents # Get data and acquisition parameters if not processed: # a fid or a ser has been selected f_expno = parents[0] expno = f_expno.name procno = kwargs.get('procno', '1') f_procno = f_expno / 'pdata' / procno f_name = parents[1] else: # a processes spectra has been selected (1r, ....) f_procno = parents[0] procno = f_procno.name f_expno = parents[2] expno = f_expno.name f_name = parents[3] acqus_files = _get_files(f_expno, 'acqu') procs_files = _get_files(f_procno, 'proc') if not processed: if not lowmem: dic, data = read_fid(f_expno, acqus_files=acqus_files, procs_files=procs_files) else: dic, data = read_lowmem(f_expno, acqus_files=acqus_files, procs_files=procs_files) # apply a -90 phase shift to be compatible with topspin data = data * np.exp(- 1j * np.pi / 2.) # Look the case when the reshaping was not correct # for example, this happen when the number # of accumulated row was incomplete if path.name in ['ser'] and data.ndim == 1: # we must reshape using the acqu parameters td1 = dic['acqu2']['TD'] try: data = data.reshape(td1, -1) except ValueError: try: td = dic['acqu']['TD'] // 2 data = data.reshape(-1, td) except ValueError: raise KeyError("Inconsistency between TD's and data size") # reduce to td ntd = dic['acqus']['TD'] // 2 data = data[..., :ntd] # Eliminate the digital filter if kwargs.get('remove_digital_filter', True) and dic['acqus']['DECIM'] > 1: data = _remove_digital_filter(dic, data) else: dic, datalist = read_pdata(f_procno, acqus_files=acqus_files, procs_files=procs_files, all_components=True) if isinstance(datalist, list): if datalist[0].ndim == 2: data, dataRI, dataIR, dataII = datalist # make quaternion shape = data.shape data = as_quat_array(list(zip(data.flatten(), dataRI.flatten(), dataIR.flatten(), dataII.flatten()))) data = data.reshape(shape) elif datalist[0].ndim == 1: # make complex data, dataI = datalist data = data + dataI * 1.j else: return None else: data = datalist # .............................................................................................................. # we now make some rearrangement of the dic to have something more user friendly # we assume that all experiments have similar (important) parameters so that the experiments are compatibles meta = Meta() # This is the parameter dictionary datatype = path.name.upper() if not processed else f'{data.ndim}D' keys = sorted(dic.keys()) # we need the ndim of the data parmode = int(dic['acqus'].get('PARMODE', data.ndim - 1)) if parmode + 1 != data.ndim: raise KeyError(f"The NMR data were not read properly as the PARMODE+1 parameter ({parmode + 1}) doesn't fit" f" the actual number of dimensions ({data.ndim})") # read the acqu and proc valid_keys = list(zip(*nmr_valid_meta))[0] keys_units = dict(nmr_valid_meta) for item in keys: if item[:4] in ['acqu', 'proc']: dim = parmode if len(item) > 4 and item[4] in ['2', '3']: dim = parmode + 1 - int(item[4]) for key in sorted(dic[item]): if key.startswith('_') or key.lower() not in valid_keys: continue value = dic[item][key] units = ur(keys_units[key.lower()]) if keys_units[key.lower()] else None if units is not None: if isinstance(value, (float, int)): value = value * units # make a quantity elif isinstance(value, list) and isinstance(value[0], (float, int)): value = np.array(value) * units if key.lower() not in meta: meta[key.lower()] = [None] * data.ndim try: meta[key.lower()][dim] = value except Exception: pass else: meta[item.lower()] = dic[item] # Warning: from now all parameter keys are lowercase. # correct some initial values meta.encoding = [0] * (parmode + 1) meta.iscomplex = [False] * (parmode + 1) if not processed: meta.isfreq = [False] meta.encoding[-1] = AQ_mod[meta.aq_mod[-1]] meta.iscomplex[-1] = meta.aq_mod[-1] > 0 if datatype in ['SER']: meta.isfreq.insert(0, False) if meta.fnmode[-2] == 0: # For historical reasons, # MC2 is interpreted when the acquisition status # parameter FnMODE has the value undefined, i.e. 0 if meta.mc2 is not None: meta.fnmode[-2] = meta.mc2[-2] + 1 meta.encoding[-2] = FnMODE[meta.fnmode[-2]] meta.iscomplex[-2] = meta.fnmode[-2] > 1 if parmode == 2: meta.isfreq.insert(0, False) if meta.fnmode[-3] == 0 and meta.mc2 is not None: meta.fnmode[-3] = meta.mc2[-3] + 1 meta.encoding[-3] = FnMODE[meta.fnmode[-3]] meta.iscomplex[-3] = meta.fnmode[-3] > 1 # correct TD, so it is the number of complex points, not the number of data # not for the last dimension which is already correct meta.tdeff = meta.td[:] meta.td = list(data.shape) for axis in range(parmode + 1): if meta.iscomplex[axis]: if axis != parmode: # already done for last axis meta.td[axis] = meta.td[axis] // 2 meta.tdeff[axis] = meta.tdeff[axis] // 2 meta.sw_h = [(meta.sw[axis].m * meta.sfo1[axis] * 1e-6).to('Hz') for axis in range(parmode + 1)] if processed: meta.si = [si for si in data.shape] meta.isfreq = [True] * (parmode + 1) # at least we assume this meta.phc0 = [0] * data.ndim # this transformation is to make data coherent with bruker processsing if meta.iscomplex[-1]: data = np.conj(data * np.exp(np.pi * 1j / 2.)) # normalised amplitudes to ns=1 and rg=1 def _norm(dat): meta.ns = meta.get('ns', [1] * data.ndim) # sometimes these parameters are not present meta.rg = meta.get('rg', [1.0] * data.ndim) fac = float(meta.ns[-1]) * float(meta.rg[-1]) meta.rgold = [meta.rg[-1]] meta.rg[-1] = 1. meta.nsold = [meta.ns[-1]] # store the old value of NS meta.ns[-1] = 1 dat /= fac return dat data = _norm(data) # add some additional information in meta meta.expno = [int(expno)] # and the metadata (and make them readonly) meta.datatype = datatype meta.pathname = str(path) # add two parameters needed for phasing meta.pivot = [0] * data.ndim meta.exptc = [0] * data.ndim # make the corresponding axis # debug_('Create coords...') coords = [] axe_range = list(range(parmode + 1)) for axis in axe_range: if not meta.isfreq[axis]: # the axis is in time units dw = (1. / meta.sw_h[axis]).to('us') # coordpoints = np.arange(meta.td[axis]) # coord = Coord(coordpoints * dw, # title=f"F{axis + 1} acquisition time") # TODO: use AQSEQ for >2D data coord = LinearCoord(offset=0.0, increment=dw, units='us', size=meta.td[axis], title=f"F{axis + 1} acquisition time") coord.meta.larmor = meta.sfo1[axis] coords.append(coord) else: size = meta.si[axis] sizem = max(size - 1, 1) deltaf = -meta.sw_h[axis] / sizem first = meta.sfo1[axis] - meta.sf[axis] - deltaf * sizem / 2. # coord = Coord(np.arange(size) * deltaf + first) coord = LinearCoord(offset=first, increment=deltaf, size=size) coord.meta.larmor = meta.sfo1[axis] # needed for ppm transformation coord.ito('ppm') if meta.nuc1 is not None: nuc1 = meta.nuc1[axis] regex = r"([^a-zA-Z]+)([a-zA-Z]+)" m = re.match(regex, nuc1) mass = m[1] name = m[2] nucleus = '^{' + mass + '}' + name else: nucleus = "" coord.title = fr"$\delta\ {nucleus}$" coords.append(coord) dataset.data = data for axis, cplex in enumerate(meta.iscomplex[::-1]): if cplex and axis > 0: dataset.set_quaternion(inplace=True) dataset.meta.update(meta) dataset.meta.readonly = True dataset.set_coordset(*tuple(coords)) dataset.title = 'intensity' dataset.origin = 'topspin' dataset.name = f'{f_name.name} expno:{expno} procno:{procno} ({datatype})' dataset.filename = f_name return dataset # list_meta.append(meta) # list_coords.append(coords) # list_data.append(data) # # store also the varpars of the series # varpars = kargs.get('varpars') # if isinstance(varpars, str): # # # varpars = varpars.split() # if len(varpars) == 1: # # this should be one of the dic parameters # # lvarpars.append(adic.par[varpars[0]]) # store the variable # elif len(varpars) == 2: # # # lvarpars.append(adic.par[varpars[0]][ # int(varpars[1])]) # store the variable # # ldates.append(adic.par.DATE) # and the date # elif isinstance(varpars, list): # # this should be a list # of parameters # p = [] # for var in varpars: # p.append(adic.par[var]) # # # lvarpars.append(p) # store the variable # ldates.append(adic.par.DATE) # and the date # store temporarily these data # debug_('data read finished : type : %s' % datatype) # # # # if len( # # list_data) == 1: # # debug_('One experiment read. Make it the current dataset') # def _read_topspin_dir(*args, **kwargs): # # expnos = kwargs.get('expnos', False) # List of expnos? # paths = None # if expnos: # paths = [os.path.join(path, str(expno)) for expno in expnos] # else: # paths = [path, ] # # # start loop on the paths # # list_data = [] # list_meta = [] # list_coords = [] # # for idx, path in enumerate(paths): # # # debug_('Reading %d:%s' % (idx, path)) # # # Acquisition parameters # # if os.path.isfile(os.path.join(path, "fid")): # datatype = 'FID' # elif os.path.isfile(os.path.join(path, "ser")): # datatype = 'SER' # elif expno is not None: # if os.path.isfile(os.path.join(path, str(expno), "fid")): # datatype = 'FID' # path = os.path.join(path, str(expno)) # elif os.path.isfile(os.path.join(path, str(expno), "ser")): # datatype = 'SER' # path = os.path.join(path, str(expno)) # else: # if not processed: # warning_('No binary fid or ser found in %s.\n' # 'Try processed files...' % path) # processed = True # # if os.path.isfile(os.path.join(path, 'pdata', procno, '1r')): # if not datatype or processed: # datatype = '1D' # elif os.path.isfile(os.path.join(path, 'pdata', procno, '2rr')): # if not datatype or processed: # datatype = '2D' # elif os.path.isfile(os.path.join(path, 'pdata', procno, '3rrr')): # if not datatype or processed: # datatype = '3D' # else: # if not datatype: # raise KeyError(f"No Bruker binary file could be found in {path}") # elif processed: # warning_(f"No processed Bruker binary file could be found in {path}. Use fid's.") # # # we read all parameters file whatever the datatype # npath, par_files = _get_par_files(path, procno, processed) # # if datatype in ['FID', 'SER']: # if not lowmem: # dic, data = read(npath, acqus_files=par_files, # read_pulseprogram=False) # else: # dic, data = read_lowmem(npath, acqus_files=par_files, read_pulseprogram=False) # # data = data * np.exp(- 1j * np.pi / 2.) # -90 phase to be compatible with topspin # # # look the case when the reshaping was not correct # # for example, this happen when the number # # of accumulated row was incomplete # if datatype in ['SER'] and data.ndim == 1: # # we must reshape using the acqu parameters # td1 = dic['acqu2']['TD'] # try: # data = data.reshape(td1, -1) # except ValueError: # try: # td = dic['acqu']['TD'] // 2 # data = data.reshape(-1, td) # except ValueError: # raise KeyError("Inconsistency between TD's and data size") # # # reduce to td # ntd = dic['acqus']['TD'] // 2 # data = data[..., :ntd] # # necessary for agreement with bruker data and phase # else: # # # debug_(f'Reading processed {idx}:{path}') # # dic, data = read_pdata(npath, procs_files=par_files, ) # # # Clean dict for pdata keys # keys = list(dic.keys()) # for key in keys: # if key.startswith('pdata'): # newkey = key.split(os.path.sep)[-1] # dic[newkey] = dic.pop(key) # # # Eliminate the digital filter # if datatype in ['FID', 'SER'] and kwargs.get('remove_digital_filter', # True): # data = _remove_digital_filter(dic, data) # # # # .............................................................................................................. # # we now make some rearrangement of the dic # # to have something more user friendly # # we assume that all experiments have similar (important) # # parameters so that the experiments are # # compatible # # meta = Meta() # This is the parameter dictionary # # keys = sorted(dic.keys()) # # # we need the ndim of the data # parmode = int(dic['acqus']['PARMODE']) # if parmode + 1 != data.ndim: # raise KeyError(f"The NMR data were not read properly as the PARMODE+1 parameter ({parmode + 1}) doesn't # fit" # f" the actual number of dimensions ({data.ndim})") # # # read the acqu and proc # valid_keys = list(zip(*nmr_valid_meta))[0] # keys_units = dict(nmr_valid_meta) # # for item in keys: # # if item[:4] in ['acqu', 'proc']: # dim = parmode # if len(item) > 4 and item[4] in ['2', '3']: # dim = parmode + 1 - int(item[4]) # # for key in sorted(dic[item]): # if key.startswith('_') or key.lower() not in valid_keys: # continue # # value = dic[item][key] # units = ur(keys_units[key.lower()]) if keys_units[key.lower()] else None # # if units is not None: # if isinstance(value, (float, int)): # value = value * units # make a quantity # elif isinstance(value, list) and isinstance(value[0], (float, int)): # value = np.array(value) * units # # if not item.endswith('s'): # initial parameter # # if dim == parmode: # meta[key.lower()] = [value, ] # else: # meta[key.lower()].insert(dim, value) # # else: # status parameters (replace initial) # try: # meta[key.lower()][dim] = value # except Exception: # pass # # else: # # meta[item.lower()] = dic[item] # # # Warning: from now all parameter keys are lowercase. # # # correct some initial values # # meta.encoding = [0] * (parmode + 1) # meta.iscomplex = [False] * (parmode + 1) # # if datatype in ['FID', 'SER']: # meta.isfreq = [False] # meta.encoding[-1] = AQ_mod[meta.aq_mod[-1]] # meta.iscomplex[-1] = meta.aq_mod[-1] > 0 # # if datatype in ['SER']: # meta.isfreq.insert(0, False) # # if meta.fnmode[-2] == 0: # # For historical reasons, # # MC2 is interpreted when the acquisition status # # parameter FnMODE has the value undefined, i.e. 0 # if meta.mc2 is not None: # meta.fnmode[-2] = meta.mc2[-2] + 1 # # meta.encoding[-2] = FnMODE[meta.fnmode[-2]] # meta.iscomplex[-2] = meta.fnmode[-2] > 1 # # if parmode == 2: # meta.isfreq.insert(0, False) # if meta.fnmode[-3] == 0 and meta.mc2 is not None: # meta.fnmode[-3] = meta.mc2[-3] + 1 # meta.encoding[-3] = FnMODE[meta.fnmode[-3]] # meta.iscomplex[-3] = meta.fnmode[-3] > 1 # # # correct TD, so it is the number of complex points, not the number of data # # not for the last dimension which is already correct # meta.tdeff = meta.td[:] # meta.td = list(data.shape) # # for axis in range(parmode + 1): # if meta.iscomplex[axis]: # if axis != parmode: # already done for last axis # meta.td[axis] = meta.td[axis] // 2 # meta.tdeff[axis] = meta.tdeff[axis] // 2 # # if datatype in ['1D', '2D', '3D']: # meta.si = [si for si in data.shape] # meta.isfreq = [True] * (parmode + 1) # at least we assume this # # # this transformation is to make data coherent with bruker processsing # if meta.iscomplex[-1]: # data = np.conj(data * np.exp(np.pi * 1j / 2.)) # # # normalised amplitudes to ns=1 and rg=1 # def _norm(dat): # fac = float(meta.ns[-1]) * float(meta.rg[-1]) # meta.rgold = [meta.rg[-1]] # meta.rg[-1] = 1. # meta.nsold = [meta.ns[-1]] # store the old value of NS # meta.ns[-1] = 1 # dat /= fac # return dat # # data = _norm(data) # # # add some additional inforation in meta # meta.expno = [int(os.path.basename(path))] # # # and the metadata (and make them readonly) # meta.datatype = datatype # meta.pathname = path # list_meta.append(meta) # # # make the corresponding axis # # debug_('Create coords...') # coords = [] # axe_range = list(range(parmode + 1)) # for axis in axe_range: # if not meta.isfreq[axis]: # # the axis is in time units # dw = (1. / meta.sw_h[axis]).to('us') # coordpoints = np.arange(meta.td[axis]) # coord = Coord(coordpoints * dw, # title=f"F{axis + 1} acquisition time") # TODO: use AQSEQ for >2D data # coords.append(coord) # else: # raise NotImplementedError('Not yet implemented') # list_coords.append(coords) # # # # store also the varpars of the series # # varpars = kargs.get('varpars') # # if isinstance(varpars, str): # # varpars = varpars.split() # # if len(varpars) == 1: # # # this should be one of the dic parameters # # lvarpars.append(adic.par[varpars[0]]) # store the variable # # elif len(varpars) == 2: # # lvarpars.append(adic.par[varpars[0]][ # # int(varpars[1])]) # store the variable # # ldates.append(adic.par.DATE) # and the date # # elif isinstance(varpars, list): # # # this should be a list of parameters # # p = [] # # for var in varpars: # # p.append(adic.par[var]) # # lvarpars.append(p) # store the variable # # ldates.append(adic.par.DATE) # and the date # # # store temporarily these data # # debug_('data read finished : type : %s' % datatype) # # list_data.append(data) # # if len(list_data) == 1: # # debug_('One experiment read. Make it the current dataset') # # dataset.data = list_data[0] # # for axis, cplex in enumerate(meta.iscomplex[::-1]): # if cplex and axis > 0: # dataset.set_quaternion(inplace=True) # # dataset.meta.update(list_meta[0]) # dataset.meta.readonly = True # dataset.set_coordset(*tuple(list_coords[0])) # must be a tuple # dataset.title = 'intensity' # dataset.origin = 'bruker' # # else: # # # TODO: Check this - # # case of multiple experiments to merge # # # find difference in data.shape # # diff = False # shape = list_data[0].shape # for data in list_data[1:]: # if np.any(data.shape != shape): # diff = True # # if not diff: # # find difference in coordss # coords = list_coords[0] # for a in list_coords[1:]: # if np.any(a != coords): # diff = True # # if not diff: # info_('the experiments look perfectly compatibles' # ' regarding the shape and the axis!') # # # find what are the differences in meta # meta = list_meta[0] # # mkeys = set() # will stroe the modified keys # from spectrochempy.utils import dict_compare # for i, d1 in enumerate(list_meta): # for j, d2 in enumerate(list_meta[i + 1:]): # added, removed, modified, _ = \ # dict_compare(d1.to_dict(), d2.to_dict(), # check_equal_only=False) # mkeys = mkeys.union(added) # mkeys = mkeys.union(removed) # mkeys = mkeys.union(modified) # # # some keys should not vary for homogeneous data but lets the # # user decide # info_("keys which have varied : %s" % mkeys) # # mkeys = list(mkeys) # meta_diffs = {} # for key in mkeys: # # find the key variation # # WARNING: restriction is that we use only the direct observation # # dimension to get the values (so a variation in another dimension # # will not be seen! # if isinstance(meta[key][-1], Quantity): # meta_diffs[key] = [meta[key][-1].m for meta in list_meta] # meta_diffs[key] = meta_diffs[key] * meta[key][-1].units # else: # meta_diffs[key] = [meta[key][-1] for meta in list_meta] # # # we can now store the meta for the datset object # dataset.meta.update(list_meta[-1]) # # we additionaly set the list of variable parameters whch will indicate # # the orders of the labels for the new axis # dataset.meta.labels = mkeys # dataset.meta.readonly = True # and from now no more modifications in metas # # # by default and if it is possible we try to create an homogeneous # # NDDataset (needs same TD, SFO1, etc.. and of course same data.shape) # merge_method = kwargs.get('merge_method', 'create_array') # if merge_method == 'create_array' and not diff: # # we create un array with the list of array # newdata = np.stack(list_data, axis=0) # # # store it in the current datset # dataset.data = newdata # # complexity? # complexity = [False] + meta.iscomplex # for axis, iscomplex in enumerate(complexity): # if iscomplex: # dataset.set_complex(axis) # # # new coords # vkey = kwargs.get('var_key', None) # vkey = vkey.lower() # # if vkey is not None and vkey in mkeys: # ax = meta_diffs[vkey] # title = vkey # else: # ax = np.arange(newdata.shape[0]) # title = '-nd-' # axis = Coord(ax, title=title) # # labels = [] # for i in range(len(ax)): # if len(mkeys) > 1: # label = [] # for key in mkeys: # label.append(meta_diffs[key][i]) # else: # label = meta_diffs[mkeys[-1]][i] # labels.append(label) # labels = np.array(labels, dtype=object) # axis.labels = labels # # # now make the coords it in the current dataset # # only one coords of the list is taken: they are all the same # # in principle... if not problem above or the experiments # # are not compatibles # dataset.coords = [axis] + list_coords[-1] # dataset.origin = 'bruker' # # return dataset <file_sep>/docs/userguide/objects.rst .. _userguide.objects: Data structures ############### The NDDataset is the main object used by |scpy|. Like numpy ndarrays, NDDataset have the capability to be sliced, sorted and subjected to mathematical operations. But, in addition, NDDataset may have units, can be masked and each dimensions can have coordinates (Coord) also with units. This make NDDataset aware of unit compatibility, *e.g.*, for binary operation such as additions or subtraction or during the application of mathematical operations. In addition or in replacement of numerical data for coordinates, NDDataset can also have labeled coordinates where labels can be different kind of objects (strings, datetime, numpy nd.ndarray or othe NDDatasets, etc...). This offers a lot of flexibility in using NDDatasets that, we hope, will be useful for the users. .. todo:: **SpectroChemPy** (will soon) provides another kind of data structure, aggregating several datasets: **NDPanel**. [*Under construction*] Finally, **Project** is a structure that allow agregating NDDatasets, NDPanels and processing scripts (Script) for a better management of complex set of spectroscopic data. NDDataset ********* .. toctree:: :glob: :maxdepth: 2 dataset/dataset Project ******* .. toctree:: :glob: :maxdepth: 2 project/project Script ****** .. todo:: To be documented <file_sep>/docs/gettingstarted/install/index.rst .. _installation: ######################## Installation guide ######################## Prerequisites ************* |scpy| requires a working `Python <http://www.python.org/>`_ installation (version 3.6.9 or higher). We highly recommend to install `Anaconda <https://www.anaconda.com/distribution/>`_ or `Miniconda <https://docs.conda.io/en/latest/miniconda.html>`_ distributions which are available for most platforms and the rest of this guide will mainly use commands for this distribution. Miniconda is lighter (400 MB disk space) while Anaconda (3 GB minimum disk space to download and install) is much more complete for scientific applications if you intend using python beyond |scpy|. Important packages in Anaconda are also required for |scpy| (e.g., `Matplotib <https://matplotlib.org>`_, `Numpy <https://numpy.org>`_, `Scipy <https://www.scipy.org>`_, `Jupyter <https://jupyter.org>`_, …). They are not included in Miniconda and will be installed anyway when installing |scpy|. So overall, the difference in installation time/disc space won’t be that big whether you choose Miniconda or Anaconda… * Go to `Anaconda download page <https://www.anaconda.com/distribution/>`_ or `Miniconda download page <https://docs.conda.io/en/latest/miniconda.html>`_ to get one of these distribution. * Choose your platform and download one of the available installer, *e.g.*, the 3.7 or + version (up to now it has been tested upon 3.9, but it is likely to work with upper version numbers). * Install the version which you just downloaded, following the instructions on the download page. Installation of |scpy| ***************************************************** |scpy| installation is very similar on the various platform, except the syntax of some command. We propose here the installation step whether you are on mac/linux systems, or on Windows. Additionaly it is possible to use a docker container or the Google Colaboratory cloud platform. * :doc:`install_mac` * :doc:`install_win` * :doc:`install_docker` * :doc:`install_sources` * :doc:`install_colab` * :doc:`install_adds` .. toctree:: :maxdepth: 3 :hidden: install_mac install_win install_docker install_sources install_colab install_adds <file_sep>/spectrochempy/core/readers/readcsv.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ['read_csv'] __dataset_methods__ = __all__ # ---------------------------------------------------------------------------------------------------------------------- # standard and other imports # ---------------------------------------------------------------------------------------------------------------------- import warnings import locale import io from datetime import datetime, timezone import numpy as np from spectrochempy.core.dataset.coord import Coord from spectrochempy.core import dataset_preferences as prefs from spectrochempy.core.readers.importer import Importer, importermethod try: locale.setlocale(locale.LC_ALL, 'en_US') # to avoid problems with date format except Exception: try: locale.setlocale(locale.LC_ALL, 'en_US.utf8') # to avoid problems with date format except Exception: warnings.warn('Could not set locale: en_US or en_US.utf8') # ====================================================================================================================== # Public functions # ====================================================================================================================== def read_csv(*paths, **kwargs): """ Open a *.csv file or a list of *.csv files. This is limited to 1D array - csv file must have two columns [index, data] without header. Parameters ---------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read_csv |NDDataset| or list of |NDDataset|. Other Parameters ---------------- protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description: str, optional A Custom description. origin : {'omnic', 'tga'}, optional in order to properly interpret CSV file it can be necessary to set the origin of the spectra. Up to now only 'omnic' and 'tga' have been implemented. csv_delimiter : str, optional Set the column delimiter in CSV file. By default it is the one set in SpectroChemPy ``Preferences``. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True). recursive : bool, optional Read also in subfolders. (default=False). See Also -------- read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_zip : Read Zip files. read_matlab : Read Matlab files. read : Generic file reading. Examples --------- >>> import spectrochempy as scp >>> scp.read_csv('agirdata/P350/TGA/tg.csv') NDDataset: [float64] unitless (shape: (y:1, x:3247)) Additional information can be stored in the dataset if the origin is given (known origin for now : tga or omnic) # TODO: define some template to allow adding new origins >>> scp.read_csv('agirdata/P350/TGA/tg.csv', origin='tga') NDDataset: [float64] wt.% (shape: (y:1, x:3247)) Sometimes the delimiteur needs to be adjusted >>> prefs = scp.preferences >>> scp.read_csv('irdata/IR.CSV', directory=prefs.datadir, origin='omnic', csv_delimiter=',') NDDataset: [float64] a.u. (shape: (y:1, x:3736)) """ kwargs['filetypes'] = ['CSV files (*.csv)'] kwargs['protocol'] = ['csv'] importer = Importer() return importer(*paths, **kwargs) # ====================================================================================================================== # Private functions # ====================================================================================================================== @importermethod def _read_csv(*args, **kwargs): # read csv file dataset, filename = args content = kwargs.get('content', None) delimiter = kwargs.get("csv_delimiter", prefs.csv_delimiter) def _open(): if content is not None: f = io.StringIO(content.decode("utf-8")) else: f = open(filename, 'r') return f try: fid = _open() d = np.loadtxt(fid, unpack=True, delimiter=delimiter) fid.close() except ValueError: # it might be that the delimiter is not correct (default is ','), but # french excel export with the french locale for instance, use ";". _delimiter = ';' try: fid = _open() if fid: fid.close() fid = _open() d = np.loadtxt(fid, unpack=True, delimiter=_delimiter) fid.close() except Exception: # in french, very often the decimal '.' is replaced by a # comma: Let's try to correct this if fid: fid.close() if not isinstance(fid, io.StringIO): with open(fid, "r") as fid_: txt = fid_.read() else: txt = fid.read() txt = txt.replace(',', '.') fil = io.StringIO(txt) try: d = np.loadtxt(fil, unpack=True, delimiter=delimiter) except Exception: raise IOError( '{} is not a .csv file or its structure cannot be recognized') # First column is the x coordinates coordx = Coord(d[0]) # create a second coordinate for dimension y of size 1 coordy = Coord([0]) # and data is the second column - we make it a vector data = d[1].reshape((1, coordx.size)) # update the dataset dataset.data = data dataset.set_coordset(y=coordy, x=coordx) # set the additional attributes name = filename.stem dataset.filename = filename dataset.name = kwargs.get('name', name) dataset.title = kwargs.get('title', None) dataset.units = kwargs.get('units', None) dataset.description = kwargs.get('description', '"name" ' + 'read from .csv file') dataset.history = str(datetime.now(timezone.utc)) + ':read from .csv file \n' dataset._date = datetime.now(timezone.utc) dataset._modified = dataset.date # here we can check some particular format origin = kwargs.get('origin', '') if 'omnic' in origin: # this will be treated as csv export from omnic (IR data) dataset = _add_omnic_info(dataset, **kwargs) elif 'tga' in origin: # this will be treated as csv export from tga analysis dataset = _add_tga_info(dataset, **kwargs) elif origin: origin = kwargs.get('origin', None) raise NotImplementedError(f"Sorry, but reading a csv file with '{origin}' origin is not implemented. " "Please, remove or set the keyword 'origin'\n " '(Up to now implemented csv files are: `omnic`, `tga`)') return dataset # ............................................................................. def _add_omnic_info(dataset, **kwargs): # get the time and name name = desc = dataset.name # modify the dataset metadata dataset.units = 'absorbance' dataset.title = 'Absorbance' dataset.name = name dataset.description = ('Dataset from .csv file: {}\n'.format(desc)) dataset.history = str(datetime.now(timezone.utc)) + ':read from omnic exported csv file \n' dataset.origin = 'omnic' # Set the NDDataset date dataset._date = datetime.now(timezone.utc) dataset._modified = dataset.date # x axis dataset.x.units = 'cm^-1' # y axis ? if '_' in name: name, dat = name.split('_') # if needed convert weekday name to English dat = dat.replace('Lun', 'Mon') dat = dat[:3].replace('Mar', 'Tue') + dat[3:] dat = dat.replace('Mer', 'Wed') dat = dat.replace('Jeu', 'Thu') dat = dat.replace('Ven', 'Fri') dat = dat.replace('Sam', 'Sat') dat = dat.replace('Dim', 'Sun') # convert month name to English dat = dat.replace('Aout', 'Aug') # get the dates acqdate = datetime.strptime(dat, "%a %b %d %H-%M-%S %Y") # Transform back to timestamp for storage in the Coord object # use datetime.fromtimestamp(d, timezone.utc)) # to transform back to datetime obkct timestamp = acqdate.timestamp() dataset.y = Coord(np.array([timestamp]), name='y') dataset.set_coordtitles(y='Acquisition timestamp (GMT)', x='Wavenumbers') dataset.y.labels = np.array([[acqdate], [name]]) dataset.y.units = 's' return dataset def _add_tga_info(dataset, **kwargs): # for TGA, some information are needed. # we add them here dataset.x.units = 'hour' dataset.units = 'weight_percent' dataset.x.title = 'Time-on-stream' dataset.title = 'Mass change' dataset.origin = 'tga' return dataset # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/docs/userguide/processing/interferogram.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # cell_metadata_filter: title,-all # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # FTIR interferogram processing # # A situation where we need transform of real data is the case of FTIR interferograms. # %% import spectrochempy as scp from spectrochempy.units import ur # %% ir = scp.read_spa("irdata/interferogram/interfero.SPA") # %% [markdown] # By default, the interferogram is displayed with an axis in points (no units). # %% prefs = ir.preferences prefs.figure.figsize = (7, 3) _ = ir.plot() print('number of points = ', ir.size) # %% [markdown] # Plotting a zoomed region around the maximum of the interferogram (the so-called `ZPD`: `Zero optical Path # Difference` ) we can see that it is located around the 64th points. The FFT processing will need this information, # but it will be determined automatically. # %% _ = ir.plot(xlim=(0, 128)) # %% [markdown] # The `x` scale of the interferogramme can also be displayed as a function of optical path difference. For this we # just make `show_datapoints` to False: # %% ir.x.show_datapoints = False _ = ir.plot(xlim=(-0.04, 0.04)) # %% [markdown] # Note that the `x` scale of the interferogram has been calculated using a laser frequency of 15798.26 cm$^{-1}$. If # this is not correct you can change it using the `set_laser_frequency` coordinate method: # %% ir.x.set_laser_frequency(15798.26 * ur('cm^-1')) # %% [markdown] # Now we can perform the Fourier transform. By default no zero-filling level is applied prior the Fourier transform # for FTIR. To add some level of zero-filling, use the `zf` method. # %% ird = ir.dc() ird = ird.zf(size=2 * ird.size) irt = ird.fft() _ = irt.plot(xlim=(3999, 400)) # %% [markdown] # A `Happ-Genzel` (Hamming window) apodization can also applied prior to the # Fourier transformation in order to decrease the H2O narrow bands. # %% ird = ir.dc() irdh = ird.hamming() irdh.zf(inplace=True, size=2 * ird.size) irth = irdh.fft() _ = irth.plot(xlim=(3999, 400)) # %% [markdown] # ## Comparison with the OMNIC processing. # # Here we compare the OMNIC processed spectra of the same interferogram and ours in red. One can see that the results # are very close # %% irs = scp.read_spa("irdata/interferogram/spectre.SPA") prefs.figure.figsize = (7, 6) _ = irs.plot(label='omnic') _ = (irt - .4).plot(c='red', clear=False, xlim=(3999, 400), label='no hamming') ax = (irth - .2).plot(c='green', clear=False, xlim=(3999, 400), label='hamming') _ = ax.legend() <file_sep>/README.md ![titre](titre.png) ## What is SpectroChemPy? SpectroChemPy (SCPy) is a framework for processing, analyzing and modeling Spectroscopic data for Chemistry with Python. It is a cross platform software, running on Linux, Windows or OS X. ||| |---:|:---| |**Tests**|[![Build Status](https://travis-ci.com/spectrochempy/spectrochempy.svg?branch=master)](https://travis-ci.com/spectrochempy/spectrochempy) [![Total alerts](https://img.shields.io/lgtm/alerts/g/spectrochempy/spectrochempy.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/spectrochempy/spectrochempy/alerts/) [![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/spectrochempy/spectrochempy.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/spectrochempy/spectrochempy/context:python) [![Maintainability](https://api.codeclimate.com/v1/badges/78681bc1aabbb8ca915f/maintainability)](https://codeclimate.com/github/spectrochempy/spectrochempy/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/78681bc1aabbb8ca915f/test_coverage)](https://codeclimate.com/github/spectrochempy/spectrochempy/test_coverage)| |**Packages**|[![Anaconda-Server Badge](https://anaconda.org/spectrocat/spectrochempy/badges/installer/conda.svg)](https://conda.anaconda.org/spectrocat) ![Conda](https://img.shields.io/conda/v/spectrocat/spectrochempy) ![Docker](https://img.shields.io/docker/cloud/automated/spectrocat/spectrochempy) | |**Docs**|[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3823841.svg)](https://doi.org/10.5281/zenodo.3823841) ![Conda](https://img.shields.io/conda/l/spectrocat/spectrochempy)| |**Implementations**|![Conda](https://img.shields.io/conda/pn/spectrocat/spectrochempy)| ## Features Among its major features: * A NDDataset object embedding array of data with labeled axes and metadata. * A Project manager to work on multiple NDDataset simultaneously. * Physical Units for NDDataset. * Mathematical operations over NDDataset such addition, multiplication and many more ... * Import functions to read data from experiments or modeling programs ... * Display functions such as plot for 1D or nD datasets ... * Export functions to csv, xls formats ... * Preprocessing functions such as baseline correction, automatic subtraction and many more ... * Fitting capabilities for single or multiple datasets ... * Exploratory analysis such as SVD, PCA, MCR_ALS, EFA ... **Warning**: SpectroChemPy is still experimental and under active development. Its current design is subject to major changes, reorganizations, bugs and crashes!!!. Please report any issues to the Issue Tracker. ## Documentation The online Html documentation is available here: [HTML documentation](https://www.spectrochempy.fr) ### Examples, tutorials A zip archive of all the notebooks corresponding to the documentation can be found [here](https://www.spectrochempy.fr/downloads/stable-spectrochempy-notebooks.zip) ## Installation Follow the instructions here: [Installation guide](https://www.spectrochempy.fr/stable/gettingstarted/install/index.html) ## Issue Tracker You find a problem, want to suggest enhancements or want to look at the current issues and milestones, you can go there: [Issue Tracker](https://github.com/spectrochempy/spectrochempy/issues) ## Citing SpectroChemPy When using SpectroChemPy for your own work, you are kindly requested to cite it this way: ``` <NAME> & <NAME>, (2020) SpectroChemPy (Version 0.1). Zenodo. http://doi.org/10.5281/zenodo.3823841 ``` ## Source repository The source are versioned using the git system and hosted on the GitHub platform: https://github.com/spectrochempy/spectrochempy ## License [CeCILL-B FREE SOFTWARE LICENSE AGREEMENT](https://cecill.info/licences/Licence_CeCILL-B_V1-en.html) <file_sep>/spectrochempy/core/analysis/api.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ API for the core.analysis package Automatically generated from file present in the analysis directory. """ from spectrochempy.utils import generate_api # generate api __all__ = generate_api(__file__) # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/spectrochempy/core/plotters/plot2d.py # -*- coding: utf-8 -*- # # ====================================================================================================================== # Copyright (©) 2015-2021 LCS # Laboratoire Catalyse et Spectrochimie, Caen, France. # # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT # See full LICENSE agreement in the root directory # ====================================================================================================================== """ Plotters """ __all__ = ['plot_2D', 'plot_map', 'plot_stack', 'plot_image', 'plot_surface', 'plot_waterfall'] __dataset_methods__ = __all__ from copy import copy as cpy from matplotlib.ticker import MaxNLocator, ScalarFormatter import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from spectrochempy.core.plotters.plotutils import make_label from spectrochempy.core.dataset.coord import LinearCoord # ====================================================================================================================== # nddataset plot2D functions # ====================================================================================================================== # contour map (default) ------------------------------------------------------- def plot_map(dataset, **kwargs): """ Plot a 2D dataset as a contoured map. Alias of plot_2D (with `method` argument set to ``map``. """ if dataset.ndim < 2: from spectrochempy.core.plotters.plot1d import plot_1D return plot_1D(dataset, **kwargs) kwargs['method'] = 'map' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_2D(dataset, **kwargs) # stack plot ----------------------------------------------------------------- def plot_stack(dataset, **kwargs): """ Plot a 2D dataset as a stacked plot. Alias of plot_2D (with `method` argument set to ``stack``). """ if dataset.ndim < 2: from spectrochempy.core.plotters.plot1d import plot_1D return plot_1D(dataset, **kwargs) kwargs['method'] = 'stack' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_2D(dataset, **kwargs) # image plot -------------------------------------------------------- def plot_image(dataset, **kwargs): """ Plot a 2D dataset as an image plot. Alias of plot_2D (with `method` argument set to ``image``). """ if dataset.ndim < 2: from spectrochempy.core.plotters.plot1d import plot_1D return plot_1D(dataset, **kwargs) kwargs['method'] = 'image' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_2D(dataset, **kwargs) # surface plot ----------------------------------------------------------------- def plot_surface(dataset, **kwargs): """ Plot a 2D dataset as a a 3D-surface. Alias of plot_2D (with `method` argument set to ``surface``. """ if dataset.ndim < 2: from spectrochempy.core.plotters.plot1d import plot_1D return plot_1D(dataset, **kwargs) kwargs['method'] = 'surface' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_2D(dataset, **kwargs) # waterfall plot ----------------------------------------------------------------- def plot_waterfall(dataset, **kwargs): """ Plot a 2D dataset as a a 3D-waterfall plot. Alias of plot_2D (with `method` argument set to ``waterfall``. """ if dataset.ndim < 2: from spectrochempy.core.plotters.plot1d import plot_1D return plot_1D(dataset, **kwargs) kwargs['method'] = 'waterfall' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_2D(dataset, **kwargs) # generic plot (default stack plot) ------------------------------------------- def plot_2D(dataset, **kwargs): """ PLot of 2D array. Parameters ---------- dataset : :class:`~spectrochempy.ddataset.nddataset.NDDataset` The dataset to plot. ax : |Axes| instance. Optional The axe where to plot. The default is the current axe or to create a new one if is None. clear : `bool`, optional, default=`True` Should we plot on the ax previously used or create a new figure?. figsize : tuple, optional The figure size expressed as a tuple (w,h) in inch. Other Parameters ----------------- method : ['stack', 'map', 'image', 'surface', 'waterfall'] , optional The method of plot of the dataset, which will determine the plotter to use. Default is stack fontsize : int, optional The font size in pixels, default is 10 (or read from preferences). style : str autolayout : `bool`, optional, default=True if True, layout will be set automatically. output : str A string containing a path to a filename. The output format is deduced from the extension of the filename. If the filename has no extension, the value of the rc parameter savefig.format is used. dpi : [ None | scalar > 0] The resolution in dots per inch. If None it will default to the value savefig.dpi in the matplotlibrc file. colorbar : transposed : clear : ax : twinx : use_plotly : bool, optional Should we use plotly instead of mpl for plotting. Default to `preferences.use_plotly` (default=False) data_only : `bool` [optional, default=`False`] Only the plot is done. No addition of axes or label specifications (current if any or automatic settings are kept. method : str [optional among ``map``, ``stack``, ``image`` or ``3D``] The type of plot, projections : `bool` [optional, default=False] style : str, optional, default='notebook' Matplotlib stylesheet (use `available_style` to get a list of available styles for plotting reverse : `bool` or None [optional, default=None In principle, coordinates run from left to right, except for wavenumbers (e.g., FTIR spectra) or ppm (e.g., NMR), that spectrochempy will try to guess. But if reverse is set, then this is the setting which will be taken into account. x_reverse : `bool` or None [optional, default=None kwargs : additional keywords """ # Get preferences # ------------------------------------------------------------------------------------------------------------------ prefs = dataset.preferences # before going further, check if the style is passed in the parameters style = kwargs.pop('style', None) if style is not None: prefs.style = style # else we assume this has been set before calling plot() prefs.set_latex_font(prefs.font.family) # reset latex settings # Redirections ? # ------------------------------------------------------------------------------------------------------------------ # should we redirect the plotting to another method if dataset._squeeze_ndim < 2: return dataset.plot_1D(**kwargs) # if plotly execute plotly routine not this one if kwargs.get('use_plotly', prefs.use_plotly): return dataset.plotly(**kwargs) # Method of plot # ------------------------------------------------------------------------------------------------------------------ method = kwargs.get('method', prefs.method_2D) # do not display colorbar if it's not a surface plot # except if we have asked to d so # often we do need to plot only data when plotting on top of a previous plot data_only = kwargs.get('data_only', False) # Get the data to plot # ------------------------------------------------------------------------------------------------------------------- # if we want to plot the transposed dataset transposed = kwargs.get('transposed', False) if transposed: new = dataset.copy().T # transpose dataset nameadd = '.T' else: new = dataset # .copy() nameadd = '' new = new.squeeze() if kwargs.get('y_reverse', False): new = new[::-1] # Figure setup # ------------------------------------------------------------------------------------------------------------------ new._figure_setup(ndim=2, **kwargs) ax = new.ndaxes['main'] ax.name = ax.name + nameadd # Other properties that can be passed as arguments # ------------------------------------------------------------------------------------------------------------------ lw = kwargs.get('linewidth', kwargs.get('lw', prefs.lines_linewidth)) alpha = kwargs.get('calpha', prefs.contour_alpha) number_x_labels = prefs.number_of_x_labels number_y_labels = prefs.number_of_y_labels number_z_labels = prefs.number_of_z_labels if method in ['waterfall']: nxl = number_x_labels * 2 nyl = number_z_labels * 2 elif method in ['stack']: nxl = number_x_labels nyl = number_z_labels else: nxl = number_x_labels nyl = number_y_labels ax.xaxis.set_major_locator(MaxNLocator(nbins=nxl)) ax.yaxis.set_major_locator(MaxNLocator(nbins=nyl)) if method not in ['surface']: ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # the next lines are to avoid multipliers in axis scale formatter = ScalarFormatter(useOffset=False) ax.xaxis.set_major_formatter(formatter) ax.yaxis.set_major_formatter(formatter) # ------------------------------------------------------------------------------------------------------------------ # Set axis # ------------------------------------------------------------------------------------------------------------------ # set the abscissa axis # ------------------------------------------------------------------------------------------------------------------ # the actual dimension name is the last in the new.dims list dimx = new.dims[-1] x = getattr(new, dimx) if x is not None and x.implements('CoordSet'): # if several coords, take the default ones: x = x.default xsize = new.shape[-1] show_x_points = False if x is not None and hasattr(x, 'show_datapoints'): show_x_points = x.show_datapoints if show_x_points: # remove data and units for display x = LinearCoord.arange(xsize) discrete_data = False if x is not None and (not x.is_empty or x.is_labeled): xdata = x.data if not np.any(xdata): if x.is_labeled: discrete_data = True # take into account the fact that sometimes axis have just labels xdata = range(1, len(x.labels) + 1) else: xdata = range(xsize) xl = [xdata[0], xdata[-1]] xl.sort() if xsize < number_x_labels + 1: # extend the axis so that the labels are not too close to the limits inc = abs(xdata[1] - xdata[0]) * .5 xl = [xl[0] - inc, xl[1] + inc] if data_only: xl = ax.get_xlim() xlim = list(kwargs.get('xlim', xl)) xlim.sort() xlim[-1] = min(xlim[-1], xl[-1]) xlim[0] = max(xlim[0], xl[0]) if kwargs.get('x_reverse', kwargs.get('reverse', x.reversed if x else False)): xlim.reverse() ax.set_xlim(xlim) xscale = kwargs.get("xscale", "linear") ax.set_xscale(xscale) # , nonpositive='mask') # set the ordinates axis # ------------------------------------------------------------------------------------------------------------------ # the actual dimension name is the second in the new.dims list dimy = new.dims[-2] y = getattr(new, dimy) if y is not None and y.implements('CoordSet'): # if several coords, take the default ones: y = y.default ysize = new.shape[-2] show_y_points = False if y is not None and hasattr(y, 'show_datapoints'): show_y_points = y.show_datapoints if show_y_points: # remove data and units for display y = LinearCoord.arange(ysize) if y is not None and (not y.is_empty or y.is_labeled): ydata = y.data if not np.any(ydata): if y.is_labeled: ydata = range(1, len(y.labels) + 1) else: ydata = range(ysize) yl = [ydata[0], ydata[-1]] yl.sort() if ysize < number_y_labels + 1: # extend the axis so that the labels are not too close to the limits inc = abs(ydata[1] - ydata[0]) * .5 yl = [yl[0] - inc, yl[1] + inc] if data_only: yl = ax.get_ylim() ylim = list(kwargs.get("ylim", yl)) ylim.sort() ylim[-1] = min(ylim[-1], yl[-1]) ylim[0] = max(ylim[0], yl[0]) yscale = kwargs.get("yscale", "linear") ax.set_yscale(yscale) # z intensity (by default we plot real component of the data) # ------------------------------------------------------------------------------------------------------------------ if not kwargs.get('imag', False): zdata = new.real.masked_data else: zdata = new.RI.masked_data # new.imag.masked_data #TODO: quaternion case (3 imag.components) zlim = kwargs.get('zlim', (np.ma.min(zdata), np.ma.max(zdata))) if method in ['stack', 'waterfall']: # the z axis info # --------------- # zl = (np.min(np.ma.min(ys)), np.max(np.ma.max(ys))) amp = 0 # np.ma.ptp(zdata) / 50. zl = (np.min(np.ma.min(zdata) - amp), np.max(np.ma.max(zdata)) + amp) zlim = list(kwargs.get('zlim', zl)) zlim.sort() z_reverse = kwargs.get('z_reverse', False) if z_reverse: zlim.reverse() # set the limits # --------------- if yscale == "log" and min(zlim) <= 0: # set the limits wrt smallest and largest strictly positive values ax.set_ylim(10 ** (int(np.log10(np.amin(np.abs(zdata)))) - 1), 10 ** (int(np.log10(np.amax(np.abs(zdata)))) + 1)) else: ax.set_ylim(zlim) else: # the y axis info # ---------------- if data_only: ylim = ax.get_ylim() ylim = list(kwargs.get('ylim', ylim)) ylim.sort() y_reverse = kwargs.get('y_reverse', y.reversed if y else False) if y_reverse: ylim.reverse() # set the limits # ---------------- ax.set_ylim(ylim) # ------------------------------------------------------------------------------------------------------------------ # plot the dataset # ------------------------------------------------------------------------------------------------------------------ ax.grid(prefs.axes_grid) normalize = kwargs.get('normalize', None) cmap = kwargs.get('colormap', kwargs.get('cmap', prefs.colormap)) if method in ['map', 'image', 'surface']: zmin, zmax = zlim zmin = min(zmin, -zmax) zmax = max(-zmin, zmax) norm = mpl.colors.Normalize(vmin=zmin, vmax=zmax) if method in ['surface']: X, Y = np.meshgrid(xdata, ydata) Z = zdata.copy() # masker data not taken into account in surface plot Z[dataset.mask] = np.nan # Plot the surface. #TODO : improve this (or remove it) antialiased = kwargs.get('antialiased', prefs.antialiased) rcount = kwargs.get('rcount', prefs.rcount) ccount = kwargs.get('ccount', prefs.ccount) ax.set_facecolor('w') ax.plot_surface(X, Y, Z, cmap=cmap, linewidth=lw, antialiased=antialiased, rcount=rcount, ccount=ccount, edgecolor='k', norm=norm, ) if method in ['waterfall']: _plot_waterfall(ax, new, xdata, ydata, zdata, prefs, xlim, ylim, zlim, **kwargs) elif method in ['image']: cmap = kwargs.get('cmap', kwargs.get('image_cmap', prefs.image_cmap)) if discrete_data: method = 'map' else: kwargs['nlevels'] = 500 if not hasattr(new, 'clevels') or new.clevels is None: new.clevels = _get_clevels(zdata, prefs, **kwargs) c = ax.contourf(xdata, ydata, zdata, new.clevels, alpha=alpha) c.set_cmap(cmap) c.set_norm(norm) elif method in ['map']: if discrete_data: _colormap = plt.get_cmap(cmap) scalarMap = mpl.cm.ScalarMappable(norm=norm, cmap=_colormap) # marker = kwargs.get('marker', kwargs.get('m', None)) markersize = kwargs.get('markersize', kwargs.get('ms', 5.)) # markevery = kwargs.get('markevery', kwargs.get('me', 1)) for i in ydata: for j in xdata: li, = ax.plot(j, i, lw=lw, marker='o', markersize=markersize) li.set_color(scalarMap.to_rgba(zdata[i - 1, j - 1])) else: # contour plot # ------------- if not hasattr(new, 'clevels') or new.clevels is None: new.clevels = _get_clevels(zdata, prefs, **kwargs) c = ax.contour(xdata, ydata, zdata, new.clevels, linewidths=lw, alpha=alpha) c.set_cmap(cmap) c.set_norm(norm) elif method in ['stack']: # stack plot # ---------- # now plot the collection of lines # -------------------------------- # map colors using the colormap vmin, vmax = ylim norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) # we normalize to the max time if normalize is not None: norm.vmax = normalize _colormap = plt.get_cmap(cmap) scalarMap = mpl.cm.ScalarMappable(norm=norm, cmap=_colormap) # we display the line in the reverse order, so that the last # are behind the first. clear = kwargs.get('clear', True) lines = [] if not clear and not transposed: lines.extend(ax.lines) # keep the old lines line0, = ax.plot(xdata, zdata[0], lw=lw, picker=True) for i in range(zdata.shape[0]): li = cpy(line0) li.set_ydata(zdata[i]) lines.append(li) li.set_color(scalarMap.to_rgba(ydata[i])) fmt = kwargs.get('label_fmt', "{:.5f}") li.set_label(fmt.format(ydata[i])) li.set_zorder(zdata.shape[0] + 1 - i) # store the full set of lines new._ax_lines = lines[:] # but display only a subset of them in order to accelerate the drawing maxlines = kwargs.get('maxlines', prefs.max_lines_in_stack) # debug_('max number of lines %d' % maxlines) setpy = max(len(new._ax_lines) // maxlines, 1) ax.lines = new._ax_lines[::setpy] # displayed ax lines if data_only or method in ['waterfall']: # if data only (we will not set axes and labels # it was probably done already in a previous plot new._plot_resume(dataset, **kwargs) return ax # display a title # ------------------------------------------------------------------------------------------------------------------ title = kwargs.get('title', None) if title: ax.set_title(title) elif kwargs.get('plottitle', False): ax.set_title(new.name) # ------------------------------------------------------------------------------------------------------------------ # labels # ------------------------------------------------------------------------------------------------------------------ # x label # ------------------------------------------------------------------------------------------------------------------ xlabel = kwargs.get("xlabel", None) if show_x_points: xlabel = 'data points' if not xlabel: xlabel = make_label(x, new.dims[-1]) ax.set_xlabel(xlabel) uselabelx = kwargs.get('uselabel_x', False) if x and x.is_labeled and (uselabelx or not np.any(x.data)) and len(x.labels) < number_x_labels + 1: # TODO refine this to use different orders of labels ax.set_xticks(xdata) ax.set_xticklabels(x.labels) # y label # ------------------------------------------------------------------------------------------------------------------ ylabel = kwargs.get("ylabel", None) if show_y_points: ylabel = 'data points' if not ylabel: if method in ['stack']: ylabel = make_label(new, 'values') else: ylabel = make_label(y, new.dims[-2]) # y tick labels uselabely = kwargs.get('uselabel_y', False) if y and y.is_labeled and (uselabely or not np.any(y.data)) and len(y.labels) < number_y_labels: # TODO refine this to use different orders of labels ax.set_yticks(ydata) ax.set_yticklabels(y.labels) # z label # ------------------------------------------------------------------------------------------------------------------ zlabel = kwargs.get("zlabel", None) if not zlabel: if method in ['stack']: zlabel = make_label(y, new.dims[-2]) elif method in ['surface']: zlabel = make_label(new, 'values') ax.set_zlabel(zlabel) else: zlabel = make_label(new, 'z') # do we display the ordinate axis? if kwargs.get('show_y', True): ax.set_ylabel(ylabel) else: ax.set_yticks([]) if 'colorbar' in new.ndaxes: if 'surface' not in method and (not hasattr(new, '_axcb') or not new._axcb): axec = new.ndaxes['colorbar'] axec.name = axec.name + nameadd new._axcb = mpl.colorbar.ColorbarBase(axec, cmap=plt.get_cmap(cmap), norm=norm) new._axcb.set_label(zlabel) # else: # new._fig.colorbar(surf, shrink=0.5, aspect=10) # do we display the zero line if kwargs.get('show_zero', False): ax.haxlines() new._plot_resume(dataset, **kwargs) return ax # ====================================================================================================================== # Waterfall # ====================================================================================================================== def _plot_waterfall(ax, new, xdata, ydata, zdata, prefs, xlim, ylim, zlim, **kwargs): degazim = kwargs.get('azim', 10) degelev = kwargs.get('elev', 30) azim = np.deg2rad(degazim) elev = np.deg2rad(degelev) # transformation function Axes coordinates to Data coordinates def transA2D(x_, y_): return ax.transData.inverted().transform(ax.transAxes.transform((x_, y_))) # expansion in Axes coordinates xe, ze = np.sin(azim), np.sin(elev) incx, incz = transA2D(1 + xe, 1 + ze) - np.array((xlim[-1], zlim[-1])) def fx(y_): return (y_ - ydata[0]) * incx / (ydata[-1] - ydata[0]) def fz(y_): return (y_ - ydata[0]) * incz / (ydata[-1] - ydata[0]) zs = incz * 0.05 base = zdata.min() - zs for i, row in enumerate(zdata): y = ydata[i] x = xdata + fx(y) z = row + fz(y) # row.masked_data[0] ma = z.max() z2 = base + fz(y) line = mpl.lines.Line2D(x, z, color='k') line.set_label(f"{ydata[i]}") line.set_zorder(row.size + 1 - i) poly = plt.fill_between(x, z, z2, alpha=1, facecolors="w", edgecolors="0.85" if 0 < i < ydata.size - 1 else 'k') poly.set_zorder(row.size + 1 - i) try: ax.add_collection(poly) except ValueError: # strange error with tests pass ax.add_line(line) (x0, y0), (x1, _) = transA2D(0, 0), transA2D(1 + xe + .15, 1 + ze) ax.set_xlim((x0, x1)) ax.set_ylim((y0 - zs - .05, ma * 1.1)) ax.set_facecolor('w') ax.vlines(x=xdata[-1] + incx, ymin=zdata.min() - zs + incz, ymax=ax.get_ylim()[-1], color='k') ax.vlines(x=xdata[0] + incx, ymin=zdata.min() - zs + incz, ymax=ax.get_ylim()[-1], color='k') ax.vlines(x=xdata[0], ymin=y0 - zs, ymax=ax.get_ylim()[-1] - incz, color='k', zorder=5000) ax.vlines(x=xdata[0], ymin=y0 - zs, ymax=ax.get_ylim()[-1] - incz, color='k', zorder=5000) x = [xdata[0], xdata[0] + incx, xdata[-1] + incx] z = [ax.get_ylim()[-1] - incz, ax.get_ylim()[-1], ax.get_ylim()[-1]] x2 = [xdata[0], xdata[-1], xdata[-1] + incx] z2 = [y0 - zs, y0 - zs, y0 - zs + incz] poly = plt.fill_between(x, z, z2, alpha=1, facecolors=".95", edgecolors="w") try: ax.add_collection(poly) except ValueError: pass poly = plt.fill_between(x2, z, z2, alpha=1, facecolors=".95", edgecolors="w") try: ax.add_collection(poly) except ValueError: pass line = mpl.lines.Line2D(x, np.array(z), color='k', zorder=50000) ax.add_line(line) line = mpl.lines.Line2D(x2, np.array(z2), color='k', zorder=50000) ax.add_line(line) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['bottom'].set_visible(False) # xticks (xaxis) ticks = ax.get_xticks() newticks = [] xt = sorted(xlim) for tick in ticks: if xt[0] <= tick <= xt[1]: newticks.append(tick) ax.set_xticks(newticks) # yticks (zaxis) ticks = ax.get_yticks() newticks = [] zt = [y0, ax.get_ylim()[-1] - incz] for tick in ticks: if zt[0] <= tick <= zt[1]: newticks.append(tick) _ = ax.set_yticks(newticks) # make yaxis def ctx(x_): return (ax.transData.inverted().transform((x_, 0)) - ax.transData.inverted().transform((0, 0)))[0] yt = [y for y in np.linspace(ylim[0], ylim[-1], 5)] for y in yt: xmin = xdata[-1] + fx(y) xmax = xdata[-1] + fx(y) + ctx(3.5) pos = y0 - zs + fz(y) ax.hlines(pos, xmin, xmax, zorder=50000) lab = ax.text(xmax + ctx(8), pos, f"{y:.0f}", va='center') # display a title # ------------------------------------------------------------------------------------------------------------------ title = kwargs.get('title', None) if title: ax.set_title(title) # ------------------------------------------------------------------------------------------------------------------ # labels # ------------------------------------------------------------------------------------------------------------------ # x label # ------------------------------------------------------------------------------------------------------------------ xlabel = kwargs.get("xlabel", None) if not xlabel: xlabel = make_label(new.x, 'x') ax.set_xlabel(xlabel, x=(ax.bbox._bbox.x0 + ax.bbox._bbox.x1) / 2 - xe) # y label # ------------------------------------------------------------------------------------------------------------------ ylabel = kwargs.get("ylabel", None) if not ylabel: ylabel = make_label(new.y, 'y') ym = (ylim[0] + ylim[1]) / 2 x = xdata[-1] + fx(ym) z = y0 - zs + fz(ym) offset = prefs.font.size * (len(lab._text)) + 30 iz = ax.transData.transform((0, incz + z))[1] - ax.transData.transform((0, z))[1] ix = ax.transData.transform((incx + x, 0))[0] - ax.transData.transform((x, 0))[0] angle = np.rad2deg(np.arctan(iz / ix)) ax.annotate(ylabel, (x, z), xytext=(offset, 0), xycoords='data', textcoords='offset pixels', ha='center', va='center', rotation=angle) # z label # ------------------------------------------------------------------------------------------------------------------ zlabel = kwargs.get("zlabel", None) if not zlabel: zlabel = make_label(new, 'value') # do we display the z axis? if kwargs.get('show_z', True): ax.set_ylabel(zlabel, y=(ax.bbox._bbox.y0 + 1 - ze) / 2) else: ax.set_yticks([]) # ====================================================================================================================== # get clevels # ====================================================================================================================== def _get_clevels(data, prefs, **kwargs): # Utility function to determine contours levels # contours maximum = data.max() # minimum = -maximum nlevels = kwargs.get('nlevels', kwargs.get('nc', prefs.number_of_contours)) start = kwargs.get('start', prefs.contour_start) * maximum negative = kwargs.get('negative', True) if negative < 0: negative = True c = np.arange(nlevels) cl = np.log(c + 1.) clevel = cl * (maximum - start) / cl.max() + start clevelneg = - clevel clevelc = clevel if negative: clevelc = sorted(list(np.concatenate((clevel, clevelneg)))) return clevelc if __name__ == '__main__': pass <file_sep>/tests/test_fitting/test_fit.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import pytest from spectrochempy import Fit, show from spectrochempy.utils.testing import assert_approx_equal @pytest.fixture() def script(): return """ #----------------------------------------------------------- # syntax for parameters definition : # name : value, low_bound, high_bound # * for fixed parameters # $ for variable parameters # > for reference to a parameter in the COMMON block # (> is forbidden in the COMMON block) # common block parameters should not have a _ in their names #----------------------------------------------------------- # COMMON: # common parameters ex. # $ gwidth: 1.0, 0.0, none $ gratio: 0.1, 0.0, 1.0 MODEL: LINE_1 shape: assymvoigtmodel * ampl: 1.0, 0.0, none $ pos: 3620, 3400.0, 3700.0 $ ratio: 0.0147, 0.0, 1.0 $ assym: 0.1, 0, 1 $ width: 200, 0, 1000 MODEL: LINE_2 shape: assymvoigtmodel $ ampl: 0.2, 0.0, none $ pos: 3520, 3400.0, 3700.0 > ratio: gratio $ assym: 0.1, 0, 1 $ width: 200, 0, 1000 """ def test_fit_single_dataset(IR_dataset_2D, script): dataset = IR_dataset_2D[54, 3700.:3400.] f1 = Fit(dataset, script, silent=True) f1.run(maxiter=10, every=1) # assert_approx_equal(dataset.model_A, -116.40475, significant=4) # assert_approx_equal(f1.fp['width_line_2'], 195.7273, significant=4) dataset.plot(plot_model=True) dataset2 = dataset.copy() * 2.34 f2 = Fit(dataset2, script, silent=True) f2.run(maxiter=10, every=1) dataset2.plot(plot_model=True) assert_approx_equal(dataset2.model_A, 272.3309560470805, significant=4) assert_approx_equal(f2.fp['width_line_2'], 195.7273, significant=4) f2 = Fit(dataset2, script, silent=False) f2.run(maxiter=1000, every=1) dataset2.plot(plot_model=True) show() def test_fit_multiple_dataset(IR_dataset_2D, script): dataset = IR_dataset_2D[54, 3700.:3400.] datasets = [dataset.copy(), dataset.copy() * 2.23456] f = Fit(datasets, script, silent=True) f.run(maxiter=10, every=1) assert_approx_equal(datasets[0].model_A, 116.3807504474709, significant=4) assert_approx_equal(datasets[1].model_A, 116.3807504474709 * 2.23456, significant=4) assert_approx_equal(f.fp['width_line_2'], 195.7273, significant=4) # TODO: plotting of multiple datasets # plotr(*datasets, showmodel=True, test=True) <file_sep>/tests/test_dataset/test_ndplot.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy.utils import show def test_plot_generic_1D(IR_dataset_1D): for method in ['scatter', 'lines']: dataset = IR_dataset_1D.copy() dataset.plot(method=method) show() def test_plot_generic_2D(IR_dataset_2D): for method in ['stack', 'map', 'image']: dataset = IR_dataset_2D.copy() dataset.plot(method=method) show() <file_sep>/spectrochempy/utils/print.py import numpy as np import re from colorama import Fore, Style from . import NOMASK from .misc import TYPE_INTEGER, TYPE_COMPLEX, TYPE_FLOAT __all__ = ['numpyprintoptions', 'insert_masked_print', 'TBold', 'TRed', 'TGreen', 'TBlue', 'TCyan', 'TMagenta', 'TYellow', 'colored', 'colored_output', 'pstr', 'convert_to_html'] def pstr(object, **kwargs): if hasattr(object, 'implements') \ and object.implements() in ['NDArray', 'NDComplexArrray', 'NDDataset', 'LinearCoord', 'Coord', 'CoordSet']: return object._cstr(**kwargs).strip() else: return str(object).strip() # ====================================================================================================================== # Terminal colors and styles # ====================================================================================================================== def TBold(text): return Style.BRIGHT + str(text) + Style.RESET_ALL def TRed(text): return Fore.RED + str(text) + Fore.RESET def TGreen(text): return Fore.GREEN + str(text) + Fore.RESET def TBlue(text): return Fore.BLUE + str(text) + Fore.RESET def TMagenta(text): return Fore.MAGENTA + str(text) + Fore.RESET def TYellow(text): return Fore.YELLOW + str(text) + Fore.RESET def TCyan(text): return Fore.CYAN + str(text) + Fore.RESET def TBlack(text): return Fore.BLACK + str(text) + Fore.RESET def colored(text, color): c = getattr(Fore, color) return c + str(text) + Fore.RESET def colored_output(out): regex = r"^(\W*(DIMENSION|DATA).*)$" subst = TBold(r"\1") out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r"^(\W{10}\(_\d{1}\))" subst = TBold(r"\1") out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r'\0{3}([\w\W]*?)\0{3}' subst = TBlack(r"\1") out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r"^(\W{0,12}\w+\W?\w+)(:\W{1}.*$)" subst = TGreen(r"\1") + r"\2" out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r'\0{2}([\w\W]*?)\0{2}' subst = TCyan(r"\1") out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r'\0{1}([\w\W]*?)\0{1}' subst = TBlue(r"\1") out = re.sub(regex, subst, out, 0, re.MULTILINE) return out # # html output # def html_output(out): return out def convert_to_html(obj): tr = "<tr>" \ "<td style='padding-right:5px; padding-bottom:0px; padding-top:0px; width:124px'>{0}</td>" \ "<td style='text-align:left; padding-bottom:0px; padding-top:0px; {2} '>{1}</td><tr>\n" obj._html_output = True out = obj._cstr() regex = r'\0{3}[\w\W]*?\0{3}' # noinspection PyPep8 def subst(match): return "<div>{}</div>".format(match.group(0).replace('\n', '<br/>').replace('\0', '')) out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r"^(\W{0,12}\w+\W?\w+)(:\W{1}.*$)" # r"^(\W*\w+\W?\w+)(:.*$)" subst = r"<font color='green'>\1</font> \2" out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r"^(.*(DIMENSION|DATA).*)$" subst = r"<strong>\1</strong>" out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r"^(\W{10}\(_\d{1}\)).*$" subst = r"<strong>\1</strong>" out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r'\0{2}[\w\W]*?\0{2}' # noinspection PyPep8 def subst(match): return "<div><font color='darkcyan'>{}</font></div>".format( match.group(0).replace('\n', '<br/>').replace('\0', '')) out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r'\0{1}[\w\W]*?\0{1}' # noinspection PyPep8 def subst(match): return "<div><font color='blue'>{}</font></div>".format( match.group(0).replace('\n', '<br/>').replace('\0', '')) out = re.sub(regex, subst, out, 0, re.MULTILINE) regex = r'\.{3}\s+\n' out = re.sub(regex, '', out, 0, re.MULTILINE) html = "<table style='background:transparent'>\n" for line in out.splitlines(): if '</font> :' in line: # keep only first match parts = line.split(':') html += tr.format(parts[0], ':'.join(parts[1:]), 'border:.5px solid lightgray; ') elif '<strong>' in line: html += tr.format(line, '<hr/>', 'padding-top:10px;') html += "</table>" obj._html_output = False return html # ====================================================================================================================== # Printing options # copied from numpy.ma.core to avoid using # the non-public interface of numpy.ma # see the header of numpy.ma.core.py for the license # ====================================================================================================================== class _MaskedPrintOption(object): # """ # Handle the string used to represent missing data in a masked array. # copied from numpy.ma.core # # """ def __init__(self, display): # """ # Create the masked_print_option object. # # """ self._display = display self._enabled = True def display(self): # """ # Display the string to print for masked values. # # """ return self._display def set_display(self, s): # """ # Set the string to print for masked values. # # """ self._display = s def enabled(self): # """ # Is the use of the display value enabled? # # """ return self._enabled def enable(self, shrink=1): # """ # Set the enabling shrink to `shrink`. # # """ self._enabled = shrink def __str__(self): return str(self._display) __repr__ = __str__ def _replace_dtype_fields_recursive(dtype, primitive_dtype): # Private function allowing recursion in _replace_dtype_fields. # -- copied from numpy.ma.core _recurse = _replace_dtype_fields_recursive # Do we have some name fields ? if dtype.names: descr = [] for name in dtype.names: field = dtype.fields[name] if len(field) == 3: # Prepend the title to the name name = (field[-1], name) descr.append((name, _recurse(field[0], primitive_dtype))) new_dtype = np.dtype(descr) # Is this some kind of composite a la (float,2) elif dtype.subdtype: descr = list(dtype.subdtype) descr[0] = _recurse(dtype.subdtype[0], primitive_dtype) new_dtype = np.dtype(tuple(descr)) # this is a primitive type, so do a direct replacement else: new_dtype = primitive_dtype # preserve identity of dtypes if new_dtype == dtype: new_dtype = dtype return new_dtype def _replace_dtype_fields(dtype, primitive_dtype): # """ # Construct a dtype description list from a given dtype. # # Returns a new dtype object, with all fields and subtypes in the given type # recursively replaced with `primitive_dtype`. # # Arguments are coerced to dtypes first. # # -- copied from numpy.ma.core # """ dtype = np.dtype(dtype) primitive_dtype = np.dtype(primitive_dtype) return _replace_dtype_fields_recursive(dtype, primitive_dtype) def _recursive_printoption(result, mask, printopt): # """ # Puts printoptions in result where mask is True. # # Private function allowing for recursion # # copied from numpy.ma.core # """ names = result.dtype.names if names: for name in names: curdata = result[name] curmask = mask[name] _recursive_printoption(curdata, curmask, printopt) else: np.copyto(result, printopt, where=mask) return def insert_masked_print(ds, mask_string='--'): """ Replace masked values with mask_string. -- copied from numpy.ma.core and modified Parameters ----------- ds : |NDDataset| instance mask_string : str """ mask = ds._mask if mask is NOMASK: res = ds._data else: # convert to object array to make filled work data = ds._data # For big arrays, to avoid a costly conversion to the # object dtype, extract the corners before the conversion. print_width = (ds._print_width if ds.ndim > 1 else ds._print_width_1d) for axis in range(ds.ndim): if data.shape[axis] > print_width: ind = print_width // 2 arr = np.split(data, (ind, -ind), axis=axis) data = np.concatenate((arr[0], arr[2]), axis=axis) arr = np.split(mask, (ind, -ind), axis=axis) mask = np.concatenate((arr[0], arr[2]), axis=axis) rdtype = _replace_dtype_fields(ds.dtype, "O") res = data.astype(rdtype) masked_print_option = _MaskedPrintOption(mask_string) _recursive_printoption(res, mask, masked_print_option) return res # ====================================================================================================================== # numpy printoptions # ====================================================================================================================== def numpyprintoptions(precision=4, threshold=6, edgeitems=2, suppress=True, formatter=None, spc=4, linewidth=150, **kargs): """ Method to control array printing Parameters ---------- precision threshold edgeitems suppress formatter spc linewidth kargs """ def _format_object(x): if isinstance(x, _MaskedPrintOption): # a workaround to format masked values # the problem is that is depends on the type # so we have add a type to the passed object: '--' -> '--int64' el = str(x)[2:].split('_') typ = el[0].lower() if 'int' in typ: fmt = "{:>{lspace}s}".format('--', lspace=precision + spc) elif 'float' in typ: fmt = "{:>{lspace}s}".format('--', lspace=2 * precision - 4 + spc) elif 'complex' in typ: fmt = "{:>{lspace}s}".format('--', lspace=4 * precision - 8 + spc) else: fmt = 'n.d.' elif isinstance(x, TYPE_FLOAT): fmt = '{:{lspace}.0{prec}g}'.format( x, prec=precision, # - 1, lspace=precision + spc) elif isinstance(x, TYPE_COMPLEX): fmt = '{:{lspace}.0{prec}g}{:+{lc}.0{prec}g}j'.format( x.real, x.imag, prec=precision - 1, lspace=precision + spc, lc=precision) elif isinstance(x, TYPE_INTEGER): fmt = '{:>{lspace}d}'.format( x, lspace=precision + spc) else: fmt = ' {}'.format(x) return fmt if not formatter: spc = 4 formatter = { 'all': _format_object, } np.set_printoptions(precision=precision, threshold=threshold, edgeitems=edgeitems, suppress=suppress, formatter=formatter, linewidth=linewidth, **kargs) <file_sep>/docs/credits/credits.rst .. _credits: Acknowledgments ================ A part of this program (Reading of TOPSPIN NMR files / digital filter removal) is based on the excellent `nmrglue <www.nmrglue.com>`__ software. [<NAME>, <NAME>, Nmrglue: An open source Python package for the analysis of multidimensional NMR data, J. Biomol. NMR 2013, 55, 355-367. [`doi: 10.1007/s10858-013-9718-x <https://dx.doi.org/10.1007/s10858-013-9718-x>`__]. Reading of Opus file use the `BrukerOpusReader <https://github.com/qedsoftware/brukeropusreader>`_ open source software. <file_sep>/tests/test_processors/test_autosub.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Tests for the ndplugin module """ import numpy as np from spectrochempy import show from spectrochempy.core.processors.autosub import autosub # autosub # ------ def test_autosub(IR_dataset_2D): dataset = IR_dataset_2D ranges = [5000., 5999.], [1940., 1820.] s1 = dataset.copy() ref = s1[-1].squeeze() dataset.plot_stack() ref.plot(clear=False, linewidth=2., color='r') s2 = dataset.copy() s3 = s2.autosub(ref, *ranges, dim=-1, method='vardiff', inplace=False) s3.plot() # inplace = False assert np.round(s2.data[-1, 0], 4) != 0.0000 assert np.round(s3.data[-1, 0], 4) == 0.0000 s3.name = "vardiff" s3.plot_stack() s4 = dataset.copy() s4.autosub(ref, *ranges, method='ssdiff', inplace=True) s4.name = "ssdiff, inplace" assert np.round(s4.data[-1, 0], 4) == 0.0000 s4.plot_stack() # true avoid blocking due to graphs s4 = dataset.copy() s = autosub(s4, ref, *ranges, method='ssdiff') assert np.round(s4.data[-1, 0], 4) != 0.0000 assert np.round(s.data[-1, 0], 4) == 0.0000 s.name = 'ssdiff direct call' s.plot_stack() # s5 = dataset.copy() # ref2 = s5[:, 0].squeeze() # ranges2 = [0, 5], [45, 54] # TODO: not yet implemented # s6 = s5.autosub(ref2, *ranges2, dim='y', method='varfit', inplace=False) # s6.plot() show() <file_sep>/tests/test_fitting/test_lstsq.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import numpy as np import matplotlib.pyplot as plt import spectrochempy.core as sc # ............................................................................ def test_lstsq_from_scratch(): t = sc.NDDataset(data=[0, 1, 2, 3], title='time', units='hour') d = sc.NDDataset(data=[-1, 0.2, 0.9, 2.1], title='distance', units='kilometer') # We would like v and d0 such as # d = v.t + d0 lstsq = sc.LSTSQ(t, d) v, d0 = lstsq.transform() assert np.around(v.magnitude) == 1 assert np.around(d0.magnitude, 2) == -0.95 assert v.units == d.units / t.units plt.plot(t.data, d.data, 'o', label='Original data', markersize=5) dfit = lstsq.inverse_transform() plt.plot(t.data, dfit.data, ':r', label='Fitted line') plt.legend() sc.show() # ............................................................................ def test_implicit_lstsq(): t = sc.Coord(data=[0, 1, 2, 3], units='hour', title='time') d = sc.NDDataset(data=[-1, 0.2, 0.9, 2.1], coordset=[t], units='kilometer', title='distance') assert d.ndim == 1 # We would like v and d0 such as # d = v.t + d0 lstsq = sc.LSTSQ(d) # v, d0 = lstsq.transform() print(v, d0) d.plot_scatter(pen=False, markersize=10, mfc='r', mec='k') dfit = lstsq.inverse_transform() dfit.plot_pen(clear=False, color='g') sc.show() def test_lstq_2D(): pass # St_i = np.linalg.lstsq(C_i, X.data)[0] # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/spectrochempy/matplotlib_preferences.py # -*- coding: utf-8 -*- # ===================================================================================================================== # Copyright (©) 2015-$today.year LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # ===================================================================================================================== # import matplotlib as mpl from matplotlib import pyplot as plt from matplotlib.lines import Line2D from traitlets import (Bool, Unicode, Tuple, List, Integer, Float, Enum, observe, All, default, TraitError, Union, Set) from spectrochempy.utils import MetaConfigurable, get_pkg_path, pathclean from spectrochempy.core import debug_ # ---------------------------------------------------------------------------------------------------------------------- # available matplotlib styles (equivalent of plt.style.available) # ---------------------------------------------------------------------------------------------------------------------- def available_styles(): """ All matplotlib `styles <https://matplotlib.org/users/style_sheets.html>`_ which are available in |scpy| Returns ------- A list of matplotlib styles """ # Todo: Make this list extensible programmatically (adding files to stylelib) cfgdir = mpl.get_configdir() stylelib = pathclean(cfgdir) / 'stylelib' styles = plt.style.available if stylelib.is_dir(): listdir = stylelib.glob('*.mplstyle') for style in listdir: styles.append(style.stem) styles = list(set(styles)) # in order to remove possible duplicates return styles class MatplotlibPreferences(MetaConfigurable): """ This is a port of matplotlib.rcParams to our configuration system (traitlets) """ name = Unicode("MatplotlibPreferences") description = Unicode("Options for Matplotlib") updated = Bool(False) _groups = Set(Unicode) _subgroups = Set(Unicode) _members = Set(Unicode) # ------------------------------------------------------------------------------------------------------------------ # Configuration entries based on the classic matplotlib style # ------------------------------------------------------------------------------------------------------------------ # # LINES # See http://matplotlib.org/api/artist_api.html#module-matplotlib.lines for more # information on line properties. # lines_linewidth = Float(0.75, help=r'''line width in points''').tag(config=True, kind='') lines_linestyle = Enum(list(Line2D.lineStyles.keys()), default_value='-', help=r'''solid line''').tag(config=True, kind='') lines_color = Unicode('b', help=r'''has no affect on plot(); see axes.prop_cycle''').tag(config=True, kind='color') lines_marker = Enum(list(Line2D.markers.keys()), default_value='None', help=r'''the default marker''').tag( config=True, kind='') lines_markerfacecolor = Unicode('auto', help=r'''the default markerfacecolor''').tag(config=True, kind='color') lines_markeredgecolor = Unicode('auto', help=r'''the default markeredgecolor''').tag(config=True, kind='color') lines_markeredgewidth = Float(0.0, help=r'''the line width around the marker symbol''').tag(config=True, kind='') lines_markersize = Float(7.0, help=r'''markersize, in points''').tag(config=True, kind='') lines_dash_joinstyle = Enum(['miter', 'round', 'bevel'], default_value='round', help=r'''miter|round|bevel''').tag( config=True, kind='') lines_dash_capstyle = Enum(['butt', 'round', 'projecting'], default_value='butt', help=r'''butt|round|projecting''').tag(config=True, kind='') lines_solid_joinstyle = Enum(['miter', 'round', 'bevel'], default_value='round', help=r'''miter|round|bevel''').tag( config=True, kind='') lines_solid_capstyle = Enum(['butt', 'round', 'projecting'], default_value='round', help=r'''butt|round|projecting''').tag(config=True, kind='') lines_antialiased = Bool(True, help=r'''render lines in antialiased (no jaggies)''').tag(config=True, kind='') lines_dashed_pattern = Tuple((6.0, 6.0), help=r'''''').tag(config=True, kind='') lines_dashdot_pattern = Tuple((3.0, 5.0, 1.0, 5.0), help=r'''''').tag(config=True, kind='') lines_dotted_pattern = Tuple((1.0, 3.0), help=r'''''').tag(config=True, kind='') lines_scale_dashes = Bool(False, help=r'''''').tag(config=True, kind='') # # Marker props # markers_fillstyle = Enum('full|left|right|bottom|top|none'.split('|'), default_value='full', help=r'''full|left|right|bottom|top|none''').tag(config=True, kind='') # # PATCHES # Patches are graphical objects that fill 2D space, like polygons or # circles. See # http://matplotlib.org/api/artist_api.html#module-matplotlib.patches # information on patch properties # patch_linewidth = Float(0.3, help=r'''edge width in points.''').tag(config=True, kind='') patch_facecolor = Unicode('4C72B0', help=r'''''').tag(config=True, kind='color') patch_edgecolor = Unicode('black', help=r'''if forced, or patch is not filled''').tag(config=True, kind='color') patch_force_edgecolor = Bool(False, help=r'''True to always use edgecolor''').tag(config=True, kind='') patch_antialiased = Bool(True, help=r'''render patches in antialiased (no jaggies)''').tag(config=True, kind='') hatch_color = Unicode('black', help=r'''''').tag(config=True, kind='color') hatch_linewidth = Float(1.0, help=r'''''').tag(config=True, kind='') # # FONT # # font properties used by text.Text. See # http://matplotlib.org/api/font_manager_api.html for more # information on font properties. The 6 font properties used for font # matching are given below with their default values. # # The font.family property has five values: 'serif' (e.g., Times), # 'sans-serif' (e.g., Helvetica), 'cursive' (e.g., Zapf-Chancery), # 'fantasy' (e.g., Western), and 'monospace' (e.g., Courier). Each of # these font families has a default list of font names in decreasing # order of priority associated with them. When text.usetex is False, # font.family may also be one or more concrete font names. # # The font.style property has three values: normal (or roman), italic # or oblique. The oblique style will be used for italic, if it is not # present. # # The font.variant property has two values: normal or small-caps. For # TrueType fonts, which are scalable fonts, small-caps is equivalent # to using a font size of 'smaller', or about 83% of the current font # size. # # The font.weight property has effectively 13 values: normal, bold, # bolder, lighter, 100, 200, 300, ..., 900. Normal is the same as # 400, and bold is 700. bolder and lighter are relative values with # respect to the current weight. # # The font.stretch property has 11 values: ultra-condensed, # extra-condensed, condensed, semi-condensed, normal, semi-expanded, # expanded, extra-expanded, ultra-expanded, wider, and narrower. This # property is not currently implemented. # # The font.size property is the default font size for text, given in pts. # 12pt is the standard value. # font_family = Enum(['sans-serif', 'serif', 'cursive', 'monospace', 'fantasy'], default_value='sans-serif', help=r'''sans-serif|serif|cursive|monospace|fantasy''').tag(config=True, kind='') font_style = Enum(['normal', 'roman', 'italic', 'oblique'], default_value='normal', help=r'''normal (or roman), italic or oblique''').tag(config=True, kind='') font_variant = Enum(['normal', 'small-caps'], default_value='normal', help=r'''''').tag(config=True, kind='') font_weight = Enum([100, 200, 300, 'normal', 400, 500, 600, 'bold', 700, 800, 900, 'bolder', 'lighter'], default_value='normal', help=r'''100|200|300|normal or 400|500|600|bold or 700|800|900|bolder|lighter''').tag( config=True, kind='') font_stretch = Unicode('normal', help=r'''''') # not implemented # note that font.size controls default text sizes. To configure # special text sizes tick labels, axes, labels, title, etc, see the # settings for axes and ticks. Special text sizes can be defined # relative to font.size, using the following values: xx-small, x-small, # small, medium, large, x-large, xx-large, larger, or smaller font_size = Float(10.0, help=r'''The default fontsize. Special text sizes can be defined relative to font.size, using the following values: xx-small, x-small, small, medium, large, x-large, xx-large, larger, or smaller''').tag(config=True, kind='') # TEXT # text properties used by text.Text. See # http://matplotlib.org/api/artist_api.html#module-matplotlib.text for more # information on text properties # text_color = Unicode('.15', help=r'''''').tag(config=True, kind='color') # # LaTeX customizations. See http://www.scipy.org/Wiki/Cookbook/Matplotlib/UsingTex # text_usetex = Bool(False, help=r'''use latex for all text handling. The following fonts are supported through the usual rc parameter settings: new century schoolbook, bookman, times, palatino, zapf chancery, charter, serif, sans-serif, helvetica, avant garde, courier, monospace, computer modern roman, computer modern sans serif, computer modern typewriter. If another font is desired which can loaded using the LaTeX \usepackage command, please inquire at the matplotlib mailing list''').tag(config=True, kind='') latex_preamble = Unicode(r"""\usepackage{siunitx} \sisetup{detect-all} \usepackage{times} # set the normal font here \usepackage{sansmath} # load up the sansmath so that math -> helvet \sansmath """, help=r'''Latex preamble for matplotlib outputs IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES. preamble is a comma separated list of LaTeX statements that are included in the LaTeX document preamble. An example: text.latex.preamble : \usepackage{bm},\usepackage{euler} The following packages are always loaded with usetex, so beware of package collisions: color, geometry, graphicx, type1cm, textcomp. Adobe Postscript (PSSNFS) font packages may also be loaded, depending on your font settings.''').tag(config=True, kind='') text_hinting = Enum(['none', 'auto', 'native', 'either'], default_value='auto', help=r'''May be one of the following: 'none': Perform no hinting * 'auto': Use freetype's autohinter * 'native': Use the hinting information in the font file, if available, and if your freetype library supports it * 'either': Use the native hinting information or the autohinter if none is available. For backward compatibility, this value may also be True === 'auto' or False === 'none'.''').tag(config=True) text_hinting_factor = Float(8, help=r'''Specifies the amount of softness for hinting in the horizontal direction. A value of 1 will hint to full pixels. A value of 2 will hint to half pixels etc.''').tag(config=True, kind='') text_antialiased = Bool(True, help=r'''If True (default), the text will be antialiased. This only affects the Agg backend.''').tag(config=True, kind='') # The following settings allow you to select the fonts in math mode. # They map from a TeX font name to a fontconfig font pattern. # These settings are only used if mathtext.fontset is 'custom'. # Note that this "custom" mode is unsupported and may go away in the # future. mathtext_cal = Unicode('cursive', help=r'''''').tag(config=True, kind='') mathtext_rm = Unicode('dejavusans', help=r'''''').tag(config=True, kind='') mathtext_tt = Unicode('monospace', help=r'''''').tag(config=True, kind='') mathtext_it = Unicode("dejavusans:italic", help=r'''italic''').tag(config=True, kind='') mathtext_bf = Unicode("dejavusans:bold", help=r'''bold''').tag(config=True, kind='') mathtext_sf = Unicode('sans\-serif', help=r'''''').tag(config=True, kind='') # noqa: W605 mathtext_fontset = Unicode('dejavusans', help=r'''Should be "dejavusans" (default), "dejavuserif", "cm" (Computer Modern), "stix", "stixsans" or "custom"''').tag( config=True, kind='') mathtext_fallback_to_cm = Bool(False, help=r'''When True, use symbols from the Computer Modern fonts when a symbol can not be found in one of the custom math fonts.''').tag(config=True, kind='') mathtext_default = Unicode('regular', help=r'''The default font to use for math. Can be any of the LaTeX font names, including the special name "regular" for the same font used in regular text.''').tag(config=True, kind='') # # AXES # default face and edge color, default tick sizes, # default fontsizes for ticklabels, and so on. See # http://matplotlib.org/api/axes_api.html#module-matplotlib.axes # axes_facecolor = Unicode('F0F0F0', help=r'''axes background color''').tag(config=True, kind='color') axes_edgecolor = Unicode('black', help=r'''axes edge color''').tag(config=True, kind='color') axes_linewidth = Float(0.8, help=r'''edge linewidth''').tag(config=True, kind='') axes_grid = Bool(False, help=r'''display grid or not''').tag(config=True, kind='') axes_grid_which = Unicode('major').tag(config=True, kind='') axes_grid_axis = Unicode('both').tag(config=True, kind='') axes_titlesize = Float(14.0, help=r'''fontsize of the axes title''').tag(config=True, kind='') axes_titley = Float(1.0, help=r'''at the top, no autopositioning.''').tag(config=True, kind='') axes_titlepad = Float(5.0, help=r'''pad between axes and title in points''').tag(config=True, kind='') axes_titleweight = Unicode('normal', help=r'''font weight for axes title''').tag(config=True, kind='') axes_labelsize = Float(10.0, help=r'''fontsize of the x any y labels''').tag(config=True, kind='') axes_labelpad = Float(4.0, help=r'''space between label and axis''').tag(config=True, kind='') axes_labelweight = Unicode('normal', help=r'''weight of the x and y labels''').tag(config=True, kind='') axes_labelcolor = Unicode('black', help=r'''''').tag(config=True, kind='color') axes_axisbelow = Bool(True, help=r'''whether axis gridlines and ticks are below the axes elements (lines, text, etc)''').tag(config=True, kind='') axes_formatter_limits = Tuple((-5, 6), help=r'use scientific notation if log10 of the axis range is smaller than the ' r'first or larger than the second').tag(config=True, kind='') axes_formatter_use_locale = Bool(False, help=r'''When True, format tick labels according to the user"s locale. For example, use "," as a decimal separator in the fr_FR locale.''').tag( config=True, kind='') axes_formatter_use_mathtext = Bool(False, help=r'''When True, use mathtext for scientific notation.''').tag( config=True, kind='') axes_formatter_useoffset = Bool(True, help=r'''If True, the tick label formatter will default to labeling ticks relative to an offset when the data range is small compared to the minimum absolute value of the data.''').tag(config=True, kind='') axes_formatter_offset_threshold = Integer(4, help=r'''When useoffset is True, the offset will be used when it can remove at least this number of significant digits from tick labels.''').tag( config=True, kind='') axes_unicode_minus = Bool(True, help=r'''use unicode for the minus symbol rather than hyphen. See http://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes''').tag(config=True, kind='') axes_prop_cycle = Unicode("cycler('color', ['007200', '009E73', 'D55E00', 'CC79A7', 'F0E442', '56B4E9'])", help=r'''color cycle for plot lines as list of string colorspecs: single letter, long name, or web-style hex''').tag(config=True, kind='function') axes_autolimit_mode = Unicode('data', help=r'''How to scale axes limits to the data. Use "data" to use data limits, plus some margin. Use "round_number" move to the nearest "round" number''').tag( config=True, kind='') axes_xmargin = Float(0.05, help=r'''x margin. See `axes.Axes.margins`''').tag(config=True, kind='') axes_ymargin = Float(0.05, help=r'''y margin See `axes.Axes.margins`''').tag(config=True, kind='') axes_spines_bottom = Bool(True).tag(config=True, kind='') axes_spines_left = Bool(True).tag(config=True, kind='') axes_spines_right = Bool(True).tag(config=True, kind='') axes_spines_top = Bool(True).tag(config=True, kind='') polaraxes_grid = Bool(True, help=r'''display grid on polar axes''').tag(config=True, kind='') axes3d_grid = Bool(True, help=r'''display grid on 3d axes''').tag(config=True, kind='') # # DATE # timezone = Unicode('UTC', help=r'''a pytz timezone string, e.g., US/Central or Europe/Paris''').tag(config=True, kind='') date_autoformatter_year = Unicode('%Y').tag(config=True, kind='') date_autoformatter_month = Unicode('%b %Y').tag(config=True, kind='') date_autoformatter_day = Unicode('%b %d %Y').tag(config=True, kind='') date_autoformatter_hour = Unicode('%H:%M:%S').tag(config=True, kind='') date_autoformatter_minute = Unicode('%H:%M:%S.%f').tag(config=True, kind='') date_autoformatter_second = Unicode('%H:%M:%S.%f').tag(config=True, kind='') date_autoformatter_microsecond = Unicode('%H:%M:%S.%f').tag(config=True, kind='') # # TICKS # see http://matplotlib.org/api/axis_api.html#matplotlib.axis.Tick # xtick_top = Bool(False, help=r'''draw ticks on the top side''').tag(config=True, kind='') xtick_bottom = Bool(True, help=r'''draw ticks on the bottom side''').tag(config=True, kind='') xtick_major_size = Float(3.5, help=r'''major tick size in points''').tag(config=True, kind='') xtick_minor_size = Float(2.0, help=r'''minor tick size in points''').tag(config=True, kind='') xtick_major_width = Float(0.8, help=r'''major tick width in points''').tag(config=True, kind='') xtick_minor_width = Float(0.6, help=r'''minor tick width in points''').tag(config=True, kind='') xtick_major_pad = Float(3.5, help=r'''distance to major tick label in points''').tag(config=True, kind='') xtick_minor_pad = Float(3.4, help=r'''distance to the minor tick label in points''').tag(config=True, kind='') xtick_color = Unicode('.15', help=r'''color of the tick labels''').tag(config=True, kind='color') xtick_labelsize = Float(10.0, help=r'''fontsize of the tick labels''').tag(config=True, kind='') xtick_direction = Unicode('out', help=r'''direction''').tag(config=True, kind='') xtick_minor_visible = Bool(False, help=r'''visibility of minor ticks on x-axis''').tag(config=True, kind='') xtick_major_top = Bool(True, help=r'''draw x axis top major ticks''').tag(config=True, kind='') xtick_major_bottom = Bool(True, help=r'''draw x axis bottom major ticks''').tag(config=True, kind='') xtick_minor_top = Bool(True, help=r'''draw x axis top minor ticks''').tag(config=True, kind='') xtick_minor_bottom = Bool(True, help=r'''draw x axis bottom minor ticks''').tag(config=True, kind='') ytick_left = Bool(True, help=r'''draw ticks on the left side''').tag(config=True, kind='') ytick_right = Bool(False, help=r'''draw ticks on the right side''').tag(config=True, kind='') ytick_major_size = Float(3.5, help=r'''major tick size in points''').tag(config=True, kind='') ytick_minor_size = Float(2.0, help=r'''minor tick size in points''').tag(config=True, kind='') ytick_major_width = Float(0.8, help=r'''major tick width in points''').tag(config=True, kind='') ytick_minor_width = Float(0.6, help=r'''minor tick width in points''').tag(config=True, kind='') ytick_major_pad = Float(3.5, help=r'''distance to major tick label in points''').tag(config=True, kind='') ytick_minor_pad = Float(3.4, help=r'''distance to the minor tick label in points''').tag(config=True, kind='') ytick_color = Unicode('.15', help=r'''color of the tick labels''').tag(config=True, kind='color') ytick_labelsize = Float(10.0, help=r'''fontsize of the tick labels''').tag(config=True, kind='') ytick_direction = Unicode('out', help=r'''direction''').tag(config=True, kind='') ytick_minor_visible = Bool(False, help=r'''visibility of minor ticks on y-axis''').tag(config=True, kind='') ytick_major_left = Bool(True, help=r'''draw y axis left major ticks''').tag(config=True, kind='') ytick_major_right = Bool(True, help=r'''draw y axis right major ticks''').tag(config=True, kind='') ytick_minor_left = Bool(True, help=r'''draw y axis left minor ticks''').tag(config=True, kind='') ytick_minor_right = Bool(True, help=r'''draw y axis right minor ticks''').tag(config=True, kind='') # # GRIDS # grid_color = Unicode('.85', help=r'''grid color''').tag(config=True, kind='color') grid_linestyle = Enum(list(Line2D.lineStyles.keys()), default_value='-', help=r'''solid''').tag(config=True, kind='') grid_linewidth = Float(0.85, help=r'''in points''').tag(config=True, kind='') grid_alpha = Float(1.0, help=r'''transparency, between 0.0 and 1.0''').tag(config=True, kind='') legend_loc = Unicode('best', help=r'''''').tag(config=True, kind='') legend_frameon = Bool(False, help=r'''if True, draw the legend on a background patch''').tag(config=True, kind='') # # LEGEND # legend_framealpha = Union((Float(0.8), Unicode('None')), help=r'''legend patch transparency''').tag(config=True, kind='', default=0.0) legend_facecolor = Unicode('inherit', help=r'''inherit from axes.facecolor; or color spec''').tag(config=True, kind='color') legend_edgecolor = Unicode('0.8', help=r'''background patch boundary color''').tag(config=True, kind='color') legend_fancybox = Bool(True, help=r'''if True, use a rounded box for the legend background, else a rectangle''').tag( config=True, kind='') legend_shadow = Bool(False, help=r'''if True, give background a shadow effect''').tag(config=True, kind='') legend_numpoints = Integer(1, help=r'''the number of marker points in the legend line''').tag(config=True, kind='') legend_scatterpoints = Integer(1, help=r'''number of scatter points''').tag(config=True, kind='') legend_markerscale = Float(1.0, help=r'''the relative size of legend markers vs. original''').tag(config=True, kind='') legend_fontsize = Float(9.0, help=r'''''').tag(config=True, kind='') legend_borderpad = Float(0.4, help=r'''border whitespace''').tag(config=True, kind='') legend_labelspacing = Float(0.2, help=r'''the vertical space between the legend entries''').tag(config=True, kind='') legend_handlelength = Float(2.0, help=r'''the length of the legend lines''').tag(config=True, kind='') legend_handleheight = Float(0.7, help=r'''the height of the legend handle''').tag(config=True, kind='') legend_handletextpad = Float(0.1, help=r'''the space between the legend line and legend text''').tag(config=True, kind='') legend_borderaxespad = Float(0.5, help=r'''the border between the axes and legend edge''').tag(config=True, kind='') legend_columnspacing = Float(0.5, help=r'''column separation''').tag(config=True, kind='') figure_titlesize = Float(12.0, help=r'''size of the figure title (Figure.suptitle())''').tag(config=True, kind='') figure_titleweight = Unicode('normal', help=r'''weight of the figure title''').tag(config=True, kind='') figure_figsize = Tuple((6.8, 4.4), help=r'''figure size in inches''').tag(config=True, kind='') figure_dpi = Float(96.0, help=r'''figure dots per inch''').tag(config=True, kind='') figure_facecolor = Unicode('white', help=r'''figure facecolor; 0.75 is scalar gray''').tag(config=True, kind='color') figure_edgecolor = Unicode('white', help=r'''figure edgecolor''').tag(config=True, kind='color') figure_autolayout = Bool(True, help=r'''When True, automatically adjust subplot parameters to make the plot fit the figure''').tag(config=True, kind='') # # FIGURE # See http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure # figure_max_open_warning = Integer(30, help=r'''The maximum number of figures to open through the pyplot interface before emitting a warning. If less than one this feature is disabled.''').tag(config=True, kind='') figure_subplot_left = Float(0.15, help=r'''the left side of the subplots of the figure''').tag(config=True, kind='') figure_subplot_right = Float(0.95, help=r'''the right side of the subplots of the figure''').tag(config=True, kind='') figure_subplot_bottom = Float(0.12, help=r'''the bottom of the subplots of the figure''').tag(config=True, kind='') figure_subplot_top = Float(0.98, help=r'''the top of the subplots of the figure''').tag(config=True, kind='') figure_subplot_wspace = Float(0.0, help=r'''the amount of width reserved for blank space between subplots, expressed as a fraction of the average axis width''').tag(config=True, kind='') figure_subplot_hspace = Float(0.0, help=r'''the amount of height reserved for white space between subplots, expressed as a fraction of the average axis height''').tag(config=True, kind='') figure_frameon = Bool(True, help='Show figure frame').tag(config=True) # # IMAGES # image_aspect = Unicode('equal', help=r'''equal | auto | a number''').tag(config=True, kind='') image_interpolation = Unicode('antialiased', help=r'''see help(imshow) for options''').tag(config=True, kind='') image_cmap = Enum(plt.colormaps(), default_value='viridis', help=r'''A colormap name, gray etc...''').tag( config=True, kind='') image_lut = Integer(256, help=r'''the size of the colormap lookup table''').tag(config=True, kind='') image_origin = Unicode('upper', help=r'''lower | upper''').tag(config=True, kind='') image_resample = Bool(True, help=r'''''').tag(config=True, kind='') image_composite_image = Bool(True, help=r'''When True, all the images on a set of axes are combined into a single composite image before saving a figure as a vector graphics file, such as a PDF.''').tag(config=True, kind='') # # CONTOUR PLOTS # contour_negative_linestyle = Enum(['dashed', 'solid'], default_value='dashed', help=r'''dashed | solid''').tag( config=True, kind='') contour_corner_mask = Enum([True, False, 'legacy'], default_value=True, help=r'''True | False | legacy''').tag( config=True, kind='') # # ERRORBAR # errorbar_capsize = Float(1.0, help=r'''length of end cap on error bars in pixels''').tag(config=True, kind='') # # HIST # hist_bins = Union((Unicode('auto'), Integer(10)), help=r'''The default number of histogram bins. If Numpy 1.11 or later is installed, may also be `auto`''').tag(config=True, kind='', default='auto') # # SCATTER # scatter_marker = Enum(list(Line2D.markers.keys()), default_value='o', help=r'''The default marker type for scatter plots.''').tag(config=True, kind='') # # SAVING FIGURES # savefig_dpi = Unicode('300', help=r'''figure dots per inch or "figure"''').tag(config=True, kind='') savefig_facecolor = Unicode('white', help=r'''figure facecolor when saving''').tag(config=True, kind='color') savefig_edgecolor = Unicode('white', help=r'''figure edgecolor when saving''').tag(config=True, kind='color') savefig_format = Enum(['png', 'ps', 'pdf', 'svg'], default_value='png', help=r'''png, ps, pdf, svg''').tag( config=True, kind='') savefig_bbox = Enum(["tight", "standard"], default_value='standard', help=r'''"tight" or "standard". "tight" is incompatible with pipe-based animation backends but will workd with temporary file based ones: e.g. setting animation.writer to ffmpeg will not work, use ffmpeg_file instead''').tag(config=True, kind='') savefig_pad_inches = Float(0.1, help=r'''Padding to be used when bbox is set to "tight"''').tag(config=True, kind='') savefig_jpeg_quality = Integer(95, help=r'''when a jpeg is saved, the default quality parameter.''').tag( config=True, kind='') savefig_directory = Unicode("", help=r'''default directory in savefig dialog box, leave empty to always use current working directory''').tag(config=True, kind='') savefig_transparent = Bool(False, help=r'''setting that controls whether figures are saved with a transparent background by default''').tag(config=True, kind='') # # Agg rendering # agg_path_chunksize = Integer(20000, help=r'''0 to disable; values in the range 10000 to 100000 can improve speed slightly and prevent an Agg rendering failure when plotting very large data sets, especially if they are very gappy. It may cause minor artifacts, though. A value of 20000 is probably a good starting point.''').tag(config=True, kind='') path_simplify = Bool(True, help=r'''When True, simplify paths by removing "invisible" points to reduce file size and increase rendering speed''').tag(config=True, kind='') path_simplify_threshold = Float(0.111111111111, help=r'''The threshold of similarity below which vertices will be removed in the simplification process''').tag(config=True, kind='') path_snap = Bool(True, help=r'''When True, rectilinear axis-aligned paths will be snapped to the nearest pixel when certain criteria are met. When False, paths will never be snapped.''').tag(config=True, kind='') path_sketch = Unicode('None', help=r'''May be none, or a 3-tuple of the form (scale, length, randomness). *scale* is the amplitude of the wiggle perpendicular to the line (in pixels). *length* is the length of the wiggle along the line (in pixels). *randomness* is the factor by which the length is randomly scaled.''').tag(config=True, kind='') # ================================================================================================================== # NON MATPLOTLIB OPTIONS # ================================================================================================================== style = Union((Unicode(), List(), Tuple()), help='Basic matplotlib style to use').tag(config=True, default_='scpy') stylesheets = Unicode(help='Directory where to look for local defined matplotlib styles when they are not in the ' ' standard location').tag(config=True, type="folder") use_plotly = Bool(False, help='Use Plotly instead of MatPlotLib for plotting (mode Matplotlib more suitable for ' 'printing publication ready figures)').tag(config=True) method_1D = Enum(['pen', 'scatter', 'scatter+pen', 'bar'], default_value='pen', help='Default plot methods for 1D datasets').tag(config=True) method_2D = Enum(['map', 'image', 'stack', 'surface', '3D'], default_value='stack', help='Default plot methods for 2D datasets').tag(config=True) method_3D = Enum(['surface'], default_value='surface', help='Default plot methods for 3D datasets').tag(config=True) # - 2d # ------ colorbar = Bool(False, help='Show color bar for 2D plots').tag(config=True) show_projections = Bool(False, help='Show all projections').tag(config=True) show_projection_x = Bool(False, help='Show projection along x').tag(config=True) show_projection_y = Bool(False, help='Show projection along y').tag(config=True) colormap = Enum(plt.colormaps(), default_value='viridis', help=r'''A colormap name, gray etc... (equivalent to image_cmap''').tag(config=True) max_lines_in_stack = Integer(1000, min=1, help='Maximum number of lines to plot in stack plots').tag(config=True) simplify = Bool(help='Matplotlib path simplification for improving performance').tag(config=True, group='mpl') # -1d # ---_ # antialias = Bool(True, help='Antialiasing') number_of_x_labels = Integer(5, min=3, help='Number of X labels').tag(config=True) number_of_y_labels = Integer(5, min=3, help='Number of Y labels').tag(config=True) number_of_z_labels = Integer(5, min=3, help='Number of Z labels').tag(config=True) number_of_contours = Integer(50, min=10, help='Number of contours').tag(config=True) contour_alpha = Float(1.00, min=0., max=1.0, help='Transparency of the contours').tag(config=True) contour_start = Float(0.05, min=0.001, help='Fraction of the maximum for starting contour levels').tag(config=True) antialiased = Bool(True, help='antialiased option for surface plot').tag(config=True) rcount = Integer(50, help='rcount (steps in the row mode) for surface plot').tag(config=True) ccount = Integer(50, help='ccount (steps in the column mode) for surface plot').tag(config=True) # .................................................................................................................. def __init__(self, **kwargs): super().__init__(jsonfile='MatplotlibPreferences', **kwargs) for key in plt.rcParams: lis = key.split('.') if len(lis) > 1: self._groups.add(lis.pop(0)) if len(lis) > 1: self.subgroups.add(lis.pop(0)) if len(lis) > 1: raise NotImplementedError self._members.add(lis[0]) @property def available_styles(self): return available_styles() @property def members(self): return self.members @property def groups(self): return self._groups @property def subgroups(self): return self._subgroups def set_latex_font(self, family=None): def update_rcParams(): mpl.rcParams['text.usetex'] = self.text_usetex mpl.rcParams['mathtext.fontset'] = self.mathtext_fontset mpl.rcParams['mathtext.bf'] = self.mathtext_bf mpl.rcParams['mathtext.cal'] = self.mathtext_cal mpl.rcParams['mathtext.default'] = self.mathtext_default mpl.rcParams['mathtext.rm'] = self.mathtext_rm mpl.rcParams['mathtext.it'] = self.mathtext_it if family is None: family = self.font_family # take the current one if family == 'sans-serif': self.text_usetex = False self.mathtext_fontset = 'dejavusans' self.mathtext_bf = 'dejavusans:bold' self.mathtext_cal = 'cursive' self.mathtext_default = 'regular' self.mathtext_rm = 'dejavusans' self.mathtext_it = 'dejavusans:italic' update_rcParams() elif family == 'serif': self.text_usetex = False self.mathtext_fontset = 'dejavuserif' self.mathtext_bf = 'dejavuserif:bold' self.mathtext_cal = 'cursive' self.mathtext_default = 'regular' self.mathtext_rm = 'dejavuserif' self.mathtext_it = 'dejavuserif:italic' update_rcParams() elif family == 'cursive': self.text_usetex = False self.mathtext_fontset = 'custom' self.mathtext_bf = 'cursive:bold' self.mathtext_cal = 'cursive' self.mathtext_default = 'regular' self.mathtext_rm = 'cursive' self.mathtext_it = 'cursive:italic' update_rcParams() elif family == 'monospace': self.text_usetex = False mpl.rcParams['mathtext.fontset'] = 'custom' mpl.rcParams['mathtext.bf'] = 'monospace:bold' mpl.rcParams['mathtext.cal'] = 'cursive' mpl.rcParams['mathtext.default'] = 'regular' mpl.rcParams['mathtext.rm'] = 'monospace' mpl.rcParams['mathtext.it'] = 'monospace:italic' elif family == 'fantasy': self.text_usetex = False mpl.rcParams['mathtext.fontset'] = 'custom' mpl.rcParams['mathtext.bf'] = 'Humor Sans:bold' mpl.rcParams['mathtext.cal'] = 'cursive' mpl.rcParams['mathtext.default'] = 'regular' mpl.rcParams['mathtext.rm'] = 'Comic Sans MS' mpl.rcParams['mathtext.it'] = 'Humor Sans:italic' @observe('simplify') def _simplify_changed(self, change): plt.rcParams['path.simplify'] = change.new plt.rcParams['path.simplify_threshold'] = 1. @default('stylesheets') def _get_stylesheets_default(self): # the spectra path in package data return get_pkg_path('stylesheets', 'scp_data') @observe('style') def _style_changed(self, change): changes = change.new if not isinstance(changes, list): changes = [changes] for _style in changes: debug_(f'\n\n\nSTYLE: {_style} \n') try: if isinstance(_style, (list, tuple)): for s in _style: self._apply_style(s) else: self._apply_style(_style) except Exception as e: raise e # additional setting self.set_latex_font(self.font_family) @staticmethod def _get_fontsize(fontsize): if fontsize == 'None': return float(mpl.rcParams['font.size']) plt.ioff() fig, ax = plt.subplots() t = ax.text(0.5, 0.5, 'Text') plt.ion() try: t.set_fontsize(fontsize) fontsize = str(round(t.get_fontsize(), 2)) except Exception: pass plt.close(fig) plt.ion() return fontsize @staticmethod def _get_color(color): prop_cycle = plt.rcParams['axes.prop_cycle'] colors = prop_cycle.by_key()['color'] c = [f'C{i}' for i in range(10)] if color in c: return f"{colors[c.index(color)]}" else: return f"{color}" def _apply_style(self, _style): f = (pathclean(self.stylesheets) / _style).with_suffix('.mplstyle') if not f.exists(): # we have to look matplotlib predetermined style. f = (pathclean(mpl.__file__).parent / 'mpl-data' / 'stylelib' / _style).with_suffix('.mplstyle') if not f.exists(): raise TypeError(f'This style {_style} doesn\'t exists') txt = f.read_text() pars = txt.split('\n') for line in pars: if line.strip() and not line.strip().startswith('#'): name, value = line.split(':', maxsplit=1) name_ = name.strip().replace('.', '_') value = value.split(' # ')[0].strip() if "size" in name and "figsize" not in name and 'papersize' not in name: value = self._get_fontsize(value) elif name.endswith('color') and 'force_' not in name: value = self._get_color(value) debug_(f'{name_} = {value}') if value == 'true': value = 'True' elif value == 'false': value = 'False' try: setattr(self, name_, value) except ValueError: if name.endswith('color') and len(value) == 6: value = '#' + value.replace('\'', '') except TraitError: if hasattr(self.traits()[name_], 'default_args'): try: value = type(self.traits()[name_].default_args)(map(float, value.split(','))) except Exception: value = type(self.traits()[name_].default_args)(value.split(',')) value = tuple(map(str.strip, value)) else: value = type(self.traits()[name_].default_value)(eval(value)) except Exception as e: raise e try: setattr(self, name_, value) except Exception as e: raise e if line.strip() and line.strip().startswith('##@'): # SPECTROCHEMPY Parameters name, value = line[3:].split(':', maxsplit=1) name = name.strip() value = value.strip() try: setattr(self, name, value) except TraitError: setattr(self, name, eval(value)) def to_rc_key(self, key): rckey = "" lis = key.split('_') if len(lis) > 1 and lis[0] in self.groups: rckey += lis.pop(0) rckey += '.' if len(lis) > 1 and lis[0] in self.subgroups: rckey += lis.pop(0) rckey += '.' rckey += '_'.join(lis) return rckey @observe(All) def _anytrait_changed(self, change): # ex: change { # 'owner': object, # The HasTraits instance # 'new': 6, # The new value # 'old': 5, # The old value # 'name': "foo", # The name of the changed trait # 'type': 'change', # The event type of the notification, usually 'change' # } if change.name in self.trait_names(config=True): key = self.to_rc_key(change.name) if key in mpl.rcParams: if key.startswith('font'): print() try: mpl.rcParams[key] = change.new except ValueError: mpl.rcParams[key] = change.new.replace('\'', '') else: debug_(f'no such parameter in rcParams: {key} - skipped') if key == 'font.size': mpl.rcParams['legend.fontsize'] = int(change.new * .8) mpl.rcParams['xtick.labelsize'] = int(change.new) mpl.rcParams['ytick.labelsize'] = int(change.new) mpl.rcParams['axes.labelsize'] = int(change.new) if key == 'font.family': self.set_latex_font( change.new) # @observe('use_latex') # def _use_latex_changed(self, change): # mpl.rc( # 'text', usetex=change.new) # # @observe('latex_preamble') # def _set_latex_preamble(self, # change): # mpl.rcParams[ # # # # 'text.latex.preamble'] = change.new.split('\n') super()._anytrait_changed(change) return # EOF <file_sep>/tests/readme.md Testing ======== The tests in this directory are intended to be processed using pytest. If the whole tests` directory must be tested : ```bash $ cd <spectrochempy top directory> $ pytest tests ``` No images or dialog should appear. IF it is not the case, please report with a minimal example showing this doesn't work. <file_sep>/docs/gettingstarted/examples/nddataset/plot_units.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ # Units manipulation examples In this example, we show how units can be used in SpectroChemPy """ import spectrochempy as scp ############################################################################### # Spectrochempy can do calculations with units - it uses [pint](https://pint.readthedocs.io) to define and perform # operation on data with units. ############################################################################### # ## Create quantities # To create quantity, use for instance, one of the following expression: scp.Quantity('10.0 cm^-1') "" scp.Quantity(1.0, 'cm^-1/hour') ############################################################################### # or may be simpler using `ur`: ur = scp.ur 10.0 * ur.meter / ur.gram / ur.volt ############################################################################### # `ur` stands for **unit registry**, which handle many type of units (and conversion between them) ############################################################################### # ## Units for dataset # # When loading experimental dataset using the `read` method, units are generally affected to coordinates and data ds = scp.read('wodger.spg')[0] prefs = ds.preferences prefs.figure.figsize = (7, 3) _ = ds.plot() ############################################################################### # * `wavenumbers` (`x`) coordinates are here expressed in $cm^{-1}$ # * and `data` are in absorbance ($a.u.$) units. ############################################################################### # ## Convert between units # # Here are some examples x = 36 * ur('km/hr') x.to('cm/s') ############################################################################### # We can make the conversion *inplace* using *ito* instead of *to* x.ito('m/s') x ############################################################################### # Obviously you cannot convert between incompatible units try: x.to('hour') except scp.DimensionalityError as e: scp.error_(e) ############################################################################### # This, of course, also applies to NDDataset. # Lets try for the `x` coordinate. It is `wavenumber` in $cm^{-1}$ that can be transformed in $Hz$ for instance: ds.x.ito('terahertz') _ = ds.plot() ############################################################################### # We can also change the wavenumbers (or frequency units), to energy units or wavelength as # Spectrochempy (thanks to [pint](https://pint.readthedocs.io)) knows how to make the transformation. ds.x.ito('eV') _ = ds.plot() "" try: ds.x.ito('nanometer') except Exception as e: scp.error_(e) "" ds.x = ds.x.to('nanometer') _ = ds.plot() print(ds.x) # The LinearCoord object is transformed into a Coord object ############################################################################### # ``absorbance`` units (the units of the data) can also be transformed into ``transmittance`` ds.ito('transmittance') _ = ds.plot() "" ds.ito('absorbance') ds.x.ito('cm^-1') _ = ds.plot() "" # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/docs/gettingstarted/examples/analysis/plot_efa_keller_massart.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ EFA analysis (Keller and Massart original example) =================================================== In this example, we perform the Evolving Factor Analysis of a TEST dataset (ref. Keller and Massart, Chemometrics and Intelligent Laboratory Systems, 12 (1992) 209-224 ) """ import spectrochempy as scp import numpy as np # sphinx_gallery_thumbnail_number = 5 ######################################################################################################################## # Generate a test dataset # ---------------------------------------------------------------------------------------------------------------------- # 1) simulated chromatogram # ************************* t = scp.Coord(np.arange(15), units='minutes', title='time') # time coordinates c = scp.Coord(range(2), title='components') # component coordinates data = np.zeros((2, 15), dtype=np.float64) data[0, 3:8] = [1, 3, 6, 3, 1] # compound 1 data[1, 5:11] = [1, 3, 5, 3, 1, 0.5] # compound 2 dsc = scp.NDDataset(data=data, coords=[c, t]) ######################################################################################################################## # 2) absorption spectra # ********************** spec = np.array([[2., 3., 4., 2.], [3., 4., 2., 1.]]) w = scp.Coord(np.arange(1, 5, 1), units='nm', title='wavelength') dss = scp.NDDataset(data=spec, coords=[c, w]) ######################################################################################################################## # 3) simulated data matrix # ************************ dataset = scp.dot(dsc.T, dss) dataset.data = np.random.normal(dataset.data, .2) dataset.title = 'intensity' dataset.plot(); ######################################################################################################################## # 4) evolving factor analysis (EFA) # ********************************* efa = scp.EFA(dataset) ######################################################################################################################## # Plots of the log(EV) for the forward and backward analysis # efa.f_ev.T.plot(yscale="log", legend=efa.f_ev.y.labels) efa.b_ev.T.plot(yscale="log"); ######################################################################################################################## # Looking at these EFA curves, it is quite obvious that only two components # are really significant, and this correspond to the data that we have in # input. # We can consider that the third EFA components is mainly due to the noise, # and so we can use it to set a cut of values n_pc = 2 efa.cutoff = np.max(efa.f_ev[:, n_pc].data) f2 = efa.f_ev b2 = efa.b_ev # we concatenate the datasets to plot them in a single figure both = scp.concatenate(f2, b2) both.T.plot(yscale="log"); # TODO: add "legend" keyword in NDDataset.plot() ######################################################################################################################## # Get the abstract concentration profile based on the FIFO EFA analysis # efa.cutoff = None c = efa.get_conc(n_pc) c.T.plot(); # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/spectrochempy/core/processors/smooth.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ["smooth"] __dataset_methods__ = __all__ import numpy as np from spectrochempy.core import error_ def smooth(dataset, window_length=5, window='flat', **kwargs): """ Smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output data. Parameters ---------- dataset : |NDDataset| or a ndarray-like object Input object. window_length : int, optional, default=5 The dimension of the smoothing window; must be an odd integer. window : str, optional, default='flat' The type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'. flat window will produce a moving average smoothing. **kwargs : dict See other parameters. Returns ------- smoothed Same type as input dataset. Other Parameters ---------------- dim : str or int, optional, default='x'. Specify on which dimension to apply this method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, optional, default=False. True if we make the transform inplace. If False, the function return a new object See Also -------- savgol_filter : Apply a Savitzky-Golay filter. Examples -------- >>> import spectrochempy as scp >>> ds = scp.read("irdata/nh4y-activation.spg") >>> ds.smooth(window_length=11) NDDataset: [float64] a.u. (shape: (y:55, x:5549)) """ if not kwargs.pop('inplace', False): # default new = dataset.copy() else: new = dataset is_ndarray = False axis = kwargs.pop('dim', kwargs.pop('axis', -1)) if hasattr(new, 'get_axis'): axis, dim = new.get_axis(axis, negative_axis=True) else: is_ndarray = True swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) # must be done in place swaped = True if (window_length % 2) != 1: error_("Window length must be an odd integer.") if new.shape[-1] < window_length: error_("Input vector needs to be bigger than window size.") return new if window_length < 3: return new wind = { 'flat': np.ones, 'hanning': np.hanning, 'hamming': np.hamming, 'bartlett': np.bartlett, 'blackman': np.blackman, } if not callable(window): if window not in wind.keys(): error_("Window must be a callable or a string among 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'") return new window = wind[window] # extend on both side to limit side effects dat = np.r_['-1', new.data[..., window_length - 1:0:-1], new.data, new.data[..., -1:-window_length:-1]] w = window(window_length) data = np.apply_along_axis(np.convolve, -1, dat, w / w.sum(), mode='valid') data = data[..., int(window_length / 2):-int(window_length / 2)] if not is_ndarray: new.data = data new.history = f'smoothing with a window:{window.__name__} of length {window_length}' # restore original data order if it was swaped if swaped: new.swapdims(axis, -1, inplace=True) # must be done inplace else: new = data return new if __name__ == '__main__': pass <file_sep>/docs/gettingstarted/install/install_docker.rst .. _install_docker: *************************** Install a Docker container *************************** Docker is an open platform for shipping, and running applications. It allows to run |scpy| in an unified environment whatever the host platform is, avoiding all potential installation problems as the images created have been tested before being shipped. .. _install_docker_details: Installation ============ Before going further, if **Docker** is not yet installed on your system, you need to install it. Refer to `this page <https://www.docker.com/products/docker-desktop>`__ to download the version you need. Additional steps on windows ---------------------------- * `Enable WSL, install a Linux distribution, and update to WSL 2 <https://docs.microsoft.com/en-us/windows/wsl/install-win10#manual-installation-steps>`__. - Open PowerShell as Administrator : to do this **RIGHT**-click on the start button and select `Windows Powershell (admin)` - run .. sourcecode:: powershell dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart - Restart your machine to complete the WSL install. - Update WSL to version 2: * Download the latest package : `WSL2 Linux kernel update package for x64 machines <WSL2 Linux kernel update package for x64 machines>`__ and install. * Open PowerShell and run this command to set WSL 2 as the default version. .. sourcecode:: powershell wsl --set-default-version 2 .. - Install a linux distribution, e.g., .. `the lightweight Alpine WSL (on Microsoft Store) <https://aka.ms/wslstore>`__. .. or another of your choice. - Install `Docker Desktop <https://www.docker.com/products/docker-desktop>`__. - Once installed, start Docker Desktop from the Windows Start menu, then select the Docker icon from the hidden icons menu of your taskbar. Right-click the icon to display the Docker commands menu and select "Settings". .. image:: images/docker1.png :alt: docker_hidden_menu * Ensure that "Use the WSL 2 based engine" is checked in Settings > General. .. warning:: TO BE COMPLETED Executing a |scpy| Docker container ========================================= This be done using the following ``Docker run`` command : .. sourcecode:: bash docker run -v /path/on/host:/home/jovyan/work \ -p 8888:8888 \ --name scpy \ spectrocat/spectrochempy:latest \ start.sh jupyter lab This command will create a container where python, jupyter lab and spectrochempy are preinstalled. During the creation of the container, the image containing these componrents will be downloaded from our Docker repository. .. note:: This may take a while the first time this command is executed due to the size of the image to be downloaded, but once this is done, the image will be saved on your system so it will not be downloaded again except some update are detected **Description of the parameters** * ``-v`` or ``--volume`` allows to bind a local directory with the Docker application. For instance if you want to works on files located in ``C:\Users\toto\mywork``, you can use: ``-v //C:/Users/myaccount/mywork:/home/jovyan/work``. Note that ``backslash (\)`` separator of windows path must be replaced by simple ``slash (/)``. The container will be unable to access directories at upper levels than those specified in ``-v`` bindings. Thus if for instance you need to access to a directory where you your data are savec you will need to write a binding explicitely. You can bind as many directory you want. .. sourcecode:: bash docker run -v /path/on/host:/home/jovyan/work \ -v /another/path/on/host:/home/jovyan/data \ -p 8888:8888 \ --name scpy-latest \ spectrocat/spectrochempy:latest \ start.sh jupyter lab Another possibility is to select for example your home directory; in this case you will have access as on your local system to all files accessibles from here. * ``-p`` is used to map an host port to the internal container port=8888 used by jupyter lab by default (It is not directly accessible). For instance, if you write -p 10000:8888, the Jupyter Lab application will be accessible on the host on port 10000. * ``--name``: This is optional to specify a container name. If not given a random name will be chosen. * ``spectrocat/spectrochempy:latest`` This is the name of the image to download. * ``start.sh jupyter lab`` This is a command to start the Jupyter lab server. Once the ``Docker run`` command is exectuted in a terminal, it will output somme informations and display the internal address at the end: .. sourcecode:: bash ... To access the server, open this file in a browser: file:///home/jovyan/.local/share/jupyter/runtime/jpserver-8-open.html Or copy and paste one of these URLs: http://982b516d00bd:8888/lab?token=<KEY> or http://127.0.0.1:8888/lab?token=<KEY> Go to you browser and paste ``http://127.0.0.1:8888/lab?token=<KEY>`` in the address bar to display the application interface. It your port binding is different, for exemple ``-p 10000:8888``, then you will have to change this address to: ``http://127.0.0.1:10000/lab?token=<KEY>``. The token string is necessary for security reason, but can be replaced by a password. .. note:: The first time the Jupyter Lab session is opened for the container, it will need to rebuild the extensions. Click on the accept button when you are required to do so. <file_sep>/spectrochempy/core/processors/concatenate.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ['concatenate', 'stack'] __dataset_methods__ = __all__ import numpy as np import datetime as datetime from warnings import warn from orderedset import OrderedSet from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.coord import Coord from spectrochempy.core.dataset.ndarray import DEFAULT_DIM_NAME from spectrochempy.utils import SpectroChemPyWarning, DimensionsCompatibilityError def concatenate(*datasets, **kwargs): """ Concatenation of |NDDataset| objects along a given axis. Any number of |NDDataset| objects can be concatenated (by default the last on the last dimension). For this operation to be defined the following must be true : #. all inputs must be valid |NDDataset| objects; #. units of data and axis must be compatible #. concatenation is along the axis specified or the last one; #. along the non-concatenated dimensions, shape and units coordinates must match. Parameters ---------- *datasets : positional |NDDataset| arguments The dataset(s) to be concatenated to the current dataset. The datasets must have the same shape, except in the dimension corresponding to axis (the last, by default). **kwargs : dict See other parameters. Returns -------- out A |NDDataset| created from the contenations of the |NDDataset| input objects. Other Parameters ---------------- dims : str, optional, default='x' The dimension along which the operation is applied. force_stack : bool, optional, default=False If True, the dataset are stacked instead of being concatenated. This means that a new dimension is prepended to each dataset before being stacked, except if one of the dimension is of size one. If this case the datasets are squeezed before stacking. The stacking is only possible is the shape of the various datasets are identical. This process is equivalent of using the method `stack`. See Also --------- stack : Stack of |NDDataset| objects along the first dimension. Examples -------- >>> import spectrochempy as scp >>> A = scp.read('irdata/nh4y-activation.spg', protocol='omnic') >>> B = scp.read('irdata/nh4y-activation.scp') >>> C = scp.concatenate(A[10:], B[3:5], A[:10], axis=0) >>> A[10:].shape, B[3:5].shape, A[:10].shape, C.shape ((45, 5549), (2, 5549), (10, 5549), (57, 5549)) or >>> D = A.concatenate(B, B, axis=0) >>> A.shape, B.shape, D.shape ((55, 5549), (55, 5549), (165, 5549)) >>> E = A.concatenate(B, axis=1) >>> A.shape, B.shape, E.shape ((55, 5549), (55, 5549), (55, 11098)) Stacking of datasets: for nDimensional datasets (with the same shape), a new dimension is added >>> F = A.concatenate(B, force_stack=True) >>> A.shape, B.shape, F.shape ((55, 5549), (55, 5549), (2, 55, 5549)) If one of the dimensions is of size one, then this dimension is removed before stacking >>> G = A[0].concatenate(B[0], force_stack=True) >>> A[0].shape, B[0].shape, G.shape ((1, 5549), (1, 5549), (2, 5549)) """ # ------------------------------------------------------------------------------------------------------------------ # checks dataset validity # ------------------------------------------------------------------------------------------------------------------ # We must have a list of datasets if isinstance(datasets, tuple): if isinstance(datasets[0], (list, tuple)): datasets = datasets[0] # make a copy of the objects (in order that input data are not modified) datasets = [ds.copy() for ds in datasets] # try to cast of dataset to NDDataset for i, item in enumerate(datasets): if not isinstance(item, NDDataset): try: datasets[i] = NDDataset(item) except Exception: raise TypeError(f"Only instance of NDDataset can be concatenated, not {type(item).__name__}, " f"but casting to this type failed. ") # get the shapes and ndims for comparison rshapes = [] rndims = [] for item in datasets: sh = list(item.shape) rshapes.append(sh) rndims.append(len(sh)) # The number of dimensions is expected to be the same for all datasets if len(list(set(rndims))) > 1: raise DimensionsCompatibilityError("Only NDDataset with the same number of dimensions can be concatenated.") rcompat = list(map(list, list(map(set, list(zip(*rshapes)))))) # a flag to force stacking of dataset instead of the default concatenation force_stack = kwargs.get('force_stack', False) if force_stack: # when stacking, we add a new first dimension except if one dimension is of size one: in this case we use this # dimension for stacking prepend = False if len(set(list(map(len, rcompat)))) == 1: # all dataset have the same shape # they can be stacked by prepending a new dimension prepend = True # else we will try to stack them on the first dimension if not prepend: warn('These datasets have not the same shape, so they cannot be stacked. By default they will be ' 'concatenated along the first dimension.', category=SpectroChemPyWarning) for i, dataset in enumerate(datasets): if not prepend or dataset.shape[0] == 1: continue dataset._data = dataset.data[np.newaxis] dataset._mask = dataset.mask[np.newaxis] newcoord = Coord([i], labels=[dataset.name]) newcoord.name = (OrderedSet(DEFAULT_DIM_NAME) - dataset._dims).pop() dataset.add_coordset(newcoord) dataset.dims = [newcoord.name] + dataset.dims # TODO: make a function to simplify this process of adding new dimensions with coords axis, dim = datasets[0].get_axis(dim=0) else: # get axis from arguments (or set it to the default) axis, dim = datasets[0].get_axis(**kwargs) # check if data shapes are compatible (all dimension must have the same size # except the one to be concatenated) for i, item in enumerate(zip(*rshapes)): if i != axis and len(set(item)) > 1: raise DimensionsCompatibilityError( "Datasets must have the same shape for all dimensions except the one along which the" " concatenation is performed") # Check unit compatibility # ------------------------------------------------------------------------------------------------------------------ units = datasets[0].units for dataset in datasets: if not dataset.is_units_compatible(datasets[0]): raise ValueError( 'units of the datasets to concatenate are not compatible') # if needed transform to the same unit dataset.ito(units) # TODO: make concatenation of heterogeneous data possible by using labels # Check coordinates compatibility # ------------------------------------------------------------------------------------------------------------------ # coordinates units of NDDatasets must be compatible in all dimensions # get the coordss coordss = [dataset.coordset for dataset in datasets] # def check_coordinates(coordss, force_stack): # # # We will call this only in case of problems because it takes a lot of time # # # how many different coordss # coordss = set(coordss) # if len(coordss) == 1 and force_stack: # # nothing to do (all datasets have the same coords and so are # # perfectly compatibles for stacking) # pass # # else: # for i, cs in enumerate(zip(*coordss)): # # axs = set(cs) # axref = axs.pop() # for ax in axs: # # we expect compatible units # if not ax.is_units_compatible(axref): # raise ValueError( # "units of the dataset's axis are not compatible" # ) # if i != axis and ax.size != axref.size: # # and same size for the non-concatenated axis # raise ValueError( # "size of the non-concatenated dimension must be " # "identical" # ) # concatenate or stack the data array + mask # ------------------------------------------------------------------------------------------------------------------ sss = [] for i, dataset in enumerate(datasets): d = dataset.masked_data sss.append(d) sconcat = np.ma.concatenate(sss, axis=axis) data = np.asarray(sconcat) mask = sconcat.mask # concatenate coords if they exists # ------------------------------------------------------------------------------------------------------------------ if len(coordss) == 1 and coordss.pop() is None: # no coords coords = None else: # we take the coords of the first dataset, and extend the coord along the concatenate axis coords = coordss[0].copy() try: coords[dim] = Coord(coords[dim], linear=False) # de-linearize the coordinates coords[dim]._data = np.concatenate(tuple((c[dim].data for c in coordss))) except ValueError: pass # concatenation of the labels (first check the presence of at least one labeled coordinates) is_labeled = False for i, c in enumerate(coordss): if c[dim].implements() in ['Coord', 'LinearCoord']: # this is a coord if c[dim].is_labeled: # at least one of the coord is labeled is_labeled = True break if c[dim].implements('CoordSet'): # this is a coordset for coord in c[dim]: if coord.is_labeled: # at least one of the coord is labeled is_labeled = True break if is_labeled: labels = [] # be sure that now all the coordinates have a label, or create one for i, c in enumerate(coordss): if c[dim].implements() in ['Coord', 'LinearCoord']: # this is a coord if c[dim].is_labeled: labels.append(c[dim].labels) else: labels.append(str(i)) if c[dim].implements('CoordSet'): # this is a coordset for coord in c[dim]: if coord.is_labeled: labels.append(c[dim].labels) else: labels.append(str(i)) if isinstance(coords[dim], Coord): coords[dim]._labels = np.concatenate(labels) if coords[dim].implements('CoordSet'): for i, coord in enumerate(coords[dim]): coord._labels = np.concatenate(labels[i::len(coords[dim])]) coords[dim]._labels = np.concatenate(labels) # out = NDDataset(data, coordset=coords, mask=mask, units=units) # This doesn't keep the order of the # coordinates out = dataset.copy() out._data = data out._coordset[dim] = coords[dim] out._mask = mask out._units = units thist = 'Stack' if axis == 0 else 'Concatenation' out.description = '{} of {} datasets:\n'.format(thist, len(datasets)) out.description += '( {}'.format(datasets[0].name) out.title = datasets[0].title authortuple = (datasets[0].author,) for dataset in datasets[1:]: if out.title != dataset.title: warn('Different data title => the title is that of the 1st dataset') if not (dataset.author in authortuple): authortuple = authortuple + (dataset.author,) out.author = out.author + ' & ' + dataset.author out.description += ', {}'.format(dataset.name) out.description += ' )' out._date = out._modified = datetime.datetime.now(datetime.timezone.utc) out._history = [str(out.date) + ': Created by %s' % thist] return out def stack(*datasets): """ Stack of |NDDataset| objects along the first dimension. Any number of |NDDataset| objects can be stacked. For this operation to be defined the following must be true : #. all inputs must be valid dataset objects, #. units of data and axis must be compatible (rescaling is applied automatically if necessary). The remaining dimension sizes must match along all dimension but the first. Parameters ---------- *datasets : a series of |NDDataset| The dataset to be stacked to the current dataset. Returns -------- out A |NDDataset| created from the stack of the `datasets` datasets. Examples -------- >>> import spectrochempy as scp >>> A = scp.read('irdata/nh4y-activation.spg', protocol='omnic') >>> B = scp.read('irdata/nh4y-activation.scp') >>> C = scp.stack(A, B) >>> print(C) NDDataset: [float64] a.u. (shape: (z:2, y:55, x:5549)) """ return concatenate(*datasets, force_stack=True) if __name__ == '__main__': pass <file_sep>/tests/test_plotters/test_1D.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy import preferences, NDDataset, os, show # TODO: from spectrochempy.utils.testing import figures_dir, same_images prefs = preferences # @pytest.mark.skip def test_1D(): dataset = NDDataset.read_omnic(os.path.join(prefs.datadir, 'irdata', 'nh4y-activation.spg')) # get first spectrum nd0 = dataset[0] # plot generic nd0.plot() # nd0.plot(output=os.path.join(figures_dir, 'IR_dataset_1D'), # savedpi=150) # # # plot generic style # nd0.plot(style='poster', # output=os.path.join(figures_dir, 'IR_dataset_1D_poster'), # savedpi=150) # # # check that style reinit to default # nd0.plot(output='IR_dataset_1D', savedpi=150) # # try: # # assert same_images('IR_dataset_1D.png', # # os.path.join(figures_dir, 'IR_dataset_1D.png')) # # except AssertionError: # # os.remove('IR_dataset_1D.png') # # raise AssertionError('comparison fails') # # os.remove('IR_dataset_1D.png') # # # try other type of plots # nd0.plot_pen() # nd0[:, ::100].plot_scatter() # nd0.plot_lines() # nd0[:, ::100].plot_bar() # # show() # # # multiple # d = dataset[:, ::100] # datasets = [d[0], d[10], d[20], d[50], d[53]] # labels = ['sample {}'.format(label) for label in # ["S1", "S10", "S20", "S50", "S53"]] # # # plot multiple # plot_multiple(method='scatter', # datasets=datasets, labels=labels, legend='best', # output=os.path.join(figures_dir, # 'multiple_IR_dataset_1D_scatter'), # savedpi=150) # # # plot mupltiple with style # plot_multiple(method='scatter', style='sans', # datasets=datasets, labels=labels, legend='best', # output=os.path.join(figures_dir, # 'multiple_IR_dataset_1D_scatter_sans'), # savedpi=150) # # # check that style reinit to default # plot_multiple(method='scatter', # datasets=datasets, labels=labels, legend='best', # output='multiple_IR_dataset_1D_scatter', # savedpi=150) # try: # assert same_images('multiple_IR_dataset_1D_scatter', # os.path.join(figures_dir, # 'multiple_IR_dataset_1D_scatter')) # except AssertionError: # os.remove('multiple_IR_dataset_1D_scatter.png') # raise AssertionError('comparison fails') # os.remove('multiple_IR_dataset_1D_scatter.png') # plot 1D column col = dataset[:, 3500.] # note the indexing using wavenumber! _ = col.plot_scatter() show() # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/spectrochempy/units/__init__.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Package to handle units (interface with `pint`. """ from .units import * # noqa: F403, F401, E402 from .units import __all__ # noqa: F401 <file_sep>/spectrochempy/api.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== # """ # Main package # # During the initialization of this package, a `matplotlib` backend is set # and some `IPython` configurations are made. # # # """ import sys import matplotlib as mpl from IPython.core.interactiveshell import InteractiveShell from IPython import get_ipython # ---------------------------------------------------------------------------------------------------------------------- # Check the environment for plotting # ---------------------------------------------------------------------------------------------------------------------- # Do we run in IPython ? IN_IPYTHON = False kernel = None ip = None if InteractiveShell.initialized(): IN_IPYTHON = True ip = get_ipython() kernel = getattr(ip, "kernel", None) NO_DISPLAY = False NO_DIALOG = False # Are we buidings the docs ? if 'make.py' in sys.argv[0]: # if we are building the documentation, in principle it should be done # using the make.py located at the root of the spectrchempy package. NO_DISPLAY = True NO_DIALOG = True mpl.use('agg', force=True) # is there a --nodisplay flag if '--nodisplay' in sys.argv: NO_DISPLAY = True NO_DIALOG = True mpl.use('agg', force=True) # Are we running pytest? if 'pytest' in sys.argv[0] or 'py.test' in sys.argv[0]: # if we are testing we also like a silent work with no figure popup! NO_DISPLAY = True NO_DIALOG = True # OK, but if we are doing individual function testing in PyCharm # it is interesting to see the plots and the file dialogs (except if we set explicitely --nodisplay argument! # if len(sys.argv) > 1 and not any([arg.endswith(".py") for arg in sys.argv[1:]]) and '--nodisplay' not in sys.argv: if len(sys.argv) > 1 and any( [arg.split('::')[0].endswith(".py") for arg in sys.argv[1:]]) and '--nodisplay' not in sys.argv: # individual module testing NO_DISPLAY = False NO_DIALOG = False if NO_DISPLAY: mpl.use('agg', force=True) # Are we running in PyCharm scientific mode? if mpl.get_backend() == 'module://backend_interagg': IN_PYCHARM_SCIMODE = True else: IN_PYCHARM_SCIMODE = False if not (IN_IPYTHON and kernel) and not IN_PYCHARM_SCIMODE and not NO_DISPLAY: backend = mpl.rcParams['backend'] # 'Qt5Agg' mpl.use(backend, force=True) ALL = ['NO_DISPLAY', 'NO_DIALOG'] # ---------------------------------------------------------------------------------------------------------------------- # Now we can start loading the API # ---------------------------------------------------------------------------------------------------------------------- # import the core api from spectrochempy import core from spectrochempy.core import * # noqa: F403, F401, E402 ALL += core.__all__ if not IN_IPYTHON: # needed in windows terminal - but must not be inited in Jupyter notebook from colorama import init as initcolor initcolor() # def set_backend(): # workaround this problem https://github.com/jupyter/notebook/issues/3385 # ip.magic('matplotlib notebook') if IN_IPYTHON and kernel and not NO_DISPLAY: try: if 'ipykernel_launcher' in sys.argv[0] and \ "--InlineBackend.rc={'figure.dpi': 96}" in sys.argv: # We are running from NBSphinx - the plot must be inline to show up. ip.magic('matplotlib inline') else: # Do not set the widget backend.... do not work most of the time after upbgrade of the various # library and # jupyter!!! ... ip.magic('matplotlib inline') # widget except Exception: ip.magic('matplotlib qt') # set_backend() # a usefull utilities for dealing with path from spectrochempy.utils import pathclean DATADIR = pathclean(preferences.datadir) __all__ = ['pathclean', 'DATADIR'] + ALL import warnings warnings.filterwarnings(action='ignore', module='matplotlib') # , category=UserWarning) # warnings.filterwarnings(action="error", category=DeprecationWarning) # ============================================================================== if __name__ == '__main__': pass <file_sep>/tests/test_dataset/test_meta.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ """ from spectrochempy.core.dataset.meta import Meta from spectrochempy.utils.testing import raises from spectrochempy.units import ur def test_init(): meta = Meta() meta.td = [200, 400] assert meta.td[0] == 200 assert meta.si is None meta['si'] = 'a string' assert isinstance(meta.si, str) assert meta.si.startswith('a') def test_instance(): meta = Meta() assert isinstance(meta, Meta) def test_equal(): meta1 = Meta() meta2 = Meta() assert meta1 == meta2 def test_readonly(): meta = Meta() meta.chaine = "a string" assert meta.chaine == 'a string' meta.readonly = True with raises(ValueError): meta.chaine = "a modified string" assert meta.chaine != "a modified string" def test_invalid_key(): meta = Meta() meta.readonly = False # this is accepted` with raises(KeyError): meta['readonly'] = True # this not because readonly is reserved with raises(KeyError): meta['_data'] = True # this not because _xxx type attributes are private def test_get_inexistent(): meta = Meta() assert meta.existepas is None def test_get_keys_items(): meta = Meta() meta.td = [200, 400] meta.si = 1024 assert list(meta.keys()) == ['si', 'td'] assert list(meta.items()) == [('si', 1024), ('td', [200, 400])] def test_iterator(): meta = Meta() meta.td = [200, 400] meta.si = 2048 meta.ls = 3 meta.ns = 1024 assert sorted([val for val in meta]) == ['ls', 'ns', 'si', 'td'] def test_copy(): meta = Meta() meta.td = [200, 400] meta.si = 2048 meta.ls = 3 meta.ns = 1024 meta2 = meta assert meta2 is meta meta2 = meta.copy() assert meta2 is not meta assert sorted([val for val in meta2]) == ['ls', 'ns', 'si', 'td'] # bug with quantity si = 2048 * ur.s meta.si = si meta3 = meta.copy() meta3.si = si / 2. assert meta3 is not meta def test_swap(): meta = Meta() meta.td = [200, 400, 500] meta.xe = [30, 40, 80] meta.si = 2048 meta.swap(1, 2) assert meta.td == [200, 500, 400] assert meta.xe == [30, 80, 40] assert meta.si == 2048 def test_permute(): meta = Meta() meta.td = [200, 400, 500] meta.xe = [30, 40, 80] meta.si = 2048 p = (2, 0, 1) meta.permute(*p) assert meta.td == [500, 200, 400] assert meta.xe == [80, 30, 40] assert meta.si == 2048 <file_sep>/docs/gettingstarted/examples/nddataset/plot_coordinates.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ NDDataset coordinates example ============================= In this example, we show how coordinates can be used in SpectroChemPy """ import spectrochempy as scp ############################################################################### # ## Uploading a dataset X = scp.read('irdata/CO@Mo_Al2O3.SPG') ############################################################################### # ``X`` has two coordinates: # * `wavenumbers` named "x" # * and `timestamps` (*i.e.,* the time of recording) named "y". print(X.coordset) ############################################################################### # To display them individually use the ``x`` and ``y`` attributes of # the dataset ``X``: X.x "" X.y ############################################################################### # ## Setting new coordinates # # In this example, each experiments have a timestamp corresponds to the time # when a given pressure of CO in the intrared cell was set. # # Hence it would be interesting to replace the "useless" timestamps (``y``) # by a pressure coordinates: pressures = [0.00300, 0.00400, 0.00900, 0.01400, 0.02100, 0.02600, 0.03600, 0.05100, 0.09300, 0.15000, 0.20300, 0.30000, 0.40400, 0.50300, 0.60200, 0.70200, 0.80100, 0.90500, 1.00400] ############################################################################### # 1. A first way to do this is to replace the time coordinates by the pressure # coordinate ############################################################################### # *(we first make a copy of the time coordinates for later use the original will # be destroyed by the following operation)* c_times = X.y.copy() ############################################################################### # Now we perform the replacement with this new coordinate: c_pressures = scp.Coord(pressures, title='pressure', units='torr') X.y = c_pressures print(X.y) ############################################################################### # 2. A second way is to affect several different coordinates to the corresponding dimension. # To do this, the simplest is to affect a list of coordinates instead of a single one: X.y = [c_times, c_pressures] print(X.y) ############################################################################### # By default, the current coordinate is the first one (here `c_times`). # For example, it will be used for plotting: prefs = X.preferences prefs.figure.figsize = (7,3) _ = X.plot(colorbar=True) _ = X.plot_map(colorbar=True) ############################################################################### # To seamlessly work with the second coordinates (pressures), # we can change the default coordinate: X.y.select(2) # to select coordinate ``_2`` X.y.default ############################################################################### # Let's now plot the spectral range of interest. The default coordinate is now used: X_ = X[:, 2250.:1950.] print(X_.y.default) _ = X_.plot() _ = X_.plot_map() ############################################################################### # The same can be done for the x coordinates. # # Let's take for instance row with index 10 of the previous dataset row10 = X_[10].squeeze() row10.plot() print(row10.coordset) ############################################################################### # Now we wants to add a coordinate with the wavelength instead of wavenumber. c_wavenumber = row10.x.copy() c_wavelength = row10.x.to('nanometer') print(c_wavenumber, c_wavelength) row10.x = [c_wavenumber, c_wavelength] row10.x.select(2) _ = row10.plot() "" # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/docs/gettingstarted/install/install_adds.rst .. _install_adds: Install additional libraries ============================= Depending on your project, you may complete |scpy| with additional features. Examples and test data ---------------------- When installing the |scpy| package, the data and examples used in documentation and for testing are not provided. If you want to try the documentation examples you need to install them separately using: .. sourcecode:: bash $ mamba install -c spectrocat spectrochempy_data Alternatively you can download an archive on `github <https://github.com/spectrochempy/spectrochempy_data/tags>`__ and unpack it in the directory of your choice. In this case you may need to adapt the path for the reading fonctions. Cantera ------- Cantera is a suite of tools for problems involving chemical kinetics, thermodynamics and transport process (see `cantera documentation <https://cantera.org>`__). We provide some functionalities based on cantera in |scpy|. If you want to use it you need first to install cantera: .. sourcecode:: bash $ mamba install -c cantera cantera for the stable version or .. sourcecode:: bash $ mamba install -c cantera/label/dev cantera for the development version. QT -- IF you like to have the matplotlib qt backend for your plots, you need to install the pyqt library. .. sourcecode:: bash $ mamba install pyqt Then you can use *e.g.,* the qt backend in notebooks using the IPython "magic" line: .. sourcecode:: ipython %matplotlib qt <file_sep>/tests/test_processors/test_align.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Tests for the interpolate module """ from spectrochempy.core.processors.align import align # align # ------- def test_align(ds1, ds2): ds1c = ds1.copy() dss = ds1c.align(ds2, dim='x') # first syntax # TODO: flag copy=False raise an error assert dss is not None ds3, ds4 = dss # a tuple is returned assert (ds3.shape == (10, 100, 6)) # TODO: labels are not aligned dss2 = align(ds1, ds2, dim='x') # second syntax assert dss2 == dss assert dss2[0] == dss[0] ds5, ds6 = dss2 # align another dim dss3 = align(ds1, ds2, dim='z') # by default it would be the 'x' dim ds7, ds8 = dss3 assert ds7.shape == (17, 100, 3) # align two dims dss4 = align(ds1, ds2, dims=['x', 'z']) ds9, ds10 = dss4 # align inner a, b = align(ds1, ds2, method='inner') <file_sep>/tests/test_docs/test_py_in_docs.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== # ---------------------------------------------------------------------------------------------------------------------- # Testing examples and notebooks (Py version) in docs # ---------------------------------------------------------------------------------------------------------------------- import pytest from pathlib import Path path = Path.cwd() scripts = list((path.parent / 'user').glob('**/*.py')) for item in scripts[:]: if 'checkpoints' in str(item): scripts.remove(item) # ...................................................................................................................... def example_run(path): import subprocess pipe = None so = None serr = None try: pipe = subprocess.Popen( ["python", path, '--nodisplay'], stdout=subprocess.PIPE) (so, serr) = pipe.communicate() except Exception: pass return pipe.returncode, so, serr # ...................................................................................................................... @pytest.mark.parametrize('example', scripts) def test_example(example): # some test will failed due to the magic commands or for other known reasons # SKIP THEM name = example.name if (name in ['tuto2_agir_IR_processing.py', 'tuto3_agir_tg_processing.py', 'agir_setup_figure.py', '1_nmr.py', '1_nmr-Copy1.py', 'fft.py', 'Import.py']): print(example, ' ---> test skipped - DO IT MANUALLY') return if example.suffix == '.py': e, message, err = example_run(example) print(e, message.decode('utf8'), err) assert not e, message.decode('utf8') <file_sep>/docs/gettingstarted/examples/read/readme.txt .. _read_examples-index: Read / Write ------------- Example of import or export function in SpectroChemPy <file_sep>/spectrochempy/core/fitting/optimization.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ["optimize", ] # ====================================================================================================================== # imports # ====================================================================================================================== import scipy.optimize from spectrochempy.core import warning_ from spectrochempy.core.fitting.parameters import FitParameters # =========================================================================== # _fitting # =========================================================================== # Internal/external transformation # These transformations are used in the MINUIT package, # and described in detail # in the section 1.3.1 of the MINUIT User's Guide. def optimize(func, fp0, args=(), constraints={}, method="SIMPLEX", maxfun=None, maxiter=1000, ftol=1e-8, xtol=1e-8, callback=None): """ Parameters ---------- func fp0 args constraints method maxfun maxiter ftol xtol callback Returns ------- """ global keys def restore_external(fp, p, keys): # restore external parameters for key in list(fp.keys()): keysp = key.split('_') if keysp[0] in fp.expvars: ps = [] for i in range(fp.expnumber): ks = "%s_exp%d" % (key, i) if ks not in keys: break k = keys.index(ks) ps.append(p[k]) if len(ps) > 0: fp.to_external(key, ps) else: if key not in keys: continue k = keys.index(key) fp.to_external(key, p[k]) return fp def internal_func(p, dat, fp, keys, *args): fp = restore_external(fp, p, keys) return func(fp, dat, *args) def internal_callback(*args): if callback is None: return return callback(*args) if not isinstance(fp0, FitParameters): raise TypeError('fp0 is not of FitParameter type') # make internal parameters par = [] keys = [] for key in sorted(fp0.keys()): if not fp0.fixed[key]: # we make internal parameters in case of bounding # We also take care of the multiple experiments keysp = key.split('_')[0] if keysp in fp0.expvars: for i in range(fp0.expnumber): par.append(fp0.to_internal(key, i)) keys.append("%s_exp%d" % (key, i)) else: par.append(fp0.to_internal(key)) keys.append(key) args = list(args) args.append(fp0) args.append(keys) if constraints: args.append(constraints) if not maxfun: maxfun = 4 * maxiter if method.upper() == "SIMPLEX": result = scipy.optimize.fmin(internal_func, par, args=tuple(args), maxfun=maxfun, maxiter=maxiter, ftol=ftol, xtol=xtol, full_output=True, disp=False, callback=internal_callback) res, fopt, iterations, funcalls, warnmess = result elif method.upper() == "HOPPING": result = scipy.optimize.basinhopping(internal_func, par, niter=100, T=1.0, stepsize=0.5, minimizer_kwargs={ 'args': tuple(args) }, take_step=None, accept_test=None, callback=internal_callback, interval=50, disp=False, niter_success=None) # fmin(func, par, args=args, maxfun=maxfun, maxiter=maxiter, ftol=ftol, xtol=xtol, # full_output=True, disp=False, callback=callback) res, fopt, warnmess = result.x, result.fun, result.message elif method == "XXXX": raise NotImplementedError("method: %s" % method) # TODO: implement other algorithms else: raise NotImplementedError("method: %s" % method) # restore the external parameter fpe = restore_external(fp0, res, keys) # for i, key in enumerate(keys): # fp0.to_external(key, res[i]) if warnmess == 1: warning_("Maximum number of function evaluations made.") if warnmess == 2: warning_("Maximum number of iterations reached.") return fpe, fopt if __name__ == "__main__": pass <file_sep>/tests/conftest.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== # suppress test for PEP8 in this file # flake8: noqa from os import environ import pathlib import numpy as np import pytest try: # work only if spectrochempy is installed import spectrochempy except ModuleNotFoundError: # pragma: no cover raise ModuleNotFoundError('You must install spectrochempy and its dependencies before executing tests!') from spectrochempy.core import preferences as prefs from spectrochempy.core.dataset.ndarray import NDArray from spectrochempy.core.dataset.ndcomplex import NDComplexArray from spectrochempy.core.dataset.coordset import CoordSet from spectrochempy.core.dataset.coord import Coord from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.scripts.script import Script from spectrochempy.core.project.project import Project from spectrochempy.utils import pathclean from spectrochempy.utils.testing import RandomSeedContext # ====================================================================================================================== # FIXTURES # ====================================================================================================================== # initialize a ipython session before calling spectrochempy # ---------------------------------------------------------------------------------------------------------------------- @pytest.fixture(scope='session') def session_ip(): try: from IPython.testing.globalipapp import start_ipython return start_ipython() except ImportError: return None @pytest.fixture(scope='module') def ip(session_ip): yield session_ip def pytest_sessionfinish(session, exitstatus): # pragma: no cover """ whole test run finishes. """ # cleaning cwd = pathlib.Path(__file__).parent.parent for f in list(cwd.glob('**/*.?scp')): f.unlink() for f in list(cwd.glob('**/*.jdx')): f.unlink() for f in list(cwd.glob('**/*.json')): f.unlink() for f in list(cwd.glob('**/*.log')): f.unlink() docs = cwd / 'docs' for f in list(docs.glob('**/*.ipynb')): f.unlink() # set test file and folder in environment # set a test file in environment datadir = pathclean(prefs.datadir) environ['TEST_FILE'] = str(datadir / 'irdata' / 'nh4y-activation.spg') environ['TEST_FOLDER'] = str(datadir / 'irdata' / 'subdir') environ['TEST_NMR_FOLDER'] = str(datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'topspin_2d') # ---------------------------------------------------------------------------------------------------------------------- # create reference arrays # ---------------------------------------------------------------------------------------------------------------------- with RandomSeedContext(12345): ref_data = 10. * np.random.random((10, 8)) - 5. ref3d_data = 10. * np.random.random((10, 100, 3)) - 5. ref3d_2_data = np.random.random((9, 50, 4)) ref_mask = ref_data < -4 ref3d_mask = ref3d_data < -3 ref3d_2_mask = ref3d_2_data < -2 # ---------------------------------------------------------------------------------------------------------------------- # Fixtures: some NDArray's # ---------------------------------------------------------------------------------------------------------------------- @pytest.fixture(scope="function") def refarray(): return ref_data.copy() @pytest.fixture(scope="function") def refmask(): return ref_mask.copy() @pytest.fixture(scope="function") def ndarray(): # return a simple ndarray with some data return NDArray(ref_data, desc= "An array", copy=True).copy() @pytest.fixture(scope="function") def ndarrayunit(): # return a simple ndarray with some data and units return NDArray(ref_data, units='m/s', copy=True).copy() @pytest.fixture(scope="function") def ndarraymask(): # return a simple ndarray with some data and units return NDArray(ref_data, mask=ref_mask, units='m/s', history='Creation with mask', copy=True).copy() # ---------------------------------------------------------------------------------------------------------------------- # Fixtures: Some NDComplex's array # ---------------------------------------------------------------------------------------------------------------------- @pytest.fixture(scope="function") def ndarraycplx(): # return a complex ndarray return NDComplexArray(ref_data, units='m/s', dtype=np.complex128, copy=True).copy() @pytest.fixture(scope="function") def ndarrayquaternion(): # return a quaternion ndarray return NDComplexArray(ref_data, units='m/s', dtype=np.quaternion, copy=True).copy() # ---------------------------------------------------------------------------------------------------------------------- # Fixtures: Some NDDatasets # ---------------------------------------------------------------------------------------------------------------------- coord0_ = Coord(data=np.linspace(4000., 1000., 10), labels=list('abcdefghij'), units="cm^-1", title='wavenumber') @pytest.fixture(scope="function") def coord0(): return coord0_.copy() coord1_ = Coord(data=np.linspace(0., 60., 100), units="s", title='time-on-stream') @pytest.fixture(scope="function") def coord1(): return coord1_.copy() coord2_ = Coord(data=np.linspace(200., 300., 3), labels=['cold', 'normal', 'hot'], units="K", title='temperature') @pytest.fixture(scope="function") def coord2(): return coord2_.copy() coord2b_ = Coord(data=np.linspace(1., 20., 3), labels=['low', 'medium', 'high'], units="tesla", title='magnetic field') @pytest.fixture(scope="function") def coord2b(): return coord2b_.copy() coord0_2_ = Coord(data=np.linspace(4000., 1000., 9), labels=list('abcdefghi'), units="cm^-1", title='wavenumber') @pytest.fixture(scope="function") def coord0_2(): return coord0_2_.copy() coord1_2_ = Coord(data=np.linspace(0., 60., 50), units="s", title='time-on-stream') @pytest.fixture(scope="function") def coord1_2(): return coord1_2_.copy() coord2_2_ = Coord(data=np.linspace(200., 1000., 4), labels=['cold', 'normal', 'hot', 'veryhot'], units="K", title='temperature') @pytest.fixture(scope="function") def coord2_2(): return coord2_2_.copy() @pytest.fixture(scope="function") def nd1d(): # a simple ddataset return NDDataset(ref_data[:, 1].squeeze()).copy() @pytest.fixture(scope="function") def nd2d(): # a simple 2D ndarrays return NDDataset(ref_data).copy() @pytest.fixture(scope="function") def ref_ds(): # a dataset with coordinates return ref3d_data.copy() @pytest.fixture(scope="function") def ds1(): # a dataset with coordinates return NDDataset(ref3d_data, coordset=[coord0_, coord1_, coord2_], title='Absorbance', units='absorbance').copy() @pytest.fixture(scope="function") def ds2(): # another dataset return NDDataset(ref3d_2_data, coordset=[coord0_2_, coord1_2_, coord2_2_], title='Absorbance', units='absorbance').copy() @pytest.fixture(scope="function") def dsm(): # dataset with coords containing several axis and a mask coordmultiple = CoordSet(coord2_, coord2b_) return NDDataset(ref3d_data, coordset=[coord0_, coord1_, coordmultiple], mask=ref3d_mask, title='Absorbance', units='absorbance').copy() dataset = NDDataset.read_omnic(datadir/'irdata'/'nh4y-activation.spg') @pytest.fixture(scope="function") def IR_dataset_2D(): nd = dataset.copy() nd.name = 'IR_2D' return nd @pytest.fixture(scope="function") def IR_dataset_1D(): nd = dataset[0].squeeze().copy() nd.name = 'IR_1D' return nd # ---------------------------------------------------------------------------------------------------------------------- # Fixture: NMR spectra # ---------------------------------------------------------------------------------------------------------------------- @pytest.fixture(scope="function") def NMR_dataset_1D(): path = datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'topspin_1d' / '1' / 'fid' dataset = NDDataset.read_topspin(path, remove_digital_filter=True, name='NMR_1D') return dataset.copy() @pytest.fixture(scope="function") def NMR_dataset_2D(): path = datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'topspin_2d' / '1' / 'ser' dataset = NDDataset.read_topspin(path, expno=1, remove_digital_filter=True, name="NMR_2D") return dataset.copy() # ---------------------------------------------------------------------------------------------------------------------- # fixture Project # ---------------------------------------------------------------------------------------------------------------------- @pytest.yield_fixture(scope="function") def simple_project(): proj = Project( # subprojects Project(name='P350', label=r'$\mathrm{M_P}\,(623\,K)$'), Project(name='A350', label=r'$\mathrm{M_A}\,(623\,K)$'), Project(name='B350', label=r'$\mathrm{M_B}\,(623\,K)$'), # attributes name='project_1', label='main project', ) assert proj.projects_names == ['A350', 'B350', 'P350'] ir = NDDataset([1.1, 2.2, 3.3], coordset=[[1, 2, 3]]) tg = NDDataset([1, 3, 4], coordset=[[1, 2, 3]]) proj.A350['IR'] = ir proj.A350['TG'] = tg script_source = 'set_loglevel(INFO)\n' \ 'info_(f"samples contained in the project are {proj.projects_names}")' proj['print_info'] = Script('print_info', script_source) return proj <file_sep>/spectrochempy/gui/scpy_gui.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ SpectroChemPy DashBoard: Dash Application Note ---- Run this app with the command `scpy` in a terminal and then visit http://127.0.0.1:8050/ in your web browser. """ import webbrowser from threading import Timer import dash import dash_bootstrap_components as dbc import spectrochempy as scp from spectrochempy.gui import Layout, Callbacks def main(): debug = scp.get_loglevel() == scp.DEBUG # create the standalone application layout = Layout(calling_script_name=__file__, fix_navbar=debug, data_storage='session') theme = dbc.themes.BOOTSTRAP app = dash.Dash(__name__, title='SpectroChemPy by Dash', external_stylesheets=[theme]) app.css.config.serve_locally = True app.scripts.config.serve_locally = True app.index_string = """ <!DOCTYPE html> <html> <head> {%metas%} <title>{%title%}</title> {%favicon%} {%css%} </head> <body> {%app_entry%} <footer> {%config%} {%scripts%} <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [ ['$','$'],], processEscapes: true } }); </script> {%renderer%} </footer> </body> </html> """ # Assign layout app.layout = layout.app_page_layout() # Register all callbacks callbacks = Callbacks() callbacks.add_callbacks(app) # Run flask server but if the server is already running on the selected port, choose another one port = scp.app.port for i in range(10): try: _open_browser = \ lambda: webbrowser.open_new(f'http://127.0.0.1:{port + i}/') # lgtm [py/loop-variable-capture] Timer(1, _open_browser).start() app.run_server(debug=debug, port=port + i) break except OSError as e: if "Address already in use" in e.strerror: continue if __name__ == '__main__': main() <file_sep>/docs/devguide/general_principles.rst .. _contributing.general_principles: General Principles =================== The instructions below are a general guide. We do our best to follow this guide, and if you wish to contribute we encourage you to follow it as well. But you don't have to follow everything to the letter: Any kind of contribution is welcome! In this guide, we will talk about some basic but very useful contributions such as bug reports our feature requests, and of some more advanced topics concerning contributions to documentation and to the code base. Note that the content of this guide has been partly inspired by the `pandas developer guide <https://pandas.pydata.org/docs/development/contributing.html>`__). **Where to go next?** .. toctree:: :maxdepth: 1 issues be_prepared <file_sep>/tests/test_api/test_agir_application.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os from spectrochempy import NDDataset from spectrochempy import preferences as prefs # TODO: to revise with project! def make_samples(force_original=False): _samples = { 'P350': { 'label': r'$\mathrm{M_P}\,(623\,K)$' }, # 'A350': {'label': r'$\mathrm{M_A}\,(623\,K)$'}, # 'B350': {'label': r'$\mathrm{M_B}\,(623\,K)$'} } for key, sample in _samples.items(): # our data are in our test `datadir` directory. basename = os.path.join(prefs.datadir, f'agirdata/{key}/FTIR/FTIR') if os.path.exists(basename + '.scp') and not force_original: # check if the scp file have already been saved filename = basename + '.scp' sample['IR'] = NDDataset.read(filename) else: # else read the original zip file filename = basename + '.zip' sample['IR'] = NDDataset.read_zip(filename, only=5, origin='omnic', merge=True) # save sample['IR'].save() for key, sample in _samples.items(): basename = os.path.join(prefs.datadir, f'agirdata/{key}/TGA/tg') if os.path.exists(basename + '.scp') and not force_original: # check if the scp file have already been saved filename = basename + '.scp' sample['TGA'] = NDDataset.read(filename) else: # else read the original csv file filename = basename + '.csv' ss = sample['TGA'] = NDDataset.read_csv(filename, origin='tga') ss.squeeze(inplace=True) # lets keep only data from something close to 0. s = sample['TGA'] = ss[-0.5:35.0] # save s.save() return _samples def test_slicing_agir(): samples = make_samples(force_original=True) # We will resize the data in the interesting region of wavenumbers for key in samples.keys(): s = samples[key]['IR'] # reduce to a useful window of wavenumbers W = (1290., 3990.) s = s[:, W[0]:W[1]] samples[key]['IR'] = s assert samples['P350']['IR'].shape == (5, 2801) # set_loglevel(DEBUG) <file_sep>/tests/test_readers_writers/test_read_omnic.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from pathlib import Path import os import spectrochempy as scp from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core import preferences as prefs def test_read_omnic(): # Class method opening a dialog (but for test it is preset) nd = NDDataset.read_omnic() assert nd.name == 'nh4y-activation' # class method nd1 = scp.NDDataset.read_omnic('irdata/nh4y-activation.spg') assert nd1.title == 'absorbance' assert str(nd1) == 'NDDataset: [float64] a.u. (shape: (y:55, x:5549))' # API method nd2 = scp.read_omnic('irdata/nh4y-activation.spg') assert nd1 == nd2 # opening list of dataset l1 = scp.read_omnic('wodger.spg', 'irdata/nh4y-activation.spg') assert len(l1) == 2 assert str(l1[0]) == 'NDDataset: [float64] a.u. (shape: (y:2, x:5549))' assert str(l1[1]) == 'NDDataset: [float64] a.u. (shape: (y:55, x:5549))' # It is also possible to use more specific reader function such as # `read_spg`, `read_spa` or `read_srs` - they are alias of the read_omnic function. l2 = scp.read_spg('wodger.spg', 'irdata/nh4y-activation.spg') assert len(l2) == 2 # pathlib.Path objects can be used instead of string for filenames p = Path('wodger.spg') nd3 = scp.read_omnic(p) assert nd3 == l1[0] # merging nd = scp.read_omnic(['wodger.spg', 'irdata/nh4y-activation.spg']) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:57, x:5549))' # merging nd = scp.read_omnic('wodger.spg', 'irdata/nh4y-activation.spg', merge=True) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:57, x:5549))' def test_read_omnic_dir(): # Read in a directory (assume that only OMNIC files are present in the directory # (else we must use the generic `read` function instead) nd = scp.read_omnic('irdata/subdir/1-20') assert isinstance(nd, NDDataset) assert len(nd) == 3 # we can use merge=False lst = scp.read_omnic('irdata/subdir/1-20', merge=False) assert isinstance(lst, list) assert len(lst) == 3 def test_read_omnic_contents(): # test read_omnic with byte spg content datadir = prefs.datadir filename = 'wodger.spg' with open(os.path.join(datadir, filename), 'rb') as fil: content = fil.read() nd1 = scp.read_omnic(filename) nd2 = scp.read_omnic({ filename: content }) assert nd1 == nd2 # Test bytes contents for spa files datadir = prefs.datadir filename = '7_CZ0-100 Pd_101.SPA' with open(os.path.join(datadir, 'irdata', 'subdir', filename), 'rb') as fil: content = fil.read() nd = NDDataset.read_omnic({ filename: content }) assert nd.shape == (1, 5549) # test read_omnic with several contents datadir = prefs.datadir filename1 = '7_CZ0-100 Pd_101.SPA' with open(os.path.join(datadir, 'irdata', 'subdir', filename1), 'rb') as fil: content1 = fil.read() filename2 = 'wodger.spg' with open(os.path.join(datadir, filename2), 'rb') as fil: content2 = fil.read() listnd = NDDataset.read_omnic({ filename1: content1, filename2: content2 }, merge=True) assert listnd.shape == (3, 5549) def test_read_spa(): nd = scp.read_spa('irdata/subdir/20-50/7_CZ0-100 Pd_21.SPA') assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:1, x:5549))' nd = scp.read_spa('irdata/subdir', merge=True) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:4, x:5549))' nd = scp.read_spa('irdata/subdir', merge=True, recursive=True) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:8, x:5549))' lst = scp.read('irdata', merge=True, recursive=True) # not selective on extension assert isinstance(lst, list) assert len(lst) >= 88 def test_read_srs(): a = scp.read('irdata/omnic series/rapid_scan.srs') assert str(a) == 'NDDataset: [float64] V (shape: (y:643, x:4160))' b = scp.read('irdata/omnic series/rapid_scan_reprocessed.srs') assert str(b) == 'NDDataset: [float64] a.u. (shape: (y:643, x:3734))' c = scp.read('irdata/omnic series/GC Demo.srs') assert c == [] d = scp.read('irdata/omnic series/TGA demo.srs') assert d == [] <file_sep>/tests/test_readers_writers/test_read_matlab.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os import pytest from spectrochempy.core.dataset.nddataset import NDDataset # comment the next line to test it manually @pytest.mark.skip('interactive so cannot be used with full testing') def test_read_without_filename(): NDDataset.read_matlab() def test_read_with_filename(): A = NDDataset.read_matlab(os.path.join('matlabdata', 'als2004dataset.MAT')) assert len(A) == 6 assert A[3].shape == (204, 96) def test_read_DSO(): A = NDDataset.read_matlab(os.path.join('matlabdata', 'dso.mat')) assert A.name == "Group sust_base line withoutEQU.SPG" assert A.shape == (20, 426) <file_sep>/tests/test_utils/test_misc.py # -*- coding: utf-8 -*- # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # ===================================================================================================================== from spectrochempy.utils import dict_compare def test_dict_compare(): x = dict(a=1, b=2) y = dict(a=2, b=2) added, removed, modified, same = dict_compare(x, y, check_equal_only=False) assert modified == set('a') assert not dict_compare(x, y) <file_sep>/spectrochempy/core/fitting/parameters.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Model parameters handling """ __all__ = ['FitParameters', 'ParameterScript'] # ============== # python import # ============== import sys import re # For regular expression search from collections import UserDict # This is to be able to create a special dictionary from spectrochempy.core import info_ from spectrochempy.core.dataset.nddataset import NDDataset import numpy as np from traitlets import (HasTraits, Unicode, Instance, List, observe) # ============= # id_generator # ============= # def _id_generator(): # """Returns a sequence of numbers for the title of the objects. # # Examples # -------- # # >>> id_generator # 1 # # """ # n = 1 # while True: # yield n # n += 1 # # # id_generator = _id_generator() # ============== # FitParameters # ============== class FitParameters(UserDict): """ Allow passing a dictionary of parameters with additional properties to the fit function. Check if the parameter is between the specified bounds if any. """ # ------------------------------------------------------------------------------------------------------------------ def __init__(self): UserDict.__init__(self) # Create a dictionary class self.lob = {} # Lower bound self.upb = {} # Upper bound self.fixed = {} # true for non-variable parameter self.reference = {} # self.common = {} # indicates if a parameters belong to a common block self.model = {} # model to use self.models = [] # list of models self.sequence = '' # sequence used in the experiment self.expvars = [] # list of parameters which are experiment dependent self.expnumber = 1 # number of experiments # ------------------------------------------------------------------------------------------------------------------ def __setitem__(self, key, value): key = str(key) if key not in self.reference: self.reference[key] = False if self.reference[key]: # we get a reference to another parameter self.data[key] = str(value) self.fixed[key] = True elif isinstance(value, tuple) or isinstance(value, list): self.data[key] = self._evaluate(value[0]) self.lob[key] = None self.upb[key] = None try: if len(value) > 2: self.lob[key] = self._evaluate(value[1]) self.upb[key] = self._evaluate(value[2]) self._checkerror(key) except Exception: pass self.fixed[key] = False if isinstance(value[-1], bool): self.fixed[key] = value[-1] else: self.data[key] = self._evaluate(value) self.lob[key] = None self.upb[key] = None self.fixed[key] = False # ------------------------------------------------------------------------------------------------------------------ def __getitem__(self, key): key = str(key) if key in self.data: return self.data[key] raise KeyError("parameter %s is not found" % key) # ------------------------------------------------------------------------------------------------------------------ def iteritems(self): return iter(self.data.items()) # ------------------------------------------------------------------------------------------------------------------ def _checkerror(self, key): key = str(key) if self.lob[key] is None and self.upb[key] is None: return False elif (self.lob[key] is not None and self.data[key] < self.lob[key]) or (self.upb[key] is not None and self.data[key] > self.upb[key]): raise ValueError('%s value %s is out of bounds' % (key, str(self.data[key]))) # ------------------------------------------------------------------------------------------------------------------ def __str__(self): # ............................................................. def makestr(key): keystring = key.split('_')[0] if self.reference[key]: return "\t> %s:%s \n" % (keystring, self.data[key]) else: if self.fixed[key]: keystring = "\t* %s" % keystring else: keystring = "\t$ %s" % keystring lob = self.lob[key] upb = self.upb[key] if lob <= -0.1 / sys.float_info.epsilon: lob = "none" if upb >= +0.1 / sys.float_info.epsilon: upb = "none" val = str(self.data[key]) return "%s: %10.4f, %s, %s \n" % ( keystring, float(val), lob, upb) # .............................................................. message = "#PARAMETER SCRIPT\n\nCOMMON: \n" var = "" for item in self.expvars: var += " %s" % item if var: message += "\texperiment_number: %s \n" % str(self.expnumber) message += "\texperiment_variables: %s \n" % var # look for common parameters for key in list(self.keys()): keysp = key.split('_')[0] if self.common[keysp]: message += makestr(key) # model parameters models = self.models for model in models: message += "\nMODEL: %s\n" % model message += "shape: %s\n" % self.model[model] for key in sorted(self.keys()): keyspl = key.split('_') if model not in '_'.join(keyspl[1:]): continue message += makestr(key) return message # ------------------------------------------------------------------------------------------------------------------ @staticmethod def _evaluate(strg): """ Allow the evaluation of strings containing some operations Parameters ---------- strg : string A string to evaluate containing multiplier, e.g., '10 k' evaluate to 10 000. Return ------ value : float or bool Value of the string, or False, if there is an error """ res = False if isinstance(strg, str): # strg=string.upper(strg) p = re.compile(r'\s+') m = p.split(strg.strip()) try: res = eval(m[0]) except NameError: message = "Cannot evaluate '" + strg + "' >> " + m[ 0] + " is not defined" raise NameError(message) except SyntaxError: message = "Syntax error in '" + strg + "'" raise SyntaxError(message) # read mulitplier if len(m) > 1: try: res = res * eval(m[1]) except NameError: message = "Cannot evaluate '" + strg + "' >> " + m[ 1] + " is not defined" raise NameError(message) except SyntaxError: message = "Syntax error in '" + strg + "'" raise SyntaxError(message) else: # not a string (probably a scalar that can be return as it is) res = strg return res # ------------------------------------------------------------------------------------------------------------------ def to_internal(self, key, expi=None): """ if expi is not none, several parameters to create """ key = str(key) if key not in self.data: raise KeyError("parameter %s is not found" % key) if expi is not None: pe = self.data[key][expi] else: pe = self.data[key] lob = self.lob[key] upb = self.upb[key] is_lob = lob is not None and lob > -0.1 / sys.float_info.epsilon # lob is not None is_upb = lob is not None and upb < +0.1 / sys.float_info.epsilon # upb is not None if is_lob and is_upb: lob = min(pe, lob) upb = max(pe, upb) # With min and max bounds defined pi = np.arcsin((2 * (pe - lob) / (upb - lob)) - 1.) elif is_upb: upb = max(pe, upb) # With only max defined pi = np.sqrt((upb - pe + 1.) ** 2 - 1.) elif is_lob: lob = min(pe, lob) # With only min defined pi = np.sqrt((pe - lob + 1.) ** 2 - 1.) else: pi = pe return pi # ------------------------------------------------------------------------------------------------------------------ def to_external(self, key, pi): key = str(key) if key not in self.data: raise KeyError("parameter %s is not found" % key) lob = self.lob[key] upb = self.upb[key] is_lob = lob is not None and lob > -0.1 / sys.float_info.epsilon # lob is not None is_upb = lob is not None and upb < +0.1 / sys.float_info.epsilon # upb is not None if not isinstance(pi, list): pi = [pi, ] # make a list pe = [] for item in pi: if is_lob and is_upb: # With min and max bounds defined pei = lob + ((upb - lob) / 2.) * (np.sin(item) + 1.) elif is_upb: # With only max defined pei = upb + 1. - np.sqrt(item ** 2 + 1.) elif is_lob: # With only min defined pei = lob - 1. + np.sqrt(item ** 2 + 1.) else: pei = pi pe.append(pei) if len(pe) == 1: pe = pe[0] self.data[key] = pe return pe def copy(self): import copy as cpy data = cpy.copy(self.data) lob = cpy.copy(self.lob) upb = cpy.copy(self.upb) fixed = cpy.copy(self.fixed) reference = cpy.copy(self.reference) c = cpy.copy(self) c.data = data c.lob = lob c.upb = upb c.fixed = fixed c.reference = reference return c # ================ # ParameterScript # ================ class ParameterScript(HasTraits): """ This class allow some manipulation of the parameter list for modelling """ fp = Instance(FitParameters) script = Unicode('') datasets = List(Instance(NDDataset)) # =========================================================================== # properties # =========================================================================== # ------------------------------------------------------------------------------------------------------------------ @observe('script') def _check_parameters(self, change): """ Check the validity of the parameters """ self.fp = self._interpret(self.script) # ------------------------------------------------------------------------------------------------------------------ def _interpret(self, script): """ Interpreter of the script content """ # init some flags modlabel = None common = False fixed = False reference = False # create a new FitParameters instance fp = FitParameters() # set the number of experiments fp.expnumber = len(self.datasets) info_("The number of experiment(s) is set to %d" % fp.expnumber) # start interpreting ------------------------------------------------------ lines = script.split('\n') lc = 0 for item in lines: lc += 1 # -------------- count the lines line = item.strip() if line == '' or line.startswith("#"): # this is a blank or comment line, go to next line continue # split around the semi-column s = line.split(':') if len(s) != 2: raise ValueError( 'Cannot interpret line %d: A semi-column is missing?' % lc) key, values = s key = key.strip().lower() if key.startswith('model'): modlabel = values.lower().strip() if modlabel not in fp.models: fp.models.append(modlabel) common = False continue elif key.startswith('common') or key.startswith('vars'): common = True modlabel = 'common' continue elif key.startswith('shape'): shape = values.lower().strip() if shape is None: # or (shape not in self._list_of_models and shape not in self._list_of_baselines): raise ValueError( 'Shape of this model "%s" was not specified or is not implemented' % shape) fp.model[modlabel] = shape common = False continue elif key.startswith("experiment"): # must be in common if not common: raise ValueError( "'experiment_...' specification was found outside the common block.") if "variables" in key: expvars = values.lower().strip() expvars = expvars.replace(',', ' ').replace(';', ' ') expvars = expvars.split() fp.expvars.extend(expvars) continue else: if modlabel is None and not common: raise ValueError( "The first definition should be a label for a model or a block of variables or constants.") # get the parameters if key.startswith('*'): fixed = True reference = False key = key[1:].strip() elif key.startswith('$'): fixed = False reference = False key = key[1:].strip() elif key.startswith('>'): fixed = True reference = True key = key[1:].strip() else: raise ValueError( 'Cannot interpret line %d: A parameter definition must start with *,$ or >' % lc) # store this parameter s = values.split(',') s = [ss.strip() for ss in s] if len(s) > 1 and ('[' in s[0]) and (']' in s[1]): # list s[0] = "%s, %s" % (s[0], s[1]) if len(s) > 2: s[1:] = s[2:] if len(s) > 3: raise ValueError( 'line %d: value, min, max should be defined in this order' % lc) elif len(s) == 2: raise ValueError('only two items in line %d' % lc) # s.append('none') elif len(s) == 1: s.extend(['none', 'none']) value, mini, maxi = s if mini.strip().lower() in ['none', '']: mini = str(-1. / sys.float_info.epsilon) if maxi.strip().lower() in ['none', '']: maxi = str(+1. / sys.float_info.epsilon) if modlabel != 'common': ks = "%s_%s" % (key, modlabel) # print(ks) # if "ratio_line_1" in ks: # print('xxxx'+ks) fp.common[key] = False else: ks = "%s" % key fp.common[key] = True # if key in fp.expvars: # for i in xrange(len(self.datasets)): # ks = "%s_exp%d"%(ks, i) fp.reference[ks] = reference if not reference: val = value.strip() val = eval(val) if isinstance(val, list): # if the parameter is already a list, that's ok if the number of parameters is ok if len(val) != fp.expnumber: raise ValueError( 'the number of parameters for %s is not the number of experiments.' % len( val)) if key not in fp.expvars: raise ValueError( 'parameter %s is not declared as variable' % key) else: if key in fp.expvars: # we create a list of parameters corresponding val = [val] * fp.expnumber fp[ks] = val, mini.strip(), maxi.strip(), fixed else: fp[ks] = value.strip() return fp ########################### <file_sep>/docs/devguide/visualcode.rst Editors ======== Visual Studio Installation --------------------------- Download `Visual Studio Code <https://code.visualstudio.com/>`__ and install it. Configuration -------------- .. image:: images/vscode.png Click on ``Customize > Tools and languages > python`` to install support to python. Source control --------------- If you have already already cloned the scpy repository, you can open the corresponding folder. Click on the Source control icons on the left bar and then open folder. If your repository is not yet cloned you can also do it from here (use ``Clone Repository`` button). If `git` is not yet installed you can also do it from here (``install git``) Once git is installed you need to restart VSCode. Start editing ------------- once you have selected the spectrochempy folder you should get something like this, where you have access to all components of the project. .. image:: images/vscode-scpy.png<file_sep>/spectrochempy/core/processors/zero_filling.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # ====================================================================================================================== __all__ = ["zf_auto", "zf_double", "zf_size", "zf"] __dataset_methods__ = __all__ import functools import numpy as np from spectrochempy.utils import largest_power_of_2 from spectrochempy.core import error_ from spectrochempy.core.dataset.coord import LinearCoord # ====================================================================================================================== # Decorators # ====================================================================================================================== def _zf_method(method): @functools.wraps(method) def wrapper(dataset, **kwargs): # On which axis do we want to shift (get axis from arguments) axis, dim = dataset.get_axis(**kwargs, negative_axis=True) # output dataset inplace (by default) or not if not kwargs.pop('inplace', False): new = dataset.copy() # copy to be sure not to modify this dataset else: new = dataset swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) # must be done in place swaped = True x = new.coordset[dim] if hasattr(x, '_use_time_axis'): x._use_time_axis = True # we need to havze dimentionless or time units # get the lastcoord if x.unitless or x.dimensionless or \ x.units.dimensionality == '[time]': if not x.linear: # This method apply only to linear coordinates. # we try to linearize it x = LinearCoord(x) if not x.linear: raise TypeError('Coordinate x is not linearisable') data = method(new.data, **kwargs) new._data = data # we needs to increase the x coordinates array x._size = new._data.shape[-1] # update with the new td new.meta.td[-1] = x.size new.history = f'`{method.__name__}` shift performed on dimension `{dim}` with parameters: {kwargs}' else: error_('zero-filling apply only to dimensions with [time] dimensionality or dimensionless coords\n' 'The processing was thus cancelled') # restore original data order if it was swaped if swaped: new.swapdims(axis, -1, inplace=True) # must be done inplace return new return wrapper # ====================================================================================================================== # Private methods # ====================================================================================================================== def _zf_pad(data, pad=0, mid=False, **kwargs): """ Zero fill by padding with zeros. Parameters ---------- dataset : ndarray Array of NMR data. pad : int Number of zeros to pad data with. mid : bool True to zero fill in middle of data. Returns ------- ndata : ndarray Array of NMR data to which `pad` zeros have been appended to the end or middle of the data. """ size = list(data.shape) size[-1] = int(pad) z = np.zeros(size, dtype=data.dtype) if mid: h = int(data.shape[-1] / 2.0) return np.concatenate((data[..., :h], z, data[..., h:]), axis=-1) else: return np.concatenate((data, z), axis=-1) # ====================================================================================================================== # Public methods # ====================================================================================================================== @_zf_method def zf_double(dataset, n, mid=False, **kwargs): """ Zero fill by doubling original data size once or multiple times. Parameters ---------- dataset : ndataset Array of NMR data. n : int Number of times to double the size of the data. mid : bool True to zero fill in the middle of data. Returns ------- ndata : ndarray Zero filled array of NMR data. """ return _zf_pad(dataset, int((dataset.shape[-1] * 2 ** n) - dataset.shape[-1]), mid) @_zf_method def zf_size(dataset, size=None, mid=False, **kwargs): """ Zero fill to given size. Parameters ---------- dataset : ndarray Array of NMR data. size : int Size of data after zero filling. mid : bool True to zero fill in the middle of data. Returns ------- ndata : ndarray Zero filled array of NMR data. """ if size is None: size = dataset.shape[-1] return _zf_pad(dataset, pad=int(size - dataset.shape[-1]), mid=mid) def zf_auto(dataset, mid=False): """ Zero fill to next largest power of two. Parameters ---------- dataset : ndarray Array of NMR data. mid : bool True to zero fill in the middle of data. Returns ------- ndata : ndarray Zero filled array of NMR data. """ return zf_size(dataset, size=largest_power_of_2(dataset.shape[-1]), mid=mid) zf = zf_size <file_sep>/spectrochempy/gui/layout.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements the base |Dash| class. """ __all__ = [] import base64 import os import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import dash_defer_js_import as dji import dash_daq as daq def numeric_input(id, placeholder=''): # we use text input as number doesn't work for float in dash-dbc return dbc.Input(type="text", id=id, pattern=r'[+-]{0,1}\d+.{0,1}\d*', debounce=True, placeholder=placeholder) def card_body(children, id=None, className=None): if id is None: return dbc.CardBody(children=children, className=className) else: return dbc.CardBody(children=children, className=className, id=id) def collapsable_card(*, body=None, header=None, key=None, id=None, className=None): # make a card return dbc.Card([dbc.CardHeader(children=header), dbc.Collapse(id=f'open-{key}-more', is_open=True, children=card_body(children=body, id=id, className=className))]) def card(*, body=None, className=None): # make a card return dbc.Card(card_body(children=body, className=className)) def generic_card(key, title, markdown='', children=None): return collapsable_card( header=[html.H5(title), dbc.Button("More", id=f'{key}-more', outline=True, color="info", size='sm', )], body=[dcc.Markdown(children=markdown, className="Markdown"), html.Div(children, id=key)], key=key, ) class Layout(object): def __init__(self, calling_script_name='', fix_navbar=False, data_storage='session'): self.LOGO = html.Img(src='data:image/png;base64,{}'.format(base64.b64encode( open( os.path.join(os.path.dirname(os.path.abspath(self.calling_script_name)), 'assets', 'scpy_logo.png'), 'rb').read()).decode()), width='75px', ) self.TITLE = dbc.NavbarBrand(children=dcc.Markdown('**S**pectro**C**hem**P**y *by Dash*'), id="navbarbrand", className='navbarbrand') self.data_storage = data_storage self.STORE = [dcc.Store(id='original-data', storage_type=self.data_storage), dcc.Store(id='intermediate-data', storage_type=self.data_storage), dcc.Store(id='action-history', storage_type=self.data_storage)] self.calling_script_name = calling_script_name self.sticky = 'top' if not fix_navbar else None # ------------------------------------------------------------------------------------------------------------------ # TOP BAR # ------------------------------------------------------------------------------------------------------------------ def topbar(self): return dbc.Navbar([self.LOGO, self.TITLE], color="dark", dark=True, sticky=self.sticky, ) # ------------------------------------------------------------------------------------------------------------------ # DATA TAB # ------------------------------------------------------------------------------------------------------------------ @staticmethod def about_tab(): return card(body=dcc.Markdown(""" ##### What is SpectroChemPy? **SpectroChemPy** is a framework for processing, analyzing and modeling Spectroscopic data for Chemistry with Python. It is a cross platform software, running on Linux, Windows or OS X. ##### Documentation The online Html documentation is available here: [HTML documentation](https://www.spectrochempy.fr) ##### Issue Tracker SpectroChemPy is still experimental and under active development. Its current design is subject to major changes, reorganizations, bugs and crashes!!!. You find a problem, want to suggest enhancements or want to look at the current issues and milestones, you can go there: [Issue Tracker](https://github.com/spectrochempy/spectrochempy/issues) ##### Citing SpectroChemPy When using SpectroChemPy for your own work, you are kindly requested to cite it this way: ```text <NAME> & <NAME>, (2020) SpectroChemPy (Version 0.1). Zenodo. http://doi.org/10.5281/zenodo.3823841 ``` ##### Source repository The source are versioned using the git system and hosted on the GitHub platform: https://github.com/spectrochempy/spectrochempy ##### License [CeCILL-B FREE SOFTWARE LICENSE AGREEMENT](https://cecill.info/licences/Licence_CeCILL-B_V1-en.html) """, className='markdown', ), className='control-tab') # ------------------------------------------------------------------------------------------------------------------ # PROJECT TAB # ------------------------------------------------------------------------------------------------------------------ @staticmethod def upload_form(): return card(body=[ dcc.Upload(id='upload-data', children=dbc.Button("Upload data", outline=True, color="info", size='sm', ), # Allow multiple files to be uploaded multiple=True, style={ 'float': 'left' }, ), dbc.Button("Clear current data", color="danger", outline=True, size='sm', id='close-data'), ]) def project_tab(self): return dbc.Card( dbc.CardBody( [ dbc.InputGroup( [ dbc.InputGroupAddon( dbc.DropdownMenu(label="Project", bs_size='sm', addon_type='prepend', children=[ dbc.DropdownMenuItem("New", id='project-new'), dbc.DropdownMenuItem(dcc.Upload("Open", id='upload-project'), id='project-open'), dbc.DropdownMenuItem("Save", id='project-save', disabled=True), dbc.DropdownMenuItem("Close", id='project-close', disabled=True), ]) ), dbc.Input( id='project-name', placeholder='', disabled=True, size='sm') ]), dbc.Collapse(id='show-project', children=[ self.upload_form(), dbc.Collapse(id='show-project-data', children=generic_card( key='current-data', title='Uploaded data', markdown='' # children filled from a callback ) ) ], ) ], style={ 'min-height': '200px' }), className='control-tab') # ------------------------------------------------------------------------------------------------------------------ # DATA TAB # ------------------------------------------------------------------------------------------------------------------ def roi_content(self): return [dcc.Markdown(""" Most SpectroChemPy's processing and analysis methods operate only on a region of interest (roi). By default, it is set to the whole range of data. This set up is done on the ``Original`` data. The limit are automatically visualized on the graph and applied in the ``Processed`` graph. If an offset is defined then the actual roi below is displayed accordingly (*see actual roi values below*). """, className='markdown'), # roi x limits dbc.InputGroup([dbc.InputGroupAddon(id='x-roi', addon_type="prepend"), dbc.InputGroupAddon(id='x-roi-units', addon_type="append"), ], size='sm'), dbc.InputGroup([numeric_input(id='x-roi-lower', placeholder='Lower limit'), numeric_input(id='x-roi-upper', placeholder="Upper limit"), ], size='sm', ), # x axis offset (default = 0) dbc.InputGroup([dbc.InputGroupAddon('offset', addon_type="prepend"), numeric_input(id='x-offset', placeholder="Offset value, default=0"), ], size='sm', ), dbc.FormText(id='actual-x-roi'), html.Hr(), # roi y limits dbc.InputGroup([dbc.InputGroupAddon(id='y-roi', addon_type="prepend"), dbc.InputGroupAddon(id='y-roi-units', addon_type="append"), ], size='sm'), dbc.InputGroup([numeric_input(id='y-roi-lower', placeholder="Lower limit"), numeric_input(id='y-roi-upper', placeholder="Upper limit"), ], size='sm', ), # y axis offset (default = 0) dbc.InputGroup([dbc.InputGroupAddon('Offset', addon_type="prepend"), numeric_input(id='y-offset', placeholder="Offset value, default=0"), ], size='sm', ), dbc.FormText(id='actual-y-roi'), html.Hr(), ] def mask_content(self): return [dcc.Markdown(""" To mask a region, click on the **Select region button** then select your region on the graph. To mask one of the trace, click on it (selected trace are highlihted. Confirmation will be asked before saving the masks. """, className='markdown'), # roi x limits dbc.InputGroup([dbc.InputGroupAddon("Masks", id='masks', addon_type="prepend"), dbc.Button("Select region", color="secondary", outline=True, size='sm', id='select-mask')], size='sm'), html.Pre(children="No masks selected", id='text-data'), dcc.ConfirmDialog( id='confirm-mask', ), ] def data_tab(self): return dbc.Card(dbc.CardBody([ dbc.Collapse(id='show-current-data', children=[ generic_card( key='roi', title='Region of interest', markdown="", children=[*self.roi_content()] ), generic_card( key='mask', title='Mask selection', markdown="", children=[*self.mask_content()] ) ]) ], ), className='control-tab') # ------------------------------------------------------------------------------------------------------------------ # GRAPH TAB # ------------------------------------------------------------------------------------------------------------------ def graph_tab(self): return dbc.Card( dbc.CardBody( [generic_card('layout', title='Graph layout', markdown="", children=[ dbc.Button("Zoom reset", color="secondary", outline=True, size='sm', id='zoom-reset'), dcc.Markdown( "*To reset to full range display, one can also double click on the " "graph area (It will be faster!)* "), # data type selection dcc.Markdown("###### Data to display"), dcc.Checklist( id='graph-selector', options=[ { 'label': 'Processed', 'value': 'Processed' }, { 'label': 'Transposed', 'value': 'Transposed' }, ], value=['Processed'], labelStyle={ 'display': 'inline-block', 'margin-right': '10px' }), # optimisation dcc.Markdown("###### Graph display optimisation"), html.Div(daq.Slider(min=0, max=4, value=3, step=1, marks={ '0': 'None', '1': 'Low', '2': 'Moderate', '3': 'High', '4': 'Severe' }, id='graph-optimisation', ), style={ 'margin-left': '30px', 'margin-bottom': '30px' }), # Colormap dcc.Markdown("###### Colormap"), dcc.Dropdown(id='cmap-select', options=[ { 'label': 'jet', 'value': 'jet' }, { 'label': 'jetr', 'value': 'jet_r' }, { 'label': 'viridis', 'value': 'viridis' }, { 'label': 'viridis_r', 'value': 'viridis_r' }, { 'label': 'magma', 'value': 'magma' }, { 'label': 'magma_r', 'value': 'magma_r' }, ], value='jet', style={ 'width': '150px' } ) ], ), generic_card('xaxis', 'Horizontal axis layout', """ xaxis description """), generic_card('zaxis', 'vertical axis layout', """ zaxis description """), ] ), className='control-tab') # ------------------------------------------------------------------------------------------------------------------ # PROCESSING TAB # ------------------------------------------------------------------------------------------------------------------ def baseline(self): return [html.Hr(), html.H6('Method'), dcc.Dropdown(options=[{ 'label': 'Detrend', 'value': 'detrend' }, { 'label': 'PChip', 'value': 'pchip' }, { 'label': 'Polynomial', 'value': 'polynomial' }, { 'label': 'Multivariate', 'value': 'multivariate' }, ], multi=False, id='subtraction_correction') ] def subtraction(self): return [html.Hr(), html.H6('Method'), dcc.Dropdown(options=[{ 'label': 'Subtract first row', 'value': 'first' }, { 'label': 'Subtract last row', 'value': 'last' }, { 'label': 'Subtract an external reference spectra', 'value': 'external' }, ], multi=False, id='subtraction-correction'), html.Div(id='baseline_parameters')] def processing_tab(self): return dbc.Card(dbc.CardBody( [generic_card('subtraction', 'Subtraction correction', # DO NOT FORGET TO ADD NEW KEYS IN CALLBACK children=self.subtraction()), generic_card('baseline', 'Baseline correction', children=self.baseline()), generic_card('peakpicking', 'Peak Picking', """ essai """), ]), className='control-tab') # ------------------------------------------------------------------------------------------------------------------ # TABS ZONE # ------------------------------------------------------------------------------------------------------------------ def tabs_zone(self): return dbc.Col( [ dbc.Tabs([dbc.Tab(self.about_tab(), label="About", tab_id='about'), dbc.Tab(self.project_tab(), label="Project", tab_id='project'), dbc.Tab(self.data_tab(), label="Data", tab_id='data', id='data-tab'), dbc.Tab(self.graph_tab(), label="Graph", tab_id='graph', id='graph-tab'), dbc.Tab(self.processing_tab(), label="Processing", tab_id='processing', id='processing-tab') ], active_tab='project'), ], width=4, id='scpy-control-tabs', className='control-tabs') # ------------------------------------------------------------------------------------------------------------------ # DISPLAY ZONE # ------------------------------------------------------------------------------------------------------------------ def graph_zone(self): graph_selector = dbc.ButtonGroup([ ], ) config = { 'scrollZoom': True, 'doubleClick': 'reset', 'displayModeBar': False, 'displaylogo': False } graph = dcc.Loading(dcc.Graph(id='graph', config=config, responsive=True, ), type='circle', ) return dbc.Col(dbc.Collapse([ graph, graph_selector, ], id='show-graph'), ) # ------------------------------------------------------------------------------------------------------------------ # FINAL LAYOUT # ------------------------------------------------------------------------------------------------------------------ def layout(self): mathjax_script = dji.Import( src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_SVG") refresh_plots = dji.Import(src="https://www.spectrochempy.fr/gui/redraw.js") layout = html.Div([html.P(""), dbc.Container(children=[dbc.Row([self.tabs_zone(), self.graph_zone()], ), ], fluid=True, style={ "font-size": '10pt', 'height': '80vh' }, ), refresh_plots, mathjax_script, ], ) return layout # ...................................................................................................................... def app_page_layout(self): return html.Div(id='main_page', children=[dcc.Location(id='url', refresh=False), *self.STORE, self.topbar(), self.layout(), ]) <file_sep>/docs/userguide/analysis/peak_integration.py # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # Peak integration # # This tutorial shows how to find peak maxima and determine peak areas with spectrochempy. As prerequisite, # the user is expected to have read the [Import](../IO/import.ipynb), [Import IR](../IO/importIR.ipynb), # [slicing](../processing/slicing.ipynb) and [baseline correction](../processing/baseline_correct.ipynb) tutorials. # %% [markdown] # First lets import the SpectroChemPy API # %% import spectrochempy as scp # %% [markdown] # Now import some 2D data into a NDDataset object # %% ds = scp.read_omnic("irdata/nh4y-activation.spg") ds # %% [markdown] # It's a series of 55 spectra. # # For the demonstration select only the first 20 on a limited region from 1250 to 1800 cm$^{-1}$ (Do not forget to # use floating numbers for slicing) # %% X = ds[:20, 1250.0:1800.] # %% [markdown] # We can also eventually remove offset on the acquisition time dimension (y) # %% X.y -= X.y[0] X.y.ito('min') X.y.title = 'Acquisition time' # %% [markdown] # We set some plotting preferences and then plot the raw data # %% prefs = X.preferences prefs.figure.figsize = (6, 3) prefs.colormap = 'Dark2' prefs.colorbar = True X.plot(); # %% [markdown] # Now we can perform some baseline correction # %% blc = scp.BaselineCorrection(X) regions = ( [1740., 1800.0], [1550., 1570.], [1250., 1300.]) # define 3 regions where we want the baseline to reach zero. Xcorr = blc.compute(*regions) # compute the corrected NDDataset Xcorr.plot(); # %% [markdown] # To integrate each row on the full range, we can use the sum or trapz method of a NDDataset. # %% inttrapz = Xcorr.trapz(dim='x') intsimps = Xcorr.simps(dim='x') # %% [markdown] # As you can see both method give almost the same results in this case # %% scp.plot_multiple(method='scatter', ms=5, datasets=[inttrapz, intsimps], labels=['trapzoidal rule', 'simpson\' rule'], legend='best'); # %% [markdown] # The difference between the trapezoidal and simpson integration methods is visualized below. In this case they are # extremly close. # %% diff = ((inttrapz - intsimps) * 100. / intsimps) diff.title = 'Difference' diff.units = 'percent' diff.plot(scatter=True, ms=5); <file_sep>/docs/devguide/docker.rst .. _contributing.docker: ********************** Building Docker images ********************** Docker is an open platform for developing, shipping, and running applications. It allows to develop and run |scpy| in an unified environment whatever the host platform is. For the end-user it should also help to avoid all installation problems as the images created have been tested before being shipped. If you like to understand better how it works you can go to the `Docker tutorial <https://www.docker.com/101-tutorial>`__. Docker Installation ==================== see :ref:`install_docker_details` Building the environment image locally ======================================= To build a |scpy| image you can do it using the ``Docker build`` command in the directory where is located the ``Dockerfile``: .. sourcecode:: bash cd /path/to/spectrochempy/local/repository/.ci docker build -t spectrocat/spectrochempy:latest . Due to the large number of operations to achieve (mainly downloading required packeges), this process can be rather long the first time it is executed. Further build after modification of the Dockerfile will generally be faster as most of the step are in a cache. Creating and executing a Docker container ========================================= Creating a container can be done using the Docker run command with the previously created image. The recommended way: .. sourcecode:: bash docker run -v /full/path/on/host/spectrochempy:/home/jovyan/spectrochempy \ -p 8888:8888 \ --name scpy \ spectrocat/spectrochempy:latest \ start.sh jupyter lab This start a Jupyter Lab server on port 8888. docker run -p 8888:8888 \ --name scpy \ spectrocat/spectrochempy:latest \ start.sh jupyter lab <file_sep>/docs/gettingstarted/examples/analysis/plot_mcrals_chrom1.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ MCR-ALS optimization example (original example from Jaumot) =========================================================== In this example, we perform the MCR ALS optimization of a dataset corresponding to a HPLC-DAD run, from `Jaumot et al. Chemolab, 76 (2005) 101-110, <https://doi.org/10.1016/j.chemolab.2004.12.007>`_ and `Jaumot et al. Chemolab, 140 (2015) pp. 1-12. <https://doi.org/10.1016/j.chemolab.2014.10.003>`_ This dataset (and others) can be loaded from the `"Multivariate Curve Resolution Homepage". <https://mcrals.wordpress.com/download/example-data-sets>`_ For the user convenience, this dataset is present in the `datadir`of SpectroChemPy as 'als2004dataset.MAT' """ import spectrochempy as scp ######################################################################################################################## # Load the dataset datasets = scp.read_matlab("matlabdata/als2004dataset.MAT") ######################################################################################################################## # As the .mat file contains 6 matrices, 6 NDDataset objects are returned: print('\n NDDataset names: ' + str([ds.name for ds in datasets])) ######################################################################################################################## # We are interested in the first dataset ('m1') that contains a single HPLS-DAD run (51x96) dataset. # As usual, the 51 rows correspond to the 'time axis' of the HPLC run, and the 96 columns to the 'wavelength' axis # of the UV spectra. The original dataset does not contain information as to the actual time and wavelength coordinates. # # MCR-ALS needs also an initial guess for either concentration profiles or pure spectra concentration profiles. # The second dataset 'spure' is a (4x96) guess of spectral profiles. # # Load the experimental data as X and the guess: X = datasets[0] guess = datasets[1] ######################################################################################################################## # Create a MCR-ALS object with the default settings # The verbose option can be set True to get a summary of optimization steps mcr = scp.MCRALS(X, guess, verbose=False) ######################################################################################################################## # The optimization has converged. We can get the concentration (C) and pure spectra profiles (St) # and plot them _ = mcr.C.T.plot() _ = mcr.St.plot() ######################################################################################################################## # Finally, plots the reconstructed dataset (X_hat = C St) vs original dataset (X) # an residuals. The fit is good and comparable with the original paper. X_hat = mcr.plotmerit() # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/Dockerfile # Choose the minimal jupyter image: https://jupyter-docker-stacks.readthedocs.io/en/latest/using/selecting.html FROM jupyter/base-notebook:latest USER root RUN sudo apt-get update -y && \ sudo apt-get install -y libx11-6 USER $NB_UID # Choose python 3.8 version ARG PY_VERSION=3.8 ARG DEV='' ARG DASH='' ARG CANTERA='' ARG BRANCH='' # ENV CONDA_ENV scpy$PY_VERSION # We will first create a YAML file and then use it to update the environment # to be suitable for spectrochempy COPY --chown=${NB_UID}:${NB_GID} .ci/env/env* /home/$NB_USER/tmp/ RUN cd /home/$NB_USER/tmp/ && \ conda update conda && \ conda install -c conda-forge mamba jinja2 && \ python env_create.py -v $PY_VERSION $DEV $DASH $CANTERA scpy$PY_VERSION.yml && \ # mamba env create -p $CONDA_DIR/envs/$CONDA_ENV -f scpy$PY_VERSION.yml && \ mamba env update --name base -f scpy$PY_VERSION.yml && \ conda clean --all -f -y && \ rm -rf /home/$NB_USER/tmp # Install spectrochempy COPY --chown=${NB_UID}:${NB_GID} . /home/$NB_USER/spectrochempy/ RUN cd spectrochempy && \ git checkout $BRANCH && \ python setup.py install <file_sep>/docs/userguide/databases/databases.rst .. _userguide.databases: Databases ############### .. todo:: To be documented<file_sep>/docs/gettingstarted/examples/plotting/plot_plotting.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Introduction to the plotting librairie =========================================== """ import spectrochempy as scp import os # this also import the os namespace # sp.set_loglevel('DEBUG') datadir = scp.preferences.datadir dataset = scp.NDDataset.read_omnic( os.path.join(datadir, 'irdata', 'nh4y-activation.spg')) ######################################################################################################################## # plot generic ax = dataset[0].plot() ######################################################################################################################## # plot generic style ax = dataset[0].plot(style='classic') ######################################################################################################################## # check that style reinit to default # should be identical to the first ax = dataset[0].plot() ######################################################################################################################## # Multiple plots dataset = dataset[:, ::100] datasets = [dataset[0], dataset[10], dataset[20], dataset[50], dataset[53]] labels = ['sample {}'.format(label) for label in ["S1", "S10", "S20", "S50", "S53"]] scp.plot_multiple(method='scatter', datasets=datasets, labels=labels, legend='best') ######################################################################################################################## # plot mupltiple with style scp.plot_multiple(method='scatter', style='sans', datasets=datasets, labels=labels, legend='best') ######################################################################################################################## # check that style reinit to default scp.plot_multiple(method='scatter', datasets=datasets, labels=labels, legend='best') # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/docs/userguide/reference/api-hidden.rst .. Generate API reference pages, but don't display these in tables. :orphan: .. currentmodule:: spectrochempy .. autosummary:: :toctree: generated/ NDDataset.ab NDDataset.abc NDDataset.abs NDDataset.absolute NDDataset.add_coordset NDDataset.align NDDataset.all NDDataset.any NDDataset.arange NDDataset.argmax NDDataset.argmin NDDataset.asfortranarray NDDataset.astype NDDataset.autosub NDDataset.average NDDataset.bartlett NDDataset.blackmanharris NDDataset.clip NDDataset.close_figure NDDataset.concatenate NDDataset.conj NDDataset.coord NDDataset.coordmax NDDataset.coordmin NDDataset.copy NDDataset.cumsum NDDataset.delete_coordset NDDataset.detrend NDDataset.diag NDDataset.diagonal NDDataset.download_IRIS NDDataset.dump NDDataset.em NDDataset.empty NDDataset.empty_like NDDataset.expand_dims NDDataset.eye NDDataset.fft NDDataset.find_peaks NDDataset.fromfunction NDDataset.fromiter NDDataset.full NDDataset.full_like NDDataset.geomspace NDDataset.get_axis NDDataset.get_labels NDDataset.get_zpd NDDataset.gm NDDataset.hamming NDDataset.identity NDDataset.ifft NDDataset.implements NDDataset.is_units_compatible NDDataset.ito NDDataset.ito_base_units NDDataset.ito_reduced_units NDDataset.linspace NDDataset.load NDDataset.logspace NDDataset.max NDDataset.mean NDDataset.mertz NDDataset.min NDDataset.ones NDDataset.ones_like NDDataset.part NDDataset.pipe NDDataset.plot NDDataset.plot_1D NDDataset.plot_2D NDDataset.plot_bar NDDataset.plot_generic NDDataset.plot_image NDDataset.plot_map NDDataset.plot_pen NDDataset.plot_scatter NDDataset.plot_scatter_pen NDDataset.plot_stack NDDataset.plot_surface NDDataset.plot_waterfall NDDataset.plotly NDDataset.plotly_stack NDDataset.ptp NDDataset.qsin NDDataset.random NDDataset.read NDDataset.read_carroucell NDDataset.read_csv NDDataset.read_dir NDDataset.read_jcamp NDDataset.read_labspec NDDataset.read_mat NDDataset.read_matlab NDDataset.read_omnic NDDataset.read_opus NDDataset.read_spa NDDataset.read_spg NDDataset.read_srs NDDataset.read_topspin NDDataset.read_zip NDDataset.remove_masks NDDataset.save NDDataset.save_as NDDataset.savgol_filter NDDataset.set_complex NDDataset.set_coordset NDDataset.set_coordtitles NDDataset.set_coordunits NDDataset.set_hypercomplex NDDataset.set_quaternion NDDataset.simps NDDataset.sine NDDataset.sinm NDDataset.smooth NDDataset.sort NDDataset.sp NDDataset.squeeze NDDataset.stack NDDataset.std NDDataset.sum NDDataset.swapaxes NDDataset.swapdims NDDataset.take NDDataset.to NDDataset.to_array NDDataset.to_base_units NDDataset.to_reduced_units NDDataset.to_xarray NDDataset.transpose NDDataset.trapz NDDataset.triang NDDataset.var NDDataset.write NDDataset.write_csv NDDataset.write_excel NDDataset.write_jcamp NDDataset.write_jdx NDDataset.write_mat NDDataset.write_matlab NDDataset.zeros NDDataset.zeros_like NDDataset.II NDDataset.IR NDDataset.RI NDDataset.RR NDDataset.T NDDataset.author NDDataset.ax NDDataset.axT NDDataset.axec NDDataset.axecT NDDataset.axex NDDataset.axey NDDataset.coordset NDDataset.coordtitles NDDataset.coordunits NDDataset.created NDDataset.data NDDataset.date NDDataset.desc NDDataset.description NDDataset.dimensionless NDDataset.dims NDDataset.directory NDDataset.divider NDDataset.dtype NDDataset.fig NDDataset.fignum NDDataset.filename NDDataset.has_complex_dims NDDataset.has_data NDDataset.has_defined_name NDDataset.has_units NDDataset.history NDDataset.id NDDataset.imag NDDataset.is_1d NDDataset.is_complex NDDataset.is_empty NDDataset.is_float NDDataset.is_integer NDDataset.is_labeled NDDataset.is_masked NDDataset.is_quaternion NDDataset.itemsize NDDataset.limits NDDataset.linear NDDataset.m NDDataset.magnitude NDDataset.mask NDDataset.masked_data NDDataset.meta NDDataset.modeldata NDDataset.modified NDDataset.name NDDataset.ndaxes NDDataset.ndim NDDataset.origin NDDataset.parent NDDataset.preferences NDDataset.real NDDataset.roi NDDataset.shape NDDataset.size NDDataset.suffix NDDataset.title NDDataset.umasked_data NDDataset.unitless NDDataset.units NDDataset.value NDDataset.values Coord.arange Coord.astype Coord.copy Coord.fromfunction Coord.fromiter Coord.geomspace Coord.get_labels Coord.implements Coord.is_units_compatible Coord.ito Coord.ito_base_units Coord.ito_reduced_units Coord.linspace Coord.logspace Coord.max Coord.min Coord.ptp Coord.to Coord.to_base_units Coord.to_reduced_units Coord.created Coord.data Coord.date Coord.desc Coord.description Coord.dimensionless Coord.dtype Coord.has_data Coord.has_defined_name Coord.has_units Coord.id Coord.is_empty Coord.is_float Coord.is_integer Coord.is_labeled Coord.itemsize Coord.labels Coord.limits Coord.linear Coord.m Coord.magnitude Coord.meta Coord.modified Coord.name Coord.reversed Coord.roi Coord.size Coord.title Coord.unitless Coord.units Coord.value Coord.values LinearCoord.arange LinearCoord.astype LinearCoord.copy LinearCoord.fromfunction LinearCoord.fromiter LinearCoord.get_labels LinearCoord.implements LinearCoord.is_units_compatible LinearCoord.ito LinearCoord.ito_base_units LinearCoord.ito_reduced_units LinearCoord.linspace LinearCoord.max LinearCoord.min LinearCoord.ptp LinearCoord.to LinearCoord.to_base_units LinearCoord.to_reduced_units LinearCoord.created LinearCoord.data LinearCoord.date LinearCoord.desc LinearCoord.description LinearCoord.dimensionless LinearCoord.dtype LinearCoord.has_data LinearCoord.has_defined_name LinearCoord.has_units LinearCoord.id LinearCoord.is_empty LinearCoord.is_float LinearCoord.is_integer LinearCoord.is_labeled LinearCoord.itemsize LinearCoord.labels LinearCoord.limits LinearCoord.linear LinearCoord.m LinearCoord.magnitude LinearCoord.meta LinearCoord.modified LinearCoord.name LinearCoord.reversed LinearCoord.roi LinearCoord.size LinearCoord.title LinearCoord.unitless LinearCoord.units LinearCoord.value LinearCoord.values CoordSet.copy CoordSet.implements CoordSet.keys CoordSet.set CoordSet.set_titles CoordSet.set_units CoordSet.to_dict CoordSet.update CoordSet.available_names CoordSet.has_defined_name CoordSet.id CoordSet.is_empty CoordSet.is_same_dim CoordSet.labels CoordSet.names CoordSet.size CoordSet.sizes CoordSet.titles CoordSet.units SVD.ev SVD.ev_cum SVD.ev_ratio SVD.sv PCA.printev PCA.reconstruct PCA.reduce PCA.scoreplot PCA.screeplot PCA.LT PCA.S PCA.X PCA.ev PCA.ev_cum PCA.ev_ratio LSTSQ.inverse_transforms LSTSQ.trans LSTSQ.itrans LSTSQ.transform CurveFit.inverse_transforms CurveFit.trans CurveFit.itrans CurveFit.transform NNLS.inverse_transforms NNLS.trans NNLS.itrans NNLS.transform EFA.get_conc EFA.cutoff EFA.f_ev EFA.b_ev SIMPLISMA.plotmerit SIMPLISMA.reconstruct SIMPLISMA.C SIMPLISMA.Pt SIMPLISMA.St SIMPLISMA.X SIMPLISMA.logs SIMPLISMA.s IRIS.plotdistribution IRIS.plotlcurve IRIS.plotmerit IRIS.reconstruct MCRALS.plotmerit MCRALS.reconstruct MCRALS.C MCRALS.St MCRALS.X MCRALS.extC MCRALS.extOutput MCRALS.logs MCRALS.params <file_sep>/spectrochempy/core/processors/shift.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ A collection of NMR spectral processing functions which operate on the last dimension (1) of 2D arrays. Adapted from NMRGLUE proc_base (New BSD License) """ __all__ = ['rs', 'ls', 'roll', 'cs', 'fsh', 'fsh2'] __dataset_methods__ = __all__ import numpy as np from spectrochempy.core.processors.utils import _units_agnostic_method pi = np.pi # ====================================================================================================================== # Public methods # ====================================================================================================================== @_units_agnostic_method def rs(dataset, pts=0.0, **kwargs): """ Right shift and zero fill. For multidimensional NDDataset, the shift is by default performed on the last dimension. Parameters ---------- dataset : nddataset nddataset to be right-shifted pts : int Number of points to right shift. Returns ------- dataset dataset right shifted and zero filled. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the shift method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. See Also -------- roll : shift without zero filling. """ data = np.roll(dataset, int(pts)) data[..., :int(pts)] = 0 return data @_units_agnostic_method def ls(dataset, pts=0.0, **kwargs): """ Left shift and zero fill. For multidimensional NDDataset, the shift is by default performed on the last dimension. Parameters ---------- dataset : nddataset nddataset to be left-shifted pts : int Number of points to right shift. Returns ------- dataset dataset left shifted and zero filled. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the shift method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. See Also -------- roll : shift without zero filling. """ data = np.roll(dataset, -int(pts)) data[..., -int(pts):] = 0 return data # no decorator as it delegate to roll def cs(dataset, pts=0.0, neg=False, **kwargs): """ Circular shift. For multidimensional NDDataset, the shift is by default performed on the last dimension. Parameters ---------- dataset : nddataset nddataset to be shifted pts : int Number of points toshift. neg : bool True to negate the shifted points. Returns ------- dataset dataset shifted Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the shift method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. See Also -------- roll : shift without zero filling. """ return roll(dataset, pts, neg, **kwargs) @_units_agnostic_method def roll(dataset, pts=0.0, neg=False, **kwargs): """ Roll dimensions. For multidimensional NDDataset, the shift is by default performed on the last dimension. Parameters ---------- dataset : nddataset nddataset to be shifted pts : int Number of points toshift. neg : bool True to negate the shifted points. Returns ------- dataset dataset shifted Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the shift method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. See Also -------- ls, rs, cs, fsh, fsh2 """ data = np.roll(dataset, int(pts)) if neg: if pts > 0: data[..., :int(pts)] = -data[..., :int(pts)] else: data[..., int(pts):] = -data[..., int(pts):] return data @_units_agnostic_method def fsh(dataset, pts, **kwargs): """ Frequency shift by Fourier transform. Negative signed phase correction. For multidimensional NDDataset, the shift is by default performed on the last dimension. Parameters ---------- data : ndarray Array of NMR data. pts : float Number of points to frequency shift the data. Positive value will shift the spectrum to the right, negative values to the left. Returns ------- dataset dataset shifted Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the shift method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. See Also -------- ls, rs, cs, roll, fsh2 """ from spectrochempy.core.processors.fft import _fft, _ifft s = float(dataset.shape[-1]) data = _ifft(dataset) data = np.exp(-2.j * pi * pts * np.arange(s) / s) * data data = _fft(data) return data @_units_agnostic_method def fsh2(dataset, pts, **kwargs): """ Frequency Shift by Fourier transform. Positive signed phase correction. For multidimensional NDDataset, the shift is by default performed on the last dimension. Parameters ---------- data : ndarray Array of NMR data. pts : float Number of points to frequency shift the data. Positive value will shift the spectrum to the right, negative values to the left. Returns ------- dataset dataset shifted Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the shift method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. See Also -------- ls, rs, cs, roll, fsh2 """ from spectrochempy.core.processors.fft import _fft_positive, _ifft_positive s = float(dataset.shape[-1]) data = _ifft_positive(dataset) data = np.exp(2.j * pi * pts * np.arange(s) / s) * data data = _fft_positive(data) return data <file_sep>/docs/gettingstarted/examples/nddataset/plot_create_dataset.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ NDDataset creation and plotting example ======================================= In this example, we create a 3D NDDataset from scratch, and then we plot one section (a 2D plane) """ ############################################################################### # As usual, we start by loading the spectrochempy library import spectrochempy as scp import numpy as np ############################################################################### # Creation # ---------------------------------------------------------------------------------------------------------------------- # Now we will create a 3D NDDataset from scratch # # Data # ++++++ # here we make use of numpy array functions to create the data fot coordinates # axis and the array of data c0 = np.linspace(200., 300., 3) c1 = np.linspace(0., 60., 100) c2 = np.linspace(4000., 1000., 100) nd_data = np.array([np.array( [np.sin(2. * np.pi * c2 / 4000.) * np.exp(-y / 60) for y in c1]) * t for t in c0]) ############################################################################### # Coordinates # +++++++++++ # The `Coord` object allow making an array of coordinates # with additional metadata such as units, labels, title, etc coord0 = scp.Coord(data=c0, labels=['cold', 'normal', 'hot'], units="K", title='temperature') coord1 = scp.Coord(data=c1, labels=None, units="minutes", title='time-on-stream') coord2 = scp.Coord(data=c2, labels=None, units="cm^-1", title='wavenumber') ############################################################################### # Labels can be useful for instance for indexing a = coord0['normal'] print(a) #################################################### # nd-Dataset # +++++++++++ # The |NDDataset| object allow making the array of data with units, etc... mydataset = scp.NDDataset(nd_data, coordset=[coord0, coord1, coord2], title='Absorbance', units='absorbance') mydataset.description = """Dataset example created for this tutorial. It's a 3-D dataset (with dimensionless intensity: absorbance )""" mydataset.name = 'An example from scratch' mydataset.author = '<NAME> Mortimer' print(mydataset) ################################################################## # We want to plot a section of this 3D NDDataset: # # NDDataset can be sliced like conventional numpy-array... new = mydataset[..., 0] ################################################################## # or maybe more conveniently in this case, using an axis labels: new = mydataset['hot'] ################################################################## # To plot a dataset, use the `plot` command (generic plot). # As the section NDDataset is 2D, a contour plot is displayed by default. new.plot() ################################################################## # But it is possible to display image # # sphinx_gallery_thumbnail_number = 2 new.plot(method='image') ################################################################## # or stacked plot new.plot(method='stack') ################################################################## # Note that the scp allows one to use this syntax too: scp.plot_stack(new) # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/docs/gettingstarted/whyscpy.rst .. _whyscpy: **************************************** Why |scpy| ? **************************************** **Table of contents** .. contents:: :local: The |scpy| project was developed to provide advanced tools for processing and analyzing spectroscopic data, initially for internal purposes in the `LCS <https://www.lcs.ensicaen.fr/>`__, for the following reasons: Designed for Open Science ========================== While commercial software usually provides powerful and easy-to-use graphical user interfaces (GUIs), basic algorithms such as baseline correction systems, automatic subtraction, peak detection, curve fitting, etc. are generally not disclosed to the user. Although they are generally to be trusted (it is in the sole interest of these companies to provide reliable tools), the spectroscopist sometimes needs to know the details of how the data provided is processed or analyzed. These details are usually neither given in the software manual nor disclosed by the company's technical staff. In addition, the "click, drag and drop" approach of many graphical interfaces often prevents full reproducibility. This is the case, for example, with advanced integration or basic editing in many commercial software products. Some of them do not always allow to check the history of the data, which is also problematic for the verification of data integrity and reproducibility. In particular, |scpy| : - is entirely open source and relies on algorithms documented in the code. - allows to follow the complete history of data sets and analyses ("history" field) - allows to integrate the content of a particular job (data, scripts, notebooks, ...) into a dedicated data structure ("Project"), guaranteeing a complete follow-up from the import of raw data to the final results.. .. note:: SpectroChemPy does not guarantee "data integrity", in that the validity of the raw data and the correct use of the processing and analysis tools is the responsibility of the user. SpectroChemPy is probably not free of bugs in some (hopefully rare) cases. In any case, critical bugs affecting data integrity will be reported in the documentation for the version(s) of |scpy| concerned, allowing the source of these errors to be traced. Open souce software on an open source platform =============================================== While powerful and popular tools have been developed by instrument manufacturers, software companies, or academic research groups, most are proprietary or require proprietary computing environments (e.g., MATLAB). The cost of licensing can be problematic in some cases: "isolated" research groups, developing countries, doctoral or post-doc students leaving a group with their data, etc. It was important for us to be able to share spectroscopic data / data processing tools / data analysis tools with our colleagues, without imposing a financial burden on them... or pushing them to use cracked copies. |scpy| is free of charge and under a free software license (`Licence [CeCILL-B] <https://cecill.info/index.en.html>`__). CeCILL-B follows the principle of the popular BSD license and its variants (Apache, X11 or W3C among others). In exchange for strong citation obligations (in all software incorporating a program covered by CeCILL-B and also through a Web site), the author authorizes the reuse of its software without any other constraints. Powered by Python ================== Python is probably the most popular, open-source language used by Data Scientists. It is extensible and cross-platform, allowing |scpy| to be used in an entirely open-source software environment. |scpy| uses state-of-the-art libraries for numerical computation (`numpy <https://numpy.org/>`__, `scipy <https://www.scipy.org/>`__) and visualization (`matplotlib <https://matplotlib.org/>`__). As the Python community is extremely dynamic, all users should easily find resources to solve specific needs that are not (yet) directly or completely satisfied by |scpy|. We also rely on the motivated members of this community (of which you are a part), to contribute to the improvement of |scpy| through (:ref:`contributing.bugs_report`), or contributions to the code (:ref:`develguide`). Why NOT |scpy| ? ======================== You might **NOT** want to use |scpy| if: - you are resistant to command line code (Python) or scripts. Since |scpy| is essentially an Application Programming Interface (API), it requires writing commands and small scripts. its documentation and resources contain fully documented examples (see :ref:`examples-index`) and tutorials (see :ref:`userguide`), which should be easy to transpose into your own data. In particular, the use of Jupyter notebooks mixing texts, code blocks and figures, so that basic procedures (data import, basic processing and analysis, etc...) do not require much programming knowledge. - you are working on spectroscopic data that are difficult to process, including |scpy| (currently mainly focused on optical spectroscopy and NMR) because some components or tools (e.g. importing your raw data, ...) are missing: please suggest new features that should be added (:ref:`contributing.bugs_report`). We will take into consideration all suggestions to make |scpy| more widely and easily usable. - you are working on very sensitive data (health, chemical safety, plant production, ...) and cannot take the risk to use a software under development and subject to bugs and changes before "maturity". We do not dispute this! - you are fully satisfied with your current tools. "The heart has its reasons, of which the reason knows nothing". We don't dispute that either, but we are open to your opinion and suggestions (bug reports and requests for improvements/functionality)! - you are fully satisfied with your current tools. "The heart has its reasons, of which the reason knows nothing". We don't dispute that either, but we are open to your opinion and suggestions (:ref:`contributing.bugs_report`)! <file_sep>/spectrochempy/core/dataset/nddataset.py # -*- coding: utf-8 -*- # # ====================================================================================================================== # Copyright (©) 2015-2019 LCS # Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT # See full LICENSE agreement in the root directory # ====================================================================================================================== """ This module implements the |NDDataset| class. """ __all__ = ['NDDataset'] import textwrap import warnings import sys import numpy as np from traitlets import HasTraits, Instance, Bool, Float, validate, default from traittypes import Array from spectrochempy.core.project.baseproject import AbstractProject from spectrochempy.core.dataset.ndarray import NDArray, DEFAULT_DIM_NAME from spectrochempy.core.dataset.ndcomplex import NDComplexArray from spectrochempy.core.dataset.coord import Coord, LinearCoord from spectrochempy.core.dataset.coordset import CoordSet from spectrochempy.core.dataset.ndmath import NDMath, _set_ufuncs, _set_operators from spectrochempy.core.dataset.ndio import NDIO from spectrochempy.core.dataset.ndplot import NDPlot from spectrochempy.core import error_, warning_ from spectrochempy.utils import (colored_output, SpectroChemPyException, SpectroChemPyWarning, ) HAS_XARRAY = False try: import xarray as xr HAS_XARRAY = True # pragma: no cover except ImportError: xr = None # pragma: no cover # ====================================================================================================================== # NDDataset class definition # ====================================================================================================================== class NDDataset(NDIO, NDPlot, NDMath, NDComplexArray): # coordinates _coordset = Instance(CoordSet, allow_none=True) # model data (e.g., for fit) _modeldata = Array(Float(), allow_none=True) # some setting for NDDataset _copy = Bool(False) _labels_allowed = Bool(False) # no labels for NDDataset # dataset can be members of a project. # we use the abstract class to avoid circular imports. _parent = Instance(AbstractProject, allow_none=True) # ------------------------------------------------------------------------------------------------------------------ # initialisation # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def __init__(self, data=None, coordset=None, coordunits=None, coordtitles=None, **kwargs): """ The main N-dimensional dataset class used by |scpy|. The NDDataset is the main object use by SpectroChemPy. Like numpy ndarrays, NDDataset have the capability to be sliced, sorted and subject to mathematical operations. But, in addition, NDDataset may have units, can be masked and each dimensions can have coordinates also with units. This make NDDataset aware of unit compatibility, e.g., for binary operation such as additions or subtraction or during the application of mathematical operations. In addition or in replacement of numerical data for coordinates, NDDataset can also have labeled coordinates where labels can be different kind of objects (strings, datetime, numpy nd.ndarray or othe NDDatasets, etc…). Parameters ---------- data : array of floats Data array contained in the object. The data can be a list, a tuple, a |ndarray|, a ndarray-like, a |NDArray| or any subclass of |NDArray|. Any size or shape of data is accepted. If not given, an empty |NDArray| will be inited. At the initialisation the provided data will be eventually casted to a numpy-ndarray. If a subclass of |NDArray| is passed which already contains some mask, labels, or units, these elements will be used to accordingly set those of the created object. If possible, the provided data will not be copied for `data` input, but will be passed by reference, so you should make a copy of the `data` before passing them if that's the desired behavior or set the `copy` argument to True. coordset : An instance of |CoordSet|, optional `coords` contains the coordinates for the different dimensions of the `data`. if `coords` is provided, it must specified the `coord` and `labels` for all dimensions of the `data`. Multiple `coord`'s can be specified in an |CoordSet| instance for each dimension. coordunits : list, optional A list of units corresponding to the dimensions in the order of the coordset. coordtitles : list, optional A list of titles corresponding of the dimensions in the order of the coordset. **kwargs : dict See other parameters. Other Parameters ---------------- dtype : str or dtype, optional, default=np.float64 If specified, the data will be casted to this dtype, else the data will be casted to float64 or complex128. dims : list of chars, optional If specified the list must have a length equal to the number od data dimensions (ndim) and the chars must be taken among among x,y,z,u,v,w or t. If not specified, the dimension names are automatically attributed in this order. name : str, optional A user friendly name for this object. If not given, the automatic `id` given at the object creation will be used as a name. labels : array of objects, optional Labels for the `data`. labels can be used only for 1D-datasets. The labels array may have an additional dimension, meaning several series of labels for the same data. The given array can be a list, a tuple, a |ndarray|, a ndarray-like, a |NDArray| or any subclass of |NDArray|. mask : array of bool or `NOMASK`, optional Mask for the data. The mask array must have the same shape as the data. The given array can be a list, a tuple, or a |ndarray|. Each values in the array must be `False` where the data are *valid* and True when they are not (like in numpy masked arrays). If `data` is already a :class:`~numpy.ma.MaskedArray`, or any array object (such as a |NDArray| or subclass of it), providing a `mask` here will causes the mask from the masked array to be ignored. units : |Unit| instance or str, optional Units of the data. If data is a |Quantity| then `units` is set to the unit of the `data`; if a unit is also explicitly provided an error is raised. Handling of units use the `pint <https://pint.readthedocs.org/>`_ package. title : str, optional The title of the dimension. It will later be used for instance for labelling plots of the data. It is optional but recommended to give a title to each ndarray. dlabel : str, optional Alias of `title`. meta : dict-like object, optional Additional metadata for this object. Must be dict-like but no further restriction is placed on meta. author : str, optional Name(s) of the author(s) of this dataset. BNy default, name of the computer note where this dataset is created. description : str, optional A optional description of the nd-dataset. A shorter alias is `desc`. history : str, optional A string to add to the object history. copy : bool, optional Perform a copy of the passed object. Default is False. See Also -------- Coord : Explicit coordinates object. LinearCoord : Implicit coordinates objet. CoordSet : Set of coordinates. Notes ----- The underlying array in a |NDDataset| object can be accessed through the `data` attribute, which will return a conventional |ndarray|. Examples -------- Usage by an end-user >>> from spectrochempy import * >>> x = NDDataset([1, 2, 3]) >>> print(x.data) # doctest: +NORMALIZE_WHITESPACE [ 1 2 3] """ super().__init__(data, **kwargs) self._parent = None # eventually set the coordinates with optional units and title if isinstance(coordset, CoordSet): self.set_coordset(**coordset) else: if coordset is None: coordset = [None] * self.ndim if coordunits is None: coordunits = [None] * self.ndim if coordtitles is None: coordtitles = [None] * self.ndim _coordset = [] for c, u, t in zip(coordset, coordunits, coordtitles): if not isinstance(c, CoordSet): if isinstance(c, LinearCoord): coord = LinearCoord(c) else: coord = Coord(c) if u is not None: coord.units = u if t is not None: coord.title = t else: if u: # pragma: no cover warning_('units have been set for a CoordSet, but this will be ignored ' '(units are only defined at the coordinate level') if t: # pragma: no cover warning_('title will be ignored as they are only defined at the coordinates level') coord = c _coordset.append(coord) if _coordset and set(_coordset) != {Coord()}: # if they are no coordinates do nothing self.set_coordset(*_coordset) # ------------------------------------------------------------------------------------------------------------------ # special methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def __dir__(self): # WARNING: be carefull to keep the present order of the three first elements! Needed for save/load operations return ['dims', 'coordset', 'data', 'name', 'title', 'mask', 'units', 'meta', 'preferences', 'author', 'description', 'history', 'date', 'modified', 'modeldata', 'origin', 'roi', 'offset'] + NDIO().__dir__() # .................................................................................................................. def __getitem__(self, items): saveditems = items # coordinate selection to test first if isinstance(items, str): try: return self._coordset[items] except Exception: pass # slicing new, items = super().__getitem__(items, return_index=True) if new is None: return None if self._coordset is not None: names = self._coordset.names # all names of the current coordinates new_coords = [None] * len(names) for i, item in enumerate(items): # get the corresponding dimension name in the dims list name = self.dims[i] # get the corresponding index in the coordinate's names list idx = names.index(name) if self._coordset[idx].is_empty: new_coords[idx] = Coord(None, name=name) elif isinstance(item, slice): # add the slice on the corresponding coordinates on the dim to the new list of coordinates if not isinstance(self._coordset[idx], CoordSet): new_coords[idx] = self._coordset[idx][item] else: # we must slice all internal coordinates newc = [] for c in self._coordset[idx]: newc.append(c[item]) new_coords[idx] = CoordSet(*newc[::-1], name=name) # we reverse to be sure # the order will be # kept for internal coordinates new_coords[idx]._default = self._coordset[idx]._default # set the same default coord new_coords[idx]._is_same_dim = self._coordset[idx]._is_same_dim elif isinstance(item, (np.ndarray, list)): new_coords[idx] = self._coordset[idx][item] new.set_coordset(*new_coords, keepnames=True) new.history = f'Slice extracted: ({saveditems})' return new # .................................................................................................................. def __getattr__(self, item): # when the attribute was not found if item in ["__numpy_ufunc__", "interface", '_pytestfixturefunction', '__dataclass_fields__', '_ipython_canary_method_should_not_exist_', '_baseclass', '_fill_value', '_ax_lines', '_axcb', 'clevels', '__wrapped__', 'coords', '__await__', '__aiter__'] or '_validate' in item or '_changed' in item: # raise an error so that traits, ipython operation and more ... will be handled correctly raise AttributeError # syntax such as ds.x, ds.y, etc... if item[0] in self.dims or self._coordset: # look also properties attribute = None index = 0 # print(item) if len(item) > 2 and item[1] == '_': attribute = item[1:] item = item[0] index = self.dims.index(item) if self._coordset: try: c = self._coordset[item] if isinstance(c, str) and c in self.dims: # probaly a reference to another coordinate name c = self._coordset[c] if c.name in self.dims or c._parent_dim in self.dims: if attribute is not None: # get the attribute return getattr(c, attribute) else: return c else: raise AttributeError except Exception as err: if item in self.dims: return None else: raise err elif attribute is not None: if attribute == 'size': # we want the size but there is no coords, get it from the data shape return self.shape[index] else: raise AttributeError(f'Can not find `{attribute}` when no coordinate is defined') return None raise AttributeError def __setattr__(self, key, value): if key in DEFAULT_DIM_NAME: # syntax such as ds.x, ds.y, etc... # Note the above test is important to avoid errors with traitlets # even if it looks redundant with the folllowing if key in self.dims: if self._coordset is None: # we need to create a coordset first self.set_coordset(dict((self.dims[i], None) for i in range(self.ndim))) idx = self._coordset.names.index(key) _coordset = self._coordset listcoord = False if isinstance(value, list): listcoord = all([isinstance(item, Coord) for item in value]) if listcoord: _coordset[idx] = list(CoordSet(value).to_dict().values())[0] _coordset[idx].name = key _coordset[idx]._is_same_dim = True elif isinstance(value, CoordSet): if len(value) > 1: value = CoordSet(value) _coordset[idx] = list(value.to_dict().values())[0] _coordset[idx].name = key _coordset[idx]._is_same_dim = True elif isinstance(value, (Coord, LinearCoord)): value.name = key _coordset[idx] = value else: _coordset[idx] = Coord(value, name=key) _coordset = self._valid_coordset(_coordset) self._coordset.set(_coordset) else: raise AttributeError(f'Coordinate `{key}` is not used.') else: super().__setattr__(key, value) # .................................................................................................................. def __eq__(self, other, attrs=None): attrs = self.__dir__() for attr in ( 'filename', 'preferences', 'name', 'description', 'history', 'date', 'modified', 'modeldata', 'origin', 'roi', 'offset'): # these attibutes are not used for comparison (comparison based on data and units!) attrs.remove(attr) return super().__eq__(other, attrs) # .................................................................................................................. def __hash__(self): # all instance of this class has same hash, so they can be compared return super().__hash__ + hash(self._coordset) # ------------------------------------------------------------------------------------------------------------------ # Default values # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @default('_coordset') def _coordset_default(self): return None # .................................................................................................................. @default('_modeldata') def _modeldata_default(self): return None # ------------------------------------------------------------------------------------------------------------------ # Validators # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @validate('_coordset') def _coordset_validate(self, proposal): coords = proposal['value'] return self._valid_coordset(coords) def _valid_coordset(self, coords): # uses in coords_validate and setattr if coords is None: return for k, coord in enumerate(coords): if coord is not None and not isinstance(coord, CoordSet) and coord.data is None: continue # For coord to be acceptable, we require at least a NDArray, a NDArray subclass or a CoordSet if not isinstance(coord, (LinearCoord, Coord, CoordSet)): if isinstance(coord, NDArray): coord = coords[k] = Coord(coord) else: raise TypeError('Coordinates must be an instance or a subclass of Coord class or NDArray, or of ' f' CoordSet class, but an instance of {type(coord)} has been passed') if self.dims and coord.name in self.dims: # check the validity of the given coordinates in terms of size (if it correspond to one of the dims) size = coord.size if self.implements('NDDataset'): idx = self._get_dims_index(coord.name)[0] # idx in self.dims if size != self._data.shape[idx]: raise ValueError(f'the size of a coordinates array must be None or be equal' f' to that of the respective `{coord.name}`' f' data dimension but coordinate size={size} != data shape[{idx}]=' f'{self._data.shape[idx]}') else: pass # bypass this checking for any other derived type (should be done in the subclass) coords._parent = self return coords # .................................................................................................................. @property def _dict_dims(self): _dict = {} for index, dim in enumerate(self.dims): if dim not in _dict: _dict[dim] = {'size': self.shape[index], 'coord': getattr(self, dim)} return _dict # ------------------------------------------------------------------------------------------------------------------ # public methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def add_coordset(self, *coords, dims=None, **kwargs): """ Add one or a set of coordinates from a dataset. Parameters ---------- *coords : iterable Coordinates object(s). dims : list Name of the coordinates. **kwargs : dict Keywords passed to the coordset. """ if not coords and not kwargs: # reset coordinates self._coordset = None return if self._coordset is None: # make the whole coordset at once self._coordset = CoordSet(*coords, dims=dims, **kwargs) else: # add one coordinate self._coordset._append(*coords, **kwargs) if self._coordset: # set a notifier to the updated traits of the CoordSet instance HasTraits.observe(self._coordset, self._dims_update, '_updated') # force it one time after this initialization self._coordset._updated = True # .................................................................................................................. def coord(self, dim='x'): """ Return the coordinates along the given dimension. Parameters ---------- dim : int or str A dimension index or name, default index = `x`. If an integer is provided, it is equivalent to the `axis` parameter for numpy array. Returns ------- |Coord| Coordinates along the given axis. """ idx = self._get_dims_index(dim)[0] # should generate an error if the # dimension name is not recognized if idx is None: return None if self._coordset is None: return None # idx is not necessarily the position of the coordinates in the CoordSet # indeed, transposition may have taken place. So we need to retrieve the coordinates by its name name = self.dims[idx] if name in self._coordset.names: idx = self._coordset.names.index(name) return self._coordset[idx] else: error_(f'could not find this dimenson name: `{name}`') return None # .................................................................................................................. @property def coordset(self): """ |CoordSet| instance. Contains the coordinates of the various dimensions of the dataset. It's a readonly property. Use set_coords to change one or more coordinates at once. """ if self._coordset and all(c.is_empty for c in self._coordset): # all coordinates are empty, this is equivalent to None for the coordset return None return self._coordset # .................................................................................................................. @coordset.setter def coordset(self, coords): if isinstance(coords, CoordSet): self.set_coordset(**coords) else: self.set_coordset(coords) # .................................................................................................................. @property def coordnames(self): """ List of the |Coord| names. Read only property. """ if self._coordset is not None: return self._coordset.names # .................................................................................................................. @property def coordtitles(self): """ List of the |Coord| titles. Read only property. Use set_coordtitle to eventually set titles. """ if self._coordset is not None: return self._coordset.titles # .................................................................................................................. @property def coordunits(self): """ List of the |Coord| units. Read only property. Use set_coordunits to eventually set units. """ if self._coordset is not None: return self._coordset.units # .................................................................................................................. @property def data(self): """ The ``data`` array. If there is no data but labels, then the labels are returned instead of data. """ return super().data # .................................................................................................................. @data.setter def data(self, data): # as we can't write super().data = data, we call _set_data # see comment in the data.setter of NDArray super()._set_data(data) # .................................................................................................................. def delete_coordset(self): """ Delete all coordinate settings. """ self._coordset = None # .................................................................................................................. def implements(self, name=None): """ Check if the current object implements `NDDataset`. Rather than isinstance(obj, NDDataset) use object.implements('NDDataset'). This is useful to check type without importing the module Parameters ---------- name : str Name of the object class. If None, the function returns the class name. If name is given, it checks if it correspond to the current class name. Returns ------- str or bool If name is given, a bool is returned If name is None, the classname is returned Examples -------- >>> from spectrochempy import NDDataset, Coord >>> co = Coord([1., 2., 3.]) >>> co.implements('NDDataset') False >>> co.implements('Coord') True >>> ds = NDDataset([1., 2., 3.]) >>> ds.implements() 'NDDataset' """ if name is None: return 'NDDataset' else: return name == 'NDDataset' # .................................................................................................................. @property def labels(self): # not valid for NDDataset # There is no label for nd-dataset raise NotImplementedError # pragma: no cover # .................................................................................................................. @property def modeldata(self): """ |ndarray| - models data. Data eventually generated by modelling of the data. """ return self._modeldata # .................................................................................................................. @modeldata.setter def modeldata(self, data): self._modeldata = data # .................................................................................................................. @property def parent(self): """ |Project| instance The parent project of the dataset. """ return self._parent # .................................................................................................................. @parent.setter def parent(self, value): if self._parent is not None: # A parent project already exists for this dataset but the # entered values gives a different parent. This is not allowed, # as it can produce impredictable results. We will first remove it # from the current project. self._parent.remove_dataset(self.name) self._parent = value # .................................................................................................................. def set_coordset(self, *args, **kwargs): """ Set one or more coordinates at once. Warnings -------- This method replace all existing coordinates. See Also -------- add_coords, set_coordtitles, set_coordunits """ self._coordset = None self.add_coordset(*args, dims=self.dims, **kwargs) # .................................................................................................................. def set_coordtitles(self, *args, **kwargs): """ Set titles of the one or more coordinates. """ self._coordset.set_titles(*args, **kwargs) # .................................................................................................................. def set_coordunits(self, *args, **kwargs): """ Set units of the one or more coordinates. """ self._coordset.set_units(*args, **kwargs) # .................................................................................................................. def sort(self, **kwargs): """ Returns the dataset sorted along a given dimension. (by default, the last dimension [axis=-1]) using the numeric or label values. Parameters ---------- dim : str or int, optional, default=-1 dimension index or name along which to sort. pos : int , optional If labels are multidimensional - allow to sort on a define row of labels : labels[pos]. Experimental : Not yet checked. by : str among ['value', 'label'], optional, default=``value`` Indicate if the sorting is following the order of labels or numeric coord values. descend : `bool`, optional, default=`False` If true the dataset is sorted in a descending direction. Default is False except if coordinates are reversed. inplace : bool, optional, default=`False` Flag to say that the method return a new object (default) or not (inplace=True). Returns ------- sorted_dataset """ inplace = kwargs.get('inplace', False) if not inplace: new = self.copy() else: new = self # parameter for selecting the level of labels (default None or 0) pos = kwargs.pop('pos', None) # parameter to say if selection is done by values or by labels by = kwargs.pop('by', 'value') # determine which axis is sorted (dims or axis can be passed in kwargs) # it will return a tuple with axis and dim axis, dim = self.get_axis(**kwargs) if axis is None: axis, dim = self.get_axis(axis=0) # get the corresponding coordinates (remember the their order can be different form the order # of dimension in dims. S we cannot jsut take the coord from the indice. coord = getattr(self, dim) # get the coordinate using the syntax such as self.x descend = kwargs.pop('descend', None) if descend is None: # when non specified, default is False (except for reversed coordinates descend = coord.reversed # import warnings # warnings.simplefilter("error") indexes = [] for i in range(self.ndim): if i == axis: if not coord.has_data: # sometimes we have only label for Coord objects. # in this case, we sort labels if they exist! if coord.is_labeled: by = 'label' else: # nothing to do for sorting # return self itself return self args = coord._argsort(by=by, pos=pos, descend=descend) setattr(new, dim, coord[args]) indexes.append(args) else: indexes.append(slice(None)) new._data = new._data[tuple(indexes)] if new.is_masked: new._mask = new._mask[tuple(indexes)] return new # .................................................................................................................. def squeeze(self, *dims, inplace=False): """ Remove single-dimensional entries from the shape of a NDDataset. Parameters ---------- dim : None or int or tuple of ints, optional Selects a subset of the single-dimensional entries in the shape. If a dimension (dim) is selected with shape entry greater than one, an error is raised. inplace : bool, optional, default=`False` Flag to say that the method return a new object (default) or not (inplace=True). Returns ------- squeezed The input array, but with all or a subset of the dimensions of length 1 removed. Raises ------ ValueError If `dim` is not `None`, and the dimension being squeezed is not of length 1. """ # make a copy of the original dims old = self.dims[:] # squeeze the data and determine which axis must be squeezed new, axis = super().squeeze(*dims, inplace=inplace, return_axis=True) if axis is not None and new._coordset is not None: # if there are coordinates they have to be squeezed as well (remove # coordinate for the squeezed axis) for i in axis: dim = old[i] del new._coordset[dim] return new def expand_dims(self, dim=None): """ Expand the shape of an array. Insert a new axis that will appear at the `axis` position in the expanded array shape. Parameters ---------- dim : int or str Position in the expanded axes where the new axis (or axes) is placed. Returns ------- result : ndarray View of `a` with the number of dimensions increased. See Also -------- squeeze : The inverse operation, removing singleton dimensions """ # TODO # .................................................................................................................. def swapdims(self, dim1, dim2, inplace=False): """ Interchange two dimensions of a NDDataset. Parameters ---------- dim1 : int First axis. dim2 : int Second axis. inplace : bool, optional, default=`False` Flag to say that the method return a new object (default) or not (inplace=True). Returns ------- swaped_dataset See Also -------- transpose """ new = super().swapdims(dim1, dim2, inplace=inplace) new.history = f'Data swapped between dims {dim1} and {dim2}' return new # .................................................................................................................. @property def T(self): """ Transposed |NDDataset|. The same object is returned if `ndim` is less than 2. """ return self.transpose() # .................................................................................................................. def take(self, indices, **kwargs): """ Take elements from an array Parameters ---------- indices kwargs Returns ------- """ # handle the various syntax to pass the axis dims = self._get_dims_from_args(**kwargs) axis = self._get_dims_index(dims) axis = axis[0] if axis else None # indices = indices.tolist() if axis is None: # just do a fancy indexing return self[indices] if axis < 0: axis = self.ndim + axis index = tuple([...] + [indices] + [slice(None) for i in range(self.ndim - 1 - axis)]) new = self[index] return new def to_array(self): """ Return a numpy masked array (i.e., other NDDataset attributes are lost. Examples ======== >>> import spectrochempy as scp >>> dataset = scp.read('wodger.spg') >>> a = scp.to_array(dataset) equivalent to: >>> a = np.ma.array(dataset) or >>> a= dataset.masked_data """ return np.ma.array(self) # .................................................................................................................. def to_xarray(self, **kwargs): """ Convert a NDDataset instance to an `~xarray.DataArray` object ( the xarray library must be available ) Parameters Returns ------- object : a xarray.DataArray object """ # Information about DataArray from the DataArray docstring # # Attributes # ---------- # dims: tuple # Dimension names associated with this array. # values: np.ndarray # Access or modify DataArray values as a numpy array. # coords: dict-like # Dictionary of DataArray objects that label values along each dimension. # name: str or None # Name of this array. # attrs: OrderedDict # Dictionary for holding arbitrary metadata. # Init docstring # # Parameters # ---------- # data: array_like # Values for this array. Must be an ``numpy.ndarray``, ndarray like, # or castable to an ``ndarray``. # coords: sequence or dict of array_like objects, optional # Coordinates (tick labels) to use for indexing along each dimension. # If dict-like, should be a mapping from dimension names to the # corresponding coordinates. If sequence-like, should be a sequence # of tuples where the first element is the dimension name and the # second element is the corresponding coordinate array_like object. # dims: str or sequence of str, optional # Name(s) of the data dimension(s). Must be either a string (only # for 1D data) or a sequence of strings with length equal to the # number of dimensions. If this argument is omitted, dimension names # are taken from ``coords`` (if possible) and otherwise default to # ``['dim_0', ... 'dim_n']``. # name: str or None, optional # Name of this array. # attrs: dict_like or None, optional # Attributes to assign to the new instance. By default, an empty # attribute dictionary is initialized. # encoding: dict_like or None, optional # Dictionary specifying how to encode this array's data into a # serialized format like netCDF4. Currently used keys (for netCDF) # include '_FillValue', 'scale_factor', 'add_offset', 'dtype', # 'units' and 'calendar' (the later two only for datetime arrays). # Unrecognized keys are ignored. if not HAS_XARRAY: warnings.warn('Xarray is not available! This function can not be used', SpectroChemPyWarning) return None x, y = self.x, self.y tx = x.title if y: ty = y.title da = xr.DataArray(np.array(self.data, dtype=np.float64), coords=[(ty, y.data), (tx, x.data)], ) da.attrs['units'] = self.units else: da = xr.DataArray(np.array(self.data, dtype=np.float64), coords=[(tx, x.data)], ) da.attrs['units'] = self.units da.attrs['title'] = self.title return da # .................................................................................................................. def transpose(self, *dims, inplace=False): """ Permute the dimensions of a NDDataset. Parameters ---------- dims : sequence of dimension indexes or names, optional By default, reverse the dimensions, otherwise permute the dimensions according to the values given. inplace : bool, optional, default=`False` Flag to say that the method return a new object (default) or not (inplace=True). Returns ------- transposed_array See Also -------- swapdims : Interchange two dimensions of a NDDataset. """ new = super().transpose(*dims, inplace=inplace) new.history = f'Data transposed between dims: {dims}' if dims else '' return new # ------------------------------------------------------------------------------------------------------------------ # private methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def _cstr(self): # Display the metadata of the object and partially the data out = '' out += ' name: {}\n'.format(self.name) out += ' author: {}\n'.format(self.author) out += ' created: {}\n'.format(self._date) # out += ' modified: {}\n'.format(self._modified) if (self.modified - self.date).seconds > 1 else '' wrapper1 = textwrap.TextWrapper(initial_indent='', subsequent_indent=' ' * 15, replace_whitespace=True, width=self._text_width) pars = self.description.strip().splitlines() if pars: out += ' description: ' desc = '' if pars: desc += '{}\n'.format(wrapper1.fill(pars[0])) for par in pars[1:]: desc += '{}\n'.format(textwrap.indent(par, ' ' * 15)) # the three escaped null characters are here to facilitate # the generation of html outputs desc = '\0\0\0{}\0\0\0\n'.format(desc.rstrip()) out += desc if self._history: pars = self.history out += ' history: ' hist = '' if pars: hist += '{}\n'.format(wrapper1.fill(pars[0])) for par in pars[1:]: hist += '{}\n'.format(textwrap.indent(par, ' ' * 15)) # the three escaped null characters are here to facilitate # the generation of html outputs hist = '\0\0\0{}\0\0\0\n'.format(hist.rstrip()) out += hist out += '{}\n'.format(self._str_value().rstrip()) out += '{}\n'.format(self._str_shape().rstrip()) if self._str_shape() else '' out += '{}\n'.format(self._str_dims().rstrip()) if not out.endswith('\n'): out += '\n' out += '\n' if not self._html_output: return colored_output(out.rstrip()) else: return out.rstrip() # .................................................................................................................. def _loc2index(self, loc, dim=-1): # Return the index of a location (label or coordinates) along the dim # This can work only if `coords` exists. if self._coordset is None: raise SpectroChemPyException('No coords have been defined. Slicing or selection' ' by location ({}) needs coords definition.'.format(loc)) coord = self.coord(dim) return coord._loc2index(loc) # .................................................................................................................. def _str_dims(self): if self.is_empty: return '' if len(self.dims) < 1 or not hasattr(self, "_coordset"): return '' if not self._coordset or len(self._coordset) < 1: return '' self._coordset._html_output = self._html_output # transfert the html flag if necessary: false by default txt = self._coordset._cstr() txt = txt.rstrip() # remove the trailing '\n' return txt _repr_dims = _str_dims # ------------------------------------------------------------------------------------------------------------------ # events # ------------------------------------------------------------------------------------------------------------------ def _dims_update(self, change=None): # when notified that a coords names have been updated _ = self.dims # fire an update # debug_('dims have been updated') # .................................................................................................................. # ====================================================================================================================== # module function # ====================================================================================================================== # make some NDDataset operation accessible from the spectrochempy API thismodule = sys.modules[__name__] api_funcs = ['sort', 'copy', 'squeeze', 'swapdims', 'transpose', 'to_array', 'to_xarray', 'take', 'set_complex', 'set_quaternion', 'set_hypercomplex', 'component', 'to', 'to_base_units', 'to_reduced_units', 'ito', 'ito_base_units', 'ito_reduced_units', 'is_units_compatible', 'remove_masks', ] # todo: check the fact that some function are defined also in ndmath for funcname in api_funcs: setattr(thismodule, funcname, getattr(NDDataset, funcname)) thismodule.__all__.append(funcname) # load one method from NDIO load = NDDataset.load __all__ += ['load'] # ====================================================================================================================== # Set the operators # ====================================================================================================================== _set_operators(NDDataset, priority=100000) _set_ufuncs(NDDataset) <file_sep>/tests/test_processors/test_interpolate.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Tests for the interpolate module """ import pytest # align # ------- @pytest.mark.skip def test_interpolate(ds1, ds2): pass <file_sep>/tests/test_utils/test_json.py # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ===================================================================================================================== # import json import base64 import pickle import numpy as np from spectrochempy.utils import json_serialiser, json_decoder def test_json_serialiser_decoder(IR_dataset_2D): nd = IR_dataset_2D.copy() # make a json string to write (without encoding) js = json_serialiser(nd, encoding=None) js_string = json.dumps(js, indent=2) print('no encoding', len(js_string)) # load json from string jsd = json.loads(js_string, object_hook=json_decoder) assert np.all(np.array(js['data']['tolist']) == jsd['data']) # encoding base 64 js = json_serialiser(nd, encoding='base64') js_string = json.dumps(js, indent=2) print('base64', len(js_string)) # load json from string jsd = json.loads(js_string, object_hook=json_decoder) assert np.all(pickle.loads(base64.b64decode(js['data']['base64'])) == jsd['data']) <file_sep>/tests/test_readers_writers/test_importer.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os from pathlib import Path import spectrochempy as scp from spectrochempy import NDDataset from spectrochempy import preferences as prefs # ...................................................................................................................... def test_read(): f = Path('irdata/OPUS/test.0000') A1 = NDDataset.read_opus(f) assert A1.shape == (1, 2567) # single file read with protocol specified A2 = NDDataset.read(f, protocol='opus') assert A2 == A1 A3 = scp.read('irdata/nh4y-activation.spg', protocol='omnic') assert str(A3) == 'NDDataset: [float64] a.u. (shape: (y:55, x:5549))' # single file without protocol # inferred from filename A4 = NDDataset.read(f) assert A4 == A1 A5 = scp.read('irdata/nh4y-activation.spg') assert str(A5) == 'NDDataset: [float64] a.u. (shape: (y:55, x:5549))' # native format f = A5.save_as('nh4y.scp') A6 = scp.read('irdata/nh4y.scp') assert str(A6) == 'NDDataset: [float64] a.u. (shape: (y:55, x:5549))' A7 = scp.read('nh4y', directory='irdata', protocol='scp') assert str(A7) == 'NDDataset: [float64] a.u. (shape: (y:55, x:5549))' A8 = scp.read('nh4y', directory='irdata') assert str(A8) == 'NDDataset: [float64] a.u. (shape: (y:55, x:5549))' f.unlink() # multiple compatible 1D files automatically merged B = NDDataset.read('test.0000', 'test.0001', 'test.0002', directory=os.path.join('irdata', 'OPUS')) assert str(B) == 'NDDataset: [float64] a.u. (shape: (y:3, x:2567))' assert len(B) == 3 # multiple compatible 1D files not merged if the merge keyword is set to False C = scp.read('test.0000', 'test.0001', 'test.0002', directory=os.path.join('irdata', 'OPUS'), merge=False) assert isinstance(C, list) # multiple 1D files to merge D = NDDataset.read(['test.0000', 'test.0001', 'test.0002'], directory=os.path.join('irdata', 'OPUS')) assert D.shape == (3, 2567) # multiple 1D files not merged : they are passed as a list but merge is set to false E = scp.read(['test.0000', 'test.0001', 'test.0002'], directory=os.path.join('irdata', 'OPUS'), merge=False) assert isinstance(E, list) assert len(E) == 3 # read contents datadir = Path(prefs.datadir) p = datadir / 'irdata' / 'OPUS' / 'test.0000' content = p.read_bytes() F = NDDataset.read({ p.name: content }) assert F.name == p.name assert F.shape == (1, 2567) # read multiple 1D contents and merge them lst = [datadir / 'irdata' / 'OPUS' / f'test.000{i}' for i in range(3)] G = NDDataset.read({p.name: p.read_bytes() for p in lst}) assert G.shape == (3, 2567) assert len(G) == 3 # read multiple 1D contents awithout merging lst = [datadir / 'irdata' / 'OPUS' / f'test.000{i}' for i in range(3)] H = NDDataset.read({p.name: p.read_bytes() for p in lst}, merge=False) isinstance(H, list) assert len(H) == 3 filename = datadir / 'wodger.spg' content = filename.read_bytes() # change the filename to be sure that the file will be read from the passed content filename = 'try.spg' # The most direct way to pass the byte content information nd = NDDataset.read(filename, content=content) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:2, x:5549))' # It can also be passed using a dictionary structure {filename:content, ....} nd = NDDataset.read({ filename: content }) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:2, x:5549))' # Case where the filename is not provided nd = NDDataset.read(content) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:2, x:5549))' # Try with an .spa file filename = datadir / 'irdata/subdir/7_CZ0-100 Pd_101.SPA' content = filename.read_bytes() filename = 'try.spa' filename2 = datadir / 'irdata/subdir/7_CZ0-100 Pd_102.SPA' content2 = filename2.read_bytes() filename = 'try2.spa' nd = NDDataset.read({ filename: content }) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:1, x:5549))' # Try with only a .spa content nd = NDDataset.read(content) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:1, x:5549))' # Try with several .spa content (should be stacked into a single nddataset) nd = NDDataset.read({ filename: content, filename2: content2 }) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:2, x:5549))' nd = NDDataset.read(content, content2) assert str(nd) == 'NDDataset: [float64] a.u. (shape: (y:2, x:5549))' def test_generic_read(): # filename + extension specified ds = scp.read('wodger.spg') assert ds.name == 'wodger' # save with no filename (should save wodger.scp) path = ds.save() assert isinstance(path, Path) assert path.stem == ds.name assert path.parent == ds.directory # read should be équivalent to load (but read is a more general function, dataset = NDDataset.load('wodger.scp') assert dataset.name == 'wodger' def test_read_dir(): datadir = Path(prefs.datadir) A = scp.read() # should open a dialog (but to selects individual filename # if we want the whole dir - listdir must be used # this is equivalent to read_dir with a dialog to select directories only A = scp.read(listdir=True, directory=datadir / 'irdata' / 'subdir') assert len(A) == 4 A1 = scp.read_dir(directory=datadir / 'irdata' / 'subdir') assert A == A1 # listdir is not necessary if a directory location is given as a single argument B = scp.read(datadir / 'irdata' / 'subdir', listdir=True) B1 = scp.read(datadir / 'irdata' / 'subdir') assert B == B1 # if a directory is passed as a keyword, the behavior is different: # a dialog for file selection occurs except if listdir is set to True scp.read(directory=datadir / 'irdata' / 'subdir', listdir=True) # -> file selection dialog scp.read(directory=datadir / 'irdata' / 'subdir', listdir=True) # -> directory selection dialog <file_sep>/spectrochempy/utils/file.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ file utilities """ from os import environ import shutil import re import warnings from pathlib import Path, WindowsPath, PosixPath __all__ = ['get_filename', 'readdirname', 'pathclean', 'patterns', 'check_filenames', 'check_filename_to_open', 'check_filename_to_save', 'copytree'] # ====================================================================================================================== # Utility functions # ====================================================================================================================== def _insensitive_case_glob(pattern): def either(c): return f'[{c.lower()}{c.upper()}]' if c.isalpha() else c return ''.join(map(either, pattern)) def patterns(filetypes, allcase=True): regex = r"\*\.*\[*[0-9-]*\]*\w*\**" patterns = [] if not isinstance(filetypes, (list, tuple)): filetypes = [filetypes] for ft in filetypes: m = re.finditer(regex, ft) patterns.extend([match.group(0) for match in m]) if not allcase: return patterns else: return [_insensitive_case_glob(p) for p in patterns] def pathclean(paths): """ Clean a path or a series of path in order to be compatible with windows and unix-based system. Parameters ---------- paths : str or a list of str Path to clean. It may contain windows or conventional python separators. Returns ------- out : a pathlib object or a list of pathlib objets Cleaned path(s) Examples -------- >>> from spectrochempy.utils import pathclean Using unix/mac way to write paths >>> filename = pathclean('irdata/nh4y-activation.spg') >>> filename.suffix '.spg' >>> filename.parent.name 'irdata' or Windows >>> filename = pathclean("irdata\\\\nh4y-activation.spg") >>> filename.parent.name 'irdata' Due to the escape character \\ in Unix, path string should be escaped \\\\ or the raw-string prefix `r` must be used as shown below >>> filename = pathclean(r"irdata\\nh4y-activation.spg") >>> filename.suffix '.spg' >>> filename.parent.name 'irdata' >>> from spectrochempy import preferences as prefs >>> datadir = prefs.datadir >>> fullpath = datadir / filename """ from spectrochempy.utils import is_windows def _clean(path): if isinstance(path, Path): path = path.name if is_windows(): path = WindowsPath(path) else: # some replacement so we can handle window style path on unix path = path.strip() path = path.replace('\\', '/') path = path.replace('\n', '/n') path = path.replace('\t', '/t') path = path.replace('\b', '/b') path = path.replace('\a', '/a') path = PosixPath(path) return Path(path) if paths is not None: if isinstance(paths, str): return _clean(paths).expanduser() elif isinstance(paths, (list, tuple)): return [_clean(p).expanduser() if isinstance(p, str) else p for p in paths] return paths def _get_file_for_protocol(f, **kwargs): protocol = kwargs.get('protocol', None) if protocol is not None: if isinstance(protocol, str): if protocol in ['ALL']: protocol = '*' if protocol in ['opus']: protocol = '*.0*' protocol = [protocol] lst = [] for p in protocol: lst.extend(list(f.parent.glob(f'{f.stem}.{p}'))) if not lst: return None else: return f.parent / lst[0] def check_filenames(*args, **kwargs): from spectrochempy.core import preferences as prefs datadir = pathclean(prefs.datadir) filenames = None if args: if isinstance(args[0], (str, Path)): # one or several filenames are passed - make Path objects filenames = pathclean(args) elif isinstance(args[0], bytes): # in this case, one or several byte contents has been passed instead of filenames # as filename where not given we passed the 'unnamed' string # return a dictionary return {pathclean(f'no_name_{i}'): arg for i, arg in enumerate(args)} elif isinstance(args[0], list): if isinstance(args[0][0], (str, Path)): filenames = pathclean(args[0]) elif isinstance(args[0][0], bytes): return {pathclean(f'no_name_{i}'): arg for i, arg in enumerate(args[0])} elif isinstance(args[0], dict): # return directly the dictionary return args[0] if not filenames: # look into keywords (only the case where a str or pathlib filename is given are accepted) filenames = kwargs.pop('filename', None) filenames = [pathclean(filenames)] if pathclean(filenames) is not None else None # Look for content in kwargs content = kwargs.pop('content', None) if content: if not filenames: filenames = [pathclean('no_name')] return { filenames[0]: content } if not filenames: # no filename specified open a dialog filetypes = kwargs.pop('filetypes', ['all files (*)']) directory = pathclean(kwargs.pop("directory", None)) filenames = get_filename(directory=directory, dictionary=True, filetypes=filetypes, **kwargs) if filenames and not isinstance(filenames, dict): filenames_ = [] for filename in filenames: # in which directory ? directory = filename.parent if directory.resolve() == Path.cwd() or directory == Path('.'): directory = '' kw_directory = pathclean(kwargs.get("directory", None)) if directory and kw_directory and directory != kw_directory: # conflit we do not take into account the kw. warnings.warn( 'Two differents directory where specified (from args and keywords arg). ' 'Keyword `directory` will be ignored!') elif not directory and kw_directory: filename = kw_directory / filename # check if the file exists here if not directory or str(directory).startswith('.'): # search first in the current directory directory = Path.cwd() f = directory / filename fexist = None if f.exists(): fexist = f else: fexist = _get_file_for_protocol(f, **kwargs) if fexist is None: f = datadir / filename if f.exists(): fexist = f else: fexist = _get_file_for_protocol(f, **kwargs) if fexist: filename = fexist # particular case for topspin where filename can be provided as a directory only # use of expno and procno if filename.is_dir() and 'topspin' in kwargs.get('protocol', []): if kwargs.get('listdir', False) or kwargs.get('glob', None) is not None: # when we list topspin dataset we have to read directories, not directly files # we can retreive them using glob patterns glob = kwargs.get('glob', None) if glob: files_ = list(filename.glob(glob)) else: if not kwargs.get('processed', False): files_ = list(filename.glob('**/ser')) files_.extend(list(filename.glob('**/fid'))) else: files_ = list(filename.glob('**/1r')) files_.extend(list(filename.glob('**/2rr'))) files_.extend(list(filename.glob('**/3rrr'))) else: expno = kwargs.pop('expno', None) procno = kwargs.pop('procno', None) if expno is None: expnos = sorted(filename.glob('[0-9]*')) if expnos: expno = expnos[0] if procno is None: # read a fid or a ser f = filename / str(expno) if (f / 'ser').exists(): files_ = [f / 'ser'] else: files_ = [f / 'fid'] else: # get the adsorption spectrum f = filename / str(expno) / 'pdata' / str(procno) if (f / '3rrr').exists(): files_ = [f / '3rrr'] elif (f / '2rr').exists(): files_ = [f / '2rr'] else: files_ = [f / '1r'] # depending of the glob patterns too many files may have been selected : restriction to the valid subset filename = [] for item in files_: if item.name in ['fid', 'ser', '1r', '2rr', '3rrr']: filename.append(item) if not isinstance(filename, list): filename = [filename] # for f in filename: # if not f.exists(): # raise FileNotFoundError(f'{f} in {filename}') filenames_.extend(filename) filenames = filenames_ return filenames def get_filename(*filenames, **kwargs): """ returns a list or dictionary of the filenames of existing files, filtered by extensions Parameters ---------- filenames : `str` or pathlib object, `tuple` or `list` of strings of pathlib object, optional. A filename or a list of filenames. If not provided, a dialog box is opened to select files in the current directory if no `directory` is specified) directory : `str` or pathlib object, optional. The directory where to look at. If not specified, read in current directory, or in the datadir if unsuccessful filetypes : `list`, optional, default=['all files, '.*)']. file type filter dictionary : `bool`, optional, default=True Whether a dictionary or a list should be returned. listdir : bool, default=False read all file (possibly limited by `filetypes` in a given `directory`. recursive : bool, optional, default=False. Read also subfolders Warnings -------- if several filenames are provided in the arguments, they must all reside in the same directory! Returns -------- out : list of filenames Examples -------- """ from spectrochempy.core import preferences as prefs from spectrochempy import NO_DISPLAY, NO_DIALOG from spectrochempy.core import open_dialog NODIAL = NO_DIALOG or 'DOC_BUILDING' in environ # suppress dialog when doc is built or during full testing # allowed filetypes # ----------------- # alias filetypes and filters as both can be used filetypes = kwargs.get("filetypes", kwargs.get("filters", ["all files (*)"])) # filenames # --------- if len(filenames) == 1 and isinstance(filenames[0], (list, tuple)): filenames = filenames[0] filenames = pathclean(list(filenames)) directory = None if len(filenames) == 1: # check if it is a directory f = readdirname(filenames[0]) if f and f.is_dir(): # this specify a directory not a filename directory = f filenames = None NODIAL = True # else: # filenames = pathclean(list(filenames)) # directory # --------- if directory is None: directory = pathclean(kwargs.get("directory", None)) if directory is not None: if filenames: # prepend to the filename (incompatibility between filename and directory specification # will result to a error filenames = [directory / filename for filename in filenames] else: directory = readdirname(directory) # check the parent directory # all filenames must reside in the same directory if filenames: parents = set() for f in filenames: parents.add(f.parent) if len(parents) > 1: raise ValueError('filenames provided have not the same parent directory. ' 'This is not accepted by the readfilename function.') # use readdirname to complete eventual missing part of the absolute path directory = readdirname(parents.pop()) filenames = [filename.name for filename in filenames] # now proceed with the filenames if filenames: # look if all the filename exists either in the specified directory, # else in the current directory, and finally in the default preference data directory temp = [] for i, filename in enumerate(filenames): if not (directory / filename).exists(): # the filename provided doesn't exists in the working directory # try in the data directory directory = pathclean(prefs.datadir) if not (directory / filename).exists(): raise IOError(f"Can't find this filename {filename}") temp.append(directory / filename) # now we have checked all the filename with their correct location filenames = temp else: # no filenames: # open a file dialog # except if a directory is specified or listdir is True. # currently Scpy use QT (needed for next GUI features) getdir = kwargs.get('listdir', directory is not None or kwargs.get('protocol', None) == ['topspin']) if not getdir: # we open a dialogue to select one or several files manually if not (NO_DISPLAY or NODIAL): filenames = open_dialog(single=False, directory=directory, filters=filetypes) if not filenames: # cancel return None elif environ.get('TEST_FILE', None) is not None: # happen for testing filenames = [pathclean(environ.get('TEST_FILE'))] else: if not (NO_DISPLAY or NODIAL): directory = open_dialog( directory=directory, filters='directory') if not directory: # cancel return None elif NODIAL and not directory: directory = readdirname(environ.get('TEST_FOLDER')) elif NODIAL and kwargs.get('protocol', None) == ['topspin']: directory = readdirname(environ.get('TEST_NMR_FOLDER')) if directory is None: return None filenames = [] if kwargs.get('protocol', None) != ['topspin']: # automatic reading of the whole directory for pat in patterns(filetypes): if kwargs.get('recursive', False): pat = f'**/{pat}' filenames.extend(list(directory.glob(pat))) else: # Topspin directory detection filenames = [directory] # on mac case insensitive OS this cause doubling the number of files. # Eliminates doublons: filenames = list(set(filenames)) filenames = pathclean(filenames) if not filenames: # problem with reading? return None # now we have either a list of the selected files if isinstance(filenames, list): if not all(isinstance(elem, Path) for elem in filenames): raise IOError('one of the list elements is not a filename!') # or a single filename if isinstance(filenames, Path): filenames = [filenames] filenames = pathclean(filenames) for filename in filenames[:]: if filename.name.endswith('.DS_Store'): # sometime present in the directory (MacOSX) filenames.remove(filename) dictionary = kwargs.get("dictionary", True) if dictionary and kwargs.get('protocol', None) != ['topspin']: # make and return a dictionary filenames_dict = {} for filename in filenames: if filename.is_dir(): continue extension = filename.suffix.lower() if not extension: if re.match(r"^fid$|^ser$|^[1-3][ri]*$", filename.name) is not None: extension = '.topspin' elif extension[1:].isdigit(): # probably an opus file extension = '.opus' if extension in filenames_dict.keys(): filenames_dict[extension].append(filename) else: filenames_dict[extension] = [filename] return filenames_dict else: return filenames def readdirname(directory): """ returns a valid directory name Parameters ---------- directory : `str` or `pathlib.Path` object, optional. A directory name. If not provided, a dialog box is opened to select a directory. Returns -------- out: `pathlib.Path` object valid directory name """ from spectrochempy.core import preferences as prefs from spectrochempy import NO_DISPLAY, NO_DIALOG from spectrochempy.core import open_dialog data_dir = pathclean(prefs.datadir) working_dir = Path.cwd() directory = pathclean(directory) if directory: if directory.is_dir(): # nothing else to do return directory elif (working_dir / directory).is_dir(): # if no parent directory: look at current working dir return working_dir / directory elif (data_dir / directory).is_dir(): return data_dir / directory else: # raise ValueError(f'"{dirname}" is not a valid directory') warnings.warn(f'"{directory}" is not a valid directory') return None else: # open a file dialog directory = data_dir if not NO_DISPLAY and not NO_DIALOG: # this is for allowing test to continue in the background directory = open_dialog(single=False, directory=working_dir, filters='directory') return pathclean(directory) # ...................................................................................................................... def check_filename_to_save(dataset, filename=None, save_as=True, confirm=True, **kwargs): from spectrochempy import NO_DIALOG from spectrochempy.core import save_dialog NODIAL = NO_DIALOG or 'DOC_BUILDING' in environ if not filename or save_as: # no filename provided if filename is None or (NODIAL and pathclean(filename).is_dir()): filename = dataset.name filename = filename + kwargs.get('suffix', '.scp') if not NODIAL and confirm: filename = save_dialog(caption=kwargs.get('caption', 'Save as ...'), filename=filename, filters=kwargs.get('filetypes', ['All file types (*.*)'])) if filename is None: # this is probably due to a cancel action for an open dialog. return if pathclean(filename).parent.resolve() == Path.cwd(): return Path.cwd() / filename return pathclean(filename) # .................................................................................................................. def check_filename_to_open(*args, **kwargs): # Check the args and keywords arg to determine the correct filename filenames = check_filenames(*args, **kwargs) if filenames is None: # not args and # this is probably due to a cancel action for an open dialog. return None if not isinstance(filenames, dict): # deal with some specific cases key = filenames[0].suffix.lower() if not key: if re.match(r"^fid$|^ser$|^[1-3][ri]*$", filenames[0].name) is not None: key = '.topspin' if key[1:].isdigit(): # probably an opus file key = '.opus' return { key: filenames } elif len(args) > 0 and args[0] is not None: # args where passed so in this case we have directly byte contents instead of filenames only contents = filenames return { 'frombytes': contents } else: # probably no args (which means that we are coming from a dialog or from a full list of a directory return filenames # we need to copy file so it will work def copytree(src, dst, symlinks=False, ignore=None): for item in src.iterdir(): s = src / item.name d = dst / item.name if s.is_dir(): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) # EOF <file_sep>/docs/gettingstarted/examples/project/readme.txt .. _project_examples-index: Project Management ---------------------- Example of how to create and manipulate Projects in SpectroChemPy <file_sep>/spectrochempy/core/fitting/lstsq.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== # TODO: create tests __all__ = ['CurveFit', 'LSTSQ', 'NNLS'] import numpy as np import scipy.optimize as sopt import scipy.linalg as lng from traitlets import HasTraits, Instance from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.ndarray import NDArray from spectrochempy.units import Quantity class LSTSQ(HasTraits): """ Least-squares solution to a linear matrix equation. Given a vector `X` and a vector Y, the equation `A.X + B = Y` is solved by computing ``A``, and ``B`` that minimizes the Euclidean 2-norm `|| Y - (A.X + B) ||^2`. """ X = Instance(NDArray) Y = Instance(NDDataset) def __init__(self, *datasets): """ Parameters ---------- *datasets : one or two |NDDataset|'s or array-like objects If a single dataset `Y` is provided, the `X` data will be the `x` coordinates of the `Y` dataset, or the index of the data if not coordinates exists. If two datasets `X`, and `Y` are given, the `x` coordinates of `Y` are ignored and replaced by the `X` data. """ super().__init__() if len(datasets) > 2 or len(datasets) < 1: raise ValueError('one or two dataset at max are expected') if len(datasets) == 2: X, Y = datasets else: # nb dataset ==1 # abscissa coordinates are the X dim = datasets[0].dims[-1] X = getattr(datasets[0], dim) Y = datasets[0] self.X = X self.Y = Y Xdata = np.vstack([X.data, np.ones(len(X.data))]).T Ydata = Y.data P, res, rank, s = lng.lstsq(Xdata, Ydata) self._P = P self._res = res self._rank = rank self._s = s def transform(self): """ Return the least square coefficients A and B Returns ------- Quantity or NDDataset, depending on the dimension of the linear system. """ P = self._P X = self.X Y = self.Y if P.shape == (2,): # this is the result of the single equation, so only one value # should be returned A = P[0] * Y.units / X.units B = P[1] * Y.units else: A = NDDataset(data=P[0], units=Y.units / X.units, title="%s/%s" % (Y.title, X.title), ) B = NDDataset(data=P[1] * np.ones(X.size), units=Y.units, title="%s at origin" % Y.title) A.history = 'Computed by spectrochempy.lstsq \n' B.history = 'Computed by spectrochempy.lstsq \n' return A, B trans = transform # short-cut def inverse_transform(self): """ Return the reconstructed data from the A and B least-square coefficients Returns ------- |NDDataset| """ A, B = self.transform() if isinstance(A, Quantity): Yp = self.Y.copy() Yp.data = (self.X * A + B).data else: Yp = (A * self.X + B) return Yp itrans = inverse_transform class NNLS(HasTraits): """ Least-squares solution to a linear matrix equation with non-negativity constraints This is a wrapper to the `scipy.optimize.nnls`` function """ X = Instance(NDArray) Y = Instance(NDDataset) def __init__(self, *datasets): """ Parameters ---------- *datasets : one or two |NDDataset|'s or array-like objects If a single dataset `Y` is provided, the `X` data will be the `x` coordinates of the `Y` dataset, or the index of the data if not coordinates exists. If two datasets `X`, and `Y` are given, the `x` coordinates of `Y` are ignored and replaced by the `X` data. maxiter: int, optional Maximum number of iterations, optional. Default is ``3 * X.shape``. """ super().__init__() if len(datasets) > 2 or len(datasets) < 1: raise ValueError('one or two dataset at max are expected') if len(datasets) == 2: X, Y = datasets else: # nb dataset ==1 # abscissa coordinates are the X dim = datasets[0].dims[-1] X = getattr(datasets[0], dim) Y = datasets[0] self.X = X self.Y = Y Xdata = np.vstack([X.data, np.ones(len(X.data))]).T Ydata = Y.data P, res = sopt.nnls(Xdata, Ydata, maxiter=None) self._P = P self._res = res def transform(self): """ Return the least square coefficients A and B Returns ------- Quantity or NDDataset, depending on the dimension of the linear system. """ P = self._P X = self.X Y = self.Y if P.shape == (2,): # this is the result of the single equation, so only one value # should be returned A = P[0] * Y.units / X.units B = P[1] * Y.units else: A = NDDataset(data=P[0], units=Y.units / X.units, title="%s/%s" % (Y.title, X.title), ) B = NDDataset(data=P[1] * np.ones(X.size), units=Y.units, title="%s at origin" % Y.title) A.history = 'Computed by spectrochempy.lstsq \n' B.history = 'Computed by spectrochempy.lstsq \n' return A, B trans = transform # short-cut def inverse_transform(self): """ Return the reconstructed data from the A and B least-square coefficients Returns ------- |NDDataset| """ A, B = self.transform() if isinstance(A, Quantity): Yp = self.Y.copy() Yp.data = (self.X * A + B).data else: Yp = (A * self.X + B) return Yp itrans = inverse_transform class CurveFit(HasTraits): """ Use non-linear least squares to fit a function, ``f``, to data. It assumes Y = f(X, *params) + eps. This is a wrapper to the `scipy.optimize.curve_fit`` function """ X = Instance(NDArray) Y = Instance(NDDataset) def __init__(self, *datasets): """ Parameters ---------- *datasets : one or two |NDDataset|'s or array-like objects If a single dataset `Y` is provided, the `X` data will be the `x` coordinates of the `Y` dataset, or the index of the data if not coordinates exists. If two datasets `X`, and `Y` are given, the `x` coordinates of `Y` are ignored and replaced by the `X` data. maxiter: int, optional Maximum number of iterations, optional. Default is ``3 * X.shape``. """ super().__init__() if len(datasets) > 2 or len(datasets) < 1: raise ValueError('one or two dataset at max are expected') if len(datasets) == 2: X, Y = datasets else: # nb dataset ==1 # abscissa coordinates are the X dim = datasets[0].dims[-1] X = getattr(datasets[0], dim) Y = datasets[0] self.X = X self.Y = Y Xdata = np.vstack([X.data, np.ones(len(X.data))]).T Ydata = Y.data P, res = sopt.nnls(Xdata, Ydata, maxiter=None) self._P = P self._res = res def transform(self): """ Return the least square coefficients A and B Returns ------- Quantity or NDDataset, depending on the dimension of the linear system. """ P = self._P X = self.X Y = self.Y if P.shape == (2,): # this is the result of the single equation, so only one value # should be returned A = P[0] * Y.units / X.units B = P[1] * Y.units else: A = NDDataset(data=P[0], units=Y.units / X.units, title="%s/%s" % (Y.title, X.title), ) B = NDDataset(data=P[1] * np.ones(X.size), units=Y.units, title="%s at origin" % Y.title) A.history = 'Computed by spectrochempy.lstsq \n' B.history = 'Computed by spectrochempy.lstsq \n' return A, B trans = transform # short-cut def inverse_transform(self): """ Return the reconstructed data from the A and B least-square coefficients Returns ------- |NDDataset| """ A, B = self.transform() if isinstance(A, Quantity): Yp = self.Y.copy() Yp.data = (self.X * A + B).data else: Yp = (A * self.X + B) return Yp itrans = inverse_transform <file_sep>/docs/userguide/processing/smoothing.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # cell_metadata_filter: title,-all # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # Smoothing # # In this tutorial, we shows how to smooth spectra along one dimension (another tutorial will be devoted to 2-D # smoothing) # and gives informations on the algorithms used in Spectrochempy. # # We first import spectrochempy, the other libraries used in this tutorial, and a sample dataset ( # nh4y-activation.spg) from which we extract a noisy part: # %% import spectrochempy as scp import numpy as np # %% X = scp.read_omnic('irdata//nh4y-activation.spg') # import spectra X = X[0:5, 3600.0:2800.0] # select a noisy part (the first 5 spectra in the 3700-2800 cm-1 range) # %% prefs = X.preferences prefs.figure.figsize = (7, 3) ax = X.plot() # plot # %% Two methods implemented in spectrochempy can be used to smooth spectra along either one dimension ( [markdown] # In this tutorial we will apply smoothing of the # spectra along the wavlength dimension. These methods are based on window functions, which ptototype is the *moving # average*. # %% Two methods implemented in spectrochempy can be used to smooth spectra along either one dimension ( [markdown] # ## The `smooth()` method # %% Two methods implemented in spectrochempy can be used to smooth spectra along either one dimension ( [markdown] # The `smooth()` method is adapted from the ["Smoothing of a 1D signal" code]( # https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html) of the [Scipy cookbook]( # https://scipy-cookbook.readthedocs.io/). It is a (weighted)-moving average method and consist in the convolution of # a window of a given length with the spectrum. # # In its simplest form - *i.e.* unweighted moving average - each absorbance at a given wavenumber of the smoothed # spectrum is the average of the aborbances at the the absorbance at the considered wavenumber and the N neighboring # wavenumbers (*i.e.* N/2 before and N/2 after), hence the conventional use of an odd number of N+1 points to define # the window length. For the points located at both end of the spectra, the extremities of the spectrum are mirrored # beyond the initial limits so as to minimize boundary effects. # # When passed as is, i.e. `X.smooth()`, the method uses a moving average of 5 points: # %% ax = X.smooth().plot() # %% [markdown] # ### Window length # # The following code compares the influence of the window size on the smoothing of the first spectrum of the # NDDataset `X[0]`. # %% [markdown] # Loop over window lengths. i index will run from 0 to 6. # %% lspectra = [X[0], ] llabels = ['Initial', ] for i, length in enumerate([5, 11, 27, 51, 101, 201, 501]): s = X[0].smooth(window_length=length) # smooth s += 0.1 * (1 + i) # shift the absorbance by +0.1 a.u. with respect to previous iteration lspectra.append(s) llabels.append(f'length: {length}') ax = scp.plot_multiple(figsize=(7, 6), method='pen', datasets=lspectra, labels=llabels, legend='upper left') # %% The above spectra clearly show that as that the width of the window increases, the peaks belonging to [markdown] # the spectrum are flattened out and distorted. When determining the optimum window length, one should thus consier # the balance between noise removal and signal integrity: the larger the window length, the stronger the smoothing, # but also the greater the chance to distort the spectrum. # # ### Window function # # Besides the window `length` (default=11 points), the user can also choose the type of # window (`window`) from `flat`, `hanning` (i.e. Hann window), `hamming`, `bartlett` or `blackman`. The `flat` # window - which is the default shown above - should be fine for the vast majority of cases. # # The code below compares the effect of the type of window: # %% wspectra = [X[0], ] wlabels = ['Initial', ] for i, window in enumerate(['flat', 'bartlett', 'hanning', 'hamming', 'blackman']): s = X[0].smooth(window_length=27, window=window) + 0.1 * (1 + i) # smooth and shift wspectra.append(s) wlabels.append(f'window: {window}') ax = scp.plot_multiple(figsize=(7, 4), method='pen', datasets=wspectra, labels=wlabels, legend='upper left') # %% Close examination of the spectra shows that the flat window leads to the stronger smoothing. This is [markdown] # because the other window functions (also known as *apodization functions*) are used as weighting functions for the # N+1 points, with the largest weight on the central point and smaller weights for external points. # # The window functions as used in SpectroChemPy are derived from the numpy library. These builtin functions are such # that the value of the central point is 1. Hence, as shown below, they are normalised to the sum of weights. The # code below displays the corresponding normalized fucntions for 27 points: # %% functions = [] labels = [] for i, f in enumerate([np.bartlett, np.hanning, np.hamming, np.blackman]): coord = scp.NDDataset.linspace(-13, 13, 27) s = scp.NDDataset(f(27) / np.sum(27) + i * 0.01, coordset=[coord]) # normalized window function, y shifted : +0.1 for each function functions.append(s) labels.append(f'function: {f.__name__}') ax = scp.plot_multiple(figsize=(7, 4), method='pen', datasets=functions, labels=labels, legend='upper left') # %% As shown above, the "bartlett" function is equivalent to a triangular apodization, while other [markdown] # fonctions (`hanning`, `hamming`, `blackman`) are bell-shaped. More information on window funcntions can be found [ # here](https://en.wikipedia.org/wiki/Window_function). # # Overall, the impact of the window function on the final spectrum is moderate, as can be shown by comparing the # differences (noisy spectrum *minus* smoothed spectra and the standard deviation along dimension x: # %% diffs = [] stds = [] labels = wlabels[1:] for s in wspectra[1:]: s = s - X[0] diffs.append(s) stds.append(s.std(dim='x').values.m) ax = scp.plot_multiple(figsize=(7, 4), method='pen', datasets=diffs, labels=labels, legend='upper left') ax.set_ylim(0, 0.8) # %% [markdown] # and the standard deviations (the largest the value, the stronger the smoothing): # %% for ll, s in zip(labels, stds): print(f'{ll[7:]:10s}: {s:.4f}') # %% [markdown] # ## Savitzky-Golay algorithm:`savgol_filter()` # # The second algorithm implemented in spectrochempy is the Savitzky-Golay filter which uses a polynomial # interpolation in the moving window. A demonstrative illustration of the method can be found on the [Savitzky-Golay # filter](https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter) entry of Wikipedia. # # The function implemented in spectrochempy is a wrapper of the [savgol_filert() method]( # https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.savgol_filter.html) from the [scipy.signal]( # https://docs.scipy.org/doc/scipy/reference/signal.html) module to which we refer the interested reader. It not only # used to smooth spectra but also to compute their successive derivatives. The latter are treated in [the # peak-finding tutorial](../analysis/peak_finding.ipynb) and we will focus here on the smoothing which is the default # of the filter (default parameter: `deriv=0`). # # As for the `smooth()` method, it is a moving-window based method. Hence, the window length (`window_length` # parameter) plays an equivalent role, except that it *must* be odd. Moreover, instead of choosing a window function, # the user can choose the order of the polynomial used to fit the window data points (`polyorder`, default value: 0). # The latter must be strictly smaller than the window size (so that the polynomial coefficients can be fully # determined). # # The use of this method is illustrated below, we leave to the reader to assess the impact of the window length and # polynomial order (see Exercises below) # %% _ = X.savgol_filter(window_length=5, polyorder=0).plot() # %% [markdown] # <div class='alert alert-info'> # <b>Exercises</b> # # <em>intermediate</em>: - what would be the parameters to use in the `savogol_filter()` method to mimic `smooth()`? # Write a # code to check your answer - examine the impacts of `window_length` and `polyorder` on the extent of smoothing with # a Svitzky-Golay filter. # </div> <file_sep>/spectrochempy/core/writers/writejcamp.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Plugin module to extend NDDataset with a JCAMP-DX export method. """ # import os as os import numpy as np from datetime import datetime, timezone from spectrochempy.core import debug_ from spectrochempy.core.writers.exporter import Exporter, exportermethod __all__ = ['write_jcamp', 'write_jdx'] __dataset_methods__ = __all__ # ....................................................................................................................... def write_jcamp(*args, **kwargs): """ Writes a dataset in JCAMP-DX format (see Published JCAMP-DX Protocols http://www.jcamp-dx.org/protocols.html#ir4.24) Up to now, only IR output is available Parameters ---------- filename: str or pathlib objet, optional If not provided, a dialog is opened to select a file for writing protocol : {'scp', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for writing. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional Where to write the specified `filename`. If not specified, write in the current directory. description: str, optional A Custom description. Returns ------- out : `pathlib` object path of the saved file Examples -------- The extension will be added automatically >>> X.write_jcamp('myfile') """ exporter = Exporter() kwargs['filetypes'] = ['JCAMP-DX files (*.jdx)'] kwargs['suffix'] = '.jdx' return exporter(*args, **kwargs) write_jdx = write_jcamp write_jdx.__doc__ = 'This method is an alias of `write_jcamp` ' @exportermethod def _write_jcamp(*args, **kwargs): # Writes a dataset in JCAMP-DX format debug_("writing jcamp_dx file") dataset, filename = args dataset.filename = filename # Make JCAMP_DX file with filename.open('w') as fid: # Writes first lines fid.write(f'##TITLE={dataset.name}\n') fid.write('##JCAMP-DX=5.01\n') if dataset.shape[0] > 1: # Several spectra => Data Type = LINK fid.write('##DATA TYPE=LINK\n') # Number of spectra (size of 1st dimension) fid.write(f'##BLOCKS={dataset.shape[0]}\n') else: fid.write('##DATA TYPE=INFRARED SPECTRUM\n') # Determine whether the spectra have a title and a datetime field in the labels, # by default, the title if any will be is the first string; the timestamp will # be the fist datetime.datetime title_index = None timestamp_index = None if dataset.y.labels is not None: for i, label in enumerate(dataset.y.labels[0]): if not title_index and type(label) is str: title_index = i if not timestamp_index and type(label) is datetime: timestamp_index = i if timestamp_index is None: timestamp = datetime.now(timezone.utc) for i in range(dataset.shape[0]): if dataset.shape[0] > 1: title = dataset.y.labels[i][title_index] if title_index else f'spectrum #{i}' fid.write(f'##TITLE={title}\n') fid.write('##JCAMP-DX=5.01\n') fid.write(f'##ORIGIN={dataset.origin}\n') fid.write(f'##OWNER={dataset.author}\n') if timestamp_index is not None: timestamp = dataset.y.labels[i][timestamp_index] fid.write(f'##LONGDATE={timestamp.strftime("%Y/%m/%d")}\n') fid.write(f'##TIME={timestamp.strftime("%H:%M:%S")}\n') fid.write('##XUNITS=1/CM\n') fid.write('##YUNITS=ABSORBANCE\n') firstx, lastx = dataset.x.data[0], dataset.x.data[-1] maxx, minx = max(firstx, lastx), min(firstx, lastx) xfactor = 1.0 fid.write(f'##FIRSTX={firstx:.6f}\n') fid.write(f'##LASTX={lastx:.6f}\n') fid.write(f'##MAXX={maxx:.6f}\n') fid.write(f'##MINX={minx:.6f}\n') fid.write(f'##XFACTOR={xfactor}\n') firsty, lasty = dataset.data[0, 0], dataset.data[0, -1] # TODO : mask maxy, miny = np.nanmax(dataset.data), np.nanmin(dataset.data) yfactor = 1.0e-8 fid.write(f'##FIRSTY={firsty:.6f}\n') fid.write(f'##LASTY={lasty:.6f}\n') fid.write(f'##MAXY={maxy:.6f}\n') fid.write(f'##MINY={miny:.6f}\n') fid.write(f'##YFACTOR={yfactor}\n') nx = dataset.shape[1] fid.write(f'##NPOINTS={nx}\n') fid.write('##XYDATA=(X++(Y..Y))\n') line = f'{firstx:.6f} ' for j in np.arange(nx): Y = '? ' if np.isnan(dataset.data[i, j]) else f'{int(dataset.data[i, j] / yfactor):.6f} ' line += Y if len(line) >= 75 or j == nx - 1: fid.write(f'{line}\n') if j + 1 < nx: line = f'{dataset.x.data[j + 1]:.6f} ' fid.write('##END\n') fid.write('##END=' + '\n') return filename <file_sep>/spectrochempy/utils/packages.py # -*- coding: utf-8 -*- # # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import sys import os from pkgutil import walk_packages from traitlets import import_item __all__ = ['list_packages', 'generate_api', 'get_pkg_path'] # ====================================================================================================================== # PACKAGE and API UTILITIES # ====================================================================================================================== # ...................................................................................................................... def list_packages(package): """Return a list of the names of a package and its subpackages. This only works if the package has a :attr:`__path__` attribute, which is not the case for some (all?) of the built-in packages. """ # Based on response at # http://stackoverflow.com/questions/1707709 names = [package.__name__] for __, name, __ in walk_packages(package.__path__, prefix=package.__name__ + '.', onerror=lambda x: None): names.append(name) return names # ...................................................................................................................... def generate_api(api_path): # name of the package dirname, name = os.path.split(os.path.split(api_path)[0]) if not dirname.endswith('spectrochempy'): dirname, _name = os.path.split(dirname) name = _name + '.' + name pkgs = sys.modules['spectrochempy.%s' % name] api = sys.modules['spectrochempy.%s.api' % name] pkgs = list_packages(pkgs) __all__ = [] for pkg in pkgs: if pkg.endswith('api') or "test" in pkg: continue try: pkg = import_item(pkg) except Exception: if not hasattr(pkg, '__all__'): continue raise ImportError(pkg) if not hasattr(pkg, '__all__'): continue a = getattr(pkg, '__all__', []) dmethods = getattr(pkg, '__dataset_methods__', []) __all__ += a for item in a: # set general method for the current package API obj = getattr(pkg, item) setattr(api, item, obj) # some methods are class method of NDDatasets if item in dmethods: from spectrochempy.core.dataset.nddataset import NDDataset setattr(NDDataset, item, getattr(pkg, item)) return __all__ def get_pkg_path(data_name, package=None): data_name = os.path.normpath(data_name) path = os.path.dirname(import_item(package).__file__) path = os.path.join(path, data_name) if not os.path.isdir(path): # pragma: no cover return os.path.dirname(path) return path # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/docs/_templates/versionlog.rst :orphan: {% if bugs or features or tasks %} Version {{ target }} ----------------------------------- {% if prs %} {% for item in prs %} * `#{{ item["number"] }} <{{ item["url"] }}>`_ : {{ item["title"] }} {%- endfor %} {%- endif %} {% if bugs %} Bugs fixed ~~~~~~~~~~~ {% for item in bugs %} * FIX `#{{ item["number"] }} <{{ item["url"] }}>`_ : {{ item["title"] }} {%- endfor %} {%- endif %} {% if features %} Features added ~~~~~~~~~~~~~~~~ {% for item in features %} * `#{{ item["number"] }} <{{ item["url"] }}>`_ : {{ item["title"] }} {%- endfor %} {%- endif %} {% if tasks %} Tasks terminated ~~~~~~~~~~~~~~~~~ {% for item in tasks %} * `#{{ item["number"] }} <{{ item["url"] }}>`_ : {{ item["title"] }} {%- endfor %} {%- endif %} {%- endif %} <file_sep>/docs/make.py # -*- coding: utf-8 -*- # ===================================================================================================================== # Copyright (©) 2015-$today.year LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # ===================================================================================================================== # """ Clean, build, and release the HTML and PDF documentation for SpectroChemPy. ```bash python make.py [options] ``` where optional parameters indicates which job(s) is(are) to perform. """ from os import environ import argparse import shutil import sys import warnings import zipfile from pathlib import Path import numpy as np from skimage.io import imread, imsave from skimage.transform import resize from sphinx.application import Sphinx from sphinx.deprecation import RemovedInSphinx50Warning, RemovedInSphinx40Warning from spectrochempy import version from spectrochempy.utils import sh warnings.filterwarnings(action='ignore', module='matplotlib', category=UserWarning) warnings.filterwarnings(action='ignore', category=RemovedInSphinx50Warning) warnings.filterwarnings(action='ignore', category=RemovedInSphinx40Warning) # CONSTANT PROJECTNAME = "spectrochempy" REPO_URI = f"spectrochempy/{PROJECTNAME}" API_GITHUB_URL = "https://api.github.com" URL_SCPY = "www.spectrochempy.fr" # GENERAL PATHS DOCS = Path(__file__).parent TEMPLATES = DOCS / '_templates' STATIC = DOCS / '_static' PROJECT = DOCS.parent DOCREPO = Path().home() / "spectrochempy_docs" DOCTREES = DOCREPO / "~doctrees" HTML = DOCREPO / "html" LATEX = DOCREPO / 'latex' DOWNLOADS = HTML / 'downloads' SOURCES = PROJECT / PROJECTNAME # DOCUMENTATION SRC PATH SRC = DOCS USERGUIDE = SRC / 'userguide' GETTINGSTARTED = SRC / 'gettingstarted' DEVGUIDE = SRC / 'devguide' REFERENCE = SRC / 'userguide' / 'reference' # generated by sphinx API = REFERENCE / 'generated' GALLERY = GETTINGSTARTED / 'gallery' PY = list(SRC.glob(('**/*.py'))) for f in PY[:]: if ( 'generated' in f.parts or '.ipynb_checkpoints' in f.parts or 'gallery' in f.parts or 'examples' in f.parts or 'sphinxext' in f.parts): PY.remove(f) if f.name in ['conf.py', 'make.py']: PY.remove(f) __all__ = [] # %% class BuildDocumentation(object): # .................................................................................................................. def __init__(self): # determine if we are in the developement branch (latest) or master (stable) if 'dev' in version: self._doc_version = 'latest' else: self._doc_version = 'stable' # .................................................................................................................. @property def doc_version(self): return self._doc_version # .................................................................................................................. def __call__(self): parser = argparse.ArgumentParser() parser.add_argument("-H", "--html", help="create html pages", action="store_true") parser.add_argument("-P", "--pdf", help="create pdf manual", action="store_true") parser.add_argument("--clean", help="clean for a full regeneration of the documentation", action="store_true") parser.add_argument("--delnb", help="delete all ipynb", action="store_true") parser.add_argument("-m", "--message", default='DOCS: updated', help='optional git commit message') parser.add_argument("--api", help="execute a full regeneration of the api", action="store_true") parser.add_argument("-R", "--release", help="release the current version documentation on website", action="store_true") parser.add_argument("--all", help="Build all docs", action="store_true") args = parser.parse_args() if len(sys.argv) == 1: parser.print_help(sys.stderr) return self.regenerate_api = args.api if args.clean and args.html: self.clean('html') if args.clean and args.pdf: self.clean('latex') if args.delnb: self.delnb() if args.html: self.make_docs('html') self.make_tutorials() if args.pdf: self.make_docs('latex') self.make_pdf() if args.all: self.delnb() self.make_docs('html', clean=True) self.make_docs('latex', clean=True) self.make_pdf() self.make_tutorials() @staticmethod def _confirm(action): # private method to ask user to enter Y or N (case-insensitive). answer = "" while answer not in ["y", "n"]: answer = input(f"OK to continue `{action}` Y[es]/[N[o] ? ", ).lower() return answer[:1] == "y" # .................................................................................................................. def make_docs(self, builder='html', clean=False): # Make the html or latex documentation doc_version = self.doc_version self.make_changelog() if builder not in ['html', 'latex']: raise ValueError('Not a supported builder: Must be "html" or "latex"') BUILDDIR = DOCREPO / builder print(f'{"-" * 80}\n' f'building {builder.upper()} documentation ({doc_version.capitalize()} version : {version})' f'\n{"-" * 80}') # recreate dir if needed if clean: print('CLEAN:') self.clean(builder) self.make_dirs() # update modified notebooks self.sync_notebooks() shutil.rmtree(API, ignore_errors=True) print(f'remove {API}') # run sphinx print(f'\n{builder.upper()} BUILDING:') srcdir = confdir = DOCS outdir = f"{BUILDDIR}/{doc_version}" doctreesdir = f"{DOCTREES}/{doc_version}" sp = Sphinx(srcdir, confdir, outdir, doctreesdir, builder) sp.verbosity = 1 sp.build() print(f"\n{'-' * 130}\nBuild finished. The {builder.upper()} pages " f"are in {outdir}.") if doc_version == 'stable': doc_version = 'latest' # make also the lastest identical print(f'\n{builder.upper()} BUILDING:') srcdir = confdir = DOCS outdir = f"{BUILDDIR}/{doc_version}" doctreesdir = f"{DOCTREES}/{doc_version}" sp = Sphinx(srcdir, confdir, outdir, doctreesdir, builder) sp.verbosity = 1 sp.build() print(f"\n{'-' * 130}\nBuild 'latest' finished. The {builder.upper()} pages " f"are in {outdir}.") doc_version = 'stable' if builder == 'html': self.make_redirection_page() # a workaround to reduce the size of the image in the pdf document # TODO: v.0.2 probably better solution exists? if builder == 'latex': self.resize_img(GALLERY, size=580.) # .................................................................................................................. @staticmethod def resize_img(folder, size): # image resizing mainly for pdf doc for filename in folder.rglob('**/*.png'): image = imread(filename) h, l, c = image.shape ratio = 1. if l > size: ratio = size / l if ratio < 1: # reduce size image_resized = resize(image, (int(image.shape[0] * ratio), int(image.shape[1] * ratio)), anti_aliasing=True) imsave(filename, (image_resized * 255.).astype(np.uint8)) # .................................................................................................................. def make_pdf(self): # Generate the PDF documentation doc_version = self.doc_version LATEXDIR = LATEX / doc_version print('Started to build pdf from latex using make.... ' 'Wait until a new message appear (it is a long! compilation) ') print('FIRST COMPILATION:') sh(f"cd {LATEXDIR}; lualatex -synctex=1 -interaction=nonstopmode spectrochempy.tex") print('MAKEINDEX:') sh(f"cd {LATEXDIR}; makeindex spectrochempy.idx") print('SECOND COMPILATION:') sh(f"cd {LATEXDIR}; lualatex -synctex=1 -interaction=nonstopmode spectrochempy.tex") print("move pdf file in the download dir") sh(f"cp {LATEXDIR / PROJECTNAME}.pdf {DOWNLOADS}/{doc_version}-{PROJECTNAME}.pdf") # .................................................................................................................. def sync_notebooks(self, pyfiles=PY): # Use jupytext to sync py and ipynb files in userguide and tutorials print(f'\n{"-" * 80}\nSync *.py and *.ipynb using jupytex\n{"-" * 80}') count = 0 for item in pyfiles: difftime = 1 print(f'sync: {item.name}') if item.with_suffix('.ipynb').exists(): difftime = item.stat().st_mtime - item.with_suffix('.ipynb').stat().st_mtime if difftime > .5: # may be modified count += 1 sh.jupytext("--update-metadata", '{"jupytext": {"notebook_metadata_filter":"all"}}', "--set-formats", "ipynb,py:percent", "--sync", item, silent=False) else: print('\tNo sync needed.') if count == 0: print('\nAll notebooks are up-to-date and synchronised with py files') print('\n') # .................................................................................................................. def delnb(self): # Remove all ipynb before git commit for nb in SRC.rglob('**/*.ipynb'): sh.rm(nb) for nbch in SRC.glob('**/.ipynb_checkpoints'): sh(f'rm -r {nbch}') # .................................................................................................................. def make_tutorials(self): # make tutorials.zip # clean notebooks output for nb in DOCS.rglob('**/*.ipynb'): # This will erase all notebook output sh(f"jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace {nb}", silent=True) # make zip of all ipynb def zipdir(path, dest, ziph): # ziph is zipfile handle for nb in path.rglob('**/*.ipynb'): if '.ipynb_checkpoints' in nb.parent.suffix: continue basename = nb.stem sh(f"jupyter nbconvert {nb} --to notebook" f" --ClearOutputPreprocessor.enabled=True" f" --stdout > out_{basename}.ipynb") sh(f"rm {nb}", silent=True) sh(f"mv out_{basename}.ipynb {nb}", silent=True) arcnb = str(nb).replace(str(path), str(dest)) ziph.write(nb, arcname=arcnb) zipf = zipfile.ZipFile('~notebooks.zip', 'w', zipfile.ZIP_STORED) zipdir(SRC, 'notebooks', zipf) zipdir(GALLERY / 'auto_examples', Path('notebooks') / 'examples', zipf) zipf.close() sh(f"mv ~notebooks.zip {DOWNLOADS}/{self.doc_version}-{PROJECTNAME}-notebooks.zip") # .................................................................................................................. def make_redirection_page(self, ): # create an index page a the site root to redirect to latest version html = f""" <html> <head> <title>Redirect to the dev version of the documentation</title> <meta http-equiv="refresh" content="0; URL=https://{URL_SCPY}/latest"> </head> <body> <p> We have moved away from the <strong>spectrochempy.github.io</strong> domain. If you're not automatically redirected, please visit us at <a href="https://{URL_SCPY}">https://{URL_SCPY}</a>. </p> </body> </html> """ with open(HTML / 'index.html', 'w') as f: f.write(html) # .................................................................................................................. def clean(self, builder): # Clean/remove the built documentation. print(f'\n{"-" * 80}\nCleaning\n{"-" * 80}') doc_version = self.doc_version if builder == 'html': shutil.rmtree(HTML / doc_version, ignore_errors=True) print(f'remove {HTML / doc_version}') shutil.rmtree(DOCTREES / doc_version, ignore_errors=True) print(f'remove {DOCTREES / doc_version}') shutil.rmtree(API, ignore_errors=True) print(f'remove {API}') shutil.rmtree(GALLERY, ignore_errors=True) print(f'remove {GALLERY}') else: shutil.rmtree(LATEX / doc_version, ignore_errors=True) print(f'remove {LATEX / doc_version}') # .................................................................................................................. def make_dirs(self): # Create the directories required to build the documentation. doc_version = self.doc_version # Create regular directories. build_dirs = [DOCREPO, DOCTREES, HTML, LATEX, DOCTREES / doc_version, HTML / doc_version, LATEX / doc_version, DOWNLOADS, ] for d in build_dirs: if not d.exists(): print(f'Make dir {d}') Path.mkdir(d, exist_ok=False) # .................................................................................................................. def make_changelog(self): print(f'\n{"-" * 80}\nMake `changelogs`\n{"-" * 80}') outfile = REFERENCE / 'changelog.rst' sh.pandoc(PROJECT / 'CHANGELOG.md', '-f', 'markdown', '-t', 'rst', '-o', outfile) print(f'`Complete what\'s new` log written to:\n{outfile}\n') # %% Build = BuildDocumentation() # %% if __name__ == '__main__': environ['DOC_BUILDING'] = 'yes' Build() del environ['DOC_BUILDING'] <file_sep>/tests/test_readers_writers/test_write_csv.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import pytest import spectrochempy as scp def test_write_csv(IR_dataset_2D): # 1D dataset without coords ds = scp.NDDataset([1, 2, 3]) f = ds.write_csv('myfile.csv', confirm=False) assert f.name == 'myfile.csv' f.unlink() f = ds.write_csv('myfile', confirm=False) assert f.name == 'myfile.csv' f.unlink() # 1D dataset with coords ds = IR_dataset_2D[0] f = ds.write_csv('myfile.csv', confirm=False) assert f.name == 'myfile.csv' f.unlink() # 2D dataset with coords ds = IR_dataset_2D with pytest.raises(NotImplementedError): f = ds.write_csv('myfile.csv', confirm=False) <file_sep>/docs/userguide/reference/changelog.rst What's new ========== Version 0.2.12 -------------- **BUGS FIXED** - LinearCoord operations now working. - Baseline default now “sequential” as expected. **WARNING**: It was wrongly set to “mutivariate” in previous releases, so you should expect some difference with processings you may have done before. - Comparison of coordinates now correct for mathematical operations. - Alignment methods now working (except for multidimensional alignement). Version 0.2.11 -------------- **BUGS FIXED** - Plot2D now works when more than one coord in ‘y’ axis (#238). - Spectrochempy_data location have been corrected (#239). Version 0.2.10 -------------- **NEW FEATURES** - All data for tests and examples are now external. They are now located in a separate conda package: ``spectrochempy_data``. - Installation in Colab with Examples is now supported. **BUGS FIXED** - Read_quadera() and example now based on a correct asc file Version 0.2.9 ------------- **BUGS FIXED** - Hotfix regarding dispay of NMR x scale Version 0.2.8 ------------- **NEW FEATURES** - Added write_csv() dir 1D datasets - Added read_quadera() for Pfeiffer Vacuum’s QUADERA® MS files - Added test for trapz(), simps(), readquadera() - Improved displaying of Interferograms **BUGS FIXED** - Problem with trapz(), simps() - FIX: interferogram x scaling Version 0.2.7 ------------- **NEW FEATURES** - Test and data for read_carroucell(), read_srs(), read_dso() - Added NMR processing of 2D spectra. - Added FTIR interferogram processing. **BUGS FIXED** - Problem with read_carroucell(), read_srs(), read_dso() - Colaboratory compatibility - Improved check updates Version 0.2.6 ------------- **NEW FEATURES** - Check for new version on anaconda cloud spectrocat channel. - 1D NMR processing with the addition of several new methods. - Improved handling of Linear coordinates. **BUGS FIXED** - Adding quantity to datasets with different scaling (#199). - Math operates now on linear coordinates. - Compatibility with python 3.6 Version 0.2.5 ------------- **TASKS** - Docker image building. - instructions to use it added in the documentation. **NEW FEATURES** - cantera installation optional. - use of pyqt for matplotlib optional. **BUGS FIXED** - added fonts in order to solve missing fonts problems on linux and windows. Version 0.2.4 ------------- **TASKS** - Documentation largely revisited and hopefully improved. *Still some work to be done*. - NDMath (mathematical and dataset creation routines) module revisited. *Still some work to be done*. **NEW FEATURES** - Changed CoordRange behavior. **BUGS FIXED** - Fix a problem with importing the API. - Fix dim handling in processing functions. Version 0.2.0 ------------- **NEW FEATURES** - Copyright update. - Requirements and env yml files updated. - Use of the coordinates in math operation improved. - Added ROI and Offset properties to NDArrays. - Readers / Writers revisited. - Bruker TOPSPIN reader. - Added LabSpec reader for .txt exported files. - Simplified the format of scp file - now zipped JSON files. - Rewriting json serialiser. - Add function pathclean to the API. - Add some array creation function to NDMath. - Refactoring plotting preferences system. - Baseline correction now accept single value for ranges. - Add a waterfall plot. - Refactoring plot2D and 1D methods. - Added Simpson’rule integration. - Addition of multiple coordinates to a dimension works better. - Added Linear coordinates (EXPERIMENTAL). - Test for NDDataset dtype change at initialisation. - Added subdir of txt files in ramandata. - Comparison of datasets improved in testing.py. - Comparison of datasets and projects. **BUGS FIXED** - Dtype parameter was not taken into account during initialisation of NDArrays. - Math function behavior for coords. - Color normalisation on the full range for colorscale. - Configuration settings in the main application. - Compatibility read_zip with py3.7. - NDpanel temporary removed from the master. - 2D IRIS fixed. - Trapz integration to return NDDataset. - Suppressed a forgotten sleep statement that was slowing down the SpectroChemPy initialisation. - Error in SIMPLISMA (changed affectations such as C.data[…] = something by C[…] = something. - Cleaning mplstyle about non-style parameters and fix makestyle. - Argument of set_xscale. - Use read_topspin instead of the deprecated function read_bruker_nmr. - Some issues with interactive baseline. - Baseline and fitting tutorials. - Removed dependency of isotopes.py to pandas. Version 0.1.x ------------- - Initial development versions. <file_sep>/spectrochempy/core/processors/apodization.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ['em', 'gm', "sp", "sine", "sinm", "qsin", "general_hamming", "hamming", "hann", "triang", "bartlett", "blackmanharris"] __dataset_methods__ = __all__ import functools import numpy as np from scipy.signal import windows from spectrochempy.units import Quantity from spectrochempy.utils import EPSILON from spectrochempy.core import error_ pi = np.pi # ====================================================================================================================== # Decorators # ====================================================================================================================== def _apodize_method(**units): # Decorator to set units of parameters according to dataset units def decorator_apodize_method(method): @functools.wraps(method) def wrapper(dataset, **kwargs): # what to return retapod = kwargs.pop('retapod', False) dryrun = kwargs.pop('dryrun', False) # is_nmr = dataset.origin.lower() in ["topspin", ] is_ir = dataset.origin.lower() in ["omnic", "opus"] # On which axis do we want to apodize? (get axis from arguments) axis, dim = dataset.get_axis(**kwargs, negative_axis=True) # output dataset inplace (by default) or not if not kwargs.pop('inplace', False) and not dryrun: new = dataset.copy() # copy to be sure not to modify this dataset else: new = dataset # The last dimension is always the dimension on which we apply the apodization window. # If needed, we swap the dimensions to be sure to be in this situation swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) # must be done in place swaped = True # Get the coordinates for the last dimension x = new.coordset[dim] if hasattr(x, '_use_time_axis'): store = x._use_time_axis x._use_time_axis = True # we need to have dimentionless or time units # check if the dimensionality is compatible with this kind of functions if x.unitless or x.dimensionless or x.units.dimensionality == '[time]': # Set correct units for parameters dunits = dataset.coordset[dim].units apod = {} for key, default_units in units.items(): if key not in kwargs or default_units is None: continue par = kwargs[key] if isinstance(par, str): par = Quantity(par) if not isinstance(par, Quantity): # set to default units par *= Quantity(1., default_units) apod[key] = par if par.dimensionality == 1 / dunits.dimensionality: kwargs[key] = 1. / (1. / par).to(dunits) else: kwargs[key] = par.to(dunits) kwargs[key] = kwargs[key].magnitude # Call to the apodize function # ---------------------------- # now call the method with unitless parameters if is_ir: # we must apodize at the top of the interferogram. zpd = int(np.argmax(new.data, -1)) dist2end = x.size - zpd apod_arr = method(np.empty(2 * dist2end), **kwargs) apod_arr = apod_arr[-x.size:] else: apod_arr = method(x.data, **kwargs) if kwargs.pop('rev', False): apod_arr = apod_arr[::-1] # reverse apodization if kwargs.pop('inv', False): apod_arr = 1. / apod_arr # invert apodization if not dryrun: new.history = f'`{method.__name__}` apodization performed on dimension `{dim}` ' \ f'with parameters: {apod}' # Apply? if not dryrun: new._data *= apod_arr else: # not (x.unitless or x.dimensionless or x.units.dimensionality != '[time]') error_('This method apply only to dimensions with [time] or [dimensionless] dimensionality.\n' 'Apodization processing was thus cancelled') apod_arr = 1. # restore original data order if it was swaped if swaped: new.swapdims(axis, -1, inplace=True) # must be done inplace if hasattr(x, '_use_time_axis'): new.x._use_time_axis = store if retapod: apodcurve = type(new)(apod_arr, coordset=[x]) return new, apodcurve else: return new return wrapper return decorator_apodize_method # ====================================================================================================================== # Public module methods # ====================================================================================================================== @_apodize_method(lb='Hz', shifted='us') def em(dataset, lb=1, shifted=0, **kwargs): r""" Calculate exponential apodization. For multidimensional NDDataset, the apodization is by default performed on the last dimension. The data in the last dimension MUST be time-domain, or an error is raised. Functional form of apodization window : .. math:: em(t) = \exp(- e (t-t_0) ) where .. math:: e = \pi * lb Parameters ---------- dataset : Dataset Input dataset. lb : float or |Quantity|, optional, default=1 Hz Exponential line broadening, If it is not a quantity with units, it is assumed to be a broadening expressed in Hz. shifted : float or `quantity`, optional, default=0 us Shift the data time origin by this amount. If it is not a quantity it is assumed to be expressed in the data units of the last dimension. Returns ------- apodized Dataset. apod_arr The apodization array only if 'retapod' is True. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False True for inverse apodization. rev : bool, keyword parameter, optional, default=False True to reverse the apodization before applying it to the data. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. retapod : bool, keyword parameter, optional, default=False True to return the apodization array along with the apodized object. See Also -------- gm, sp, sine, sinm, qsin, hamming, triang, bartlett, blackmanharris, mertz """ # units are set by a decorator x = dataset e = np.ones_like(x) if abs(lb) <= EPSILON: return e if shifted < EPSILON: shifted = 0. tc = 1. / lb xs = pi * np.abs(x - shifted) e = xs / tc return np.exp(-e) # ...................................................................................................................... @_apodize_method(gb='Hz', lb='Hz', shifted='us') def gm(dataset, gb=1, lb=0, shifted=0, **kwargs): r""" Calculate lorentz-to-gauss apodization. Functional form of apodization window : .. math:: gm(t) = \exp(e - g^2 ) where : .. math:: e = \pi * lb * (t - t0) and .. math:: g = 0.6 * \pi * gb * (t - t0) Parameters ---------- dataset : ndarray. Dataset we want to apodize using an Lorentz Multiplication. lb : float or `quantity`, optional, default=0 Hz Inverse exponential width. If it is not a quantity with units, it is assumed to be a broadening expressed in Hz. gb : float or `quantity`, optional, default=1 Hz Gaussian broadening width. If it is not a quantity with units, it is assumed to be a broadening expressed in Hz. shifted : float or `quantity`, optional, default=0 us Shift the data time origin by this amount. If it is not a quantity it is assumed to be expressed in the data units of the last dimension. Returns ------- apodized Dataset. apod_arr The apodization array only if 'retapod' is True. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False True for inverse apodization. rev : bool, keyword parameter, optional, default=False True to reverse the apodization before applying it to the data. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset retapod : bool, keyword parameter, optional, default=False True to return the apodization array along with the apodized object. See Also -------- em, sp, sine, sinm, qsin, hamming, triang, bartlett, blackmanharris, mertz """ x = dataset g = np.ones_like(x) if abs(lb) <= EPSILON and abs(gb) <= EPSILON: return g if shifted < EPSILON: shifted = 0. xs = pi * np.abs(x - shifted) if abs(lb) > EPSILON: tc1 = 1. / lb e = x / tc1 else: e = np.zeros_like(x) if abs(gb) > EPSILON: tc2 = 1. / gb g = 0.6 * xs / tc2 else: g = np.zeros_like(x) return np.exp(e - g ** 2) # ...................................................................................................................... @_apodize_method(ssb=None, pow=None) def sp(dataset, ssb=1, pow=1, **kwargs): r""" Calculate apodization with a Sine window multiplication. For multidimensional NDDataset, the apodization is by default performed on the last dimension. Functional form of apodization window (cfBruker TOPSPIN manual): .. math:: sp(t) = \sin(\frac{(\pi - \phi) t }{\text{aq}} + \phi)^{pow} where :math:`0 < t < \text{aq}` and :math:`\phi = \pi ⁄ \text{sbb}` when :math:`\text{ssb} \ge 2` or :math:`\phi = 0` when :math:`\text{ssb} < 2` :math:`\text{aq}` is an acquisition status parameter and :math:`\text{ssb}` is a processing parameter (see the `ssb` parameter definition below) and :math:`\text{pow}` is an exponent equal to 1 for a sine bell window or 2 for a squared sine bell window. Parameters ---------- dataset : Dataset Dataset we want to apodize using Sine Bell or Squared Sine Bell window multiplication. sbb : int or float, optional, default=1 This processing parameter mimics the behaviour of the SSB parameter on bruker TOPSPIN software: Typical values are 1 for a pure sine function and 2 for a pure cosine function. Values greater than 2 give a mixed sine/cosine function. Note that all values smaller than 2, for example 0, have the same effect as :math:`\text{ssb}=1`, namely a pure sine function. pow : enum [1,2], optional, default=1 Exponent value - If pow=2 a Squared Sine Bell window multiplication is performed. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False True for inverse apodization. rev : bool, keyword parameter, optional, default=False True to reverse the apodization before applying it to the data. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. retapod : bool, keyword parameter, optional, default=False True to return the apodization array along with the apodized object. Returns ------- apodized Dataset. apod_arr The apodization array only if 'retapod' is True. See Also -------- em, gm, sine, sinm, qsin, hamming, triang, bartlett, blackmanharris, mertz """ x = dataset # ssb if ssb < 1.: ssb = 1. # pow pow = 2 if int(pow) % 2 == 0 else 1 aq = (x[-1] - x[0]) t = x / aq if ssb < 2: phi = 0. else: phi = np.pi / ssb return np.sin((np.pi - phi) * t + phi) ** pow # ...................................................................................................................... def sine(dataset, *args, **kwargs): """ Strictly equivalent to :meth:`sp`. See Also -------- em, gm, sp, sinm, qsin, hamming, triang, bartlett, blackmanharris, mertz """ return sp(dataset, *args, **kwargs) # ...................................................................................................................... def sinm(dataset, ssb=1, **kwargs): """ Equivalent to :meth:`sp`, with pow = 1 (sine bell apodization window). See Also -------- em, gm, sp, sine, qsin, hamming, triang, bartlett, blackmanharris, mertz """ return sp(dataset, ssb=ssb, pow=1, **kwargs) # ...................................................................................................................... def qsin(dataset, ssb=1, **kwargs): """ Equivalent to :meth:`sp`, with pow = 2 (squared sine bell apodization window). See Also -------- em, gm, sp, sine, sinm, hamming, triang, bartlett, blackmanharris, mertz """ return sp(dataset, ssb=ssb, pow=2, **kwargs) # ...................................................................................................................... @_apodize_method(alpha=None) def general_hamming(dataset, alpha, **kwargs): r""" Calculate generalized Hamming apodization. For multidimensional NDDataset, the apodization is by default performed on the last dimension. The data in the last dimension MUST be time-domain or dimensionless, otherwise an error is raised. Functional form of apodization window : .. math:: w(n) = \alpha - \left(1 - \alpha\right) \cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1 where M is the number of point of the input dataset. Both the common Hamming window and Hann window are special cases of the generalized Hamming window with :math:`\alpha` = 0.54 and :math:`\alpha` = 0.5, respectively Parameters ---------- dataset : array. Input dataset. alpha : float The window coefficient, :math:`\alpha`. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False True for inverse apodization. rev : bool, keyword parameter, optional, default=False True to reverse the apodization before applying it to the data. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. retapod : bool, keyword parameter, optional, default=False True to return the apodization array along with the apodized object. Returns ------- apodized Dataset. apod_arr The apodization array only if 'retapod' is True. See Also -------- gm, sp, sine, sinm, qsin, hamming, triang, bartlett, blackmanharris, mertz """ x = dataset return windows.general_hamming(len(x), alpha, sym=True) def hamming(dataset, **kwargs): """ Calculate generalized Hamming (== Happ-Genzel) apodization. For multidimensional NDDataset, the apodization is by default performed on the last dimension. The data in the last dimension MUST be time-domain or dimensionless, otherwise an error is raised. Functional form of apodization window : .. math:: w(n) = \alpha - (1 - \alpha)\cos(\frac{2\pi n}{M-1})\qquad 0\leq n\leq M-1 where M is the number of point of the input dataset and :math:`\alpha` = 0.54. Parameters ---------- dataset : array. Input dataset. alpha : float The window coefficient, :math:`\alpha`. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x'. Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False. True for inverse apodization. rev : bool, keyword parameter, optional, default=False. True to reverse the apodization before applying it to the data. inplace : bool, keyword parameter, optional, default=False. True if we make the transform inplace. If False, the function return a new dataset retapod : bool, keyword parameter, optional, default=False True to return the apodization array along with the apodized object Returns ------- apodized Dataset. apod_arr The apodization array only if 'retapod' is True. See Also -------- general_hamming, hann """ return general_hamming(dataset, alpha=0.54) def hann(dataset, **kwargs): """ Return a Hann window. For multidimensional NDDataset, the apodization is by default performed on the last dimension. The data in the last dimension MUST be time-domain or dimensionless, otherwise an error is raised. Functional form of apodization window : .. math:: w(n) = \alpha - (1 - \alpha) \cos(\frac{2\pi{n}}{M-1}) \qquad 0 \leq n \leq M-1 where M is the number of point of the input dataset and :math:`\alpha` = 0.5 Parameters ---------- dataset : array. Input dataset. alpha : float The window coefficient, :math:`\alpha`. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x'. Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False. True for inverse apodization. rev : bool, keyword parameter, optional, default=False. True to reverse the apodization before applying it to the data. inplace : bool, keyword parameter, optional, default=False. True if we make the transform inplace. If False, the function return a new dataset retapod : bool, keyword parameter, optional, default=False True to return the apodization array along with the apodized object Returns ------- apodized Dataset. apod_arr The apodization array only if 'retapod' is True. See Also -------- general_hamming, hamming """ return general_hamming(dataset, alpha=0.5) @_apodize_method() def triang(dataset, **kwargs): r""" Calculate triangular apodization with non-null extremities and maximum value normalized to 1 For multidimensional NDDataset, the apodization is by default performed on the last dimension. The data in the last dimension MUST be time-domain or dimensionless, otherwise an error is raised. Parameters ---------- dataset : array. Input dataset. Returns ------- apodized Dataset. apod_arr The apodization array only if 'retapod' is True. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x'. Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False. True for inverse apodization. rev : bool, keyword parameter, optional, default=False. True to reverse the apodization before applying it to the data. inplace : bool, keyword parameter, optional, default=False. True if we make the transform inplace. If False, the function return a new dataset retapod : bool, keyword parameter, optional, default=False True to return the apodization array along with the apodized object See Also -------- gm, sp, sine, sinm, qsin, hamming, bartlett, blackmanharris, mertz """ x = dataset return x * windows.triang(len(x), sym=True) @_apodize_method() def bartlett(dataset, **kwargs): """ Calculate Bartlett apodization (triangular window with end points at zero). For multidimensional NDDataset, the apodization is by default performed on the last dimension. The data in the last dimension MUST be time-domain or dimensionless, otherwise an error is raised. The Bartlett window is defined as .. math:: w(n) = \frac{2}{M-1} (\frac{M-1}{2} - |n - \frac{M-1}{2}|) where M is the number of point of the input dataset. Parameters ---------- dataset : Dataset Input dataset. Returns ------- apodized dataset. apod_arr The apodization array only if 'retapod' is True. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False True for inverse apodization. rev : bool, keyword parameter, optional, default=False True to reverse the apodization before applying it to the data. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new dataset. retapod : bool, keyword parameter, optional, default=False True to return the apodization array along with the apodized object. See Also -------- triang : A triangular window that does not touch zero at the ends. """ x = dataset return x * windows.bartlett(len(x), sym=True) @_apodize_method() def blackmanharris(dataset, **kwargs): """ Calculate a minimum 4-term Blackman-Harris apodization. For multidimensional NDDataset, the apodization is by default performed on the last dimension. The data in the last dimension MUST be time-domain or dimensionless, otherwise an error is raised. Parameters ---------- dataset : dataset Input dataset. Returns ------- apodized dataset. apod_arr The apodization array only if 'retapod' is True. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x' Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False True for inverse apodization. rev : bool, keyword parameter, optional, default=False True to reverse the apodization before applying it to the data. inplace : bool, keyword parameter, optional, default=False True if we make the transform inplace. If False, the function return a new datase retapod : bool, keyword parameter, optional, default=False True to return the apodization array along with the apodized object. """ x = dataset return x * windows.blackmanharris(len(x), sym=True) <file_sep>/tests/test_dataset/test_ndcoord.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from copy import copy import numpy as np import pytest from spectrochempy.core.dataset.coord import Coord, LinearCoord from spectrochempy.units import ur, Quantity from spectrochempy.utils.testing import assert_array_equal, assert_equal_units from spectrochempy.core import debug_ # ====================================================================================================================== # Coord # ====================================================================================================================== def test_coord(): # simple coords a = Coord([1, 2, 3], name='x') assert a.id is not None assert not a.is_empty assert not a.is_masked assert_array_equal(a.data, np.array([1, 2, 3])) assert not a.is_labeled assert a.units is None assert a.unitless debug_(a.meta) assert not a.meta assert a.name == 'x' # set properties a.title = 'xxxx' assert a.title == 'xxxx' a.name = 'y' assert a.name == 'y' a.meta = None a.meta = {'val': 125} # need to be an OrderedDic assert a.meta['val'] == 125 # now with labels x = np.arange(10) y = list('abcdefghij') a = Coord(x, labels=y, title='processors', name='x') assert a.title == 'processors' assert isinstance(a.data, np.ndarray) assert isinstance(a.labels, np.ndarray) # any kind of object can be a label assert a.labels.dtype == 'O' # even an array a._labels[3] = x assert a._labels[3][2] == 2 # coords can be defined only with labels y = list('abcdefghij') a = Coord(labels=y, title='processors') assert a.title == 'processors' assert isinstance(a.labels, np.ndarray) assert_array_equal(a.values, a.labels) # any kind of object can be a label assert a.labels.dtype == 'O' # even an array a._labels[3] = range(10) assert a._labels[3][2] == 2 # coords with datetime from datetime import datetime x = np.arange(10) y = [datetime(2017, 6, 2 * (i + 1)) for i in x] a = Coord(x, labels=y, title='time') assert a.title == 'time' assert isinstance(a.data, np.ndarray) assert isinstance(a.labels, np.ndarray) a._sort(by='label', descend=True) # but coordinates must be 1D with pytest.raises(ValueError): # should raise an error as coords must be 1D Coord(data=np.ones((2, 10))) # unitless coordinates coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=list('abcdefghij'), mask=None, units=None, title='wavelength') assert coord0.units is None assert coord0.data[0] == 4000. assert repr(coord0) == 'Coord: [float64] unitless (size: 10)' # dimensionless coordinates coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=list('abcdefghij'), mask=None, units=ur.dimensionless, title='wavelength') assert coord0.units.dimensionless assert coord0.units.scaling == 1. assert coord0.data[0] == 4000. assert repr(coord0) == 'Coord: [float64] (size: 10)' # scaled dimensionless coordinates coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=list('abcdefghij'), mask=None, units='m/km', title='wavelength') assert coord0.units.dimensionless assert coord0.data[0] == 4000. # <- displayed data to be multiplied by the scale factor assert repr(coord0) == 'Coord: [float64] scaled-dimensionless (0.001) (size: 10)' coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=list('abcdefghij'), mask=None, units=ur.m / ur.km, title='wavelength') assert coord0.units.dimensionless assert coord0.data[0] == 4000. # <- displayed data to be multiplied by the scale factor assert repr(coord0) == 'Coord: [float64] scaled-dimensionless (0.001) (size: 10)' coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=list('abcdefghij'), mask=None, units="m^2/s", title='wavelength') assert not coord0.units.dimensionless assert coord0.units.scaling == 1. assert coord0.data[0] == 4000. assert repr(coord0) == 'Coord: [float64] m^2.s^-1 (size: 10)' # comparison coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=list('abcdefghij'), mask=None, title='wavelength') coord0b = Coord(data=np.linspace(4000, 1000, 10), labels='a b c d e f g h i j'.split(), mask=None, title='wavelength') coord1 = Coord(data=np.linspace(4000, 1000, 10), labels='a b c d e f g h i j'.split(), mask=None, title='titi') coord2 = Coord(data=np.linspace(4000, 1000, 10), labels='b c d e f g h i j a'.split(), mask=None, title='wavelength') coord3 = Coord(data=np.linspace(4000, 1000, 10), labels=None, mask=None, title='wavelength') assert coord0 == coord0b assert coord0 != coord1 # different title assert coord0 != coord2 # different labels assert coord0 != coord3 # one coord has no label # init from another coord coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=list('abcdefghij'), units='s', mask=None, title='wavelength') coord1 = Coord(coord0) assert coord1._data is coord0._data coord1 = Coord(coord0, copy=True) assert coord1._data is not coord0._data assert_array_equal(coord1._data, coord0._data) assert isinstance(coord0, Coord) assert isinstance(coord1, Coord) # sort coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=list('abcdefghij'), units='s', mask=None, title='wavelength') assert coord0.is_labeled ax = coord0._sort() assert (ax.data[0] == 1000) coord0._sort(descend=True, inplace=True) assert (coord0.data[0] == 4000) ax1 = coord0._sort(by='label', descend=True) assert (ax1.labels[0] == 'j') # copy coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=list('abcdefghij'), units='s', mask=None, title='wavelength') coord1 = coord0.copy() assert coord1 is not coord0 assert_array_equal(coord1.data, coord0.data) assert_array_equal(coord1.labels, coord0.labels) assert coord1.units == coord0.units coord2 = copy(coord0) assert coord2 is not coord0 assert_array_equal(coord2.data, coord0.data) assert_array_equal(coord2.labels, coord0.labels) assert coord2.units == coord0.units # automatic reversing for wavenumbers coord0 = Coord(data=np.linspace(4000, 1000, 10), units='cm^-1', mask=None, title='wavenumbers') assert coord0.reversed def test_coord_slicing(): # slicing by index coord0 = Coord(data=np.linspace(4000, 1000, 10), mask=None, title='wavelength') assert coord0[0] == 4000.0 coord1 = Coord(data=np.linspace(4000, 1000, 10), units='cm^-1', mask=None, title='wavelength') c1 = coord1[0] assert isinstance(c1.values, Quantity) assert coord1[0].values == 4000.0 * (1. / ur.cm) # slicing with labels labs = list('abcdefghij') coord0 = Coord(data=np.linspace(4000, 1000, 10), labels=labs, units='cm^-1', mask=None, title='wavelength') assert coord0[0].values == 4000.0 * (1. / ur.cm) assert isinstance(coord0[0].values, Quantity) assert coord0[2] == coord0['c'] assert coord0['c':'d'] == coord0[2:4] # label included # slicing only-labels coordinates y = list('abcdefghij') a = Coord(labels=y, name='x') assert a.name == 'x' assert isinstance(a.labels, np.ndarray) assert_array_equal(a.values, a.labels) # Math # ---------------------------------------------------------------------------------------------------------------------- # first operand has units km, second is a scalar with units m @pytest.mark.parametrize(('operation', 'result_units'), [('__add__', ur.km), ('__sub__', ur.km), ('__mul__', ur.km * ur.m), ('__truediv__', ur.km / ur.m)]) def test_coord_unit_conversion_operators_a(operation, result_units): print(operation, result_units) in_km = Coord(data=np.linspace(4000, 1000, 10), units='km', mask=None, title='something') scalar_in_m = 2. * ur.m operator_km = in_km.__getattribute__(operation) combined = operator_km(scalar_in_m) assert_equal_units(combined.units, result_units) UNARY_MATH = ["fabs", "ceil", "floor", "negative", "reciprocal", "rint", "sqrt", "square"] @pytest.mark.parametrize('name', UNARY_MATH) def test_coord_unary_ufuncs_simple_data(name): coord0 = Coord(data=np.linspace(4000, 1000, 10), units='km', mask=None, title='something') f = getattr(np, name) r = f(coord0) assert isinstance(r, Coord) # first operand has units km, second is a scalar unitless @pytest.mark.parametrize(('operation', 'result_units'), [('__mul__', ur.km), ('__truediv__', ur.km)]) def test_coord_unit_conversion_operators(operation, result_units): in_km = Coord(data=np.linspace(4000, 1000, 10), units='km', mask=None, title='something') scalar = 2. operator_km = in_km.__getattribute__(operation) combined = operator_km(scalar) debug_(f'{operation}, {combined}') assert_equal_units(combined.units, result_units) NOTIMPL = ['mean', 'pipe', 'remove_masks', 'std', 'sum', 'swapdims'] @pytest.mark.parametrize('name', NOTIMPL) def test_coord_not_implemented(name): coord0 = Coord(data=np.linspace(4000, 1000, 10), units='cm^-1', mask=None, title='wavelength') with pytest.raises(NotImplementedError): getattr(coord0, name)() def test_linearcoord(): coord1 = Coord([1, 2.5, 4, 5]) coord2 = Coord(np.array([1, 2.5, 4, 5])) assert coord2 == coord1 coord3 = Coord(range(10)) coord4 = Coord(np.arange(10)) assert coord4 == coord3 coord5 = coord4.copy() coord5 += 1 assert np.all(coord5.data == coord4.data + 1) assert coord5 is not None coord5.linear = True coord6 = Coord(linear=True, offset=2.0, increment=2.0, size=10) assert np.all(coord6.data == (coord4.data + 1.0) * 2.) LinearCoord(offset=2.0, increment=2.0, size=10) coord0 = LinearCoord.linspace(200., 300., 3, labels=['cold', 'normal', 'hot'], units="K", title='temperature') coord1 = LinearCoord.linspace(0., 60., 100, labels=None, units="minutes", title='time-on-stream') coord2 = LinearCoord.linspace(4000., 1000., 100, labels=None, units="cm^-1", title='wavenumber') assert coord0.size == 3 assert coord1.size == 100 assert coord2.size == 100 coordc = coord0.copy() assert coord0 == coordc coordc = coord1.copy() assert coord1 == coordc <file_sep>/tests/test_api/test_application_api_magics.py # -*- coding: utf-8 -*- from subprocess import Popen, PIPE # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import pytest from spectrochempy import APIref, set_loglevel, get_loglevel, warning_, version set_loglevel('WARNING') def test_api(): assert 'EFA' in APIref assert 'CRITICAL' in APIref assert 'np' in APIref assert 'NDDataset' in APIref assert 'abs' in APIref def test_datadir(): from spectrochempy.application import DataDir print(DataDir().listing()) def test_version(): # test version assert len(version.split('.')) >= 3 def test_log(): # test log set_loglevel("WARNING") assert get_loglevel() == 30 warning_('Ok, this is nicely executing!') set_loglevel(10) assert get_loglevel() == 10 def test_magic_addscript(ip): if ip is None: warning_('ip is None - pss this test ') return from spectrochempy.application import SpectroChemPyMagics ip.register_magics(SpectroChemPyMagics) ip.run_cell("from spectrochempy import *") assert "preferences" in ip.user_ns.keys() ip.run_cell("print(preferences.available_styles)", store_history=True) ip.run_cell("project = Project()", store_history=True) x = ip.run_line_magic('addscript', '-p project -o prefs -n preferences 2') print("x", x) assert x.strip() == 'Script prefs created.' # with cell contents x = ip.run_cell('%%addscript -p project -o essai -n preferences\n' 'print(preferences.available_styles)') print('result\n', x.result) assert x.result.strip() == 'Script essai created.' @pytest.mark.skip() def test_console_subprocess(): # to test this, the scripts must be installed so the spectrochempy # package must be installed: use pip install -e . res = Popen(['scpy'], stdout=PIPE, stderr=PIPE) output, error = res.communicate() assert "nh4y-activation.spg'" in error.decode("utf-8") assert 'A.Travert & C.Fernandez @ LCS' in output.decode("utf-8") def test_config(capsys): from spectrochempy.application import SpectroChemPy app = SpectroChemPy(show_config_json=True) app.start() out, err = capsys.readouterr() assert 'SpectroChemPy' in out <file_sep>/tests/test_utils/test_logger.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import logging from spectrochempy import WARNING, INFO, error_, debug_, info_, warning_, set_loglevel def test_logger(caplog): logger = logging.getLogger('SpectroChemPy') logger.propagate = True caplog.set_level(logging.DEBUG) # We can set the level using strings set_loglevel("DEBUG") assert logger.level == logging.DEBUG set_loglevel(WARNING) assert logger.level == logging.WARNING error_('\n' + '*' * 80 + '\n') debug_('debug in WARNING level - should not appear') info_('info in WARNING level - should not appear') warning_('OK this is a Warning') error_('OK This is an Error') error_('\n' + '*' * 80 + '\n') set_loglevel(INFO) assert logger.level == logging.INFO debug_('debug in INFO level - should not appear') info_('OK - info in INFO level') warning_('OK this is a Warning') error_('OK This is an Error') error_('\n' + '*' * 80 + '\n') set_loglevel('DEBUG') assert logger.level == logging.DEBUG debug_('OK - debug in DEBUG level') info_('OK - info in DEBUG level') assert caplog.records[-1].levelname == 'INFO' assert caplog.records[-1].message == 'OK - info in DEBUG level' warning_('OK this is a Warning') assert caplog.records[-1].levelname == 'WARNING' assert caplog.records[-1].message == 'OK this is a Warning' error_('OK This is an Error') assert caplog.records[-1].levelname == 'ERROR' assert caplog.records[-1].message == 'OK This is an Error' <file_sep>/spectrochempy/core/writers/writeexcel.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Plugin module to extend NDDataset with a JCAMP-DX export method. """ # import os as os from spectrochempy.core.writers.exporter import Exporter, exportermethod __all__ = ['write_excel'] __dataset_methods__ = __all__ # ....................................................................................................................... def write_excel(*args, **kwargs): """ Writes a dataset in XLS format Parameters ---------- filename: str or pathlib objet, optional If not provided, a dialog is opened to select a file for writing protocol : {'scp', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for writing. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional Where to write the specified `filename`. If not specified, write in the current directory. description: str, optional A Custom description. Returns ------- out : `pathlib` object path of the saved file Examples -------- The extension will be added automatically >>> X.write_xls('myfile') """ exporter = Exporter() kwargs['filetypes'] = ['Microsoft Excel files (*.xls)'] kwargs['suffix'] = '.xls' return exporter(*args, **kwargs) write_xls = write_excel write_xls.__doc__ = 'This method is an alias of `write_excel` ' @exportermethod def _write_excel(*args, **kwargs): raise NotImplementedError <file_sep>/.github/ISSUE_TEMPLATE/need-help-template.md --- name: Need help about: 'Ask for help / Questions' title: '' labels: 'help wanted' assignees: '' --- **Describe you problem** Ask you question the most precisely you can. **Desktop (please complete the following information):** - OS: [e.g., OSX Catalina] - Python version (e.g;, 3.7) - SpectroChemPy version [e.g., 0.1.20] **Additional context** Add any other context about the problem here. <file_sep>/docs/devguide/issues.rst .. _contributing.bugs_report: Reporting Issues ================= All contributions, bug reports, bug fixes, enhancements requests and ideas are welcome Bug reports are a very important part of any software project. Helping us to discover issues or proposing enhancements should allow making |scpy| more stable, reliable and adapted to more scientific activities. You can report the ``Bug(s)`` you discover or the ``Feature Requests`` to the `Issue Tracker <https://github.com/spectrochempy/spectrochempy/issues>`__ .. warning:: The issue tracker is hosted on well known `GitHub <https://www.github.com/spectrochempy/spectrochempy>`__ platform. If you do not sign in, you will have only read right on the issues page. Thus, to be able to post issues or feature requests you need to register for a `free GitHub account <https://github.com/signup/free>`__. Before creating a new issue, it is worth searching for existing bug reports and pull requests to see if the problem has already been reported and may be already fixed. Bug reports should : #. Include a short stand-alone Python snippet reproducing the problem. You can format the code using `GitHub Flavored Markdown <http://github.github.com/github-flavored-markdown/>`__ .. sourcecode:: ipython3 >>> from spectrochempy import * SpectroChemPy's API ... >>> nd = NDDataset() #. Include the full version string of |scpy|. You can use the built in property .. sourcecode:: ipython3 >>> print(version) 0.1.23... #. Explain why the current behavior is wrong/not desired and what you expect instead. The issue will then ishow up to the |scpy| community and be open to comments/ideas from others. <file_sep>/docs/gettingstarted/install/install_win.rst .. _install_win: Installation Guide for Windows =============================== Installation ------------- .. _conda_win: The following steps have been checked only with windows 10 but should work with previous versions as well. We highly recommend that all new users install |scpy| interface via Conda. You can install Spectrochempy in a dedicated environment (recommended, steps 4. and 5. below). You can also use your base environment or an existing environment (then skip steps 4. and 5.) #. Open a command prompt (Select the Start button and type cmd), or preferably open the Anaconda Prompt in the Anaconda start Menu. .. image:: images/prompt.png :width: 200 :alt: Anaconda Prompt #. Update conda (yes, even if you have just installed the distribution...): .. sourcecode:: bat (base) C:\<yourDefaultPath>> conda update conda where `<yourDefaultPath>` is you default workspace directory (often: `C:\\Users\\<user>`) #. Add channels to get specific packages: .. sourcecode:: bat (base) C:\<yourDefaultPath>> conda config --add channels conda-forge (base) C:\<yourDefaultPath>> conda config --add channels spectrocat (base) C:\<yourDefaultPath>> conda config --add channels cantera #. **Recommended**: you can create a dedicated environment. We will name it `scpy` in this example but of course you can use whatever name you want. .. sourcecode:: bat (base) C:\<yourDefaultPath>> conda create --name scpy Switch to this environment. At this point, `(scpy)` should appear before the prompt instead of `(base)`. .. sourcecode:: bat (base) C:\<yourDefaultPath>> conda activate scpy (scpy) C:\<yourDefaultPath>> .. Note:: You can make the scipy environment permanent by creating and using the following batch file (.bat) .. sourcecode:: bat @REM launch a cmd window in scpy environment (path should beadapted) @CALL CD C:\<yourWorkingFolder> @CALL CMD /K C:\<yourAnacondaFolder>\Scripts\activate.bat scpy This script, where `<yourAnacondaFolder>` is the installation directory of your Miniconda/Anaconda distribution will open a command prompt in C:\\<yourWorkingFolder> with the `scpy` environment activated. Save the .bat file, for instance in `C:\\<yourAnacondaFolder>\Scripts\activate-scpy.bat`, create a shortcut, name it, for instance, `Anaconda prompt (scpy)` and place it in an easily accessible place (e.g. the Windows Startmenu Folder). #. Install |scpy| The conda installer has to solve all packages dependencies and is definitely a bit slow. So we recommand to install `mamba <https://github.com/mamba-org/mamba>`__ as a drop-in replacement via: .. sourcecode:: bash (scpy) C:\<yourDefaultPath>> conda install mamba To install a stable version of spectrochempy, then you just have to do : .. sourcecode:: bash (scpy) C:\<yourDefaultPath>> mamba install spectrochempy or if you rather prefer not to use mamba: .. sourcecode:: bat (scpy) C:\<yourDefaultPath>> conda install spectrochempy This can take time, depending on your python installation and the number of missing packages. If you prefer to deal with the latest development version, you must use the following command to install from the `spectrocat/label/dev <https://anaconda.org/spectrocat/spectrochempy>`_ channel instead of the `spectrocat` channel: .. sourcecode:: bat (scpy) C:\<yourDefaultPath>> mamba install -c spectrocat/label/dev spectrochempy Check the Installation ------------------------ Check the installation by running a `IPython <https://ipython.readthedocs.io/en/stable/>`_ session by issuing in the terminal the following command: .. sourcecode:: bat (scpy) C:\<yourDefaultPath>> ipython Then execute the following command: .. sourcecode:: ipython In [1]: from spectrochempy import * If this goes well, you should see the following output, indicating that Spectrochempy is likely functional ! .. sourcecode:: ipython SpectroChemPy's API - v.0.1.17 © Copyright 2014-2020 - A.Travert & C.Fernandez @ LCS The recommended next step is to proceed to the :ref:`userguide`. <file_sep>/spectrochempy/core/readers/download.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # ====================================================================================================================== """ In this module, methods are provided to download external datasets from public database. """ __all__ = ['download_IRIS'] __dataset_methods__ = __all__ from io import StringIO import numpy as np import requests from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.coord import Coord from spectrochempy.core import error_ # ...................................................................................................................... def download_IRIS(): """ Upload the classical IRIS dataset. The IRIS dataset is a classical example for machine learning.It is downloaded from the [UCI distant repository](https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data) Returns ------- downloaded The IRIS dataset. See Also -------- read : Ro read data from experimental data. Examples -------- Upload a dataset form a distant server >>> import spectrochempy as scp >>> dataset = scp.download_IRIS() """ url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" try: connection = True response = requests.get(url, stream=True, timeout=10) except Exception as e: error_(e) connection = False if connection: # Download data txtdata = '' for rd in response.iter_content(): txtdata += rd.decode('utf8') fil = StringIO(txtdata) try: data = np.loadtxt(fil, delimiter=',', usecols=range(4)) fil.seek(0) labels = np.loadtxt(fil, delimiter=',', usecols=(4,), dtype='|S') labels = list((lab.decode("utf8") for lab in labels)) except Exception: raise IOError('{} is not a .csv file or its structure cannot be recognized') coordx = Coord(labels=['sepal_length', 'sepal width', 'petal_length', 'petal_width'], title='features') coordy = Coord(labels=labels, title='samples') new = NDDataset(data, coordset=[coordy, coordx], title='size', name='IRIS Dataset', units='cm') new.history = 'Loaded from UC Irvine machine learning repository' return new else: # Cannot download - use the scikit-learn dataset (if scikit-learn is installed) try: from sklearn import datasets except ImportError: raise IOError('Failed in uploading the IRIS dataset!') # import some data to play with data = datasets.load_iris() coordx = Coord(labels=['sepal_length', 'sepal width', 'petal_length', 'petal_width'], title='features') labels = [data.target_names[i] for i in data.target] coordy = Coord(labels=labels, title='samples') new = NDDataset(data.data, coordset=[coordy, coordx], title='size', name='IRIS Dataset', units='cm') new.history = 'Loaded from scikit-learn datasets' return new # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/docs/devguide/contributing.rst .. _develguide: ***************************************************** Developer's Guide ***************************************************** .. .. contents:: Table of Contents: .. :local: .. toctree:: :maxdepth: 1 general_principles issues be_prepared <file_sep>/spectrochempy/core/fitting/fit.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Module to perform fitting of 1D or n-D spectral data. """ __all__ = ['Fit'] __dataset_methods__ = [] import sys import re from warnings import warn from traitlets import (HasTraits, Bool, Any, List, Instance) import numpy as np # IPython from IPython import display from spectrochempy.core.fitting.parameters import ParameterScript from spectrochempy.core.fitting.models import getmodel from spectrochempy.core.fitting.optimization import optimize from spectrochempy.utils import htmldoc from spectrochempy.core import preferences, info_, INFO # ====================================================================================================================== # Fit: main object to handle a fit # ====================================================================================================================== class Fit(HasTraits): """ Fit a 1D or 2D dataset, or a list of datasets Parameters ---------- dataset : Dataset or list of Dataset instance The data to fit mode : Unicode, optional Reserved - not used for now Attributes ---------- fp : Dict Fit parameters dictionary (read-only, but individual elements of the dict can be changed) script : Unicode A string representation of the fp dict, which can be used as input for other a fit (read-only) """ silent = Bool(False) _ = Any() datasets = List(Instance('spectrochempy.core.dataset.nddataset.NDDataset')) parameterscript = Instance(ParameterScript) # ******************************************************************************* # initialisation # ******************************************************************************* def __init__(self, *args, **kwargs): if args: # look in args if not isinstance(args[0], list): self.datasets = [args[0], ] else: self.datasets = args[0] # we create a list of dataset in all case script = args[1] else: return # get parameters form script self.parameterscript = ParameterScript(datasets=self.datasets, script=script) if self.fp is None: # for unknown reason for now, this sometimes happens during tests warn('error with fp') # sequence = kargs.get('sequence', 'ideal_pulse') # self.sequence = PulseSequence(type=sequence) self.mode = kwargs.pop('mode', None) self.method = kwargs.pop('method', None) self.silent = kwargs.pop('silent', False) for exp_idx, dataset in enumerate(self.datasets): dataset.modeldata, dataset.modelnames, dataset.model_A, dataset.model_a, dataset.model_b = \ self._get_modeldata(dataset, exp_idx) # lgtm [py/mismatched-multiple-assignment] # ******************************************************************************* # public methodss # ******************************************************************************* @staticmethod def script_default(): """ Return a default script """ return """ #----------------------------------------------------------- # syntax for parameters definition: # name: value, low_bound, high_bound # * for fixed parameters # $ for variable parameters # > for reference to a parameter in the COMMON block # (> is forbidden in the COMMON block) # common block parameters should not have a _ in their names #----------------------------------------------------------- # COMMON: # common parameters ex. experiment_variables: ampl # $ gwidth: 1.0, 0.0, none $ gratio: 0.5, 0.0, 1.0 MODEL: LINE_1 shape: voigtmodel $ ampl: 1.0, 0.0, none $ pos: 0.0, -100.0, 100.0 > ratio: gratio $ width: 1.0, 0, 100 """ def dry_run(self): return self.run(dry=True) def run(self, maxiter=100, maxfun=None, every=10, method='simplex', **kwargs): """ Main fitting procedure Parameters ---------- maxiter : int, maximum number of iteration maxfun : int, maximum number of function calls every : int, number of function call between two displays method : str, ether 'simplex' or 'hopping' dryrun : bool """ if not self.silent: level = preferences.log_level if level > INFO: preferences.log_level = INFO info_('*' * 50) info_(' Entering fitting procedure') info_('*' * 50) global niter, chi2, everyiter, ncalls ncalls = 0 everyiter = every niter = 0 # internally defined function chi2 def funchi2(params, datasets, *constraints): """ Return sum((y - x)**2) """ global chi2, ncalls # model spectrum chi2 = 0 som = 0 ncalls += 1 for exp_idx, dataset in enumerate(datasets): modeldata = self._get_modeldata(dataset, exp_idx)[0] # baseline is already summed with modeldata[-1] # important to work with the real component of dataset # not the complex number data = dataset.real.data.squeeze() # if not dataset.is_2d: mdata = modeldata[-1] # modelsum # else: # mdata = modeldata.values merror = 1. # if dataset.is_2d: # if constraints: # # # Case of SQ-DQ experiments # if self.kind == 'SQ-DQ' and \ # 'max_connections' in constraints[0]: # # check connectivity numbers # nbconnections = {} # for key in params.keys(): # if 'pos1' in key: # connect = key[-2:] # key = 'ampl_line_' + connect # get amplitude # ki = connect[0].upper() # if ki not in nbconnections.keys(): # nbconnections[ki] = 0 # if int(params[key]) > 0: # nbconnections[ki] += 1 # for k, v in nbconnections.iteritems(): # if v > constraints[0]['max_connections']: # merror *= v * 10. diff = data - mdata chi2 += np.sum(diff ** 2) * merror som += np.sum(data[0] ** 2) chi2 = np.sqrt(chi2 / som) # reset log_level return chi2 # end chi2 function --------------------------------------------------- # callback function-------------------------------------------------------- def callback(*args, **kwargs): """ callback log.info function """ global niter, chi2, everyiter, ncalls niter += 1 if niter % everyiter != 0: return if not self.silent: display.clear_output(wait=True) info_(("Iterations: %d, Calls: %d (chi2: %.5f)" % ( niter, ncalls, chi2))) sys.stdout.flush() # end callback function --------------------------------------------------- fp = self.fp # starting parameters dry = kwargs.get("dry", False) if not dry: fp, fopt = optimize(funchi2, fp, args=(self.datasets,), maxfun=maxfun, maxiter=maxiter, method=method, constraints=kwargs.get('constraints', None), callback=callback) # replace the previous script with new fp parameters self.parameterscript.script = str(fp) if not self.silent: # log.info the results info_("\n") info_('*' * 50) if not dry: info_(" Result:") else: info_(" Starting parameters:") info_('*' * 50) info_(self.parameterscript.script) # store the models for exp_idx, dataset in enumerate(self.datasets): dataset.modeldata, dataset.modelnames, dataset.model_A, dataset.model_a, dataset.model_b = \ self._get_modeldata(dataset, exp_idx) # Reset Log_level if not self.silent: preferences.log_level = level return # ******************************************************************************* # properties # ******************************************************************************* @property def fp(self): return self.parameterscript.fp @property def script(self): return self.parameterscript.script # ******************************************************************************* # Private functions # ******************************************************************************* def _repr_html_(self): if not self.datasets: return htmldoc(self.__init__.__doc__) else: return self.message def _get_modeldata(self, dataset, exp_idx): # Prepare parameters parameters = self._prepare(self.fp, exp_idx) # Get the list of models models = self.fp.models nbmodels = len(models) # Make an array 'modeldata' with the size of the dataset of data # which will contains the data produced by the models # This name must always be 'modeldata' # which will be returned to the main program. expedata = dataset.real.data.squeeze() axis, dim = dataset.get_axis(-1) x = dataset.coordset[dim].data if expedata.ndim > 1: # nD data raise NotImplementedError("Fit not implemented for nD data yet!") modeldata = np.zeros((nbmodels + 2, x.size), dtype=np.float64) if nbmodels < 1: names = ['baseline', 'modelsum'] return modeldata, names # Calculates model data # The first row (i=0) of the modeldata array is the baseline, # so we fill the array starting at row 1 row = 0 names = ['baseline', ] for model in models: calc = getmodel(x, modelname=model, par=parameters) # , dataset=dataset) if not model.startswith('baseline'): row += 1 modeldata[row] = calc names.append(model) else: modeldata[0] += calc # make the sum modeldata[row + 1] = modeldata.sum(axis=0) names.append('modelsum') # remove unused column modeldata = modeldata[:row + 2] xi = np.arange(float(x.size)) A, a, b = self._ampbas(xi, expedata, modeldata[-1]) # (fitzone-fitzone[0], data.take(fitzone), # modeldata[-1].take(fitzone)) modeldata = A * modeldata baseline = a * xi + b # a*(xi-fitzone[0]) + b # update the modeldata modeldata[0] += baseline modeldata[-1] += baseline # return modeldata return modeldata, names, A, a, b @staticmethod def _parsing(expr, param): keyword = r"\b([a-z]+[0-9]*)\b" # match a whole word pat = re.compile(keyword) mo = pat.findall(str(expr)) for kw in mo: if kw in param: expr = expr.replace(kw, str(param[kw])) elif kw in np.__dict__: # check if it is a recognized math function expr = expr.replace(kw, "np.%s" % kw) return expr def _prepare(self, param, exp_idx): # This function is needed for the script related to modelfunction # # exp_idx: int, contains the index of the experiment new_param = param.copy() for key in param: if param.reference[key]: new_param.reference[key] = False # important to put it here # before other instruction # try to interpret the given refpar expression refpar = param[key] while True: par = self._parsing(refpar, new_param) if par == refpar: break refpar = par try: new_param[key] = eval(str(refpar)) except Exception: raise ValueError('Cannot evaluate the expression %s: %s' % (key, param[refpar])) new_param.fixed[key] = True new_param.reference[key] = True # restore it for the next call if isinstance(new_param[key], list): new_param.data[key] = new_param.data[key][exp_idx] return new_param # =============================================================================== # automatic calculation of amplitude and baseline # =============================================================================== @staticmethod def _ampbas(xi, expe, calc): # Automatically calculate correct amplitude A and baseline # (baseline linear model a*i+b) by detemining the zero of the first derivative # with respect to A, a, and b expe = expe.squeeze() n = xi.size sE = sum(expe) sF = sum(calc) sFI = sum(xi * calc) sFd = sum(calc * calc) sI = sum(xi) sEF = sum(expe * calc) sEI = sum(xi * expe) sId = sum(xi ** 2) a = (-sE * (sF * sFI - sFd * sI) + sEF * (n * sFI - sF * sI) - sEI * ( n * sFd - sF ** 2) ) / ( n * sFI ** 2 - n * sFd * sId + sF ** 2 * sId - 2 * sF * sFI * sI + sFd * sI ** 2) A = (sE * (sF * sId - sFI * sI) - sEF * (n * sId - sI ** 2) + sEI * ( n * sFI - sF * sI) ) / ( n * sFI ** 2 - n * sFd * sId + sF ** 2 * sId - 2 * sF * sFI * sI + sFd * sI ** 2) b = (sE * (sFI ** 2 - sFd * sId) + sEF * (sF * sId - sFI * sI) - sEI * ( sF * sFI - sFd * sI) ) / ( n * sFI ** 2 - n * sFd * sId + sF ** 2 * sId - 2 * sF * sFI * sI + sFd * sI ** 2) # in case the modeldata is zero, to avoid further errors if np.isnan(A): A = 0.0 if np.isnan(a): a = 0.0 if np.isnan(b): b = 0.0 return A, a, b @staticmethod def _ampbas2D(xi, yj, expe, calc): n = float(xi.size) m = float(yj.size) sE = expe.sum() sF = calc.sum() sFI = (xi * calc).sum() sFJ = (yj * calc.T).sum() sFd = (calc * calc).sum() sI = sum(xi) sJ = sum(yj) sIJ = ((np.ones_like(calc) * xi).T * yj).sum() sEF = (expe * calc).sum() sEI = (xi * expe).sum() sEJ = (yj * expe.T).sum() sId = sum(xi ** 2) sJd = sum(yj ** 2) c = (sE * ( -m * n * sFd * sId * sJd + m * sFJ ** 2 * sId + n * sFI ** 2 * sJd - 2 * sFI * sFJ * sIJ + sFd * sIJ ** 2) + sEF * ( m * n * sF * sId * sJd - m * n * sFI * sI * sJd - m * n * sFJ * sId * sJ + m * sFJ * sI * sIJ + n * sFI * sIJ * sJ - sF * sIJ ** 2) + sEI * ( m * n * sFd * sI * sJd - m * sFJ ** 2 * sI - n * sF * sFI * sJd + n * sFI * sFJ * sJ - n * sFd * sIJ * sJ + sF * sFJ * sIJ) + sEJ * ( m * n * sFd * sId * sJ - m * sF * sFJ * sId + m * sFI * sFJ * sI - m * sFd * sI * sIJ - n * sFI ** 2 * sJ + sF * sFI * sIJ)) / ( -m ** 2 * n ** 2 * sFd * sId * sJd + m ** 2 * n * sFJ ** 2 * sId + m ** 2 * n * sFd * sI ** 2 * sJd - m ** 2 * sFJ ** 2 * sI ** 2 + m * n ** 2 * sFI ** 2 * sJd + m * n ** 2 * sFd * sId * sJ ** 2 + m * n * sF ** 2 * sId * sJd - 2 * m * n * sF * sFI * sI * sJd - 2 * m * n * sF * sFJ * sId * sJ + 2 * m * n * sFI * sFJ * sI * sJ - 2 * m * n * sFI * sFJ * sIJ - 2 * m * n * sFd * sI * sIJ * sJ + m * n * sFd * sIJ ** 2 + 2 * m * sF * sFJ * sI * sIJ - n ** 2 * sFI ** 2 * sJ ** 2 + 2 * n * sF * sFI * sIJ * sJ - sF ** 2 * sIJ ** 2) a = (n * sEF * ( m * n * sFI * sJd - m * sF * sI * sJd + m * sFJ * sI * sJ - m * sFJ * sIJ - n * sFI * sJ ** 2 + sF * sIJ * sJ) + n * sEI * ( -m * n * sFd * sJd + m * sFJ ** 2 + n * sFd * sJ ** 2 + sF ** 2 * sJd - 2 * sF * sFJ * sJ) + sE * ( m * n * sFd * sI * sJd - m * sFJ ** 2 * sI - n * sF * sFI * sJd + n * sFI * sFJ * sJ - n * sFd * sIJ * sJ + sF * sFJ * sIJ) - sEJ * ( m * n * sFI * sFJ + m * n * sFd * sI * sJ - m * n * sFd * sIJ - m * sF * sFJ * sI - n * sF * sFI * sJ + sF ** 2 * sIJ)) / ( -m ** 2 * n ** 2 * sFd * sId * sJd + m ** 2 * n * sFJ ** 2 * sId + m ** 2 * n * sFd * sI ** 2 * sJd - m ** 2 * sFJ ** 2 * sI ** 2 + m * n ** 2 * sFI ** 2 * sJd + m * n ** 2 * sFd * sId * sJ ** 2 + m * n * sF ** 2 * sId * sJd - 2 * m * n * sF * sFI * sI * sJd - 2 * m * n * sF * sFJ * sId * sJ + 2 * m * n * sFI * sFJ * sI * sJ - 2 * m * n * sFI * sFJ * sIJ - 2 * m * n * sFd * sI * sIJ * sJ + m * n * sFd * sIJ ** 2 + 2 * m * sF * sFJ * sI * sIJ - n ** 2 * sFI ** 2 * sJ ** 2 + 2 * n * sF * sFI * sIJ * sJ - sF ** 2 * sIJ ** 2) A = (m * n * sEF * ( -m * n * sId * sJd + m * sI ** 2 * sJd + n * sId * sJ ** 2 - 2 * sI * sIJ * sJ + sIJ ** 2) + m * sEJ * ( m * n * sFJ * sId - m * sFJ * sI ** 2 - n * sF * sId * sJ + n * sFI * sI * sJ - n * sFI * sIJ + sF * sI * sIJ) + n * sEI * ( m * n * sFI * sJd - m * sF * sI * sJd + m * sFJ * sI * sJ - m * sFJ * sIJ - n * sFI * sJ ** 2 + sF * sIJ * sJ) + sE * ( m * n * sF * sId * sJd - m * n * sFI * sI * sJd - m * n * sFJ * sId * sJ + m * sFJ * sI * sIJ + n * sFI * sIJ * sJ - sF * sIJ ** 2)) / ( -m ** 2 * n ** 2 * sFd * sId * sJd + m ** 2 * n * sFJ ** 2 * sId + m ** 2 * n * sFd * sI ** 2 * sJd - m ** 2 * sFJ ** 2 * sI ** 2 + m * n ** 2 * sFI ** 2 * sJd + m * n ** 2 * sFd * sId * sJ ** 2 + m * n * sF ** 2 * sId * sJd - 2 * m * n * sF * sFI * sI * sJd - 2 * m * n * sF * sFJ * sId * sJ + 2 * m * n * sFI * sFJ * sI * sJ - 2 * m * n * sFI * sFJ * sIJ - 2 * m * n * sFd * sI * sIJ * sJ + m * n * sFd * sIJ ** 2 + 2 * m * sF * sFJ * sI * sIJ - n ** 2 * sFI ** 2 * sJ ** 2 + 2 * n * sF * sFI * sIJ * sJ - sF ** 2 * sIJ ** 2) b = (m * sEF * ( m * n * sFJ * sId - m * sFJ * sI ** 2 - n * sF * sId * sJ + n * sFI * sI * sJ - n * sFI * sIJ + sF * sI * sIJ) + m * sEJ * ( -m * n * sFd * sId + m * sFd * sI ** 2 + n * sFI ** 2 + sF ** 2 * sId - 2 * sF * sFI * sI) + sE * ( m * n * sFd * sId * sJ - m * sF * sFJ * sId + m * sFI * sFJ * sI - m * sFd * sI * sIJ - n * sFI ** 2 * sJ + sF * sFI * sIJ) - sEI * ( m * n * sFI * sFJ + m * n * sFd * sI * sJ - m * n * sFd * sIJ - m * sF * sFJ * sI - n * sF * sFI * sJ + sF ** 2 * sIJ)) / ( -m ** 2 * n ** 2 * sFd * sId * sJd + m ** 2 * n * sFJ ** 2 * sId + m ** 2 * n * sFd * sI ** 2 * sJd - m ** 2 * sFJ ** 2 * sI ** 2 + m * n ** 2 * sFI ** 2 * sJd + m * n ** 2 * sFd * sId * sJ ** 2 + m * n * sF ** 2 * sId * sJd - 2 * m * n * sF * sFI * sI * sJd - 2 * m * n * sF * sFJ * sId * sJ + 2 * m * n * sFI * sFJ * sI * sJ - 2 * m * n * sFI * sFJ * sIJ - 2 * m * n * sFd * sI * sIJ * sJ + m * n * sFd * sIJ ** 2 + 2 * m * sF * sFJ * sI * sIJ - n ** 2 * sFI ** 2 * sJ ** 2 + 2 * n * sF * sFI * sIJ * sJ - sF ** 2 * sIJ ** 2) # in case the modeldata is zero, to avoid further errors if np.isnan(A): A = 0.0 if np.isnan(a): a = 0.0 if np.isnan(b): b = 0.0 if np.isnan(c): c = 0.0 return A, a, b, c if __name__ == '__main__': pass <file_sep>/.ci/env/env_create.py from jinja2 import Template from pathlib import Path import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("name", nargs="?", default="scpy.yml", help='name of the output yml file (ext must be .yml!) ') parser.add_argument("-v", "--version", default='3.8', help='Python version (default=3.8)') parser.add_argument("--dev", help="make a development environment", action="store_true") parser.add_argument("--dash", help="use dash", action="store_true") parser.add_argument("--cantera", help="use cantera", action="store_true") args = parser.parse_args() if len(sys.argv) == 1: parser.print_help(sys.stderr) env = Path(__file__).parent tempfile = env / "env_template.yml" template = Template(tempfile.read_text('utf-8')) name = args.name.split('.yml')[0] out = template.render(NAME=name, VERSION=args.version, DEV=args.dev, DASH=args.dash, CANTERA=args.cantera) filename = (env / args.name).with_suffix('.yml') filename.write_text(out) <file_sep>/tests/test_readers_writers/test_read_opus.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os from pathlib import Path import pytest import spectrochempy as scp from spectrochempy import NDDataset from spectrochempy import preferences as prefs # ...................................................................................................................... def test_read_opus(): # single file A = NDDataset.read_opus(os.path.join('irdata', 'OPUS', 'test.0000')) assert A.shape == (1, 2567) assert A[0, 2303.8694].data == pytest.approx(2.72740, 0.00001) # using a window path A1 = NDDataset.read_opus('irdata\\OPUS\\test.0000') assert A1.shape == (1, 2567) # single file specified with pathlib datadir = Path(prefs.datadir) p = datadir / 'irdata' / 'OPUS' / 'test.0000' A2 = NDDataset.read_opus(p) assert A2.shape == (1, 2567) # multiple files not merged B = NDDataset.read_opus('test.0000', 'test.0001', 'test.0002', directory=os.path.join('irdata', 'OPUS')) assert isinstance(B, NDDataset) assert len(B) == 3 # multiple files merged as the merge keyword is set to true C = scp.read_opus('test.0000', 'test.0001', 'test.0002', directory=os.path.join('irdata', 'OPUS'), merge=True) assert C.shape == (3, 2567) # multiple files to merge : they are passed as a list) D = NDDataset.read_opus(['test.0000', 'test.0001', 'test.0002'], directory=os.path.join('irdata', 'OPUS')) assert D.shape == (3, 2567) # multiple files not merged : they are passed as a list but merge is set to false E = scp.read_opus(['test.0000', 'test.0001', 'test.0002'], directory=os.path.join('irdata', 'OPUS'), merge=False) assert isinstance(E, list) assert len(E) == 3 # read contents p = datadir / 'irdata' / 'OPUS' / 'test.0000' content = p.read_bytes() F = NDDataset.read_opus({ p.name: content }) assert F.name == p.name assert F.shape == (1, 2567) # read multiple contents lst = [datadir / 'irdata' / 'OPUS' / f'test.000{i}' for i in range(3)] G = NDDataset.read_opus({p.name: p.read_bytes() for p in lst}) assert len(G) == 3 # read multiple contents and merge them lst = [datadir / 'irdata' / 'OPUS' / f'test.000{i}' for i in range(3)] H = NDDataset.read_opus({p.name: p.read_bytes() for p in lst}, merge=True) assert H.shape == (3, 2567) # read without filename -> open a dialog K = NDDataset.read_opus() # read in a directory (assume homogeneous type of data - else we must use the read function instead) K = NDDataset.read_opus(datadir / 'irdata' / 'OPUS') assert K.shape == (4, 2567) # again we can use merge to avoid stacking of all 4 spectra J = NDDataset.read_opus(datadir / 'irdata' / 'OPUS', merge=False) assert isinstance(J, list) assert len(J) == 4 # single opus file using generic read function # if the protocol is given it is similar to the read_opus function F = NDDataset.read(os.path.join('irdata', 'OPUS', 'test.0000'), protocol='opus') assert F.shape == (1, 2567) # No protocol? G = NDDataset.read(os.path.join('irdata', 'OPUS', 'test.0000')) assert G.shape == (1, 2567) <file_sep>/docs/gettingstarted/install/install_mac.rst .. _install_mac: Installation Guide for Mac OSX =============================== Installation ------------- .. _conda_mac: The following steps have been checked only with OSX-Catalina but should work with previous versions as well and hopfully on the more recent OSX version. As said before, we highly recommend that all new users install |scpy| interface via Conda. You can install |scpy| in a dedicated environment (recommended, steps 4. and 5. below). You can also use your base environment or an existing environment (then skip steps 4. and 5.) #. Open a terminal and update conda: .. sourcecode:: bash (base) ~ $ conda update conda your exact prompt may be different depending on the shell you are using and its configuration #. Add channels to the base configuration to simplify the installation of specific packages from different sources: .. sourcecode:: bash (base) ~ $ conda config --add channels spectrocat (base) ~ $ conda config --add channels conda-forge (base) ~ $ conda config --add channels cantera Note that the last line about cantera is only require if you intend to work the kinetics modules of |scpy|. #. **Recommended**: you should create a dedicated environment in order to isolate the changes made on the installed library from any other previous installation for another applcation. We will name this new environment `scpy` in this example but of course you can use whatever name you want. .. sourcecode:: bash (base) ~ $ conda create -n scpy Switch to this environment. At this point, `(scpy)` should appear before the prompt instead of `(base)`. .. sourcecode:: bash (base) ~ $ conda activate scpy (scpy) ~ $ .. Note:: You can chose to make the `scpy` environment as a default Edit the startup profile so that the last line is source activate environment_name. In Mac OSX this is ~/.bash_profile. If you use Mac OSX Catalina, it may be ~/.zshrc. In linux: this may be ~/.bashrc .. sourcecode:: bash (scpy) ~ $ open ~/.bash_profile Go to end of file and type the following: .. sourcecode:: bash (scpy) ~ $ conda activate scpy Save and exit File. Start a new terminal window. Type the following to see what environment is active .. sourcecode:: bash (scpy) ~ $ conda info -e The result shows that your are using your environment by default. #. Install |scpy| The conda installer has to solve all packages dependencies and is definitely a bit slow. So we recommand to install `mamba <https://github.com/mamba-org/mamba>`__ as a drop-in replacement via: .. sourcecode:: bash scpy) ~ $ conda install mamba To install a stable version of spectrochempy, then you just have to do : .. sourcecode:: bash (scpy) ~ $ mamba install spectrochempy or if you rather prefer not to use mamba: .. sourcecode:: bash (scpy) ~ $ conda install spectrochempy This can take time, depending on your python installation and the number of missing packages. If you prefer to deal with the latest development version, you must use the following command to install from the `spectrocat/label/dev <https://anaconda.org/spectrocat/spectrochempy>`_ channel instead of the `spectrocat` channel: .. sourcecode:: bash (scpy) ~ $ mamba install -c spectrocat/label/dev spectrochempy Check the Installation ----------------------- Run a `IPython <https://ipython.readthedocs.io/en/stable/>`_ session by issuing in the terminal the following command: .. sourcecode:: bash (scpy) ~ $ ipython Then execute the following command: .. sourcecode:: ipython In [1]: from spectrochempy import * If this goes well, you should see the following output, indicating that Spectrochempy is likely functional ! .. sourcecode:: ipython SpectroChemPy's API - v.0.1.17 © Copyright 2014-2020 - A.Travert & C.Fernandez @ LCS The recommended next step is to proceed to the :ref:`userguide`. <file_sep>/docs/devguide/git.rst .. _install_sources: Installation from sources (master or develop versions) ====================================================== Installing git --------------- To install |scpy| from sources, you first need to install ``git`` on your system if it is not already present. Git is a free and open source distributed control system used in well-known software repositories, such as `GitHub <https://github.com>`__ or `Bitbucket <https://bitbucket.org>`__. For this project, we use a GitHub repository: `spectrochempy repository <https://github.com/spectrochempy/spectrochempy>`__. Depending on your operating system, you may refer to these pages for installation instructions: - `Download Git for macOS <https://git-scm.com/download/mac>`__ (One trivial option is to install `XCode <https://developer.apple.com/xcode/>`__ which is shipped with the git system). - `Download Git for Windows <https://git-scm.com/download/win>`__. - `Download for Linux and Unix <https://git-scm.com/download/linux>`__. For the common Debian/Ubuntu distribution, it is as simple as typing in the Terminal: .. sourcecode:: bash $ sudo apt-get install git - Alternatively, once miniconda or anaconda is installed (see :ref:`installation` or below if it not yet done), one can use conda to install git: .. sourcecode:: bash $ conda install git To check whether or not *git* is correctly installed, use this command in the terminal: .. sourcecode:: bash $ git --version Cloning the repository locally ------------------------------- The fastest way is to type these commands in a terminal on your machine: .. sourcecode:: bash $ git clone -depth=50 https://github.com/spectrochempy/spectrochempy.git $ cd spectrochempy $ git remote add upstream https://github.com/spectrochempy/spectrochempy.git These commands create the directory ``spectrochempy`` and connects your repository to the ``upstream`` (master branch) |scpy| repository. .. _installing_conda: Create a conda environment -------------------------- * Install either `Anaconda <https://www.anaconda.com/download/>`_, `miniconda <https://conda.io/miniconda.html>`_, or `miniforge <https://github.com/conda-forge/miniforge>`_ * Make sure your conda is up to date (``conda update conda``) * ``cd`` to the |scpy| source directory (*i.e.,* ``spectrochempy`` created previously) * Generate an environment file using the script ``env_create.py``: .. sourcecode:: bash $ python .ci/env/env_create.py -v 3.9 --dev scpy_dev.yml This will create the ``scpy_dev.yml`` file that we will use in the next step. * Create and activate the environment using python 3.9. This will create a new environment and will not touch any of your other existing environments, nor any existing Python installation. (conda installer is somewhat very slow, this is why we prefer to replace it by `mamba <https://https://github.com/mamba-org/mamba>`__ .. sourcecode:: bash $ conda update conda $ conda install -c conda-forge mamba $ mamba env create -n scpy_dev -f scpy_dev.yml $ conda activate scpy_dev If you prefer to work with ``3.7`` or ``3.8`` python version, you just change ``-v 3.9`` by ``-v 3.8`` or ``3.7``. Install |scpy| in this environment ---------------------------------- .. sourcecode:: bash $ python -m pip install . At this point you should be able to ``import spectrochempy``: .. sourcecode:: bash (scpy_dev) $ python This start an interpreter in which you can check your installation. .. sourcecode:: python >>> import spectrochempy as scp >>> print(scp.version) SpectroChemPy's API ... >>> exit() To view your environments: .. sourcecode:: bash conda env list To return to the base environment: .. sourcecode:: bash conda deactivate Updating |scpy| --------------- One definite advantage of installing for git sources is that you can update your version very easily. To update your local master branch, you can do: .. sourcecode:: bash git pull upstream master --ff-only and if some changes are notified, run pip install again: .. sourcecode:: bash python -m pip install . To go further and eventually contribute to the code on the upstream, you can consult the :ref:`develguide`. <file_sep>/docs/gettingstarted/examples/project/plot_project.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Project creation ======================================= In this example, we create a Project from scratch """ import spectrochempy as scp ############################################################################## # Let's assume we have three subproject to group in a single project proj = scp.Project( # subprojects scp.Project(name='P350', label=r'$\mathrm{M_P}\,(623\,K)$'), scp.Project(name='A350', label=r'$\mathrm{M_A}\,(623\,K)$'), scp.Project(name='B350', label=r'$\mathrm{M_B}\,(623\,K)$'), # attributes name='project_1', label='main project', ) assert proj.projects_names == ['A350', 'B350', 'P350'] ############################################################################## # Add for example two datasets to the ``A350`` subproject. ir = scp.NDDataset([1.1, 2.2, 3.3], coords=[[1, 2, 3]]) print(ir) tg = scp.NDDataset([1, 3, 4], coords=[[1, 2, 3]]) print(tg) proj.A350['IR'] = ir proj.A350['TG'] = tg ############################################################################## # Members of the project or attributes are easily accesssed: print(proj.A350) print(proj) print(proj.A350.label) print(proj.A350.TG) ############################################################################## # Save this project proj.save() ############################################################################## # RELOAD the project from disk as newproj newproj = scp.Project.load('project_1') print(newproj) assert str(newproj) == str(proj) assert newproj.A350.label == proj.A350.label ############################################################################## # Now we add a script to the original proj script_source = """ set_loglevel(INFO) info_('samples contained in the project are:%s'%proj.projects_names) """ proj['print_info'] = scp.Script('print_info', script_source) print(proj) print('*******************************************') ############################################################################## # save but do not change the original data proj.save(overwrite_data=False) ############################################################################## # RELOAD it newproj = scp.Project.load('project_1') print(newproj) ############################################################################## # Execute a script scp.run_script(newproj.print_info) ############################################################################## # Another way to do the same thing is ith the following syntax (which may # seem simpler newproj.print_info() ############################################################################### # Finally lets use a more usefull script script_source_2 = """ proj.A350.TG.plot_scatter(title='my scatter plot') #show() """ proj['tgscatter'] = scp.Script('tgscatter', script_source_2) proj.tgscatter() # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/spectrochempy/core/plotters/plot1d.py # -*- coding: utf-8 -*- # # ====================================================================================================================== # Copyright (©) 2015-2021 LCS # Laboratoire Catalyse et Spectrochimie, Caen, France. # # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT # See full LICENSE agreement in the root directory # ====================================================================================================================== """ Module containing 1D plotting function(s) """ __all__ = ['plot_1D', 'plot_lines', 'plot_pen', 'plot_scatter', 'plot_bar', 'plot_multiple', 'plot_scatter_pen'] __dataset_methods__ = ['plot_1D', 'plot_lines', 'plot_pen', 'plot_scatter', 'plot_bar', 'plot_scatter_pen'] import numpy as np from matplotlib.ticker import MaxNLocator, ScalarFormatter from .plotutils import make_label from ...utils import is_sequence, deprecated from spectrochempy.core.dataset.coord import Coord # plot scatter --------------------------------------------------------------- def plot_scatter(dataset, **kwargs): """ Plot a 1D dataset as a scatter plot (points can be added on lines). Alias of plot (with `method` argument set to ``scatter``. """ kwargs['method'] = 'scatter' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_1D(dataset, **kwargs) # plot lines ----------------------------------------------------------------- @deprecated('Use method=pen or plot_pen() instead.') def plot_lines(dataset, **kwargs): """ Plot a 1D dataset with solid lines by default. Alias of plot (with `method` argument set to ``lines``. """ kwargs['method'] = 'pen' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_1D(dataset, **kwargs) # plot pen (default) --------------------------------------------------------- def plot_pen(dataset, **kwargs): """ Plot a 1D dataset with solid pen by default. Alias of plot (with `method` argument set to ``pen``. """ kwargs['method'] = 'pen' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_1D(dataset, **kwargs) # plot pen (default) --------------------------------------------------------- def plot_scatter_pen(dataset, **kwargs): """ Plot a 1D dataset with solid pen by default. Alias of plot (with `method` argument set to ``pen``. """ kwargs['method'] = 'scatter+pen' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_1D(dataset, **kwargs) # plot bars ------------------------------------------------------------------ def plot_bar(dataset, **kwargs): """ Plot a 1D dataset with bars. Alias of plot (with `method` argument set to ``bar``. """ kwargs['method'] = 'bar' if kwargs.get('use_plotly', False): return dataset.plotly(**kwargs) else: return plot_1D(dataset, **kwargs) # plot multiple -------------------------------------------------------------- def plot_multiple(datasets, method='scatter', pen=True, labels=None, **kwargs): """ Plot a series of 1D datasets as a scatter plot with optional lines between markers. Parameters ---------- datasets : a list of ndatasets method : str among [scatter, pen] pen : bool, optional, default: True if method is scatter, this flag tells to draw also the lines between the marks. labels : a list of str, optional labels used for the legend. **kwargs : other parameters that will be passed to the plot1D function """ if not is_sequence(datasets): # we need a sequence. Else it is a single plot. return datasets.plot(**kwargs) if not is_sequence(labels) or len(labels) != len(datasets): # we need a sequence of labels of same lentgh as datasets raise ValueError('the list of labels must be of same length ' 'as the datasets list') for dataset in datasets: if dataset._squeeze_ndim > 1: raise NotImplementedError('plot multiple is designed to work on ' '1D dataset only. you may achieved ' 'several plots with ' 'the `clear=False` parameter as a work ' 'around ' 'solution') # do not save during this plots, nor apply any commands # we will make this when all plots will be done output = kwargs.get('output', None) kwargs['output'] = None commands = kwargs.get('commands', []) kwargs['commands'] = [] clear = kwargs.pop('clear', True) legend = kwargs.pop('legend', None) # remove 'legend' from kwargs before calling plot # else it will generate a conflict for s in datasets: # , colors, markers): ax = s.plot(method=method, pen=pen, marker='AUTO', color='AUTO', ls='AUTO', clear=clear, **kwargs) clear = False # clear=False is necessary for the next plot to say # that we will plot on the same figure # scale all plots if legend is not None: _ = ax.legend(ax.lines, labels, shadow=True, loc=legend, frameon=True, facecolor='lightyellow') # now we can output the final figure kw = {'output': output, 'commands': commands} datasets[0]._plot_resume(datasets[-1], **kw) return ax # ---------------------------------------------------------------------------------------------------------------------- # plot_1D # ---------------------------------------------------------------------------------------------------------------------- def plot_1D(dataset, **kwargs): """ Plot of one-dimensional data. Parameters ---------- dataset : :class:`~spectrochempy.ddataset.nddataset.NDDataset` Source of data to plot. **kwargs : dict See other parameters. Other Parameters ---------------- widget : Matplotlib or PyQtGraph widget (for GUI only) The widget where to plot in the GUI application. This is not used if the plots are made in jupyter notebook. method : str, optional, default: pen The method can be one among ``pen``, ``bar``, or ``scatter`` Default values is ``pen``, i.e., solid lines are drawn. To draw a Bar graph, use method : ``bar``. For a Scatter plot, use method : ``scatter``. twinx : :class:`~matplotlib.Axes` instance, optional, default: None If this is not None, then a twin axes will be created with a common x dimension. title : str Title of the plot (or subplot) axe. style : str, optional, default='notebook' Matplotlib stylesheet (use `available_style` to get a list of available styles for plotting. reverse : bool or None [optional, default=None/False In principle, coordinates run from left to right, except for wavenumbers (*e.g.*, FTIR spectra) or ppm (*e.g.*, NMR), that spectrochempy will try to guess. But if reverse is set, then this is the setting which will be taken into account. clear : bool, optional, default: True If false, hold the current figure and ax until a new plot is performed. data_only : bool, optional, default: False Only the plot is done. No addition of axes or label specifications. imag : bool, optional, default: False Show imaginary component. By default only the real component is displayed. show_complex : bool, optional, default: False Show both real and imaginary component. By default only the real component is displayed. dpi : int, optional the number of pixel per inches. figsize : tuple, optional, default is (3.4, 1.7) figure size. fontsize : int, optional font size in pixels, default is 10. imag : bool, optional, default False By default real component is shown. Set to True to display the imaginary component xlim : tuple, optional limit on the horizontal axis. zlim or ylim : tuple, optional limit on the vertical axis. color or c : matplotlib valid color, optional color of the line. # TODO : a list if several line linewidth or lw : float, optional line width. linestyle or ls : str, optional line style definition. xlabel : str, optional label on the horizontal axis. zlabel or ylabel : str, optional label on the vertical axis. showz : bool, optional, default=True should we show the vertical axis. plot_model : Bool, plot model data if available. modellinestyle or modls : str line style of the model. offset : float offset of the model individual lines. commands : str, matplotlib commands to be executed. show_zero : boolean, optional show the zero basis. output : str, name of the file to save the figure. vshift : float, optional vertically shift the line from its baseline. """ # Get preferences # ------------------------------------------------------------------------------------------------------------------ prefs = dataset.preferences # before going further, check if the style is passed in the parameters style = kwargs.pop('style', None) if style is not None: prefs.style = style # else we assume this has been set before calling plot() prefs.set_latex_font(prefs.font.family) # reset latex settings # Redirections ? # ------------------------------------------------------------------------------------------------------------------ # should we redirect the plotting to another method if dataset._squeeze_ndim > 1: return dataset.plot_2D(**kwargs) # if plotly execute plotly routine not this one if kwargs.get('use_plotly', prefs.use_plotly): return dataset.plotly(**kwargs) # Method of plot # ------------------------------------------------------------------------------------------------------------------ method = kwargs.get('method', prefs.method_1D) # some addtional options may exists in kwargs pen = kwargs.pop('pen', False) # lines and pen synonyms scatter = kwargs.pop('scatter', False) # final choice of method pen = (method == 'pen') or pen scatter = (method == 'scatter' and not pen) or scatter scatterpen = ((method == 'scatter' or scatter) and pen) or (method == 'scatter+pen') bar = (method == 'bar') # often we do need to plot only data when plotting on top of a previous plot data_only = kwargs.get('data_only', False) # Get the data to plot # ------------------------------------------------------------------------------------------------------------------- new = dataset # .copy() if new.size > 1: # dont' apply to array of size one to preserve the x coordinate!!!! new = new.squeeze() # is that a plot with twin axis is_twinx = kwargs.pop('twinx', None) is not None # if dataset is complex it is possible to overlap with the imaginary component show_complex = kwargs.pop('show_complex', False) # some pen or scatter property color = kwargs.get('color', kwargs.get('c', 'auto')) lw = kwargs.get('linewidth', kwargs.get('lw', 'auto')) ls = kwargs.get('linestyle', kwargs.get('ls', 'auto')) marker = kwargs.get('marker', kwargs.get('m', 'auto')) markersize = kwargs.get('markersize', kwargs.get('ms', prefs.lines_markersize)) markevery = kwargs.get('markevery', kwargs.get('me', 1)) markerfacecolor = kwargs.get('markerfacecolor', kwargs.get('mfc', 'auto')) markeredgecolor = kwargs.get('markeredgecolor', kwargs.get('mec', 'k')) # Figure setup # # ------------------------------------------------------------------------------------------------------------------ new._figure_setup(ndim=1, scatter=scatter, scatterpen=scatterpen, **kwargs) ax = new.ndaxes['main'] # If no method parameters was provided when this function was called, # we first look in the meta parameters of the dataset for the defaults # Other ax properties that can be passed as arguments # ------------------------------------------------------------------------------------------------------------------ number_x_labels = prefs.number_of_x_labels number_y_labels = prefs.number_of_y_labels ax.xaxis.set_major_locator(MaxNLocator(number_x_labels)) ax.yaxis.set_major_locator(MaxNLocator(number_y_labels)) ax.xaxis.set_ticks_position('bottom') if not is_twinx: # do not move these label for twin axes! ax.yaxis.set_ticks_position('left') # the next lines are to avoid multipliers in axis scale formatter = ScalarFormatter(useOffset=False) ax.xaxis.set_major_formatter(formatter) ax.yaxis.set_major_formatter(formatter) xscale = kwargs.get('xscale', 'linear') yscale = kwargs.get('yscale', 'linear') ax.set_xscale(xscale) ax.set_yscale(yscale) ax.grid(prefs.axes_grid) # ------------------------------------------------------------------------------------------------------------------ # plot the dataset # ------------------------------------------------------------------------------------------------------------------ # abscissa axis # the actual dimension name is the first in the new.dims list dimx = new.dims[-1] x = getattr(new, dimx) if x is not None and x.implements('CoordSet'): # if several coords, take the default ones: x = x.default xsize = new.size show_x_points = False if x is not None and hasattr(x, 'show_datapoints'): show_x_points = x.show_datapoints if show_x_points: # remove data and units for display x = Coord.arange(xsize) if x is not None and (not x.is_empty or x.is_labeled): xdata = x.data # discrete_data = False if not np.any(xdata): if x.is_labeled: # discrete_data = True # take into account the fact that sometimes axis have just labels xdata = range(1, len(x.labels) + 1) else: xdata = range(xsize) # take into account the fact that sometimes axis have just labels if xdata is None: xdata = range(xsize) # ordinates (by default we plot real component of the data) if not kwargs.pop('imag', False) or kwargs.get('show_complex', False): z = new.real zdata = z.masked_data else: z = new.imag zdata = z.masked_data # plot_lines # ------------------------------------------------------------------------------------------------------------------ label = kwargs.get('label', None) if scatterpen: # pen + scatter line, = ax.plot(xdata, zdata.T, # marker = marker, markersize=markersize, markevery=markevery, markeredgewidth=1., # markerfacecolor = markerfacecolor, markeredgecolor=markeredgecolor, label=label) elif scatter: # scatter only line, = ax.plot(xdata, zdata.T, ls="", # marker = marker, markersize=markersize, markeredgewidth=1., markevery=markevery, markerfacecolor=markerfacecolor, markeredgecolor=markeredgecolor, label=label) elif pen: # pen only line, = ax.plot(xdata, zdata.T, marker="", label=label) elif bar: # bar only line = ax.bar(xdata, zdata.squeeze(), color=color, edgecolor='k', align='center', label=label) # barwidth = line[0].get_width() if show_complex and pen: # add the imaginaly component for pen only plot if new.is_quaternion: zimagdata = new.RI.masked_data else: zimagdata = new.imag.masked_data ax.plot(xdata, zimagdata.T, ls='--') if kwargs.get('plot_model', False): modeldata = new.modeldata # TODO: what's about mask? ax.plot(xdata, modeldata.T, ls=':', lw='2', label=label) # TODO: improve this!!! # line attributes if (pen or scatterpen) and not (isinstance(color, str) and color.upper() == 'AUTO'): # set the color if defined in the preferences or options line.set_color(color) if (pen or scatterpen) and not (isinstance(lw, str) and lw.upper() == 'AUTO'): # set the line width if defined in the preferences or options line.set_linewidth(lw) if (pen or scatterpen) and ls.upper() != 'AUTO': # set the line style if defined in the preferences or options line.set_linestyle(ls) if (scatter or scatterpen) and marker.upper() != 'AUTO': # set the line style if defined in the preferences or options line.set_marker(marker) # ------------------------------------------------------------------------------------------------------------------ # axis # ------------------------------------------------------------------------------------------------------------------ data_only = kwargs.get('data_only', False) if len(xdata) > 1: # abscissa limits? xl = [xdata[0], xdata[-1]] xl.sort() if bar or len(xdata) < number_x_labels + 1: # extend the axis so that the labels are not too close to the limits inc = (xdata[1] - xdata[0]) * .5 xl = [xl[0] - inc, xl[1] + inc] # ordinates limits? amp = np.ma.ptp(z.masked_data) / 50. zl = [np.ma.min(z.masked_data) - amp, np.ma.max(z.masked_data) + amp] # check if some data are not already present on the graph # and take care of their limits multiplelines = 2 if kwargs.get('show_zero', False) else 1 if len(ax.lines) > multiplelines and not show_complex: # get the previous xlim and zlim xlim = list(ax.get_xlim()) xl[-1] = max(xlim[-1], xl[-1]) xl[0] = min(xlim[0], xl[0]) zlim = list(ax.get_ylim()) zl[-1] = max(zlim[-1], zl[-1]) zl[0] = min(zlim[0], zl[0]) if data_only or len(xdata) == 1: xl = ax.get_xlim() xlim = list(kwargs.get('xlim', xl)) # we read the argument xlim # that should have the priority xlim.sort() # reversed axis? if kwargs.get('x_reverse', kwargs.get('reverse', x.reversed if x else False)): xlim.reverse() if data_only or len(xdata) == 1: zl = ax.get_ylim() zlim = list(kwargs.get('zlim', kwargs.get('ylim', zl))) # we read the argument zlim or ylim # which have the priority zlim.sort() # set the limits if not is_twinx: # when twin axes, we keep the setting of the first ax plotted ax.set_xlim(xlim) else: ax.tick_params('y', colors=color) ax.set_ylim(zlim) if data_only: # if data only (we will ot set axes and labels # it was probably done already in a previous plot new._plot_resume(dataset, **kwargs) return ax # ------------------------------------------------------------------------------------------------------------------ # labels # ------------------------------------------------------------------------------------------------------------------ # x label xlabel = kwargs.get("xlabel", None) if show_x_points: xlabel = 'data points' if not xlabel: xlabel = make_label(x, new.dims[-1]) ax.set_xlabel(xlabel) # x tick labels uselabelx = kwargs.get('uselabel_x', False) if x and x.is_labeled and (uselabelx or not np.any(x.data)) and len(x.labels) < number_x_labels + 1: # TODO refine this to use different orders of labels ax.set_xticks(xdata) ax.set_xticklabels(x.labels) # z label zlabel = kwargs.get("zlabel", None) if not zlabel: zlabel = make_label(new, 'z') # ax.set_ylabel(zlabel) # do we display the ordinate axis? if kwargs.get('show_z', True) and not is_twinx: ax.set_ylabel(zlabel) elif kwargs.get('show_z', True) and is_twinx: ax.set_ylabel(zlabel, color=color) else: ax.set_yticks([]) # do we display the zero line if kwargs.get('show_zero', False): ax.haxlines(label='zero_line') # display a title # ------------------------------------------------------------------------------------------------------------------ title = kwargs.get('title', None) if title: ax.set_title(title) elif kwargs.get('plottitle', False): ax.set_title(new.name) new._plot_resume(dataset, **kwargs) # masks if kwargs.get('show_mask', False): ax.fill_between(xdata, zdata.min() - 1., zdata.max() + 1, where=new.mask, facecolor='#FFEEEE', alpha=0.3) return ax if __name__ == '__main__': pass <file_sep>/spectrochempy/core/readers/readzip.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ['read_zip'] __dataset_methods__ = __all__ import io from spectrochempy.core.readers.importer import Importer, importermethod # ====================================================================================================================== # Public functions # ====================================================================================================================== def read_zip(*paths, **kwargs): """ Open a zipped list of data files. Parameters ---------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read_zip |NDDataset| or list of |NDDataset|. Other Parameters ---------------- protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description: str, optional A Custom description. origin : {'omnic', 'tga'}, optional in order to properly interpret CSV file it can be necessary to set the origin of the spectra. Up to now only 'omnic' and 'tga' have been implemented. csv_delimiter : str, optional Set the column delimiter in CSV file. By default it is the one set in SpectroChemPy ``Preferences``. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True). recursive : bool, optional Read also in subfolders. (default=False). See Also -------- read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_labspec : Read Raman LABSPEC spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. Examples -------- >>> import spectrochempy as scp >>> A = scp.read_zip('agirdata/P350/FTIR/FTIR.zip', only=50, origin='omnic') >>> print(A) NDDataset: [float64] a.u. (shape: (y:50, x:2843)) """ kwargs['filetypes'] = ['Compressed files (*.zip)'] # TODO: allows other type of compressed files kwargs['protocol'] = ['zip'] importer = Importer() return importer(*paths, **kwargs) # ====================================================================================================================== # Private functions # ====================================================================================================================== @importermethod def _read_zip(*args, **kwargs): # Below we assume that files to read are in a unique directory from spectrochempy.core.dataset.nddataset import NDDataset import zipfile # read zip file _, filename = args content = kwargs.pop('content', None) if content: fid = io.BytesIO(content) else: fid = open(filename, 'rb') with zipfile.ZipFile(fid) as zf: filelist = zf.filelist only = kwargs.pop('only', len(filelist)) datasets = [] # for file in filelist: # # # make a pathlib object (but this doesn't work with python 3.7) # file = zipfile.Path(zf, at=file.filename) # TODO: # # if file.name.startswith('__MACOSX'): # continue # bypass non-data files # # # seek the parent directory containing the files to read # if not file.is_dir(): # continue # # parent = file # break # # # for count, children in enumerate(parent.iterdir()): # # if count == only: # # limits to only this number of files # break # # _ , extension = children.name.split('.') # if extension == 'DS_Store': # only += 1 # continue # # read_ = getattr(NDDataset, f"read_{extension}") # # datasets.append(read_(children.name, content=children.read_bytes(), **kwargs)) # 3.7 compatible code # seek the parent directory containing the files to read for file in filelist: if not file.filename.startswith('__') and file.is_dir(): parent = file.filename break count = 0 for file in filelist: if not file.is_dir() and file.filename.startswith(parent) and 'DS_Store' not in file.filename: # read it datasets.append(NDDataset.read({ file.filename: zf.read(file.filename) }, origin=kwargs.get('origin', None))) count += 1 if count == only: break return datasets # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/docs/gettingstarted/examples/fitting/readme.txt .. _fitting_examples-index: Example of the fitting package usage ------------------------------------- <file_sep>/tests/test_utils/test_testing.py # -*- coding: utf-8 -*- # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # ===================================================================================================================== from spectrochempy.core.scripts.script import Script from spectrochempy.utils import testing def test_compare(IR_dataset_1D, simple_project): # dataset comparison nd1 = IR_dataset_1D.copy() nd2 = nd1.copy() testing.assert_dataset_equal(nd1, nd2) nd3 = nd1.copy() nd3.title = 'ddd' with testing.raises(AssertionError): testing.assert_dataset_equal(nd1, nd3) nd4 = nd1.copy() nd4.data += 0.001 with testing.raises(AssertionError): testing.assert_dataset_equal(nd1, nd4) testing.assert_dataset_almost_equal(nd1, nd4, decimal=3) with testing.raises(AssertionError): testing.assert_dataset_almost_equal(nd1, nd4, decimal=4) # project comparison proj1 = simple_project.copy() proj1.name = 'PROJ1' proj2 = proj1.copy() proj2.name = 'PROJ2' testing.assert_project_equal(proj1, proj2) proj3 = proj2.copy() proj3.add_script(Script(content='print()', name='just_a_try')) with testing.raises(AssertionError): testing.assert_project_equal(proj1, proj3) <file_sep>/tests/test_processors/test_baseline.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # = # ====================================================================================================================== import os import pytest # noinspection PyUnresolvedReferences import spectrochempy as scp from spectrochempy import show, BaselineCorrection, NDDataset, ur from spectrochempy.utils.testing import assert_dataset_almost_equal, assert_dataset_equal path = os.path.dirname(os.path.abspath(__file__)) # @pytest.mark.skip("erratic failing!") def test_basecor_sequential(IR_dataset_2D): dataset = IR_dataset_2D[5] basc = BaselineCorrection(dataset) s = basc([6000., 3500.], [2200., 1500.], method='sequential', interpolation='pchip') s.plot() s1 = basc([6000., 3500.], [2200., 1500.], method='sequential', interpolation='polynomial') s1.plot(clear=False, color='red') dataset = IR_dataset_2D[5] # with LinearCoord basc = BaselineCorrection(dataset) s2 = basc([6000., 3500.], [2200., 1500.], method='sequential', interpolation='pchip') assert_dataset_almost_equal(s, s2, decimal=5) s2.plot(clear=False, color='green') s3 = basc([6000., 3500.], [2200., 1500.], method='sequential', interpolation='polynomial') assert_dataset_almost_equal(s1, s3, decimal=5) s3.plot(clear=False, color='cyan') show() dataset = IR_dataset_2D[:15] basc = BaselineCorrection(dataset) s = basc([6000., 3500.], [2200., 1500.], method='sequential', interpolation='pchip') s.plot() s = basc([6000., 3500.], [2200., 1500.], method='sequential', interpolation='polynomial') s.plot(cmap='copper') show() def test_basecor_multivariate(IR_dataset_2D): dataset = IR_dataset_2D[5] basc = BaselineCorrection(dataset) s = basc([6000., 3500.], [1800., 1500.], method='multivariate', interpolation='pchip') s.plot() s = basc([6000., 3500.], [1800., 1500.], method='multivariate', interpolation='polynomial') s.plot(clear=False, color='red') dataset = IR_dataset_2D[:15] basc = BaselineCorrection(dataset) s = basc([6000., 3500.], [1800., 1500.], method='multivariate', interpolation='pchip') s.plot() s = basc([6000., 3500.], [1800., 1500.], method='multivariate', interpolation='polynomial') s.plot(cmap='copper') show() def test_notebook_basecor_bug(): dataset = NDDataset.read_omnic(os.path.join('irdata', 'nh4y-activation.spg')) s = dataset[:, 1260.0:5999.0] s = s - s[-1] # Important note that we use floating point number # integer would mean points, not wavenumbers! basc = BaselineCorrection(s) ranges = [[1261.86, 1285.89], [1556.30, 1568.26], [1795.00, 1956.75], [3766.03, 3915.81], [4574.26, 4616.04], [4980.10, 4998.01], [5437.52, 5994.70]] # predifined ranges _ = basc.run(*ranges, method='multivariate', interpolation='pchip', npc=5, figsize=(6, 6), zoompreview=4) # The regions used to set the baseline are accessible using the `ranges` # attibute: ranges = basc.ranges print(ranges) basc.corrected.plot_stack() def test_issue_227(): # IR spectrum, we want to make a baseline correction on the absorbance vs. time axis: ir = scp.read('irdata/nh4y-activation.spg') # baseline correction along x blc = scp.BaselineCorrection(ir) s1 = blc([5999., 3500.], [1800., 1500.], method='multivariate', interpolation='pchip') # baseline correction the transposed data along x (now on axis 0) -> should produce the same results # baseline correction along axis -1 previuosly blc = scp.BaselineCorrection(ir.T) s2 = blc([5999., 3500.], [1800., 1500.], dim='x', method='multivariate', interpolation='pchip') # compare assert_dataset_equal(s1, s2.T) ir.y = ir.y - ir[0].y irs = ir[:, 2000.0:2020.0] blc = scp.BaselineCorrection(irs) blc.compute(*[[0., 2.e3], [3.0e4, 3.3e4]], dim='y', interpolation='polynomial', order=1, method='sequential') blc.corrected.plot() scp.show() # MS profiles, we want to make a baseline correction on the ion current vs. time axis: ms = scp.read('msdata/ion_currents.asc', timestamp=False) blc = scp.BaselineCorrection(ms[10.:20., :]) blc.compute(*[[10., 11.], [19., 20.]], dim='y', interpolation='polynomial', order=1, method='sequential') blc.corrected.T.plot() scp.show() @pytest.mark.skip() def test_ab_nmr(NMR_dataset_1D): dataset = NMR_dataset_1D.copy() dataset /= dataset.real.data.max() # nromalize dataset.em(10. * ur.Hz, inplace=True) dataset = dataset.fft(tdeff=8192, size=2 ** 15) dataset = dataset[150.0:-150.] + 1. dataset.plot() transf = dataset.copy() transfab = transf.ab(window=.25) transfab.plot(clear=False, color='r') transf = dataset.copy() base = transf.ab(mode="poly", dryrun=True) transfab = transf - base transfab.plot(xlim=(150, -150), clear=False, color='b') base.plot(xlim=(150, -150), ylim=[-2, 10], clear=False, color='y') show() <file_sep>/tests/test_analysis/test_issues.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Tests for general issues """ from spectrochempy import PCA, read_omnic def _test_issue_15(): x = read_omnic('irdata/nh4y-activation.spg') my_pca = PCA(x) my_pca.reconstruct(n_pc=3) <file_sep>/spectrochempy/core/analysis/pca.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implement the PCA (Principal Component Analysis) class. """ __all__ = ['PCA'] __dataset_methods__ = [] import numpy as np from matplotlib import pyplot as plt from matplotlib.ticker import MaxNLocator, ScalarFormatter from scipy.special import gammaln from traitlets import HasTraits, Instance from spectrochempy.core import info_ from spectrochempy.core.analysis.svd import SVD from spectrochempy.core.dataset.coord import Coord from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.npy import dot from spectrochempy.utils import NRed, NBlue # ====================================================================================================================== # class PCA # ====================================================================================================================== class PCA(HasTraits): """ Principal Component Analysis This class performs a Principal Component Analysis of a |NDDataset|, *i.e.*, a linear dimensionality reduction using Singular Value Decomposition (`SVD`) of the data to perform its projection to a lower dimensional space. The reduction of a dataset :math:`X` with shape (`M`,`N`) is achieved using the decomposition : :math:`X = S.L^T`, where :math:`S` is the score's matrix with shape (`M`, `n_pc`) and :math:`L^T` is the transposed loading's matrix with shape (`n_pc`, `N`). If the dataset `X` contains masked values, these values are silently ignored in the calculation. """ _LT = Instance(NDDataset) _S = Instance(NDDataset) _X = Instance(NDDataset) _ev = Instance(NDDataset) """|NDDataset| - Explained variances (The eigenvalues of the covariance matrix).""" _ev_ratio = Instance(NDDataset) """|NDDataset| - Explained variance per singular values.""" _ev_cum = Instance(NDDataset) """|NDDataset| - Cumulative Explained Variances.""" # .................................................................................................................. def __init__(self, dataset, centered=True, standardized=False, scaled=False): """ Parameters ---------- dataset : |NDDataset| object The input dataset has shape (M, N). M is the number of observations (for examples a series of IR spectra) while N is the number of features (for example the wavenumbers measured in each IR spectrum). centered : bool, optional, default:True If True the data are centered around the mean values: :math:`X' = X - mean(X)`. standardized : bool, optional, default:False If True the data are scaled to unit standard deviation: :math:`X' = X / \\sigma`. scaled : bool, optional, default:False If True the data are scaled in the interval [0-1]: :math:`X' = (X - min(X)) / (max(X)-min(X))` """ self.prefs = dataset.preferences self._X = X = dataset Xsc = X.copy() # mean center the dataset # ----------------------- self._centered = centered if centered: self._center = center = np.mean(X, axis=0) Xsc = X - center Xsc.title = "centered %s" % X.title # Standardization # --------------- self._standardized = standardized if standardized: self._std = np.std(Xsc, axis=0) Xsc /= self._std Xsc.title = "standardized %s" % Xsc.title # Scaling # ------- self._scaled = scaled if scaled: self._min = np.min(Xsc, axis=0) self._ampl = np.ptp(Xsc, axis=0) Xsc -= self._min Xsc /= self._ampl Xsc.title = "scaled %s" % Xsc.title self._Xscaled = Xsc # perform SVD # ----------- svd = SVD(Xsc) sigma = svd.s.diag() U = svd.U VT = svd.VT # select n_pc loadings & compute scores # -------------------------------------------------------------------- # loadings LT = VT LT.title = 'Loadings (L^T) of ' + X.name LT.history = 'Created by PCA' # scores S = dot(U, sigma) S.title = 'scores (S) of ' + X.name S.set_coordset(y=X.y, x=Coord(None, labels=['#%d' % (i + 1) for i in range(svd.s.size)], title='principal component')) S.description = 'scores (S) of ' + X.name S.history = 'Created by PCA' self._LT = LT self._S = S # other attributes # ---------------- self._sv = svd.sv self._sv.x.title = 'PC #' self._ev = svd.ev self._ev.x.title = 'PC #' self._ev_ratio = svd.ev_ratio self._ev_ratio.x.title = 'PC #' self._ev_cum = svd.ev_cum self._ev_cum.x.title = 'PC #' return # ------------------------------------------------------------------------------------------------------------------ # Special methods # ------------------------------------------------------------------------------------------------------------------ def __str__(self, n_pc=5): s = '\nPC\t\tEigenvalue\t\t%variance\t' \ '%cumulative\n' s += ' \t\tof cov(X)\t\t per PC\t' \ ' variance\n' n_pc = min(n_pc, len(self.ev.data)) for i in range(n_pc): tup = (i + 1, np.sqrt(self.ev.data[i]), self.ev_ratio.data[i], self.ev_cum.data[i]) s += '#{} \t{:8.3e}\t\t {:6.3f}\t {:6.3f}\n'.format(*tup) return s # ------------------------------------------------------------------------------------------------------------------ # Private methods # ------------------------------------------------------------------------------------------------------------------ def _get_n_pc(self, n_pc=None): max_n_pc = self.ev.size if n_pc is None: n_pc = max_n_pc return n_pc elif isinstance(n_pc, int): n_pc = min(n_pc, max_n_pc) return n_pc elif n_pc == 'auto': M, N = self.X.shape if M >= N: n_pc = self._infer_pc_() return n_pc else: info_('Cannot use `auto` if n_observations < ' 'n_features. Try with threshold 0.9999') n_pc = 0.9999 if 0 < n_pc < 1.0: # number of PC for which the cumulated explained variance is # less than a given ratio n_pc = np.searchsorted(self.ev_cum.data / 100., n_pc) + 1 return n_pc else: raise ValueError('could not get a valid number of components') def _assess_dimension_(self, rank): """Compute the likelihood of a rank ``rank`` dataset The dataset is assumed to be embedded in gaussian noise having spectrum ``spectrum`` (here, the explained variances `ev` ). Parameters ---------- rank : int Tested rank value. Returns ------- float The log-likelihood. Notes ----- This implements the method of <NAME> : Automatic Choice of Dimensionality for PCA. NIPS 2000 : 598-604. Copied and modified from scikit-learn.decomposition.pca (BSD-3 license) """ spectrum = self._ev.data M, N = self._X.shape if rank > len(spectrum): raise ValueError("The tested rank cannot exceed the rank of the" " dataset") pu = -rank * np.log(2.) for i in range(rank): pu += (gammaln((N - i) / 2.) - np.log(np.pi) * (N - i) / 2.) pl = np.sum(np.log(spectrum[:rank])) pl = -pl * M / 2. if rank == N: pv = 0 v = 1 else: v = np.sum(spectrum[rank:]) / (N - rank) pv = -np.log(v) * M * (N - rank) / 2. m = N * rank - rank * (rank + 1.) / 2. pp = np.log(2. * np.pi) * (m + rank + 1.) / 2. pa = 0. spectrum_ = spectrum.copy() spectrum_[rank:N] = v for i in range(rank): for j in range(i + 1, len(spectrum)): pa += np.log((spectrum[i] - spectrum[j]) * (1. / spectrum_[j] - 1. / spectrum_[i])) + np.log(M) ll = pu + pl + pv + pp - pa / 2. - rank * np.log(M) / 2. return ll def _infer_pc_(self): """Infers the number of principal components. Notes ----- Copied and modified from _infer_dimensions in scikit-learn.decomposition.pca (BSD-3 license). """ n_ev = self._ev.size ll = np.empty(n_ev) for rank in range(n_ev): ll[rank] = self._assess_dimension_(rank) return ll.argmax() # ------------------------------------------------------------------------------------------------------------------ # Public methods # ------------------------------------------------------------------------------------------------------------------ def reduce(self, n_pc=None): """ Apply a dimensionality reduction to the X dataset of shape [M, N]. Loadings `L` with shape [``n_pc``, `N`] and scores `S` with shape [`M`, `n_pc`] are obtained using the following decomposition : :math:`X = S.L^T`. Parameters ---------- n_pc : int, optional The number of principal components to compute. If not set all components are returned, except if n_pc is set to ``auto`` for an automatic determination of the number of components. Returns ------- S, LT : |NDDataset| objects. n_pc loadings and their corresponding scores for each observations. """ # get n_pc (automatic or determined by the n_pc arguments) n_pc = self._get_n_pc(n_pc) # scores (S) and loading (L^T) matrices # ------------------------------------ S = self._S[:, :n_pc] LT = self._LT[:n_pc] return S, LT def reconstruct(self, n_pc=None): """ Transform data back to the original space using the given number of PC's. The following matrice operation is performed : :math:`X' = S'.L'^T` where S'=S[:, n_pc] and L=L[:, n_pc]. Parameters ---------- n_pc : int, optional The number of PC to use for the reconstruction. Returns ------- X_reconstructed : |NDDataset| The reconstructed dataset based on n_pc principal components. """ # get n_pc (automatic or determined by the n_pc arguments) n_pc = self._get_n_pc(n_pc) # reconstruct from scores and loadings using n_pc components S = self._S[:, :n_pc] LT = self._LT[:n_pc] X = dot(S, LT) # try to reconstruct something close to the original scaled, standardized or centered data if self._scaled: X *= self._ampl X += self._min if self._standardized: X *= self._std if self._centered: X += self._center X.history = f'PCA reconstructed Dataset with {n_pc} principal components' X.title = self._X.title return X def printev(self, n_pc=None): """ Prints figures of merit : eigenvalues and explained variance for the first n_pc PS's. Parameters ---------- n_pc : int, optional The number of components to print. """ # get n_pc (automatic or determined by the n_pc arguments) n_pc = self._get_n_pc(n_pc) print((self.__str__(n_pc))) def screeplot(self, n_pc=None, **kwargs): """ Scree plot of explained variance + cumulative variance by PCA. Parameters ---------- n_pc : int Number of components to plot. """ # get n_pc (automatic or determined by the n_pc arguments) - min = 3 n_pc = max(self._get_n_pc(n_pc), 3) color1, color2 = kwargs.get('colors', [NBlue, NRed]) # pen = kwargs.get('pen', True) ylim1, ylim2 = kwargs.get('ylims', [(0, 100), 'auto']) if ylim2 == 'auto': y1 = np.around(self._ev_ratio.data[0] * .95, -1) y2 = 101. ylim2 = (y1, y2) ax1 = self._ev_ratio[:n_pc].plot_bar(ylim=ylim1, color=color1, title='Scree plot') ax2 = self._ev_cum[:n_pc].plot_scatter(ylim=ylim2, color=color2, pen=True, markersize=7., twinx=ax1) ax1.set_title('Scree plot') return ax1, ax2 def scoreplot(self, *pcs, colormap='viridis', color_mapping='index', **kwargs): """ 2D or 3D scoreplot of samples. Parameters ---------- *pcs : a series of int argument or a list/tuple Must contain 2 or 3 elements. colormap : str A matplotlib colormap. color_mapping : 'index' or 'labels' If 'index', then the colors of each n_scores is mapped sequentially on the colormap. If labels, the labels of the n_observation are used for color mapping. """ if isinstance(pcs[0], (list, tuple, set)): pcs = pcs[0] # transform to internal index of component's index (1->0 etc...) pcs = np.array(pcs) - 1 # colors if color_mapping == 'index': if np.any(self._S.y.data): colors = self._S.y.data else: colors = np.array(range(self._S.shape[0])) elif color_mapping == 'labels': labels = list(set(self._S.y.labels)) colors = [labels.index(lab) for lab in self._S.y.labels] if len(pcs) == 2: # bidimentional score plot fig = plt.figure(**kwargs) ax = fig.add_subplot(111) ax.set_title('Score plot') ax.set_xlabel('PC# {} ({:.3f}%)'.format(pcs[0] + 1, self._ev_ratio.data[pcs[0]])) ax.set_ylabel('PC# {} ({:.3f}%)'.format(pcs[1] + 1, self._ev_ratio.data[pcs[1]])) axsc = ax.scatter(self._S.masked_data[:, pcs[0]], self._S.masked_data[:, pcs[1]], s=30, c=colors, cmap=colormap) number_x_labels = self.prefs.number_of_x_labels # get from config number_y_labels = self.prefs.number_of_y_labels # the next two line are to avoid multipliers in axis scale y_formatter = ScalarFormatter(useOffset=False) ax.yaxis.set_major_formatter(y_formatter) ax.xaxis.set_major_locator(MaxNLocator(number_x_labels)) ax.yaxis.set_major_locator(MaxNLocator(number_y_labels)) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') if len(pcs) == 3: # tridimensional score plot plt.figure(**kwargs) ax = plt.axes(projection='3d') ax.set_title('Score plot') ax.set_xlabel('PC# {} ({:.3f}%)'.format(pcs[0] + 1, self._ev_ratio.data[pcs[0]])) ax.set_ylabel('PC# {} ({:.3f}%)'.format(pcs[1] + 1, self._ev_ratio.data[pcs[1]])) ax.set_zlabel('PC# {} ({:.3f}%)'.format(pcs[2] + 1, self._ev_ratio.data[pcs[2]])) axsc = ax.scatter(self._S.masked_data[:, pcs[0]], self._S.masked_data[:, pcs[1]], self._S.masked_data[:, pcs[2]], zdir='z', s=30, c=colors, cmap=colormap, depthshade=True) if color_mapping == 'labels': import matplotlib.patches as mpatches leg = [] for lab in labels: i = labels.index(lab) c = axsc.get_cmap().colors[int(255 / (len(labels) - 1) * i)] leg.append(mpatches.Patch(color=c, label=lab)) ax.legend(handles=leg, loc='best') return ax @property def LT(self): """ LT """ return self._LT @property def S(self): """ S """ return self._S @property def X(self): """ X """ return self._X @property def ev(self): """ |NDDataset| - Explained variances (The eigenvalues of the covariance matrix). """ return self._ev @property def ev_ratio(self): """ |NDDataset| - Explained variance per singular values. """ return self._ev_ratio @property def ev_cum(self): """ |NDDataset| - Cumulative Explained Variances. """ return self._ev_cum # ============================================================================ if __name__ == '__main__': pass <file_sep>/docs/userguide/dataset/dataset.py # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # The NDDataset object # %% [markdown] # The NDDataset is the main object use by **SpectroChemPy**. # # Like numpy ndarrays, NDDataset have the capability to be sliced, sorted and subject to matematical operations. # # But, in addition, NDDataset may have units, can be masked and each dimensions can have coordinates also with units. # This make NDDataset aware of unit compatibility, *e.g.*, for binary operation such as addtions or subtraction or # during the application of mathematical operations. In addition or in replacement of numerical data for coordinates, # NDDatset can also have labeled coordinates where labels can be different kind of objects (strings, datetime, # numpy nd.ndarray or othe NDDatasets, etc...). # # This offers a lot of flexibility in using NDDatasets that, we hope, will be useful for applications. # See the **Tutorials** for more information about such possible applications. # %% [markdown] # **Below (and in the next sections), we try to give an almost complete view of the NDDataset features.** # %% import spectrochempy as scp # %% [markdown] # As we will make some reference to the `numpy` library, we also import it here. # %% import numpy as np # %% [markdown] # We additionnaly import the three main SpectroChemPy objects that we will use through this tutorial # %% from spectrochempy import NDDataset, CoordSet, Coord # %% [markdown] # For a convenient usage of units, we will also directly import `ur`, the unit registry which contains all available # units. # %% from spectrochempy import ur # %% [markdown] # Multidimensional array are defined in Spectrochempy using the `NDDataset` object. # # `NDDataset` objects mostly behave as numpy's `numpy.ndarray` # (see for instance __[numpy quikstart tutorial](https://numpy.org/doc/stable/user/quickstart.html)__). # %% [markdown] # However, unlike raw numpy's ndarray, the presence of optional properties make them (hopefully) more appropriate for # handling spectroscopic information, one of the major objectives of the SpectroChemPy package: # # * `mask`: Data can be partially masked at will # * `units`: Data can have units, allowing units-aware operations # * `coordset`: Data can have a set of coordinates, one or sevral by dimensions # # Additional metadata can also be added to the instances of this class through the `meta` properties. # %% [markdown] # ## 1D-Dataset (unidimensional dataset) # %% [markdown] # In the following example, a minimal 1D dataset is created from a simple list, to which we can add some metadata: # %% d1D = NDDataset([10., 20., 30.], name="Dataset N1", author='<NAME> Mortimer', description='A dataset from scratch') d1D # %% [markdown] # <div class='alert alert-info'> # <b>Note</b> # # In the above code, run in a notebook, the output of d1D is in html for a nice display. # # To get the same effect, from a console script, one can use `print_` (with an underscore) and not the usual python # function `print`. As you can see below, the `print` function only gives a short summary of the information, # while the `print_` method gives more detailed output # # </div> # %% print(d1D) # %% scp.print_(d1D) # %% _ = d1D.plot(figsize=(3, 2)) # %% [markdown] # Except few addtional metadata such `author`, `created` ..., there is not much # differences with respect to a conventional `numpy.ndarray`. For example, one # can apply numpy ufunc's directly to a NDDataset or make basic arithmetic # operation with these objects: # %% np.sqrt(d1D) # %% d1D + d1D / 2. # %% [markdown] # As seen above, there are some metadata that are automatically added to the dataset: # # * `id` : This is a unique identifier for the object # * `author` : author determined from the computer name if not provided # * `created` : date/time of creation # * `modified`: date/time of modification # # additionaly, dataset can have a **`name`** (equal to the `id` if it is not provided) # # Some other metadata are defined: # # * `history`: history of operation achieved on the object since the object creation # * `description`: A user friendly description of the objects purpose or contents. # * `title`: A title that will be used in plots or in some other operation on the objects. # # # All this metadata (except, the `id`, `created`, `modified`) can be changed by the user. # # For instance: # %% d1D.title = 'intensity' d1D.name = 'mydataset' d1D.history = 'created from scratch' d1D.description = 'Some experimental measurements' d1D # %% [markdown] # d1D is a 1D (1-dimensional) dataset with only one dimension. # # Some attributes are useful to check this kind of information: # %% d1D.shape # the shape of 1D contain only one dimension size # %% d1D.ndim # the number of dimensions # %% d1D.dims # the name of the dimension (it has been automatically attributed) # %% [markdown] # **Note**: The names of the dimensions are set automatically. But they can be changed, with the limitation that the # name must be a single letter. # %% d1D.dims = ['q'] # change the list of dim names. # %% d1D.dims # %% [markdown] # ### nD-Dataset (multidimensional dataset) # %% [markdown] # To create a nD NDDataset, we can provide a nD-array like object to the NDDataset instance constructor # %% a = np.random.rand(2, 4, 6) a # %% d3D = NDDataset(a) d3D.title = 'Energy' d3D.author = 'Someone' d3D.name = '3D dataset creation' d3D.history = 'created from scratch' d3D.description = 'Some example' d3D.dims = ['u', 'v', 't'] d3D # %% [markdown] # We can also add all information in a single statement # %% d3D = NDDataset(a, dims=['u', 'v', 't'], title='Energy', author='Someone', name='3D_dataset', history='created from scratch', description='a single statement creation example') d3D # %% [markdown] # Three names are attributed at the creation (if they are not provided with the `dims` attribute, then the name are: # 'z','y','x' automatically attributed) # %% d3D.dims # %% d3D.ndim # %% d3D.shape # %% [markdown] # ## Units # %% [markdown] # One interesting possibility for a NDDataset is to have defined units for the internal data. # %% d1D.units = ur.eV # ur is a registry containing all available units # %% d1D # note the eV symbol of the units added to the values field below # %% [markdown] # This allows to make units-aware calculations: # %% d1D ** 2 # note the results in eV^2 # %% np.sqrt(d1D) # note the result in e^0.5 # %% time = 5. * ur.second d1D / time # here we get results in eV/s # %% [markdown] # Conversion can be done between different units transparently # %% d1D.to('J') # %% d1D.to('K') # %% [markdown] # ## Coordinates # %% [markdown] # The above created `d3D` dataset has 3 dimensions, but no coordinate for these dimensions. Here arises a big difference # with simple `numpy`-arrays: # * We can add coordinates to each dimensions of a NDDataset. # %% [markdown] # To get the list of all defined coordinates, we can use the `coords` attribute: # %% d3D.coordset # no coordinates, so it returns nothing (None) # %% d3D.t # the same for coordinate t, v, u which are not yet set # %% [markdown] # To add coordinates, on way is to set them one by one: # %% d3D.t = Coord.arange(6) * .1 # we need a sequence of 6 values for `t` dimension (see shape above) d3D.t.title = 'time' d3D.t.units = ur.seconds d3D.coordset # now return a list of coordinates # %% d3D.t # %% d3D.coordset('t') # Alternative way to get a given coordinates # %% d3D['t'] # another alternative way to get a given coordinates # %% [markdown] # The two other coordinates u and v are still undefined # %% d3D.u, d3D.v # %% [markdown] # When the dataset is printed, only the information for the existing coordinates is given. # %% d3D # %% [markdown] # Programatically, we can use the attribute `is_empty` or `has_data` to check this # %% d3D.v.has_data, d3D.v.is_empty # %% [markdown] # An error is raised when a coordinate doesn't exist # %% try: d3D.x except KeyError as e: scp.error_(e) # %% [markdown] # In some case it can also be usefull to get a coordinate from its title instead of its name (the limitation is that if # several coordinates have the same title, then only the first ones that is found in the coordinate list, will be # returned - this can be ambiguous) # %% d3D['time'] # %% d3D.time # %% [markdown] # ## Labels # %% [markdown] # It is possible to use labels instead of numerical coordinates. They are sequence of objects .The length of the # sequence must be equal to the size of a dimension. # %% [markdown] # The labels can be simple strings, *e.g.,* # %% tags = list('ab') d3D.u.title = 'some tags' d3D.u.labels = tags # TODO: avoid repetition d3D # %% [markdown] # or more complex objects. # # For instance here we use datetime.timedelta objets: # %% from datetime import timedelta start = timedelta(0) times = [start + timedelta(seconds=x * 60) for x in range(6)] d3D.t = None d3D.t.labels = times d3D.t.title = 'time' d3D # %% [markdown] # In this case, getting a coordinate that doesn't possess numerical data but labels, will return the labels # %% d3D.time # %% [markdown] # # More insight on coordinates # %% [markdown] # ## Sharing coordinates between dimensions # %% [markdown] # Sometimes it is not necessary to have different coordinates for the each axes. Some can be shared between axes. # # For example, if we have a square matrix with the same coordinate in the two dimensions, the second dimension can # refer to the first. Here we create a square 2D dataset, using the `diag` method: # %% nd = NDDataset.diag((3, 3, 2.5)) nd # %% [markdown] # and then we add the same coordinate for both dimensions # %% coordx = Coord.arange(3) nd.set_coordset(x=coordx, y='x') nd # %% [markdown] # ## Setting coordinates using `set_coordset` # %% [markdown] # Lets create 3 `Coord` objects to be use a s coordinates for the 3 dimensions of the previous d3D dataset. # %% d3D.dims = ['t', 'v', 'u'] s0, s1, s2 = d3D.shape coord0 = Coord.linspace(10., 100., s0, units='m', title='distance') coord1 = Coord.linspace(20., 25., s1, units='K', title='temperature') coord2 = Coord.linspace(0., 1000., s2, units='hour', title='elapsed time') # %% [markdown] # ### Syntax 1 # %% d3D.set_coordset(u=coord2, v=coord1, t=coord0) d3D # %% [markdown] # ### Syntax 2 # %% d3D.set_coordset({'u': coord2, 'v': coord1, 't': coord0}) d3D # %% [markdown] # ## Adding several coordinates to a single dimension # We can add several coordinates to the same dimension # %% coord1b = Coord([1, 2, 3, 4], units='millitesla', title='magnetic field') # %% d3D.set_coordset(u=coord2, v=[coord1, coord1b], t=coord0) d3D # %% [markdown] # We can retrieve the various coordinates for a single dimention easily: # %% d3D.v_1 # %% [markdown] # ## Summary of the coordinate setting syntax # Some additional information about coordinate setting syntax # %% [markdown] # **A.** First syntax (probably the safer because the name of the dimension is specified, so this is less prone to # errors!) # %% d3D.set_coordset(u=coord2, v=[coord1, coord1b], t=coord0) # or equivalent d3D.set_coordset(u=coord2, v=CoordSet(coord1, coord1b), t=coord0) d3D # %% [markdown] # **B.** Second syntax assuming the coordinates are given in the order of the dimensions. # # Remember that we can check this order using the `dims` attribute of a NDDataset # %% d3D.dims # %% d3D.set_coordset((coord0, [coord1, coord1b], coord2)) # or equivalent d3D.set_coordset(coord0, CoordSet(coord1, coord1b), coord2) d3D # %% [markdown] # **C.** Third syntax (from a dictionary) # %% d3D.set_coordset({'t': coord0, 'u': coord2, 'v': [coord1, coord1b]}) d3D # %% [markdown] # **D.** It is also possible to use directly the `coordset` property # %% d3D.coordset = coord0, [coord1, coord1b], coord2 d3D # %% d3D.coordset = {'t': coord0, 'u': coord2, 'v': [coord1, coord1b]} d3D # %% d3D.coordset = CoordSet(t=coord0, u=coord2, v=[coord1, coord1b]) d3D # %% [markdown] # <div class='alert alert-warning'> # <b>WARNING</b> # # Do not use list for setting multiples coordinates! use tuples # </div> # %% [markdown] # This raise an error (list have another signification: it's used to set a "same dim" CoordSet see example A or B) # %% try: d3D.coordset = [coord0, coord1, coord2] except ValueError: scp.error_('Coordinates must be of the same size for a dimension with multiple coordinates') # %% [markdown] # This works : it use a tuple `()`, not a list `[]` # %% d3D.coordset = (coord0, coord1, coord2) # equivalent to d3D.coordset = coord0, coord1, coord2 d3D # %% [markdown] # **E.** Setting the coordinates individually # %% [markdown] # Either a single coordinate # %% d3D.u = coord2 d3D # %% [markdown] # or multiple coordinates for a single dimension # %% d3D.v = [coord1, coord1b] d3D # %% [markdown] # or using a CoorSet object. # %% d3D.v = CoordSet(coord1, coord1b) d3D # %% [markdown] # # Methods to create NDDataset # # There are many ways to create `NDDataset` objects. # # Let's first create 2 coordinate objects, for which we can define `labels` and `units`! Note the use of the function # `linspace`to generate the data. # %% c0 = Coord.linspace(start=4000., stop=1000., num=5, labels=None, units="cm^-1", title='wavenumber') # %% c1 = Coord.linspace(10., 40., 3, labels=['Cold', 'RT', 'Hot'], units="K", title='temperature') # %% [markdown] # The full coordset will be the following # %% cs = CoordSet(c0, c1) cs # %% [markdown] # Now we will generate the full dataset, using a ``fromfunction`` method. All needed information are passed as # parameter of the NDDataset instance constructor. # %% [markdown] # ## Create a dataset from a function # %% def func(x, y, extra): return x * y / extra # %% ds = NDDataset.fromfunction(func, extra=100 * ur.cm ** -1, # extra arguments passed to the function coordset=cs, name='mydataset', title='Absorbance', units=None) # when None, units will be determined from the function results ds.description = """Dataset example created for this tutorial. It's a 2-D dataset""" ds.author = '<NAME>' ds # %% [markdown] # ## Using numpy-like constructors of NDDatasets # %% dz = NDDataset.zeros((5, 3), coordset=cs, units='meters', title='Datasets with only zeros') # %% do = NDDataset.ones((5, 3), coordset=cs, units='kilograms', title='Datasets with only ones') # %% df = NDDataset.full((5, 3), fill_value=1.25, coordset=cs, units='radians', title='with only float=1.25') df # %% [markdown] # As with numpy, it is also possible to take another dataset as a template: # %% df = NDDataset.full_like(d3D, dtype='int', fill_value=2) df # %% nd = NDDataset.diag((3, 3, 2.5)) nd # %% [markdown] # ## Copying existing NDDataset # # To copy an existing dataset, this is as simple as: # %% d3D_copy = d3D.copy() # %% [markdown] # or alternatively: # %% d3D_copy = d3D[:] # %% [markdown] # Finally, it is also possible to initialize a dataset using an existing one: # %% d3Dduplicate = NDDataset(d3D, name='duplicate of %s' % d3D.name, units='absorbance') d3Dduplicate # %% [markdown] # ## Importing from external dataset # # NDDataset can be created from the importation of external data # # A **test**'s data folder contains some data for experimenting some features of datasets. # %% # let check if this directory exists and display its actual content: datadir = scp.preferences.datadir if datadir.exists(): print(datadir.name) # %% [markdown] # Let's load grouped IR spectra acquired using OMNIC: # %% nd = NDDataset.read_omnic(datadir / 'irdata/nh4y-activation.spg') nd.preferences.reset() _ = nd.plot() # %% [markdown] # Even if we do not specify the **datadir**, the application first look in tht directory by default. # %% [markdown] # Now, lets load a NMR dataset (in the Bruker format). # %% path = datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'topspin_2d' # load the data directly (no need to create the dataset first) nd2 = NDDataset.read_topspin(path, expno=1, remove_digital_filter=True) # view it... nd2.x.to('s') nd2.y.to('ms') ax = nd2.plot(method='map') <file_sep>/spectrochempy/core/readers/readquadera.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """Plugin module to extend NDDataset with the import methods method. """ __all__ = ['read_quadera'] __dataset_methods__ = __all__ import io from warnings import warn from datetime import datetime, timezone import re import numpy as np from spectrochempy.core.dataset.nddataset import NDDataset, Coord from spectrochempy.core.readers.importer import Importer, importermethod # ====================================================================================================================== # Public functions # ====================================================================================================================== def read_quadera(*paths, **kwargs): """ Read a Pfeiffer Vacuum's QUADERA® mass spectrometer software file with extension ``.asc`` and return its content as dataset. Parameters ----------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read_quadera |NDDataset| or list of |NDDataset|. Other Parameters ---------------- timestamp: bool, optional returns the acquisition timestamp as Coord (Default=True). If set to false, returns the time relative to the acquisition time of the data protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel', 'asc'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False) description: str, optional A Custom description. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True) recursive : bool, optional Read also in subfolders. (default=False) Examples --------- >>> import spectrochempy as scp >>> scp.read_quadera('msdata/ion_currents.asc') NDDataset: [float64] A (shape: (y:16975, x:10)) Notes: ------ Currently the acquisition time is that of the first channel as the timeshift of other channels are typically within few seconds, and the data of other channels are NOT interpolated Todo: check with users wether data interpolation should be made See Also -------- read : Read generic files. read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_labspec : Read Raman LABSPEC spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. """ kwargs['filetypes'] = ['Quadera files (*.asc)'] kwargs['protocol'] = ['asc'] importer = Importer() return importer(*paths, **kwargs) # ---------------------------------------------------------------------------------------------------------------------- # Private methods # ---------------------------------------------------------------------------------------------------------------------- @importermethod def _read_asc(*args, **kwargs): _, filename = args content = kwargs.get('content', False) if content: fid = io.BytesIO(content) else: fid = open(filename, 'r') lines = fid.readlines() fid.close() timestamp = kwargs.get('timestamp', True) # the list of channels is 2 lines after the line starting with "End Time" i = 0 while not lines[i].startswith("End Time"): i += 1 i += 2 # reads channel names channels = re.split(r'\t+', lines[i].rstrip('\t\n'))[1:] nchannels = len(channels) # the next line contains the columns titles, repeated for each channels # this routine assumes that for each channel are Time / Time relative [s] / Ion Current [A] # check it: i += 1 colnames = re.split(r'\t+', lines[i].rstrip('\t')) if colnames[0] == 'Time' or colnames[1] != 'Time Relative [s]' or colnames[2] != 'Ion Current [A]': warn('Columns names are not those expected: the reading of your .asc file could yield ' 'please notify this to the developers of scpectrochempy') if nchannels > 1 and colnames[3] != 'Time': warn('The number of columms per channel is not that expected: the reading of your .asc file could yield ' 'please notify this to the developers of spectrochempy') # the remaining lines contain data and time coords ntimes = len(lines) - i - 1 times = np.empty((ntimes, nchannels), dtype=object) reltimes = np.empty((ntimes, nchannels)) ioncurrent = np.empty((ntimes, nchannels)) i += 1 prev_timestamp = 0 for j, line in enumerate(lines[i:]): data = re.split(r'[\t+]', line.rstrip('\t')) for k in range(nchannels): datetime_ = datetime.strptime(data[3 * k].strip(' '), '%m/%d/%Y %H:%M:%S.%f') times[j][k] = datetime_.timestamp() # hours are given in 12h clock format, so we need to add 12h when hour is in the afternoon if times[j][k] < prev_timestamp: times[j][k] += 3600 * 12 reltimes[j][k] = data[1 + 3 * k].replace(',', '.') ioncurrent[j][k] = data[2 + 3 * k].replace(',', '.') prev_timestamp = times[j][k] dataset = NDDataset(ioncurrent) dataset.name = filename.stem dataset.title = "Ion Current" dataset.units = "amp" if timestamp: _y = Coord(times[:, 0], title='Acquisition timestamp (UTC)', units="s") else: _y = Coord(times[:, 0] - times[0, 0], title='Time', units="s") _x = Coord(labels=channels) dataset.set_coordset(y=_y, x=_x) # Set the NDDataset date dataset._date = datetime.now(timezone.utc) dataset._modified = dataset.date # Set origin, description and history dataset.history = f'{dataset.date}:imported from Quadera asc file {filename}' return dataset # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/docs/conf.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # cell_metadata_filter: -all # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.7.1 # --- # %% # %% [markdown] # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== # %% """ SpectroChemPy documentation build configuration file """ # %% import inspect import os import sys import warnings # %% import sphinx_rtd_theme # Theme for the website # %% import spectrochempy # isort:skip # %% [markdown] # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation general, use os.path.abspath to make it absolute, like shown # here: sys.path.insert(0, os.path.abspath('.')) # %% [markdown] # -- General configuration --------------------------------------------------- # %% [markdown] # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # %% [markdown] # Add any Sphinx extension module names here, as strings. # They can be extensions coming with Sphinx (named 'sphinx.ext.*') or your # custom ones. # %% # hack to make import sys._called_from_sphinx = True # %% # Sphinx Extensions source = os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(source, "docs", "sphinxext")) # print (sys.path) extensions = \ [ 'nbsphinx', 'sphinx_copybutton', 'sphinx.ext.mathjax', 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.linkcode', 'sphinx.ext.todo', 'sphinx_gallery.gen_gallery', 'matplotlib.sphinxext.plot_directive', 'IPython.sphinxext.ipython_console_highlighting', 'IPython.sphinxext.ipython_directive', "sphinx.ext.napoleon", "autodoc_traitlets", "sphinx.ext.autosummary", ] # %% # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # %% # The suffix of source filenames. source_suffix = '.rst' # %% # The encoding of source files. source_encoding = 'utf-8' # %% # The master toctree document. master_doc = 'index' # %% [markdown] # General information about the project. # %% [markdown] # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # %% version = spectrochempy.application.__version__ # .split('+')[0] release = version.split('+')[0] project = f"SpectroChemPy v{version}" copyright = spectrochempy.application.__copyright__ # %% # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # %% exclude_patterns = [] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns.append('_templates') exclude_patterns.append('_static') exclude_patterns.append('**.ipynb_checkpoints') exclude_patterns.append('gallery') exclude_patterns.append('~temp') # %% # The reST default role (used for this markup: `text`) to use for all # documents. default_role = 'obj' # %% # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = False # %% # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # %% [markdown] # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # %% # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # %% [markdown] # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # %% # Show Todo box todo_include_todos = True # %% [markdown] # This is added to the end of RST files - a good place to put substitutions to # be used globally. # %% rst_epilog = """ .. |scpy| replace:: **SpectroChemPy** .. |ndarray| replace:: :class:`~numpy.ndarray` .. |ma.ndarray| replace:: :class:`~numpy.ma.array` .. |Project| replace:: :class:`~spectrochempy.core.projects.project.Project` .. |Script| replace:: :class:`~spectrochempy.core.dataset.scripts.Script` .. |NDArray| replace:: :class:`~spectrochempy.core.dataset.ndarray.NDArray` .. |NDDataset| replace:: :class:`~spectrochempy.core.dataset.nddataset.NDDataset` .. |Coord| replace:: :class:`~spectrochempy.core.dataset.ndcoord.Coord` .. |CoordSet| replace:: :class:`~spectrochempy.core.dataset.ndcoordset.CoordSet` .. |NDIO| replace:: :class:`~spectrochempy.core.dataset.ndio.NDIO` .. |NDMath| replace:: :class:`~spectrochempy.core.dataset.ndmath.NDMath` .. |Meta| replace:: :class:`~spectrochempy.core.dataset.ndmeta.Meta` .. |NDPlot| replace:: :class:`~spectrochempy.core.dataset.ndplot.NDPlot` .. |Unit| replace:: :class:`~spectrochempy.units.units.Unit` .. |Quantity| replace:: :class:`~spectrochempy.units.units.Quantity` .. |Measurement| replace:: :class:`~spectrochempy.units.units.Measurement` .. |Axes| replace:: :class:`~matplotlib.Axes` .. |userguide| replace:: :ref:`userguide` """ # %% [markdown] # -- Options for HTML output --------------------------------------------------- # %% [markdown] # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # %% html_theme = 'sphinx_rtd_theme' # %% # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'logo_only': True, 'display_version': True, 'collapse_navigation': True, 'navigation_depth': 2, } # %% [markdown] # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = ['_static'] # %% html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # %% html_logo = '_static/scpy.png' # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # %% html_favicon = "_static/scpy.ico" # %% # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # %% # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # %% # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = True # %% [markdown] # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # %% [markdown] # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # %% [markdown] # If false, no module index is generated. # html_domain_indices = True # %% [markdown] # If false, no index is generated. # html_use_index = True # %% [markdown] # If true, the index is split into individual pages for each letter. # html_split_index = True # %% # If true, links to the reST sources are added to the pages. html_show_sourcelink = True # %% # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # %% # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = True # %% [markdown] # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # %% [markdown] # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # %% # Output file base name for HTML help builder. htmlhelp_basename = 'spectrochempydoc' # %% [markdown] # SINCE the new sphinx version HTML5 is generated by default, # see https://github.com/sphinx-doc/sphinx/issues/6472 # html4_writer = True # %% trim_doctests_flags = True # %% # Remove matplotlib agg warnings from generated doc when using plt.show warnings.filterwarnings("ignore", category=UserWarning, message='Matplotlib is currently using agg, which is a' ' non-GUI backend, so cannot show the figure.') # %% html_context = { 'current_version': 'latest' if ('dev' in version) else 'stable', 'release': spectrochempy.application.__release__, 'base_url': 'https://www.spectrochempy.fr', 'versions': ( ('latest', '/latest/index.html"'), ('stable', '/stable/index.html'), ) } # %% [markdown] # -- Options for LaTeX output -------------------------------------------------- # %% # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [ # howto/manual]). latex_documents = [( 'index', 'spectrochempy.tex', u'SpectroChemPy Documentation', u'<NAME> & <NAME>', 'manual', False), ] # %% # The name of an image file (relative to this directory) to place at the top of # the title page. latex_logo = "_static/scpy.png" # %% # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. latex_use_parts = False # %% latex_elements = { # The paper size ('letterpaper' or 'a4paper'). 'papersize': 'a4paper', # ''letterpaper', # The font size ('10pt', '11pt' or '12pt'). 'pointsize': '10pt', # remove blank pages (between the title page and the TOC, etc.) 'classoptions': ',openany,oneside', 'babel': '\\usepackage[english]{babel}', # Additional stuff for the LaTeX preamble. 'preamble': r''' \usepackage{hyperref} \setcounter{tocdepth}{3} ''' } # %% # If false, no module index is generated. latex_use_modindex = True # %% [markdown] # If true, show page references after internal links. # latex_show_pagerefs = False # %% [markdown] # If true, show URL addresses after external links. # latex_show_urls = False # %% [markdown] # Documents to append as an appendix to all manuals. # latex_appendices = [] # %% [markdown] # If false, no module index is generated. # latex_domain_indices = True # %% [markdown] # -- Options for PDF output --------------------------------------- # %% # Grouping the document tree into PDF files. List of tuples # (source start file, target name, title, author). pdf_documents = [ ('index', u'SpectroChempy', u'Spectrochempy Documentation', u'<NAME> & <NAME>'), ] # %% # A comma-separated list of custom stylesheets. Example: pdf_stylesheets = ['sphinx', 'kerning', 'a4'] # %% [markdown] # Create a compressed PDF # Use True/False or 1/0 # Example: compressed=True # pdf_compressed=False # %% [markdown] # A colon-separated list of folders to search for fonts. Example: # pdf_font_path=['/usr/share/fonts', '/usr/share/texmf-dist/fonts/'] # %% # Language to be used for hyphenation support pdf_language = "en_EN" # %% [markdown] # If false, no index is generated. # pdf_use_index = True # %% [markdown] # If false, no modindex is generated. # pdf_use_modindex = True # %% [markdown] # If false, no coverpage is generated. # pdf_use_coverpage = True # %% [markdown] # Sphinx-gallery --------------------------------------------------------------- # %% [markdown] # Generate the plots for the gallery # %% sphinx_gallery_conf = { 'plot_gallery': 'True', 'backreferences_dir': 'gettingstarted/gallery/backreferences', 'doc_module': ('spectrochempy',), 'reference_url': { 'spectrochempy': None, }, # path to the examples scripts 'examples_dirs': 'gettingstarted/examples', # path where to save gallery generated examples======= 'gallery_dirs': 'gettingstarted/gallery/auto_examples', 'abort_on_example_error': False, 'expected_failing_examples': [], 'download_all_examples': False, } suppress_warnings = [ 'sphinx_gallery', ] # MYST_NB # execution_excludepatterns = ['gettingstarted/gallery/auto_examples', 'sphinxext'] # jupyter_execute_notebooks = "cache" # execution_allow_errors=True # %% [markdown] # nbsphinx --------------------------------------------------------------------- # %% # List of arguments to be passed to the kernel that executes the notebooks: nbsphinx_execute_arguments = [ "--InlineBackend.figure_formats={'jpg', 'png'}", "--InlineBackend.rc={'figure.dpi': 96}", ] # %% # Execute notebooks before conversion: 'always', 'never', 'auto' (default) nbsphinx_execute = 'always' nbsphinx_allow_errors = True nbsphinx_timeout = 180 nbsphinx_prolog = """ .. raw:: html """ copybutton_prompt_text = r">>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.\.\.: | {5,8}: " copybutton_prompt_is_regexp = True # %% # Use this kernel instead of the one stored in the notebook metadata: nbsphinx_kernel_name = 'python3' # %% # set a filename and default folder by default for notebook which have file dialogs os.environ['TUTORIAL_FILENAME'] = 'wodger.spg' os.environ['TUTORIAL_FOLDER'] = 'irdata/subdir' # %% # set a flag to deactivate TQDM os.environ['USE_TQDM'] = 'No' # %% [markdown] # configuration for intersphinx ------------------------------------------------ # %% intersphinx_mapping = { 'python': ('https://docs.python.org/3', None), 'ipython': ('https://ipython.readthedocs.io/en/stable/', None), 'numpy': ('https://numpy.org/doc/stable/', None), 'SciPy': ('https://docs.scipy.org/doc/scipy/reference', None), 'matplotlib': ('https://matplotlib.org/', None), 'sklearn': ('https://scikit-learn.org/stable/', None), } # %% [markdown] # linkcode --------------------------------------------------------------------- # %% def linkcode_resolve(domain, info): # Resolve function for the linkcode extension. def find_source(): # try to find the file and line number, based on code from numpy: # https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L286 obj = sys.modules[info['module']] for part in info['fullname'].split('.'): obj = getattr(obj, part) fn = inspect.getsourcefile(obj) fn = os.path.relpath(fn, start=os.path.dirname(spectrochempy.__file__)) source, lineno = inspect.getsourcelines(obj) return fn, lineno, lineno + len(source) - 1 if domain != 'py' or not info['module']: return None try: filename = 'spectrochempy/%s#L%d-L%d' % find_source() except Exception: filename = info['module'].replace('.', '/') + '.py' tag = 'master' return f"https://github.com/spectrochempy/spectrochempy/blob/{tag}/{filename}" # %% [markdown] # Autosummary ------------------------------------------------------------------ # %% autosummary_generate = True # %% autodoc_typehints = "none" # %% napoleon_use_param = False napoleon_use_rtype = False # %% numpydoc_class_members_toctree = True numpydoc_show_class_members = False numpydoc_use_plots = True # %% autoclass_content = 'both' # Both the class’ and the __init__ method’s docstring are concatenated and inserted. # %% autodoc_default_flags = ['autosummary'] # %% exclusions = ( 'with_traceback', 'with_traceback', 'observe', 'unobserve', 'observe', 'cross_validation_lock', 'unobserve_all', 'class_config_rst_doc', 'class_config_section', 'class_get_help', 'class_print_help', 'section_names', 'update_config', 'clear_instance', "notify_change", 'document_config_options', 'flatten_flags', 'generate_config_file', 'initialize_subcommand', 'initialized', 'instance', 'json_config_loader_class', 'launch_instance', 'setup_instance', 'load_config_file', 'parse_command_line', 'print_alias_help', 'print_description', 'print_examples', 'print_flag_help', 'print_help', 'print_subcommands', 'print_version', 'python_config_loader_class', 'raises', '_*', 'unobserve', 'unobserve_all', 'trait_events', 'trait_metadata', 'trait_names', 'trait', 'setup_instance', 'set_trait', 'on_trait_change', 'observe', 'notify_change', 'hold_trait_notifications', 'has_trait', 'class_traits', 'class_trait_names', 'class_own_traits', 'class_own_trait_events', 'add_traits') # %% def autodoc_skip_member(app, what, name, obj, skip, options): doc = True if obj.__doc__ is not None else False exclude = name in exclusions or 'trait' in name or name.startswith('_') or not doc return skip or exclude def shorter_signature(app, what, name, obj, options, signature, return_annotation): """ Prevent displaying self in signature. """ if what == 'data': signature = '(dataset)' what = 'function' if what not in ('function', 'method', 'class', 'data') or signature is None: return import re new_sig = signature if inspect.isfunction(obj) or inspect.isclass(obj) or inspect.ismethod(obj): sig_obj = obj if not inspect.isclass(obj) else obj.__init__ sig_re = r'\((self|cls)?,?\s*(.*?)\)\:' try: new_sig = ' '.join(re.search(sig_re, inspect.getsource(sig_obj), re.S).group(2).replace('\n', '').split()) except Exception as e: print(sig_obj) raise e new_sig = '(' + new_sig + ')' return new_sig, return_annotation # %% def setup(app): app.connect('autodoc-skip-member', autodoc_skip_member) app.connect('autodoc-process-signature', shorter_signature) app.add_stylesheet("theme_override.css") # also can be a full URL <file_sep>/docs/userguide/processing/fourier2d.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # cell_metadata_filter: title,-all # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Two-dimensional (2D) Fourier transformation # %% import spectrochempy as scp # %% [markdown] # Additional import to simplify the use of units # %% from spectrochempy import ur # %% [markdown] # ## Processing of NMR dataset with hypercomplex detection (phase-senitive) # %% [markdown] # As a first example, we will process a 2D HMQC spectrum which has been acquired using a phase sensitive detection # method : STATES-TPPI encoding. The STATES (States, Ruben, Haberkorn) produce an hypercomplex dataset which need to # be processed in a specific way, that SpectroChemPy handle automatically. TPPI (for Time Proportinal Phase # Increment) is also handled. # %% path = scp.preferences.datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'topspin_2d' ser = scp.read_topspin(path, expno=1) ser # %% [markdown] # Change of some plotting preferences # %% prefs = ser.preferences prefs.figure.figsize = (7, 3) prefs.contour_start = 0.05 # %% [markdown] # and now plotting of contours using `plot_map`. # %% _ = ser.plot_map() # %% [markdown] # ### Processing steps # # * Optional : Apply some broadening by apodization in the time domain. # * Optional : DC correction in the time domain. # * Optional : Zero-filling. # * Fourier transform in the F2 (x) dimension. # * Phase the first transformed dimension in the frequency domain. # * Optional: Apply some apodization in the time domain for the F1 (y) dimension. # * Optional: DC Correction in F1. # * Optional: Zero-filling. # * Fourier transform the second dimension F1. # * Phase correct the second transformed dimension in the frequency domain. # # # %% [markdown] # ### Apodization, DC correction, Zero-filling # %% [markdown] # For this step we can first extract and Fourier transformation of the first row (row index:0). # %% row0 = ser[0] _ = row0.plot() # %% [markdown] # We can zoom to have a better look at the echo (with the imaginary component) # %% _ = row0.plot(show_complex=True, xlim=(0, 10000)) # %% [markdown] # Now we will perform the processing of the first row and adjust the parameters for apodization, zero-filling, etc... # %% row0 = ser[0] row0.dc(inplace=True) # DC corrrection row0.zf_size(size=2048, inplace=True) # zero-filling (size parameter can be approximate as the FFT will # anyway complete the zero-filling to next power of 2.) shifted = row0.coordmax() # find the top of the echo # %% newrow, apod = row0.em(lb=20 * ur.Hz, shifted=shifted, retapod=True) # retapod: return the apod array along with the apodized dataset newrow.plot() apod.plot(clear=False, xlim=(0, 20000), c='red') f0 = newrow.fft() # fourier transform _ = f0.plot(show_complex=True) # %% [markdown] # Once we have found correct parameters for correcting the first row, we can apply them for the whole 2D dataset in # the F2 dimension (the default dimension, so no need to specify this in the following methods) # %% sert = ser.dc() # DC correction sert.zf_size(size=2048, inplace=True) # zero-filling sert.em(lb=20 * ur.Hz, shifted=shifted, inplace=True) # shifted was set in the previous step _ = sert.plot_map() # %% [markdown] # Transform in F2 # %% spec = sert.fft() _ = spec.plot_map(); # %% [markdown] # Now we can process the F1 dimension ('y') # %% spect = spec.zf_size(size=512, dim='y') spect.em(lb=10 * ur.Hz, inplace=True, dim='y') s = spect.fft(dim='y') prefs.contour_start = 0.12 _ = s.plot_map() # %% [markdown] # Here is an expansion: # %% spk = s.pk(phc0=0, dim='y') _ = spk.plot_map(xlim=(50, 0), ylim=(-40, -15)) # %% [markdown] # ## Processing of an Echo-AntiEcho encoded dataset # %% [markdown] # In this second example, we will process a HSQC spectrum of Cyclosporin wich has been acquired using a Rance-Kay # quadrature scheme, also known as Echo-Antiecho. (The original data is extracted from the examples of the Bruker # Topspin software). # %% path = scp.preferences.datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'exam2d_HC' ser = scp.read_topspin(path) prefs = ser.preferences prefs.figure.figsize = (7, 3) ser.shape # %% sert = ser.dc() sert.sp(ssb=2, inplace=True) # Sine apodization s2 = sert.fft(1024) s2.pk(phc0=-90, inplace=True) # phasing _ = s2[0].plot() ex = (3.5, 2.5) _ = s2[0].plot(xlim=ex) # %% s2.sp(ssb=2, dim='y', inplace=True); # Sine apodization in the y dimension # %% ey = (20, 45) prefs.contour_start = 0.07 s = s2.fft(256, dim='y') s = s.pk(phc0=-40, dim='y') s = s.pk(phc0=-5, rel=True) _ = s.plot_map(xlim=ex, ylim=ey) _ = s.plot_map() # %% [markdown] # ## Processing a QF encoded file # %% path = scp.preferences.datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'exam2d_HH' ser = scp.read_topspin(path) prefs = ser.preferences ser.plot_map() ser.dtype # %% sert = ser.dc() sert.sp(ssb=2, inplace=True) # Sine apodization s2 = sert.fft(1024) s3 = s2.pk(phc0=-140, phc1=95) _ = s3[0].plot() # %% s3.sp(ssb=0, dim='y', inplace=True); # Sine apodization in the y dimension # %% ey = (20, 45) s = s3.fft(256, dim='y') sa = s.abs() prefs.contour_start = 0.005 prefs.show_projections = True prefs.figure.figsize = (7, 7) _ = sa.plot_map() <file_sep>/tests/test_readers_writers/test_read_quadera.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy import NDDataset # ...................................................................................................................... def test_read_quadera(): # single file A = NDDataset.read_quadera('msdata/ion_currents.asc') assert str(A) == 'NDDataset: [float64] A (shape: (y:16975, x:10))' <file_sep>/docs/gettingstarted/examples/analysis/plot_pca_spec.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ NDDataset PCA analysis example ------------------------------- In this example, we perform the PCA dimensionality reduction of a spectra dataset """ import spectrochempy as scp ############################################################ # Load a dataset dataset = scp.read_omnic("irdata/nh4y-activation.spg") print(dataset) dataset.plot_stack() ############################################################## # Create a PCA object pca = scp.PCA(dataset, centered=False) ############################################################## # Reduce the dataset to a lower dimensionality (number of # components is automatically determined) S, LT = pca.reduce(n_pc=.99) print(LT) ############################################################### # Finally, display the results graphically # ScreePlot _ = pca.screeplot() ######################################################################################################################## # Score Plot _ = pca.scoreplot(1, 2) ######################################################################################################################## # Score Plot for 3 PC's in 3D _ = pca.scoreplot(1, 2, 3) ############################################################################## # Displays the 4-first loadings LT[:4].plot_stack() # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/spectrochempy/core/processors/baseline.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements the `BaselineCorrection` class for baseline corrections. """ __all__ = ['BaselineCorrection', 'ab', 'abc', 'dc', 'basc'] __dataset_methods__ = ['ab', 'abc', 'dc', 'basc'] import numpy as np import scipy.interpolate from traitlets import Int, Instance, HasTraits, Float, Unicode, Tuple, List from matplotlib.widgets import SpanSelector import matplotlib.pyplot as plt from ..dataset.coordrange import trim_ranges from ..plotters.multiplot import multiplot from ..dataset.nddataset import NDDataset from ...utils import TYPE_INTEGER, TYPE_FLOAT from .smooth import smooth from .. import debug_, warning_ from spectrochempy.core.processors.utils import _units_agnostic_method class BaselineCorrection(HasTraits): """ Baseline Correction processor. 2 methods are proposed : * ``sequential`` (default) = classical polynom fit or spline interpolation with separate fitting of each row (spectrum) * ``multivariate`` = SVD modeling of baseline, polynomial fit of PC's and calculation of the modelled baseline spectra. Interactive mode is proposed using the interactive function : :meth:`run`. Parameters ---------- dataset : |NDDataset| The dataset to be transformed. See Also -------- abc : Automatic baseline correction. Examples -------- .. plot:: :include-source: from spectrochempy import * nd = NDDataset.read_omnic(os.path.join('irdata', 'nh4y-activation.spg')) ndp = nd[:, 1291.0:5999.0] bc = BaselineCorrection(ndp) ranges=[[5996., 5998.], [1290., 1300.], [2205., 2301.], [5380., 5979.], [3736., 5125.]] span = bc.compute(*ranges,method='multivariate', interpolation='pchip', npc=8) _ = bc.corrected.plot_stack() show() """ dataset = Instance(NDDataset) corrected = Instance(NDDataset) method = Unicode('sequential') interpolation = Unicode('pchip') axis = Int(-1) dim = Unicode('') order = Int(6, min=1, allow_none=True) npc = Int(5, min=1, allow_none=True) zoompreview = Float(1.) figsize = Tuple((7, 5)) sps = List() # .................................................................................................................. def __init__(self, dataset, *args, **kwargs): self.dataset = dataset self.corrected = self.dataset.copy() if args or kwargs: warning_("DEPRECATION WARNING: Pass all arguments such range, and method definition in the " "``compute`` method, not during the initialisation of the BaselineCorrection instance.\n" "Here they are ignored.") # .................................................................................................................. def _extendranges(self, *ranges, **kwargs): if not ranges: # look in the kwargs ranges = kwargs.pop('ranges', ()) if isinstance(ranges, tuple) and len(ranges) == 1: ranges = ranges[0] # probably passed with no start to the compute function if not isinstance(ranges, (list, tuple)): ranges = list(ranges) if not ranges: return if len(ranges) == 2: if (isinstance(ranges[0], TYPE_INTEGER + TYPE_FLOAT) and isinstance(ranges[1], TYPE_INTEGER + TYPE_FLOAT)): # a pair a values, we intepret this as a single range ranges = [[ranges[0], ranges[1]]] # find the single values for item in ranges: if isinstance(item, TYPE_INTEGER + TYPE_FLOAT): # a single numerical value: intepret this as a single range item = [item, item] self.ranges.append(item) # .................................................................................................................. def _setup(self, **kwargs): self.method = kwargs.get('method', self.method) self.interpolation = kwargs.get('interpolation', self.interpolation) if self.interpolation == 'polynomial': self.order = int(kwargs.get('order', self.order)) if self.method == 'multivariate': self.npc = int(kwargs.get('npc', self.npc)) self.zoompreview = kwargs.get('zoompreview', self.zoompreview) self.figsize = kwargs.get('figsize', self.figsize) # .................................................................................................................. def __call__(self, *ranges, **kwargs): return self.compute(*ranges, **kwargs) # .................................................................................................................. def compute(self, *ranges, **kwargs): """ Base function for dataset baseline correction. Parameters ---------- *ranges : a variable number of pair-tuples The regions taken into account for the manual baseline correction. **kwargs : dict See other parameters. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x'. Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. method : str, keyword parameter, optional, default='sequential' Correction method among ['multivariate','sequential'] interpolation : string, keyword parameter, optional, default='polynomial' Interpolation method for the computation of the baseline, among ['polynomial','pchip'] order : int, keyword parameter, optional, default=6 If the correction method polynomial, this give the polynomial order to use. npc : int, keyword parameter, optional, default=5 Number of components to keep for the ``multivariate`` method zoompreview : float, keyword parameter, optional, default=1.0 The zoom factor for the preview in interactive mode figsize : tuple, keyword parameter, optional, default=(8, 6) Size of the figure to display in inch """ self._setup(**kwargs) # output dataset new = self.corrected # we assume that the last dimension if always the dimension to which we want to subtract the baseline. # Swap the axes to be sure to be in this situation axis, dim = new.get_axis(**kwargs, negative_axis=True) swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) swaped = True lastcoord = new.coordset[dim] # most of the time we need sorted axis, so let's do it now is_sorted = False if lastcoord.reversed: new.sort(dim=dim, inplace=True, descend=False) is_sorted = True lastcoord = new.coordset[dim] x = lastcoord.data self.ranges = [[x[0], x[2]], [x[-3], x[-1]]] self._extendranges(*ranges, **kwargs) self.ranges = ranges = trim_ranges(*self.ranges) baseline = np.zeros_like(new) # Extract: Sbase: the matrix of data corresponding to ranges # xbase: the xaxis values corresponding to ranges s = [] for pair in ranges: # determine the slices sl = slice(*pair) sect = new[..., sl] if sect is None: continue s.append(sect) sbase = NDDataset.concatenate(s, axis=-1) # TODO: probably we could use masked data instead of concatenating - could be faster xbase = sbase.coordset(dim) if self.method == 'sequential': if self.interpolation == 'polynomial': # bad fit when NaN values => are replaced by 0 if np.any(np.isnan(sbase)): sbase[np.isnan(sbase)] = 0 polycoef = np.polynomial.polynomial.polyfit(xbase.data, sbase.data.T, deg=self.order, rcond=None, full=False) baseline = np.polynomial.polynomial.polyval(x, polycoef) elif self.interpolation == 'pchip': for i in range(new.shape[0]): interp = scipy.interpolate.PchipInterpolator(xbase.data, sbase.data[i]) baseline[i] = interp(x) elif self.method == 'multivariate': # SVD of Sbase U, s, Vt = np.linalg.svd(sbase.data, full_matrices=False, compute_uv=True) # npc cannot be higher than the size of s npc = min(self.npc, s.shape[0]) # select npc loadings & compute scores Pt = (Vt[0:npc]) T = np.dot(U[:, 0:npc], np.diag(s)[0:npc, 0:npc]) baseline_loadings = np.zeros((npc, new.shape[-1])) if self.interpolation == 'pchip': for i in range(npc): interp = scipy.interpolate.PchipInterpolator(xbase.data, Pt[i]) baseline_loadings[i] = interp(x) elif self.interpolation == 'polynomial': polycoef = np.polynomial.polynomial.polyfit(xbase.data, Pt.T, deg=self.order, rcond=None, full=False) baseline_loadings = np.polynomial.polynomial.polyval(x, polycoef) baseline = np.dot(T, baseline_loadings) new.data = new.data - baseline # eventually sort back to the original order if is_sorted: new.sort(axis=-1, inplace=True, descend=True) new.history = str(new.modified) + ': ' + 'Baseline correction.' + ' Method: ' if self.method == 'Multivariate': new.history = 'Multivariate (' + str(self.npc) + ' PCs).' else: new.history = 'Sequential.' if self.interpolation == 'polynomial': new.history = 'Interpolation: Polynomial, order=' + str(self.order) + '.\n' else: new.history = 'Interpolation: Pchip. \n' if swaped: new = new.swapdims(axis, -1) self.corrected = new return new # .................................................................................................................. def show_regions(self, ax): if self.sps: for sp in self.sps: sp.remove() self.sps = [] self.ranges = list(trim_ranges(*self.ranges)) for x in self.ranges: x.sort() sp = ax.axvspan(x[0], x[1], facecolor='#2ca02c', alpha=0.5) self.sps.append(sp) # .................................................................................................................. def run(self, *ranges, **kwargs): """ Interactive version of the baseline correction. Parameters ---------- *ranges : a variable number of pair-tuples The regions taken into account for the manual baseline correction. **kwargs : dict See other parameter of method compute. """ self._setup(**kwargs) self.sps = [] # output dataset new = self.corrected origin = self.dataset.copy() # we assume that the last dimension if always the dimension to which we want to subtract the baseline. # Swap the axes to be sure to be in this situation axis, dim = new.get_axis(**kwargs, negative_axis=True) swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) origin.swapdims(axis, -1, inplace=True) swaped = True lastcoord = new.coordset[dim] # most of the time we need sorted axis, so let's do it now if lastcoord.reversed: new.sort(dim=dim, inplace=True, descend=False) lastcoord = new.coordset[dim] x = lastcoord.data self.ranges = [[x[0], x[2]], [x[-3], x[-1]]] self._extendranges(*ranges, **kwargs) self.ranges = ranges = trim_ranges(*self.ranges) new = self.compute(*ranges, **kwargs) # display datasets = [origin, new] labels = ['Click on left button & Span to set regions. Click on right button on a region to remove it.', 'Baseline corrected dataset preview'] axes = multiplot(datasets, labels, method='stack', sharex=True, nrow=2, ncol=1, figsize=self.figsize, suptitle='INTERACTIVE BASELINE CORRECTION') fig = plt.gcf() fig.canvas.draw() ax1 = axes['axe11'] ax2 = axes['axe21'] self.show_regions(ax1) def show_basecor(ax2): corrected = self.compute(*ranges, **kwargs) ax2.clear() ax2.set_title('Baseline corrected dataset preview', fontweight='bold', fontsize=8) if self.zoompreview > 1: zb = 1. # self.zoompreview zlim = [corrected.data.min() / zb, corrected.data.max() / zb] _ = corrected.plot_stack(ax=ax2, colorbar=False, zlim=zlim, clear=False) else: _ = corrected.plot_stack(ax=ax2, colorbar=False, clear=False) show_basecor(ax2) def onselect(xmin, xmax): self.ranges.append([xmin, xmax]) self.show_regions(ax1) show_basecor(ax2) fig.canvas.draw() def onclick(event): if event.button == 3: for i, r in enumerate(self.ranges): if r[0] > event.xdata or r[1] < event.xdata: continue else: self.ranges.remove(r) self.show_regions(ax1) show_basecor(ax2) fig.canvas.draw() # _idle _ = fig.canvas.mpl_connect('button_press_event', onclick) _ = SpanSelector(ax1, onselect, 'horizontal', minspan=5, button=[1], useblit=True, rectprops=dict(alpha=0.5, facecolor='blue')) fig.canvas.draw() return # ...................................................................................................................... def basc(dataset, *ranges, **kwargs): """ Compute a baseline correction using the BaselineCorrection processor. 2 methods are proposed : * ``sequential`` (default) = classical polynom fit or spline interpolation with separate fitting of each row (spectrum) * ``multivariate`` = SVD modeling of baseline, polynomial fit of PC's and calculation of the modelled baseline spectra. Parameters ---------- dataset : a [NDDataset| instance The dataset where to calculate the baseline. *ranges : a variable number of pair-tuples The regions taken into account for the manual baseline correction. **kwargs : dict See other parameters. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x'. Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. method : str, keyword parameter, optional, default='sequential' Correction method among ['multivariate','sequential'] interpolation : string, keyword parameter, optional, default='polynomial' Interpolation method for the computation of the baseline, among ['polynomial','pchip'] order : int, keyword parameter, optional, default=6 If the correction method polynomial, this give the polynomial order to use. npc : int, keyword parameter, optional, default=5 Number of components to keep for the ``multivariate`` method See Also -------- BaselineCorrection : Manual baseline corrections. abc : Automatic baseline correction. Notes ----- For more flexibility and functionality, it is advised to use the BaselineCorrection processor instead. Examples -------- .. plot:: :include-source: import spectrochempy as scp nd = scp.read('irdata/nh4y-activation.spg') ndp = nd[:, 1291.0:5999.0] ranges=[[5996., 5998.], [1290., 1300.], [2205., 2301.], [5380., 5979.], [3736., 5125.]] ndcorr = spc.basc(ndp, *ranges,method='multivariate', interpolation='pchip', npc=8) ndcorr.plot() spc.show() """ blc = BaselineCorrection(dataset) return blc.compute(*ranges, **kwargs) # ====================================================================================================================== # abc # TODO: some work to perform on this # ====================================================================================================================== def abc(dataset, dim=-1, **kwargs): """ Automatic baseline correction. Various algorithms are provided to calculate the baseline automatically. Parameters ---------- dataset : a [NDDataset| instance The dataset where to calculate the baseline. dim : str or int, optional The dataset dimentsion where to calculate the baseline. Default is -1. **kwargs : dict See other parameters. Returns ------- baseline_corrected A baseline corrected dataset. baseline_only Only the baseline (apply must be set to False). baseline_points Points where the baseline is calculated (return_points must be set to True). Other Parameters ---------------- basetype : string, optional, default: 'linear' See notes - available = linear, basf, ... window : float/int, optional, default is 0.05 If float <1 then the corresponding percentage ot the axis size is taken as window. nbzone : int, optional, default is 32 Number of zones. We will divide the size of the last axis by this number to determine the number of points in each zone (nw). mult : int A multiplicator. determine the number of point for the database calculation (nw*mult<n base points). nstd : int, optional, default is 2 times the standard error Another multiplicator. Multiply the standard error to determine the region in which points are from the baseline. polynom : bool, optional, default is True If True a polynom is computed for the base line, else an interpolation is achieved betwwen points. porder : int, default is 6 Order of the polynom to fit on the baseline points return_points : bool, optional, default is False If True, the points abscissa used to determine the baseline are returned. apply : bool, optional, default is True If apply is False, the data are not modified only the baseline is returned. return_pts : bool, optional, default is False If True, the baseline reference points are returned. See Also -------- BaselineCorrection : Manual baseline corrections. basc : Manual baseline correction. Notes ----- #TODO: description of these algorithms * linear - * basf - Examples -------- To be done """ # # options evaluation # parser = argparse.ArgumentParser(description='BC processing.', usage=""" # ab [-h] [--mode {linear,poly, svd}] [--dryrun] # [--window WINDOW] [--step STEP] [--nbzone NBZONE] # [--mult MULT] [--order ORDER] [--verbose] # """) # # positional arguments # parser.add_argument('--mode', '-mo', default='linear', # choices=['linear', 'poly', 'svd'], help="mode of correction") # parser.add_argument('--dryrun', action='store_true', help='dry flag') # # parser.add_argument('--window', '-wi', default=0.05, type=float, help='selected window for linear and svd bc') # parser.add_argument('--step', '-st', default=5, type=int, help='step for svd bc') # parser.add_argument('--nbzone', '-nz', default=32, type=int, help='number of zone for poly') # parser.add_argument('--mult', '-mt', default=4, type=int, help='multiplicator of zone for poly') # parser.add_argument('--order', '-or', default=5, type=int, help='polynom order for poly') # # parser.add_argument('--verbose', action='store_true', help='verbose flag') # args = parser.parse_args(options.split()) # # source.history.append('baseline correction mode:%s' % args.mode) debug_('Automatic baseline correction') inplace = kwargs.pop('inplace', False) dryrun = kwargs.pop('dryrun', False) # output dataset inplace or not if not inplace or dryrun: # default new = dataset.copy() else: new = dataset axis, dim = new.get_axis(dim, negative_axis=True) swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) # must be done in place swaped = True base = _basecor(new.data.real, **kwargs) if not dryrun: new.data -= base # return the corrected spectra else: new.data = base # return the baseline # restore original data order if it was swaped if swaped: new.swapdims(axis, -1, inplace=True) # must be done inplace return new # ...................................................................................................................... def ab(dataset, dim=-1, **kwargs): """ Alias of `abc` """ return abs(dataset, dim, **kwargs) # ...................................................................................................................... @_units_agnostic_method def dc(dataset, **kwargs): """ Time domain baseline correction Parameters ---------- dataset : nddataset The time domain daatset to be corrected. kwargs : dict, optional additional parameters. Returns ------- dc DC corrected array. Other Parameters ---------------- len : float, optional Proportion in percent of the data at the end of the dataset to take into account. By default, 25%. """ len = int(kwargs.pop('len', .25) * dataset.shape[-1]) dc = np.mean(np.atleast_2d(dataset)[..., -len:]) dataset -= dc return dataset # ======================================================================================================================= # private functions # ======================================================================================================================= def _basecor(data, **kwargs): mode = kwargs.pop('mode', 'linear') if mode == 'linear': return _linearbase(data, **kwargs) if mode == 'svd': return _svdbase(data, **kwargs) if mode == 'poly': return _polybase(data, **kwargs) else: raise ValueError(f'`ab` mode = `{mode}` not known') # # _linear mode # def _linearbase(data, **kwargs): # Apply a linear baseline correction # Very simple and naive procedure that compute a straight baseline from side to the other # (averging on a window given by the window parameters : 5% of the total width on each side by default) window = kwargs.pop('window', 0.05) if window <= 1.0: # percent window = int(data.shape[-1] * window) debug_(f"Linear base correction window : {window}") if len(data.shape) == 1: npts = float(data.shape[-1]) a = (data[-window:].mean() - data[:window].mean()) / (npts - 1.) b = data[:window].mean() baseline = a * np.arange(npts) + b else: npts = float(data.shape[-1]) a = (data[:, -window:].mean(axis=-1) - data[:, :window].mean(axis=-1)) / (npts - 1.) b = data[:, :window].mean(axis=-1) baseline = (((np.ones_like(data).T * a).T * np.arange(float(npts))).T + b).T return baseline def _planeFit(points): # p, n = planeFit(points) # copied from https://stackoverflow.com/a/18968498 # # Fit an multi-dimensional plane to the points. # Return a point on the plane and the normal. # # Parameters # ---------- # points : # # Notes # ----- # Replace the nonlinear optimization with an SVD. # The following creates the moment of inertia tensor, M, and then # SVD's it to get the normal to the plane. # This should be a close approximation to the least-squares fit # and be much faster and more predictable. # It returns the point-cloud center and the normal. from numpy.linalg import svd npts = points.shape[0] points = np.reshape(points, (npts, -1)) assert points.shape[0] < points.shape[1] ctr = points.mean(axis=1) x = points - ctr[:, None] M = np.dot(x, x.T) return ctr, svd(M)[0][:, -1] def _svdbase(data, args=None, retw=False): # Apply a planar baseline correction to 2D data import pandas as pd # TODO: suppress this need if not args: window = 0.05 step = 5 else: window = args.window step = args.step if window <= 1.0: # percent window = int(data.shape[-1] * window) data = pd.DataFrame(data) # TODO: facilitate the manipulation (but to think about further) a = pd.concat([data.iloc[:window], data.iloc[-window:]]) b = pd.concat([data.iloc[window:-window, :window], data.iloc[window:-window, -window:]], axis=1) bs = pd.concat([a, b]) bs = bs.stack() bs.sort() x = [] y = [] z = [] for item in bs.index[::step]: x.append(item[0]) y.append(item[1]) z.append(bs[item].real) norm = np.max(np.abs(z)) z = np.array(z) z = z / norm XYZ = np.array((x, y, z)) p, n = _planeFit(XYZ) d = np.dot(p, n) debug_(" origin baseline plane: ", p) debug_(" normal vector component:", n) col = data.columns row = data.index X, Y = np.meshgrid(col, row) Z = -norm * (n[0] * X + n[1] * Y - d) / n[2] if retw: return Z, None # TODO: return something return Z def _polybase(data, **kwargs): # Automatic baseline correction if data.ndim == 1: dat = np.array([data, ]) nbzone = kwargs.pop('nbzone', 64) mult = kwargs.pop('mult', 4) order = kwargs.pop('order', 6) npts = data.shape[-1] w = np.arange(npts) baseline = np.ma.masked_array(dat, mask=True) sigma = 1.e6 nw = int(npts / nbzone) # print (nw) # unmask extremities of the baseline baseline[:, :nw].mask = False baseline[:, -nw:].mask = False for j in range(nbzone): s = dat[:, nw * j:min(nw * (j + 1), npts + 1)] sigma = min(s.std(), sigma) nw = nw * 2 # bigger window nw2 = int(nw / 2) found = False nb = 0 nstd = 2. while (not found) or (nb < nw * mult): nb = 0 for i in range(nw2, npts - nw2 + 1, 1): s1 = dat[:, max(i - 1 - nw2, 0):min(i - 1 + nw2, npts + 1)] s2 = dat[:, max(i - nw2, 0):min(i + nw2, npts + 1)] s3 = dat[:, max(i + 1 - nw2, 0):min(i + 1 + nw2, npts + 1)] mi1, mi2, mi3 = s1.min(), s2.min(), s3.min() ma1, ma2, ma3 = s1.max(), s2.max(), s3.max() if abs(ma1 - mi1) < float(nstd) * sigma and abs(ma2 - mi2) < float(nstd) * sigma and abs(ma3 - mi3) < float( nstd) * sigma: found = True nb += 1 baseline[:1, i].mask = False # baseline points # increase nstd nstd = nstd * 1.1 debug_('basf optimized nstd: %.2F mult: %.2f' % (nstd, mult)) wm = np.array(list(zip(*np.argwhere(~baseline[:1].mask)))[1]) bm = baseline[:, wm] if data.ndim > 1: bm = smooth(bm.T, length=max(int(dat.shape[0] / 10), 3)).T bm = smooth(bm, length=max(int(dat.shape[-1] / 10), 3)) # if not polynom: # sr = pchip(wm, bm.real) # si = pchip(wm, bm.imag) # baseline = sr(w) + si(w) * 1.0j # baseline = smooth(baseline, window_len=int(nw / 4)) # else: # fit a polynom pf = np.polyfit(wm, bm.T, order).T for i, row in enumerate(pf[:]): poly = np.poly1d(row) baseline[i] = poly(w) if data.ndim == 1: baseline = baseline[0] return baseline if __name__ == '__main__': pass <file_sep>/docs/userguide/importexport/importIR.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # cell_metadata_json: true # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.0 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Import IR Data # # This tutorial shows the specifics related to infrared data import in Spectrochempy. As prerequisite, the user is # expected to have read the [Import Tutorial](Import.ipynb). # # Let's first import spectrochempy: # %% import spectrochempy as scp # %% [markdown] # ## Supported file formats # # At the time of writing of this tutorial (Scpy v.0.1.18), spectrochempy has the following readers which are specific # to IR data: # # - `read_omnic()` to open omnic (spa and spg) files # - `read_opus()` to open Opus (*.0, ...) files # - `read_jcamp()` to open an IR JCAMP-DX datafile # - `read()` which is the generic reader. The type of data is then deduced from the file extension. # # General purpose data exchange formats such as \*.csv or \*.mat will be treated in another tutorial (yet to come...) # can also be read using: # # - `read_csv()` to open csv files # - `read_matlab()` to open .mat files # # ## Import of OMNIC files # # [Thermo Scientific OMNIC](https://www.thermofisher.com/search/browse/category/us/fr/602580/FTIR%2C+NIR+%26amp%3B+Raman+Software+%26amp%3B+Libraries) # noqa: E501 # software have two proprietary binary file formats: # - .spa files that handle single spectra # - .spg files which contain a group of spectra # # Both have been reverse engineered, hence allowing extracting their key data. The Omnic reader of # Spectrochempy (`read_omnic()`) has been developed based on posts in open forums on the .spa # file format and extended to .spg file formats. # # # ### a) import spg file # # Let's import an .spg file from the `datadir` (see [Import Tutorial](Import.ipynb)) and display # its main attributes: # %% {"pycharm": {"name": "#%%\n"}} X = scp.read_omnic('irdata/CO@Mo_Al2O3.SPG') X # %% [markdown] # The displayed attibutes are detailed in the following. # # - `name` is the name of the group of spectra as it appears in the .spg file. OMNIC sets this name to the .spg # filename used at the creation of the group. In this example, the name ("Group sust Mo_Al2O3_base line.SPG") differs # from the filemane ("CO@Mo_Al2O3.SPG") because the latter has been changed from outside OMNIC (directly in the OS). # # - `author` is that of the creator of the NDDataset (not of the .spg file, which, to our knowledge, does not have # this type of attribute). The string is composed of the username and of the machine name as given by the OS: # username@machinename. It can be accessed and changed using `X.author` # # - `created` is the creation date of the NDDataset (again not that of the .spg file). It can be accessed (or even # changed) using `X.created` # # - `description` indicates the complete pathname of the .spg file. As the pathname is also given in the history (below) # , it can be a good practice to give a self explaining description of the group, for instance: # %% X.description = 'CO adsorption on CoMo/Al2O3, difference spectra' X.description # %% [markdown] # or directly at the import: # %% X = scp.read_omnic('irdata//CO@Mo_Al2O3.SPG', description='CO@CoMo/Al2O3, diff spectra') X.description # %% [markdown] # - `history` records changes made to the dataset. Here, right after its creation, it has been sorted by date # (see below). # # Then come the attributes related to the data themselves: # # - `title` (not to be confused with the `name` of the dataset) describes the nature of data (here **absorbance**) # # - `values` shows the data as quantity (with their units when they exist - here a.u. for absorbance units). # # - The numerical values ar accessed through the`data` attribute and the units throught `units` attribute. # %% X.values # %% X.data # %% X.units # TODO: correct this display # %% [markdown] # - `shape` is the same as the ndarray `shape` attribute and gives the shape of the data array, here 19 x 3112. # # Then come the attributes related to the dimensions of the dataset. # # - `x`: this dimension has one coordinate (a `Coord` object) made of the 3112 the wavenumbers. # %% print(X.x) X.x # %% [markdown] # - `y`: this dimension contains: # # - one coordinate made of the 19 acquisition timestamps # - two labels # - the acquision date (UTC) of each spectrum # - the name of each spectrum. # %% print(X.y) X.y # %% [markdown] # - `dims`: Note that the `x` and `y` dimensions are the second and first dimension respectively. Hence, `X[i, # j]` will return # the absorbance of the ith spectrum at the jth wavenumber. However, this is subject to change, for instance if you # perform ooperation on you data such as [Transposition](../processing/transformations#Transposition). At any time # the attribute `dims`gives the correct names (which can be modified) and order of the dimensions. # %% X.dims # %% [markdown] # #### Acquisition dates and `y` axis # # The acquisition timestamps are the *Unix times* of the acquisition, i.e. the time elapsed in seconds since the # reference date of Jan 1st 1970, 00:00:00 UTC. # %% X.y.values # %% [markdown] # In OMNIC, the acquisition time is that of the start of the acquisison. # As such these may be not convenient to use directly (they are currently in the order of 1.5 billion...) # With this respect, it can be convenient to shift the origin of time coordinate to that of the 1st spectrum, # which has the index `0`: # %% X.y = X.y - X.y[0] X.y.values # %% [markdown] # Note that you can also use the inplace subtract operator to perform the same operation. # %% X.y -= X.y[0] # %% [markdown] # It is also possible to use the ability of SpectroChemPy to handle unit changes. For this one can use the `to` or # `ito` ( # inplace) methods. # ```ipython3 # val = val.to(some_units) # val.ito(some_units) # the same inplace # ``` # %% X.y.ito("minute") X.y.values # %% [markdown] # As shown above, the values of the `Coord` object are accessed through the `values` attribute. To get the last # values corresponding to the last row of the `X` dataset, you can use: # %% tf = X.y.values[-1] tf # %% [markdown] # Negative index in python indicates the position in a sequence from the end, so -1 indicate the last element. # %% [markdown] # Finally, if for instance you want the `x` time axis to be shifted by 2 minutes, it is also very easy to do so: # %% X.y = X.y + 2 X.y.values # %% [markdown] # or using the inplace add operator: # ```ipython3 # X.y += 2 # ``` # %% [markdown] # #### The order of spectra # # The order of spectra in OMNIC .spg files depends depends on the order in which the spectra were included in the OMNIC # window before the group was saved. By default, sepctrochempy reorders the spectra by acquisistion date but the # original OMNIC order can be kept using the `sortbydate=True` at the function call. For instance: # %% X2 = scp.read_omnic('irdata/CO@Mo_Al2O3.SPG', sortbydate=False) # %% [markdown] # In the present case this will not change nothing because the spectra in the OMNIC file wre already ordered by # increasing data. # # Finally, it is worth mentioning that a `NDDataset` can generally be manipulated as numpy ndarray. Hence, for # instance, the following will inverse the order of the first dimension: # %% X = X[::-1] # reorders the NDDataset along the first dimension going backward X.y.values # displays the `y` dimension # %% [markdown] # <div class='alert alert-info'> # <b>Note</b> # # **Case of groups with different wavenumbers**<br/> # An OMNIC .spg file can contain spectra having different wavenumber axes (e.g. different spacings or wavenumber # ranges). In its current implementation, the spg reader will purposedly return an error because such spectra # *cannot* be included in a single NDdataset which, by definition, contains items that share common axes or dimensions ! # Future releases might include an option to deal with such a case and return a list of NDDasets. Let us know if you # are interested in such a feature, see [Bug reports and enhancement requests] # (https://www.spectrochempy.fr/dev/dev/issues.html). # # %% [markdown] # ### b) Import of .spa files # # The import of a single spectrum follows exactly the same rules as that of the import of a group: # %% Y = scp.read_omnic('irdata/subdir/7_CZ0-100 Pd_101.SPA') Y # %% [markdown] # The omnic reader can also import several spa files together, providing that they share a common axis for the # wavenumbers. This is the case of the following files in the irdata/subdir directory: "7_CZ0-100 Pd_101.SPA", ..., # "7_CZ0-100 Pd_104.spa". It is possible to import them in a single NDDataset by using the list of filenames # in the function call: # %% list_files = ["7_CZ0-100 Pd_101.SPA", "7_CZ0-100 Pd_102.SPA", "7_CZ0-100 Pd_103.SPA", "7_CZ0-100 Pd_104.SPA"] X = scp.read_omnic(list_files, directory='irdata/subdir') print(X) # %% [markdown] # In such a case ase these .spa files are alone in the directory, a very convenient is to call the read_omnic method # using only the directory path as argument that will gather the .spa files together: # %% X = scp.read_omnic('irdata/subdir') print(X) # %% [markdown] # <div class='alert alert-warning'> # <b>Warning</b> # # There is a difference in specifiying the directory to read as an argument as above or as a keyword like here: # ```ipython3 # X = scp.read_omnic(directory='irdata/subdir') # ``` # in the latter case, a **dialog** is opened to select files in the given directory, while in the former, # the file are read silently and concatenated (if possible). # </div> # %% [markdown] {"pycharm": {"name": "#%% md\n"}} # ## Import of Bruker OPUS files # # [Bruker OPUS](https://www.bruker.com/products/infrared-near-infrared-and-raman-spectroscopy/ # opus-spectroscopy-software.html) files have also a proprietary file format. The Opus reader (`read_opus()`) # of spectrochempy is essentially a wrapper of the python module # [brukeropusreader](https://github.com/spectrochempy/brukeropusreader) developed by QED. It imports absorbance # spectra (the AB block), acquisition times and name of spectra. # # The use of `read_opus()` is similar to that of `read_omnic()` for .spa files. Hence, one can open sample # Opus files contained in the `datadir` using: # %% Z = scp.read_opus(['test.0000', 'test.0001', 'test.0002'], directory='irdata/OPUS') print(Z) # %% [markdown] # or: # %% Z2 = scp.read_opus('irdata/OPUS') print(Z2) # %% [markdown] # Note that supplementary informations can be obtained by the direct use of # `brukeropusreader`. For instance: # %% from brukeropusreader import read_file # noqa: E402 opusfile = scp.DATADIR / "irdata" / "OPUS" / "test.0000" # the full pathn of the file Z3 = read_file(opusfile) # returns a dictionary of the data and metadata extracted for key in Z3: print(key) # %% Z3['Optik'] # looks what is the Optik block: # %% [markdown] # ## Import/Export of JCAMP-DX files # # [JCAMP-DX](http://www.jcamp-dx.org/) is an open format initially developped for IR data and extended to # other spectroscopies. At present, the JCAMP-DX reader implemented in Spectrochempy is limited to IR data and # AFFN encoding (see <NAME> and <NAME>, JCAMP-DX: A Standard Form for Exchange of Infrared Spectra in # Readable Form, Appl. Spec., 1988, 1, 151–162. doi:10.1366/0003702884428734 fo details). # # The JCAMP-DX reader of spectrochempy has been essentially written to read again the jcamp-dx files exported by # spectrochempy `write_jdx()` writer. # # Hence, for instance, the first dataset can be saved in the JCAMP-DX format: # %% S0 = X[0] print(S0) S0.write_jcamp('CO@Mo_Al2O3_0.jdx', confirm=False); # %% [markdown] # Then used (and maybe changed) by a 3rd party software, and re-imported in spectrochempy: # %% newS0 = scp.read_jcamp('CO@Mo_Al2O3_0.jdx') print(newS0) # %% [markdown] # It is important to note here that the conversion to JCAMP-DX changes the last digits of absorbances and wavenumbers: # %% def difference(x, y): from numpy import max, abs nonzero = (y.data != 0) error = abs(x.data - y.data) max_rel_error = max(error[nonzero] / abs(y.data[nonzero])) return max(error), max_rel_error # %% max_error, max_rel_error = difference(S0, newS0) print(f'Max absolute difference in absorbance: {max_error:.3g}') print(f'Max relative difference in absorbance: {max_rel_error:.3g}') # %% max_error, max_rel_error = difference(S0.x, newS0.x) print(f'Max absolute difference in wavenumber: {max_error:.3g}') print(f'Max relative difference in wavenumber: {max_rel_error:.3g}') # %% [markdown] # This is much beyond the experimental accuracy but can lead to undesirable effects. # # For instance: # %% try: S0 - newS0 except Exception as e: scp.error_(e) # %% [markdown] # returns an error because of the small shift of coordinates. We will see in another tutorial how to re-align datasets # and deal with these small problems. It is worth noticing that similar distorsions arise in commercial softwares,... # except that the user is not notified. <file_sep>/tests/test_utils/test_file.py # -*- coding: utf-8 -*- # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ===================================================================================================================== # # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from pathlib import Path from os import environ from os.path import join import pytest from spectrochempy.core import preferences as prefs from spectrochempy import NO_DISPLAY from spectrochempy.utils import get_filename def test_get_filename(): # should read in the default prefs.datadir (and for testing we fix the name to environ['TEST_FILE'] f = get_filename(filetypes=["OMNIC files (*.spg *.spa *.srs)", "SpectroChemPy files (*.scp)"]) assert isinstance(f, dict) f = get_filename(filetypes=["OMNIC files (*.spg *.spa *.srs)", "SpectroChemPy files (*.scp)"], dictionary=False) assert isinstance(f, list) assert isinstance(f[0], Path) if NO_DISPLAY: assert str(f[0]) == join(prefs.datadir, environ['TEST_FILE']) # directory specified by a keyword as well as the filename f = get_filename("nh4y-activation.spg", directory="irdata") assert f == { '.spg': [Path(prefs.datadir) / 'irdata' / 'nh4y-activation.spg'] } # directory specified in the filename as a subpath of the data directory f = get_filename("irdata/nh4y-activation.spg") assert f == { '.spg': [Path(prefs.datadir) / 'irdata' / 'nh4y-activation.spg'] } # no directory specified (filename must be in the working or the default data directory f = get_filename("wodger.spg") # if it is not found an error is generated with pytest.raises(IOError): f = get_filename("nh4y-activation.spg") # directory is implicit (we get every files inside, with an allowed extension) # WARNING: Must end with a backslash f = get_filename("irdata/", filetypes=['OMNIC files (*.spa, *.spg)', 'OMNIC series (*.srs)', 'all files (*.*)'], listdir=True) if '.scp' in f.keys(): del f['.scp'] assert len(f.keys()) == 2 # should raise an error with pytest.raises(IOError): get_filename("~/xxxx", filetypes=["OMNIC files (*.sp*)", "SpectroChemPy files (*.scp)", "all files (*)"]) # EOF <file_sep>/pytest.ini [pytest] testpaths = "docs/userguide" "docs/gettingstarted/examples" "tests" norecursedirs = "gui" "generated" ".ipynb_checkpoints" "gallery" ".ci" addopts = --ignore-glob="docs/gettingstarted/examples/generated" --ignore="docs/_build" --ignore="gui" --ignore="~*" --doctest-plus doctest_plus = enabled doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ALLOW_UNICODE ALLOW_BYTES <file_sep>/spectrochempy/core/processors/align.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, # Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in # the root directory = # ====================================================================================================================== """ This module defines functions related to NDDataset alignment. """ __all__ = ['align'] __dataset_methods__ = __all__ # import scipy.interpolate import numpy as np from spectrochempy.utils import MASKED, UnitsCompatibilityError, get_n_decimals from spectrochempy.core import warning_, error_ from spectrochempy.core.dataset.coord import Coord # .................................................................................................................. def can_merge_or_align(coord1, coord2): """ Check if two coordinates can be merged or aligned Parameters ---------- coord1, coord2 : |Coord| coordinates to merge or align Returns ------- can_merge, can_align : tuple of bools Two flags about merge and alignment possibility """ if (coord1 == coord2): # same coordinates can_merge = True # merge is obvious can_align = True # of course as it is the same coordinate else: # no the same coordinates can_merge = False # we need to do alignment to merge # can align only if data exists, units compatibles, and title are # the same can_align = True can_align &= not coord1.is_empty can_align &= not coord2.is_empty can_align &= coord1.title == coord2.title if can_align and (coord1.has_units or coord2.has_units): if coord1.has_units: can_align &= coord1.is_units_compatible(coord2) else: can_align &= coord2.is_units_compatible(coord1) return can_merge, can_align # ............................................................................ def align(dataset, *others, **kwargs): """ Align individual |NDDataset| along given dimensions using various methods. Parameters ----------- dataset : |NDDataset| Dataset on which we want to salign other objects. *others : |NDDataset| Objects to align. dim : str. Optional, default='x' Along which axis to perform the alignment. dims : list of str, optional, default=None Align along all dims defined in dims (if dim is also defined, then dims have higher priority). method : enum ['outer', 'inner', 'first', 'last', 'interpolate'], optional, default='outer' Which method to use for the alignment. If align is defined : * 'outer' means that a union of the different coordinates is achieved (missing values are masked) * 'inner' means that the intersection of the coordinates is used * 'first' means that the first dataset is used as reference * 'last' means that the last dataset is used as reference * 'interpolate' means that interpolation is performed relative to the first dataset. interpolate_method : enum ['linear','pchip']. Optional, default='linear' Method of interpolation to performs for the alignment. interpolate_sampling : 'auto', int or float. Optional, default='auto' * 'auto' : sampling is determined automatically from the existing data. * int : if an integer values is specified, then the sampling interval for the interpolated data will be splitted in this number of points. * float : If a float value is provided, it determines the interval between the interpolated data. coord : |Coord|, optional, default=None coordinates to use for alignment. Ignore those corresponding to the dimensions to align. copy : bool, optional, default=True If False then the returned objects will share memory with the original objects, whenever it is possible : in principle only if reindexing is not necessary. Returns -------- aligned_datasets : tuple of |NDDataset| Same objects as datasets with dimensions aligned. Raises ------ ValueError issued when the dimensions given in `dim` or `dims` argument are not compatibles (units, titles, etc...). """ # DEVELOPPER NOTE # There is probably better methods, but to simplify dealing with # LinearCoord, we transform them in Coord before treatment (going back # to linear if possible at the end of the process) # TODO: Perform an alignment along numeric labels # TODO: add example in docs # copy objects? copy = kwargs.pop('copy', True) # make a single list with dataset and the remaining object objects = [dataset] + list(others) # should we align on given external coordinates extern_coord = kwargs.pop('coord', None) if extern_coord and extern_coord.implements('LinearCoord'): extern_coord = Coord(extern_coord, linear=False, copy=True) # what's the method to use (by default='outer') method = kwargs.pop('method', 'outer') # trivial cases where alignment is not possible or unecessary if not objects: warning_('No object provided for alignment!') return None if len(objects) == 1 and objects[0].implements('NDDataset') and extern_coord is None: # no necessary alignment return objects # evaluate on which axis we align axis, dims = dataset.get_axis(only_first=False, **kwargs) # check compatibility of the dims and prepare the dimension for alignment for axis, dim in zip(axis, dims): # get all objets to align _objects = {} _nobj = 0 for idx, object in enumerate(objects): if not object.implements('NDDataset'): error_(f'Bad object(s) found: {object}. Note that only NDDataset ' f'objects are accepted ' f'for alignment') return None _objects[_nobj] = {'obj': object.copy(), 'idx': idx, } _nobj += 1 _last = _nobj - 1 # get the reference object (by default the first, except if method if # set to 'last' ref_obj_index = 0 if method == 'last': ref_obj_index = _last ref_obj = _objects[ref_obj_index]['obj'] # as we will sort their coordinates at some point, we need to know # if the coordinates need to be reversed at # the end of the alignment process reversed = ref_obj.coordset[dim].reversed if reversed: ref_obj.sort(descend=False, dim=dim, inplace=True) # get the coordset corresponding to the reference object ref_obj_coordset = ref_obj.coordset # get the coordinate for the reference dimension ref_coord = ref_obj_coordset[dim] # as we will sort their coordinates at some point, we need to know # if the coordinates need to be reversed at # the end of the alignment process reversed = ref_coord.reversed # prepare a new Coord object to store the final new dimension new_coord = ref_coord.copy() ndec = get_n_decimals(new_coord.data.max(), 1.e-5) if new_coord.implements('LinearCoord'): new_coord = Coord(new_coord, linear=False, copy=True) # loop on all object for index, object in _objects.items(): obj = object['obj'] if obj is ref_obj: # not necessary to compare with itself! continue if reversed: obj.sort(descend=False, dim=dim, inplace=True) # get the current objet coordinates and check compatibility coord = obj.coordset[dim] if coord.implements('LinearCoord') or coord.linear: coord = Coord(coord, linear=False, copy=True) if not coord.is_units_compatible(ref_coord): # not compatible, stop everything raise UnitsCompatibilityError('NDataset to align must have compatible units!') # do units transform if necesssary so coords can be compared if coord.units != ref_coord.units: coord.ito(ref_coord) # adjust the new_cord depending on the method of alignement new_coord_data = set(np.around(new_coord.data, ndec)) coord_data = set(np.around(coord.data, ndec)) if method in ['outer', 'interpolate']: # in this case we do a union of the coords (masking the # missing values) # For method=`interpolate`, the interpolation will be # performed in a second step new_coord._data = sorted(coord_data | new_coord_data) elif method == 'inner': # take only intersection of the coordinates # and generate a warning if it result something null or new_coord._data = sorted(coord_data & new_coord_data) elif method in ['first', 'last']: # we take the reference coordinates already determined as # basis (masking the missing values) continue else: raise NotImplementedError(f'The method {method} is unknown!') # Now perform alignment of all objects on the new coordinates for index, object in _objects.items(): obj = object['obj'] # get the dim index for the given object dim_index = obj.dims.index(dim) # prepare slicing keys ; set slice(None) for the untouched # dimensions preceeding the dimension of interest prepend_keys = [slice(None)] * dim_index # New objects for obj must be created with the new coordinates # change the data shape new_obj_shape = list(obj.shape) new_obj_shape[dim_index] = len(new_coord) new_obj_data = np.full(new_obj_shape, np.NaN) # create new dataset for obj and ref_objects if copy: new_obj = obj.copy() else: new_obj = obj # update the data and mask coord = obj.coordset[dim] coord_data = set(np.around(coord.data, ndec)) dim_loc = new_coord._loc2index(sorted(coord_data)) loc = tuple(prepend_keys + [dim_loc]) new_obj._data = new_obj_data # mask all the data then unmask later the relevant data in # the next step if not new_obj.is_masked: new_obj.mask = MASKED new_obj.mask[loc] = False else: mask = new_obj.mask.copy() new_obj.mask = MASKED new_obj.mask[loc] = mask # set the data for the loc new_obj._data[loc] = obj.data # update the coordinates new_coordset = obj.coordset.copy() if coord.is_labeled: label_shape = list(coord.labels.shape) label_shape[0] = new_coord.size new_coord._labels = np.zeros(tuple(label_shape)).astype(coord.labels.dtype) new_coord._labels[:] = '--' new_coord._labels[dim_loc] = coord.labels setattr(new_coordset, dim, new_coord) new_obj._coordset = new_coordset # reversed? if reversed: # we must reverse the given coordinates new_obj.sort(descend=reversed, dim=dim, inplace=True) # update the _objects _objects[index]['obj'] = new_obj if method == 'interpolate': warning_('Interpolation not yet implemented - for now equivalent ' 'to `outer`') # the new transformed object must be in the same order as the passed # objects # and the missing values must be masked (for the moment they are defined to NaN for index, object in _objects.items(): obj = object['obj'] # obj[np.where(np.isnan(obj))] = MASKED # mask NaN values obj[np.where(np.isnan(obj))] = 99999999999999. # replace NaN values (to simplify # comparisons) idx = int(object['idx']) objects[idx] = obj # we also transform into linear coord if possible ? pass # TODO: # Now return return tuple(objects) # if method == 'interpolate': # # # reorders dataset and reference # in ascending order # is_sorted # = False # if # dataset.coordset(axis).reversed: # datasetordered = # dataset.sort(axis, # descend=False) # refordered = ref.sort( # refaxis, descend=False) # is_sorted = True # # else: # # datasetordered = dataset.copy() # refordered = ref.copy() # # try: # # datasetordered.coordset(axis).to( # refordered.coordset(refaxis).units) # except: # # raise # ValueError( # 'units of the dataset and # reference axes on which interpolate are not # compatible') # # # oldaxisdata = datasetordered.coordset(axis).data # # refaxisdata = # refordered.coordset(refaxis).data # TODO: at the # end restore the original order # # method = # kwargs.pop( # 'method', 'linear') # fill_value = kwargs.pop('fill_value', # np.NaN) # # # if method == 'linear': # interpolator # = lambda data, ax=0: scipy.interpolate.interp1d( # # # oldaxisdata, data, axis=ax, kind=method, bounds_error=False, # fill_value=fill_value, # assume_sorted=True) # # elif # method == 'pchip': # interpolator = lambda data, # ax=0: scipy.interpolate.PchipInterpolator( # # oldaxisdata, data, axis=ax, # extrapolate=False) # # else: # raise AttributeError(f'{method} is not a # # recognised option method for `align`') # # # interpolate_data = interpolator( # datasetordered.data, # axis) # newdata = interpolate_data(refaxisdata) # # # # if datasetordered.is_masked: # interpolate_mask = # interpolator( # datasetordered.mask, axis) # newmask # = interpolate_mask(refaxisdata) # # else: # # newmask = NOMASK # # # interpolate_axis = # # interpolator(datasetordered.coordset(axis).data) # # # newaxisdata = # interpolate_axis(refaxisdata) # # newaxisdata = refaxisdata.copy() # # if # method == # 'pchip' and not np.isnan(fill_value): # index = # # np.any(np.isnan(newdata)) # newdata[index] = # fill_value # # # index = np.any(np.isnan( # newaxisdata)) # newaxisdata[index] = fill_value # # # create the new axis # newaxes = dataset.coords.copy() # # newaxes[axis]._data = newaxisdata # newaxes[axis]._labels = # np.array([''] * newaxisdata.size) # # # transform the dataset # # inplace = kwargs.pop('inplace', False) # # if inplace: # # out = dataset # else: # # out = dataset.copy() # # # out._data = newdata # out._coords = newaxes # out._mask # # = newmask # # out.name = dataset.name # out.title = # dataset.title # # out.history # = '{}: Aligned along dim {} # with respect to dataset {} using coords {} \n'.format( # # str( # dataset.modified), axis, ref.name, ref.coords[refaxis].title) # # if is_sorted and out.coordset( # axis).reversed: # # out.sort(axis, descend=True, inplace=True) # ref.sort( # refaxis, # descend=True, inplace=True) # # return out <file_sep>/spectrochempy/core/writers/__init__.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Package defining exporters for the n-dimensional datasets and projects """ <file_sep>/spectrochempy/core/project/project.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ['Project'] from copy import copy as cpy import uuid import pathlib import dill from functools import wraps from traitlets import (Dict, Instance, Unicode, This, default) from spectrochempy.core.dataset.nddataset import NDDataset, NDIO from spectrochempy.core.scripts.script import Script from spectrochempy.core.dataset.meta import Meta from spectrochempy.core.project.baseproject import AbstractProject # from collections import OrderedDict # cfg = config_manager # preferences = preferences # ====================================================================================================================== # Project class # ====================================================================================================================== class Project(AbstractProject, NDIO): _id = Unicode() _name = Unicode(allow_none=True) _parent = This() _projects = Dict(This) _datasets = Dict(Instance(NDDataset)) _scripts = Dict(Instance(Script)) _others = Dict() _meta = Instance(Meta) _filename = Instance(pathlib.Path, allow_none=True) # .................................................................................................................. def __init__(self, *args, argnames=None, name=None, **meta): """ A manager for projects, datasets and scripts. It can handle multiple datsets, sub-projects, and scripts in a main project. Parameters ---------- *args : Series of objects, optional Argument type will be interpreted correctly if they are of type |NDDataset|, |Project|, or other objects such as |Script|. This is optional, as they can be added later. argnames : list, optional If not None, this list gives the names associated to each objects passed as args. It MUST be the same length that the number of args, or an error wil be raised. If None, the internal name of each object will be used instead. name : str, optional The name of the project. If the name is not provided, it will be generated automatically. **meta : dict Any other attributes to described the project. See Also -------- NDDataset : The main object containing arrays. Script : Executables scripts container. Examples -------- >>> import spectrochempy as scp >>> myproj = scp.Project(name='project_1') >>> ds = scp.NDDataset([1., 2., 3.], name='dataset_1') >>> myproj.add_dataset(ds) >>> print(myproj) Project project_1: ⤷ dataset_1 (dataset) """ super().__init__() self.parent = None self.name = name if meta: self.meta.update(meta) for i, obj in enumerate(args): name = None if argnames: name = argnames[i] self._set_from_type(obj, name) # ------------------------------------------------------------------------------------------------------------------ # Private methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def _set_from_type(self, obj, name=None): if isinstance(obj, NDDataset): # add it to the _datasets dictionary self.add_dataset(obj, name) elif isinstance(obj, type(self)): # can not use Project here! self.add_project(obj, name) elif isinstance(obj, Script): self.add_script(obj, name) elif hasattr(obj, 'name'): self._others[obj.name] = obj else: raise ValueError('objects of type {} has no name and so ' 'cannot be appended to the project '.format(type(obj).__name__)) # .................................................................................................................. def _get_from_type(self, name): pass # TODO: ??? # .................................................................................................................. def _repr_html_(self): h = self.__str__() h = h.replace('\n', '<br/>\n') h = h.replace(' ', '&nbsp;') return h # ------------------------------------------------------------------------------------------------------------------ # Special methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def __getitem__(self, key): if not isinstance(key, str): raise KeyError('The key must be a string.') if key in self.datasets_names: return self._datasets[key] elif key in self.projects_names: return self._projects[key] elif key in self.scripts_names: return self._scripts[key] else: raise KeyError("This object name does not exist in this project.") # .................................................................................................................. def __setitem__(self, key, value): if not isinstance(key, str): raise KeyError('The key must be a string.') if key in self.allnames and not isinstance(value, type(self[key])): raise ValueError('the key exists but for a different type ' 'of object: {}'.format(type(self[key]).__name__)) if key in self.datasets_names: value.parent = self self._datasets[key] = value elif key in self.projects_names: value.parent = self self._projects[key] = value elif key in self.scripts_names: value.parent = self self._scripts[key] = value else: # the key does not exists self._set_from_type(value, name=key) # .................................................................................................................. def __getattr__(self, item): if "_validate" in item or "_changed" in item: # this avoid infinite recursion due to the traits management return super().__getattribute__(item) elif item in self.allnames: # allows to access project, dataset or script by attribute return self[item] elif item in self.meta.keys(): # return the attribute return self.meta[item] else: raise AttributeError("`%s` has no attribute `%s`" % (type(self).__name__, item)) # .................................................................................................................. def __iter__(self): for items in sorted(self.allitems): yield items # .................................................................................................................. def __str__(self): s = "Project {}:\n".format(self.name) lens = len(s) def _listproj(s, project, ns): ns += 1 sep = " " * ns for k, v in sorted(project._projects.items()): s += "{} ⤷ {} (sub-project)\n".format(sep, k) s = _listproj(s, v, ns) # recursive call for k, v in sorted(project._datasets.items()): s += "{} ⤷ {} (dataset)\n".format(sep, k) for k, v in sorted(project._scripts.items()): s += "{} ⤷ {} (script)\n".format(sep, k) if len(s) == lens: # nothing has been found in the project s += "{} (empty project)\n".format(sep) return s.strip('\n') return _listproj(s, self, 0) def __dir__(self): return ['name', 'meta', 'parent', 'datasets', 'projects', 'scripts', ] def __copy__(self): new = Project() new.name = self.name + '*' for item in self.__dir__(): if item == 'name': continue item = "_" + item setattr(new, item, cpy(getattr(self, item))) return new # ------------------------------------------------------------------------------------------------------------------ # properties # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @default('_id') def _id_default(self): return str(uuid.uuid1()) # a unique id # .................................................................................................................. @property def id(self): """ str - Readonly object identifier. """ return self._id # .................................................................................................................. @property def name(self): """ str - An user friendly name for the project. The default is automatically generated. """ return self._name # .................................................................................................................. @name.setter def name(self, name): # property.setter for name if name is not None: self._name = name else: self.name = "Project-" + self.id.split('-')[0] # .................................................................................................................. @property def parent(self): """ project - instance of the Project which is the parent (if any) of the current project. """ return self._parent # .................................................................................................................. @parent.setter def parent(self, value): if self._parent is not None: # A parent project already exists for this sub-project but the # entered values gives a different parent. This is not allowed, # as it can produce impredictable results. We will fisrt remove it # from the current project. self._parent.remove_project(self.name) self._parent = value # .................................................................................................................. @default('_parent') def _get_parent(self): return None # .................................................................................................................. @default('_meta') def _meta_default(self): return Meta() # .................................................................................................................. @property def meta(self): """ meta - metadata for the project meta contains all attribute except the name, id and parent of the current project. """ return self._meta # .................................................................................................................. @property def datasets_names(self): """ list - names of all dataset included in this project. (does not return those located in sub-folders). """ lst = self._datasets.keys() lst = sorted(lst) return lst # .................................................................................................................. @property def datasets(self): """ list - datasets included in this project excluding those located in subprojects. """ d = [] for name in self.datasets_names: d.append(self._datasets[name]) return d @datasets.setter def datasets(self, datasets): self.add_datasets(*datasets) # .................................................................................................................. @property def projects_names(self): """ list - names of all subprojects included in this project. """ lst = self._projects.keys() lst = sorted(lst) return lst # .................................................................................................................. @property def projects(self): """ list - subprojects included in this project. """ p = [] for name in self.projects_names: p.append(self._projects[name]) return p @projects.setter def projects(self, projects): self.add_projects(*projects) # .................................................................................................................. @property def scripts_names(self): """ list - names of all scripts included in this project. """ lst = self._scripts.keys() lst = sorted(lst) return lst # .................................................................................................................. @property def scripts(self): """ list - scripts included in this project. """ s = [] for name in self.scripts_names: s.append(self._scripts[name]) return s @scripts.setter def scripts(self, scripts): self.add_scripts(*scripts) @property def allnames(self): """ list - names of all objects contained in this project """ return self.datasets_names + self.projects_names + self.scripts_names @property def allitems(self): """ list - all items contained in this project """ return list(self._datasets.items()) + list(self._projects.items()) + list(self._scripts.items()) # ------------------------------------------------------------------------------------------------------------------ # Public methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def implements(self, name=None): """ Utility to check if the current object implement `Project`. Rather than isinstance(obj, Project) use object.implements('Project'). This is useful to check type without importing the module. """ if name is None: return 'Project' else: return name == 'Project' def copy(self): """ Make an exact copy of the current project. """ return self.__copy__() # ------------------------------------------------------------------------------------------------------------------ # dataset items # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def add_datasets(self, *datasets): """ Add datasets to the current project. Parameters ---------- datasets : series of |NDDataset| Datasets to add to the current project. The name of the entries in the project will be identical to the names of the datasets. Examples -------- Assuming that ds1, ds2 and ds3 are already defined datasets : >>> proj = Project() >>> proj.add_datasets(ds1, ds2, ds3) # doctest: +SKIP """ for ds in datasets: self.add_dataset(ds) # .................................................................................................................. def add_dataset(self, dataset, name=None): """ Add datasets to the current project. Parameters ---------- dataset : |NDDataset| Datasets to add. The name of the entry will be the name of the dataset, except if parameter `name` is defined. name : str, optional If provided the name will be used to name the entry in the project. Examples -------- Assuming that ds1 is an already defined dataset : >>> proj = Project() >>> proj.add_dataset(ds1, name='Toto') # doctest: +SKIP """ dataset.parent = self if name is None: name = dataset.name else: dataset.name = name self._datasets[name] = dataset # .................................................................................................................. def remove_dataset(self, name): """ Remove a dataset from the project. Parameters ---------- name : str Name of the dataset to remove. """ self._datasets[name]._parent = None # remove the parent info del self._datasets[name] # remove the object from the list of datasets # .................................................................................................................. def remove_all_dataset(self): """ Remove all dataset from the project. """ for v in self._datasets.values(): v._parent = None self._datasets = {} # ------------------------------------------------------------------------------------------------------------------ # project items # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def add_projects(self, *projects): """ Add one or a series of projects to the current project. Parameters ---------- projects : project instances The projects to add to the current ones. """ for proj in projects: self.add_project(proj) # .................................................................................................................. def add_project(self, proj, name=None): """ Add one project to the current project. Parameters ---------- proj : a project instance A project to add to the current one """ proj.parent = self if name is None: name = proj.name else: proj.name = name self._projects[name] = proj # .................................................................................................................. def remove_project(self, name): """ remove one project from the current project. Parameters ---------- name : str Name of the project to remove """ self._projects[name]._parent = None del self._projects[name] # .................................................................................................................. def remove_all_project(self): """ remove all projects from the current project. """ for v in self._projects.values(): v._parent = None self._projects = {} # ------------------------------------------------------------------------------------------------------------------ # script items # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def add_scripts(self, *scripts): """ Add one or a series of scripts to the current project. Parameters ---------- scripts : |Script| instances """ for sc in scripts: self.add_script(sc) # .................................................................................................................. def add_script(self, script, name=None): """ Add one script to the current project. Parameters ---------- script : a |Script| instance name : str """ script.parent = self if name is None: name = script.name else: script.name = name self._scripts[name] = script # .................................................................................................................. def remove_script(self, name): self._scripts[name]._parent = None del self._scripts[name] # .................................................................................................................. def remove_all_script(self): for v in self._scripts.values(): v._parent = None self._scripts = {} def makescript(priority=50): def decorator(func): ss = dill.dumps(func) print(ss) @wraps(func) def wrapper(*args, **kwargs): f = func(*args, **kwargs) return f return wrapper return decorator # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/tests/test_plotters/test_multiplot.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core import preferences, show from spectrochempy.core.plotters.multiplot import multiplot, multiplot_map, multiplot_stack prefs = preferences def test_multiplot(): dataset = NDDataset.read_omnic( os.path.join(prefs.datadir, 'irdata', 'nh4y-activation.spg'))[:, 0:20] datasets = [dataset, dataset * 1.1, dataset * 1.2, dataset * 1.3] labels = ['sample {}'.format(label) for label in ["1", "2", "3", "4"]] multiplot(datasets=datasets, method='stack', labels=labels, nrow=2, ncol=2, figsize=(9, 5), style='sans', sharex=True, sharey=True, sharez=True) multiplot(datasets=datasets, method='image', labels=labels, nrow=2, ncol=2, figsize=(9, 5), sharex=True, sharey=True, sharez=True) datasets = [dataset * 1.2, dataset * 1.3, dataset, dataset * 1.1, dataset * 1.2, dataset * 1.3] labels = ['sample {}'.format(label) for label in ["1", "2", "3", "4", "5", "6"]] multiplot_map(datasets=datasets, labels=labels, nrow=2, ncol=3, figsize=(9, 5), sharex=False, sharey=False, sharez=True) multiplot_map(datasets=datasets, labels=labels, nrow=2, ncol=3, figsize=(9, 5), sharex=True, sharey=True, sharez=True) datasets = [dataset * 1.2, dataset * 1.3, dataset, ] labels = ['sample {}'.format(label) for label in ["1", "2", "3"]] multiplot_stack(datasets=datasets, labels=labels, nrow=1, ncol=3, figsize=(9, 5), sharex=True, sharey=True, sharez=True) multiplot_stack(datasets=datasets, labels=labels, nrow=3, ncol=1, figsize=(9, 5), sharex=True, sharey=True, sharez=True) multiplot(method='pen', datasets=[dataset[0], dataset[10] * 1.1, dataset[19] * 1.2, dataset[15] * 1.3], nrow=2, ncol=2, figsize=(9, 5), labels=labels, sharex=True) show() # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/docs/gettingstarted/examples/read/plot_read_raman_from_labspec.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Loading RAMAN experimental file ============================================ Here we load an experimental SPG file (OMNIC) and plot it. """ import spectrochempy as scp # %% # define the folder where are the spectra datadir = scp.preferences.datadir ramandir = datadir / "ramandata" # %% A = scp.read_labspec('Activation.txt', directory=ramandir) A.plot() A = scp.read_labspec('532nm-191216-Si 200mu.txt', directory=ramandir) A.plot() A = scp.read_labspec('serie190214-1.txt', directory=ramandir) A.plot(colorbar=True) A.plot_map(colorbar=True) A = scp.read_labspec('SMC1-Initial RT.txt', directory=ramandir) A.plot() # %% # Open a dialog - note the presence of the keyword directory B = scp.read_labspec(directory=ramandir) # %% # this pack all spectra of the subdir directory (without dialog - look at the difference above) B = scp.read_labspec(ramandir / 'subdir') B.plot() scp.show() <file_sep>/docs/gettingstarted/examples/nddataset/readme.txt .. _nddataset_examples-index: How to use NDDataset ---------------------- Example of how to create and manipulate NDDataset in SpectroChemPy <file_sep>/docs/credits/license.rst .. _license: License =============== .. raw:: html :file: ../_static/license_CeCILL.html <file_sep>/spectrochempy/utils/zip.py # -*- coding: utf-8 -*- # # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ===================================================================================================================== # import os import json from collections.abc import Mapping from numpy.lib.format import read_array from spectrochempy.utils import json_decoder __all__ = ['make_zipfile', 'ScpFile'] # ====================================================================================================================== # ZIP UTILITIES # ====================================================================================================================== # ............................................................................ def make_zipfile(file, **kwargs): """ Create a ZipFile. Allows for Zip64 (useful if files are larger than 4 GiB, and the `file` argument can accept file or str. `kwargs` are passed to the zipfile.ZipFile constructor. (adapted from numpy) """ import zipfile kwargs['allowZip64'] = True return zipfile.ZipFile(file, **kwargs) class ScpFile(Mapping): # lgtm [py/missing-equals] """ ScpFile(fid) (largely inspired by ``NpzFile`` object in numpy) `ScpFile` is used to load files stored in ``.scp`` or ``.pscp`` format. It assumes that files in the archive have a ``.npy`` extension in the case of the dataset's ``.scp`` file format) , ``.scp`` extension in the case of project's ``.pscp`` file format and finally ``pars.json`` files which contains other information on the structure and attibutes of the saved objects. Other files are ignored. Attributes ---------- files : list of str List of all files in the archive with a ``.npy`` extension. zip : ZipFile instance The ZipFile object initialized with the zipped archive. """ def __init__(self, fid): """ Parameters ---------- fid : file or str The zipped archive to open. This is either a file-like object or a string containing the path to the archive. """ _zip = make_zipfile(fid) self.files = _zip.namelist() self.zip = _zip if hasattr(fid, 'close'): self.fid = fid else: self.fid = None def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def close(self): """ Close the file. """ if self.zip is not None: self.zip.close() self.zip = None if self.fid is not None: self.fid.close() self.fid = None def __del__(self): try: self.close() except AttributeError as e: if str(e) == "'ScpFile' object has no attribute 'zip'": pass except Exception as e: raise e def __iter__(self): return iter(self.files) def __len__(self): return len(self.files) def __getitem__(self, key): member = False ext = None if key in self.files: member = True _, ext = os.path.splitext(key) if member and ext in [".npy"]: f = self.zip.open(key) return read_array(f, allow_pickle=True) elif member and ext in ['.scp']: from spectrochempy.core.dataset.nddataset import NDDataset # f = io.BytesIO(self.zip.read(key)) content = self.zip.read(key) return NDDataset.load(key, content=content) elif member and ext in ['.json']: content = self.zip.read(key) return json.loads(content, object_hook=json_decoder) elif member: return self.zip.read(key) else: raise KeyError("%s is not a file in the archive or is not " "allowed" % key) def __contains__(self, key): return self.files.__contains__(key) # ====================================================================================================================== if __name__ == '__main__': pass # EOF <file_sep>/docs/gettingstarted/examples/fitting/plot_fit.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Fitting 1D dataset ------------------ In this example, we find the least square solution of a simple linear equation. """ # sphinx_gallery_thumbnail_number = 2 import spectrochempy as scp import os ######################################################################## # Let's take an IR spectrum nd = scp.NDDataset.read_omnic(os.path.join('irdata', 'nh4y-activation.spg')) ######################################################################## # where we select only region (OH region) ndOH = nd[54, 3700.:3400.] ndOH.plot() ######################################################################## # Perform a Fit # Fit parameters are defined in a script (a single text as below) script = """ #----------------------------------------------------------- # syntax for parameters definition: # name: value, low_bound, high_bound # * for fixed parameters # $ for variable parameters # > for reference to a parameter in the COMMON block # (> is forbidden in the COMMON block) # common block parameters should not have a _ in their names #----------------------------------------------------------- # COMMON: # common parameters ex. # $ gwidth: 1.0, 0.0, none $ gratio: 0.1, 0.0, 1.0 MODEL: LINE_1 shape: assymvoigtmodel * ampl: 1.0, 0.0, none $ pos: 3620, 3400.0, 3700.0 $ ratio: 0.0147, 0.0, 1.0 $ assym: 0.1, 0, 1 $ width: 200, 0, 1000 MODEL: LINE_2 shape: assymvoigtmodel $ ampl: 0.2, 0.0, none $ pos: 3520, 3400.0, 3700.0 > ratio: gratio $ assym: 0.1, 0, 1 $ width: 200, 0, 1000 """ ############################################################################## # create a fit object f1 = scp.Fit(ndOH, script, silent=True) ############################################################################## # Show plot and the starting model before the fit (of course it is advisable # to be as close as possible of a good expectation f1.dry_run() ndOH.plot(plot_model=True) f1.run(maxiter=1000) ############################################################################## # Show the result after 1000 iterations ndOH.plot(plot_model=True) # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/spectrochempy/core/analysis/iris.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements the IRIS class. """ __all__ = ['IRIS'] __dataset_methods__ = [] import numpy as np import quadprog from matplotlib import pyplot as plt from scipy import optimize from spectrochempy.core.dataset.coord import Coord from spectrochempy.core.dataset.nddataset import NDDataset class IRIS: """ 2D Infrared inversion spectroscopy """ def __init__(self, X, param, **kwargs): """ Parameters ----------- X : |NDDataset| The dataset on which to perform the 2D-IRIS analysis param : dict Dict of inversion parameters with the following keys : * 'custom_kernel': a two-variable lambda function ker(p, eps) where p and eps are the external experimental variable and the internal physico-chemical parameter, respectively. If not given, one of the pre-defined kernel must be defined in param['kernel'], below. * 'kernel': the name of the kernel used to make the inversion. The kernel K(p, eps) is a functional relationship holding between 'p', the experimental variable that was changed in the rows direction of X (e.g. temperature, pressure, time, ...) and the concentration of pure species characterized by the physico-chemical parameter 'eps' (e.g. adsorption/desorption energy, ...). * 'epsRange': array-like of three values [start, stop, num] defining the interval of eps values. start, stop: the starting and end values of eps, num: number of values. * 'lambdaRange': None or array_like of two values [min, max] or three values [start, stop, num] defining the interval of the regularization parameter. It set to None, a non regularized solution is computed. If two values are entered, the optimum regularization parameter is searched between 10^min and 10^max using the Cultrera_Callegaro algorithm (arXiv:1608.04571v2). If three valyes are given num values are spaced evenly on a log scale between 10^start and 10^stop. * 'p': array or coordinate of the external variable. If none is given, p = X.y.values verbose : bool If set to True, prints informations during the 2D IRIS analysis. In a ny case, the same information is returned in self._log """ # eventually deal with multiple coordinates # Limited to 2D dataset # if multiple coords for a given dimension, take the default ones: coord_x = X.x.default coord_y = X.y.default # check options # defines the kernel if 'custom_kernel' in param: ker = param['custom_kernel'] elif 'kernel' in param: if param['kernel'].lower() == 'langmuir': def ker(p_, eps_): return np.exp(-eps_) * p_ / (1 + np.exp(-eps_) * p_) elif param['kernel'].lower() == 'ca': def ker(p_, eps_): return 0 if p_ < np.exp(eps_) else 1 elif param['kernel'].lower() == 'reactant-first-order': def ker(t, lnk): return np.exp(-1 * np.exp(lnk) * t) elif param['kernel'].lower() == 'product-first-order': def ker(t, lnk): return 1 - np.exp(-1 * np.exp(lnk) * t) else: raise NameError(f"This kernel: <{param['kernel']}> is not implemented") else: raise NameError('A kernel must be given !') # define eps values eps = np.linspace(param['epsRange'][0], param['epsRange'][1], param['epsRange'][2]) # defines regularization parameter values if 'lambdaRange' not in param: lambdaRange = None else: lambdaRange = param['lambdaRange'] if lambdaRange is None: regularization = False searchLambda = False lamb = [0] elif len(lambdaRange) == 2: regularization = True searchLambda = True elif len(param['lambdaRange']) == 3: regularization = True searchLambda = False lamb = np.logspace(param['lambdaRange'][0], param['lambdaRange'][1], param['lambdaRange'][2]) else: raise ValueError('lambdaRange should either None or a set of 2 or 3 integers') if 'p' in param: p = param['p'] # check p if isinstance(p, Coord): if p.shape[1] != X.shape[0]: raise ValueError('\'p\' should be consistent with the y coordinate of the dataset') pval = p.data # values # (values contains unit! to use it we must either have eps with units or noramlise p else: if len(p) != X.shape[0]: raise ValueError('\'p\' should be consistent with the y coordinate of the dataset') p = Coord(p, title='External variable') pval = p.data # values else: p = coord_y pval = p.data # values # if 'guess' in param: # guess = param['guess'] <-- # TODO: never used. # else: # guess = 'previous' verbose = kwargs.get('verbose', False) # define containers for outputs if not regularization: f = np.zeros((1, len(eps), len(coord_x.data))) RSS = np.zeros((1)) SM = np.zeros((1)) if regularization and not searchLambda: f = np.zeros((len(lamb), len(eps), len(coord_x.data))) RSS = np.zeros((len(lamb))) SM = np.zeros((len(lamb))) if regularization and searchLambda: f = np.zeros((4, len(eps), len(coord_x.data))) RSS = np.zeros((4)) SM = np.zeros((4)) # Define K matrix (kernel) # first some weighting coefficients for the numerical quadrature of the Fredholm integral w = np.zeros((len(eps), 1)) w[0] = 0.5 * (eps[-1] - eps[0]) / (len(eps) - 1) # for j in range(1, len(eps) - 1): w[j] = 2 * w[0] w[-1] = w[0] # then compute K (TODO: allow using weighting matrix W) K = NDDataset(np.zeros((p.size, len(eps)))) K.set_coordset(y=p, x=Coord(eps, title='epsilon')) for i, p_i in enumerate(pval): for j, eps_j in enumerate(eps): K.data[i, j] = w[j] * ker(p_i, eps_j) # Define S matrix (sharpness), see function Smat() below S = Smat(eps) # solve untregularized problem if not regularization: if verbose: print('Solving for {} wavenumbers and {} spectra, no regularization\n' .format(X.shape[1], X.shape[0])) # une scipy.nnls() to solve the linear problem: X = K f for j, freq in enumerate(coord_x.data): f[0, :, j] = optimize.nnls(K.data, X[:, j].data.squeeze())[0] res = X.data - np.dot(K.data, f[0].data) RSS[0] = np.sum(res ** 2) SM[0] = np.linalg.norm(np.dot(np.dot(np.transpose(f[0]), S), f[0])) if verbose: print('--> residuals = {:.2e} curvature = {:.2e}'.format(RSS[0], SM[0])) if regularization: # some matrices used for QP optimization do not depend on lambdaR # and are computed here. The standard form used by quadprog() is # minimize (1/2) xT G x - aT x ; subject to: C.T x >= b # The first part of the G matrix is independent of lambda: G = G0 + 2 * lambdaR S G0 = 2 * np.dot(K.data.T, K.data) a = 2 * np.dot(X.data.T, K.data) C = np.eye(len(eps)) b = np.zeros(len(eps)) def solve_lambda(X, K, G0, lamda, S, verbose): """ QP optimization parameters: ----------- X: NDDataset of experimental spectra K: NDDataset, kernel datase G0: the lambda independent part of G lamda: regularization parameter S: penalty function (shaprness) verbose: print info returns: -------- f, RSS and SM for a given regularization parameter """ fi = np.zeros((len(eps), len(coord_x.data))) if verbose: print('... Solving for lambda = {} ...'.format(lamda)) G = nearestPD(G0 + 2 * lamda * S) # The following line is to avoid ValueError: 'matrix G is not # positive definite' # SEE: https://github.com/facebookresearch/GradientEpisodicMemory/issues/2#issuecomment-431826393 G += G * 0.00001 for j, freq in enumerate(coord_x.data): fi[:, j] = quadprog.solve_qp(G, a[j].squeeze(), C, b)[0] resi = X.data - np.dot(K.data, fi) RSSi = np.sum(resi ** 2) SMi = np.linalg.norm(np.dot(np.dot(np.transpose(fi), S), fi)) if verbose: print('--> residuals = {:.2e} curvature = {:.2e}'.format(RSSi, SMi)) return fi, RSSi, SMi def menger(x, y): """ returns the Menger curvature of a triplet of points. x, y = sets of 3 cartesian coordinates """ numerator = 2 * (x[0] * y[1] + x[1] * y[2] + x[2] * y[0] - x[0] * y[2] - x[1] * y[0] - x[2] * y[1]) # euclidian distances r01 = (x[1] - x[0]) ** 2 + (y[1] - y[0]) ** 2 r12 = (x[2] - x[1]) ** 2 + (y[2] - y[1]) ** 2 r02 = (x[2] - x[0]) ** 2 + (y[2] - y[0]) ** 2 denominator = np.sqrt(r01 * r12 * r02) return numerator / denominator if not searchLambda: if verbose: print('Solving for {} wavenumbers, {} spectra and {} regularization parameters \n' .format(X.shape[1], X.shape[0], len(lamb))) for i, lamda in enumerate(lamb): f[i], RSS[i], SM[i] = solve_lambda(X, K, G0, lamda, S, verbose) else: if verbose: print('Solving for {} wavenumbers and {} spectra, search regularization parameter ' 'in [10**{}, 10**{}]\n' .format(X.shape[1], X.shape[0], str(min(lambdaRange)), str(max(lambdaRange)))) x = np.ndarray((4)) epsilon = 0.1 phi = (1 + np.sqrt(5)) / 2 x[0] = min(lambdaRange) x[3] = max(lambdaRange) x[1] = (x[3] + phi * x[0]) / (1 + phi) x[2] = x[0] + x[3] - x[1] lamb = 10 ** x if verbose: print('Log lambda= ' + str(x)) for i, xi in enumerate(x): f[i], RSS[i], SM[i] = solve_lambda(X, K, G0, 10 ** xi, S, verbose) Rx = RSS Sy = SM while "convergence not reached": C1 = menger(Rx[0:3], Sy[0:3]) C2 = menger(Rx[1:4], Sy[1:4]) if verbose: print('Curvatures: C1 = {} ; C2 = {}'.format(C1, C2)) while C2 < 0: x[3] = x[2] Rx[3] = Rx[2] Sy[3] = Sy[2] x[2] = x[1] Rx[2] = Rx[1] Sy[2] = Sy[1] x[1] = (x[3] + phi * x[0]) / (1 + phi) if verbose: print('Log lambda= ' + str(x)) f_, Rx[1], S[1] = solve_lambda(X, K, G0, 10 ** x[1], S, verbose) lamb = np.append(lamb, np.array(10 ** x[1])) f = np.concatenate((f, np.atleast_3d(f_.T).T)) RSS = np.concatenate((RSS, np.array(Rx[1:2]))) SM = np.concatenate((SM, np.array(Sy[1:2]))) C2 = menger(Rx[1:4], Sy[1:4]) print('new curvature: C2 = {}'.format(C2)) if C1 > C2: x[3] = x[2] Rx[3] = Rx[2] Sy[3] = Sy[2] x[2] = x[1] Rx[2] = Rx[1] Sy[2] = Sy[1] x[1] = (x[3] + phi * x[0]) / (1 + phi) if verbose: print('Log lambda= ' + str(x)) f_, Rx[1], S[1] = solve_lambda(X, K, G0, 10 ** x[1], S, verbose) f = np.concatenate((f, np.atleast_3d(f_.T).T)) lamb = np.append(lamb, np.array(10 ** x[1])) RSS = np.concatenate((RSS, np.array(Rx[1:2]))) SM = np.concatenate((SM, np.array(Sy[1:2]))) else: x[0] = x[1] Rx[0] = Rx[1] Sy[0] = Sy[1] x[1] = x[2] Rx[1] = Rx[2] Sy[1] = Sy[2] x[2] = x[0] - (x[1] - x[3]) if verbose: print('Log lambda= ' + str(x)) f_, Rx[2], S[2] = solve_lambda(X, K, G0, 10 ** x[2], S, verbose) f = np.concatenate((f, np.atleast_3d(f_.T).T)) lamb = np.append(lamb, np.array(10 ** x[2])) RSS = np.concatenate((RSS, np.array(Rx[1:2]))) SM = np.concatenate((SM, np.array(Sy[1:2]))) if (10 ** x[3] - 10 ** x[0]) / 10 ** x[3] < epsilon: break if verbose: print('\n optimum found !') if verbose: print('\n Done.') f = NDDataset(f) f.name = '2D distribution functions' f.title = 'pseudo-concentration' f.history = '2D IRIS analysis of {} dataset'.format(X.name) xcoord = X.coordset['x'] ycoord = Coord(data=eps, title='epsilon') zcoord = Coord(data=lamb, title='lambda') f.set_coordset(z=zcoord, y=ycoord, x=xcoord) self.f = f self.K = K self.X = X self.lamda = lamb self.RSS = RSS self.SM = SM def reconstruct(self): """ Transform data back to the original space The following matrix operation is performed : :math:`\\hat{X} = K.f[i]` for each value of the regularization parameter. Returns ------- X_hat : |NDDataset| The reconstructed dataset. """ X_hat = NDDataset(np.zeros((self.f.z.size, *self.X.shape)), title=self.X.title, units=self.X.units) X_hat.name = '2D-IRIS Reconstructed datasets' X_hat.set_coordset(z=self.f.z, y=self.X.y, x=self.X.x) # TODO: take into account the fact that coordinates # may have other names for i in range(X_hat.z.size): X_hat[i] = np.dot(self.K.data, self.f[i].data.squeeze()) return X_hat def plotlcurve(self, **kwargs): """ Plots the L Curve Parameters ---------- scale : str, optional, default='ll' 2 letters among 'l' (log) or 'n' (non-log) indicating whether the y and x axes should be log scales. Returns ------- ax : subplot axis """ fig = plt.figure() ax = fig.add_subplot(111) ax.set_title('L curve') scale = kwargs.get('scale', 'll').lower() plt.plot(self.RSS, self.SM, 'o') ax.set_xlabel('Residuals') ax.set_ylabel('Curvature') if scale[1] == 'l': ax.set_xscale('log') if scale[0] == 'l': ax.set_yscale('log') return ax def plotmerit(self, index=None, **kwargs): """ Plots the input dataset, reconstructed dataset and residuals. Parameters ---------- index : optional, int, list or tuple of int. Index(es) of the inversions (i.e. of the lambda values) to consider. If 'None': plots for all indices. default: None Returns ------- list of axes """ colX, colXhat, colRes = kwargs.get('colors', ['blue', 'green', 'red']) X_hats = self.reconstruct() axeslist = [] if index is None: index = range(len(self.lamda)) if type(index) is int: index = [index] for i in index: res = self.X - X_hats[i].squeeze() ax = self.X.plot() ax.plot(self.X.x.data, X_hats[i].squeeze().T.data, color=colXhat) ax.plot(self.X.x.data, res.T.data, color=colRes) ax.set_title(r'2D IRIS merit plot, $\lambda$ = ' + str(self.lamda[i])) axeslist.append(ax) return axeslist def plotdistribution(self, index=None, **kwargs): """ Plots the input dataset, reconstructed dataset and residuals. Parameters ---------- index : optional, int, list or tuple of int. Index(es) of the inversions (i.e. of the lambda values) to consider. If 'None': plots for all indices. default: None kwargs: other optional arguments are passed in the plots Returns ------- list of axes """ axeslist = [] if index is None: index = range(len(self.lamda)) if type(index) is int: index = [index] for i in index: self.f[i].plot(method='map', **kwargs) return axeslist # -------------------------------------------- # Utility functions def Smat(eps): """ returns the matrix used to compute the norm of f second derivative """ m = len(eps) S = np.zeros((m, m)) S[0, 0] = 6 S[0, 1] = -4 S[0, 2] = 1 S[1, 0] = -4 S[1, 1] = 6 S[1, 2] = -4 S[1, 3] = 1 for i in range(2, m - 2): S[i, i - 2] = 1 S[i, i - 1] = -4 S[i, i] = 6 S[i, i + 1] = -4 S[i, i + 2] = 1 S[m - 2, m - 4] = 1 S[m - 2, m - 3] = -4 S[m - 2, m - 2] = 6 S[m - 2, m - 1] = -4 S[m - 1, m - 3] = 1 S[m - 1, m - 2] = -4 S[m - 1, m - 1] = 6 S = ((eps[m - 1] - eps[0]) / (m - 1)) ** (-3) * S return S def nearestPD(A): """Find the nearest positive-definite matrix to input A Python/Numpy port of <NAME>'s `nearestSPD` MATLAB code [1], which credits [2]. [1] https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd [2] <NAME>, "Computing a nearest symmetric positive semidefinite matrix" (1988): https://doi.org/10.1016/0024-3795(88)90223-6 copyright: see https://gist.github.com/fasiha/fdb5cec2054e6f1c6ae35476045a0bbd """ B = (A + A.T) / 2 _, s, V = np.linalg.svd(B) H = np.dot(V.T, np.dot(np.diag(s), V)) A2 = (B + H) / 2 A3 = (A2 + A2.T) / 2 if isPD(A3): return A3 spacing = np.spacing(np.linalg.norm(A)) # The above is different from [1]. It appears that MATLAB's `chol` Cholesky # decomposition will accept matrixes with exactly 0-eigenvalue, whereas # Numpy's will not. So where [1] uses `eps(mineig)` (where `eps` is Matlab # for `np.spacing`), we use the above definition. CAVEAT: our `spacing` # will be much larger than [1]'s `eps(mineig)`, since `mineig` is usually on # the order of 1e-16, and `eps(1e-16)` is on the order of 1e-34, whereas # `spacing` will, for Gaussian random matrixes of small dimension, be on # othe order of 1e-16. In practice, both ways converge, as the unit test # below suggests. Ie = np.eye(A.shape[0]) k = 1 while not isPD(A3): mineig = np.min(np.real(np.linalg.eigvals(A3))) A3 += Ie * (-mineig * k ** 2 + spacing) k += 1 print('makes PD matrix') return A3 def isPD(B): """Returns true when input is positive-definite, via Cholesky copyright: see https://gist.github.com/fasiha/fdb5cec2054e6f1c6ae35476045a0bbd""" try: _ = np.linalg.cholesky(B) return True except np.linalg.LinAlgError: return False <file_sep>/spectrochempy/core/plotters/plotutils.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = [] from spectrochempy.utils import NRed, NBlue, NBlack # ............................................................................ def make_label(ss, lab='<no_axe_label>', use_mpl=True): """ make a label from title and units """ if ss is None: return lab if ss.title: label = ss.title # .replace(' ', r'\ ') else: label = lab if '<untitled>' in label: label = 'values' if use_mpl: if ss.units is not None and str(ss.units) not in ['dimensionless', 'absolute_transmittance']: units = r"/\ {:~L}".format(ss.units) units = units.replace('%', r'\%') else: units = '' label = r"%s $\mathrm{%s}$" % (label, units) else: if ss.units is not None and str(ss.units) != 'dimensionless': units = r"{:~H}".format(ss.units) else: units = '' label = r"%s / %s" % (label, units) return label def make_attr(key): name = 'M_%s' % key[1] k = r'$\mathrm{%s}$' % name if 'P' in name: m = 'o' c = NBlack elif 'A' in name: m = '^' c = NBlue elif 'B' in name: m = 's' c = NRed if '400' in key: f = 'w' s = ':' else: f = c s = '-' return m, c, k, f, s <file_sep>/spectrochempy/core/writers/writecsv.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Plugin module to extend NDDataset with a JCAMP-DX export method. """ # import os as os import csv from spectrochempy.core import debug_, dataset_preferences as prefs from spectrochempy.core.writers.exporter import Exporter, exportermethod __all__ = ['write_csv'] __dataset_methods__ = __all__ # ....................................................................................................................... def write_csv(*args, **kwargs): """ Writes a dataset in CSV format. Currently oinly implemented for 1D datasets or ND datasets with only one dimension of length larger than one Parameters ---------- filename: str or pathlib objet, optional If not provided, a dialog is opened to select a file for writing protocol : {'scp', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for writing. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional Where to write the specified `filename`. If not specified, write in the current directory. description: str, optional A Custom description. delimiter : str, optional Set the column delimiter in CSV file. By default it is ',' or the one set in SpectroChemPy `Preferences`. Returns ------- out : `pathlib` object path of the saved file Examples -------- >>> import spectrochempy as scp >>> ds = scp.NDDataset([1,2,3]) >>> f1 = ds.write_csv('myfile') >>> ds = scp.read('irdata/nh4y-activation.spg') >>> f2 = ds[0].write_csv('single_spectrum.csv') """ exporter = Exporter() kwargs['filetypes'] = ['CSV files (*.csv)'] kwargs['suffix'] = '.csv' return exporter(*args, **kwargs) @exportermethod def _write_csv(*args, **kwargs): debug_("writing csv file") dataset, filename = args dataset.filename = filename delimiter = kwargs.get('delimiter', prefs.csv_delimiter) # check dimensionality of the dataset if dataset.squeeze().ndim > 1: raise NotImplementedError('Only implemented for 1D NDDatasets') # squeeze if necessary if dataset.ndim > 1: dataset = dataset.squeeze() # Make csv file for 1D dataset: first and 2d column are the unique axis and data, respectively with filename.open('w', newline='') as fid: writer = csv.writer(fid, delimiter=delimiter) if dataset.ndim == 1: # if statement for future implementation for ndim > 1.... if dataset.coordset is not None: col_coord = True title_1 = dataset.coordset[-1].title if dataset.coordset[-1].units is not None: title_1 += ' / ' + str(dataset.coordset[-1].units) else: col_coord = False if dataset.units is not None: title_2 = dataset.title + ' / ' + str(dataset.units) else: title_2 = dataset.title if col_coord: coltitles = [title_1, title_2] else: coltitles = [title_2] writer.writerow(coltitles) if col_coord: for i, data in enumerate(dataset.data): writer.writerow([dataset.coordset[-1].data[i], data]) else: for i, data in enumerate(dataset.data): writer.writerow([data]) return filename <file_sep>/tests/test_units/test_units.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy import ur, set_nmr_context, Quantity def test_ppm(): x = 1 * ur.ppm assert x.units == ur.ppm def test_nmr_context(): set_nmr_context(larmor=104.3 * ur.MHz) fhz = 10000 * ur.Hz with ur.context('nmr'): fppm = fhz.to('ppm') assert "{:~.3f}".format(fppm) == '95.877 ppm' print("{:.1f}".format(fppm)) with ur.context('nmr'): fhz = fppm.to('Hz') assert "{:~.3f}".format(fhz) == '10000.000 Hz' print("{:.1f}".format(fhz)) def test_units(): assert 10 * ur.km == 10000 * ur.m assert ur.km / ur.m == 1000. x = (ur.km / ur.m) assert x.dimensionless def test_repr_html(): a = Quantity(10, 's/km') assert "{}".format(a) == "10 second / kilometer" assert a._repr_html_() == "10 s.km<sup>-1</sup>" def test_unit_dimensionality(): a = Quantity(1., 'cm') b = a / Quantity(1., 'km') assert b._repr_html_() == '1.0 scaled-dimensionless (1e-05)' # def test_matplotlib(): # # import matplotlib.pyplot as plt # import numpy as np # import pint # # ureg = pint.UnitRegistry() # ureg.setup_matplotlib(True) # # y = np.linspace(0, 30) * ureg.miles # x = np.linspace(0, 5) * ureg.hours # # fig, ax = plt.subplots() # ax.yaxis.set_units(ureg.inches) # ax.xaxis.set_units(ureg.seconds) # # ax.plot(x, y, 'tab:blue') # # ax.axhline(26400 * ureg.feet, color='tab:red') # ax.axvline(120 * ureg.minutes, color='tab:green') # # # here we just test that we can add some label to the default unit labeling # ax.set_xlabel('xxx ({})'.format(ax.get_xlabel())) # assert ax.get_xlabel() == 'xxx (second)' # # show() <file_sep>/spectrochempy/core/plotters/plotly.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """define plots""" import plotly.graph_objects as go import numpy as np from spectrochempy.utils import colorscale from spectrochempy.core import dataset_preferences # from matplotlib.ticker import MaxNLocator __all__ = ['plotly', 'plotly_stack'] __dataset_methods__ = __all__ # ====================================================================================================================== # nddataset plot2D functions # ====================================================================================================================== # contour map (default) ------------------------------------------------------- def plotly_map(dataset, **kwargs): """ Plot a 2D dataset as a contoured map. Alias of plot_2D (with `method` argument set to ``map``. """ kwargs['method'] = 'map' return plotly(dataset, **kwargs) # stack plot ----------------------------------------------------------------- def plotly_stack(dataset, **kwargs): """ Plot a 2D dataset as a stacked plot. Alias of plot_2D (with `method` argument set to ``stack``). """ kwargs['method'] = 'stack' return plotly(dataset, **kwargs) # image plot -------------------------------------------------------- def plotly_image(dataset, **kwargs): """ Plot a 2D dataset as an image plot. Alias of plot_2D (with `method` argument set to ``image``). """ kwargs['method'] = 'image' return plotly(dataset, **kwargs) # surface plot ----------------------------------------------------------------- def plotly_surface(dataset, **kwargs): """ Plot a 2D dataset as a a 3D-surface. Alias of plot_2D (with `method` argument set to ``surface``. """ kwargs['method'] = 'surface' return plotly(dataset, **kwargs) # generic plot (default stack plot) ------------------------------------------- def plotly(dataset, **kwargs): """ Generate a Plotly plot Parameters ---------- dataset; |NDDataset| The dataset to plot kwargs: any Additional keyword arguments Returns ------- figure A plotly figure """ # get all plot preferences # ------------------------------------------------------------------------------------------------------------------ prefs = dataset.preferences # method of plot # ------------------------------------------------------------------------------------------------------------------ method = kwargs.get('method', None) if not prefs.style: # not yet set, initialize with default project preferences prefs.update(dataset_preferences.to_dict()) # surface specific setting if method not in ['surface']: prefs['colorbar'] = False if method is None: method = prefs.method_2D selector = kwargs.get('selector', '[Processed]') data_transposed = True if 'Transposed' in selector else False name = dataset.name if data_transposed: new = dataset.copy().T # transpose dataset nameadd = ' (Transposed)' else: new = dataset nameadd = '' # new = new.squeeze() # ------------------------------------------------------------------------------------------------------------------ # coordinates # ------------------------------------------------------------------------------------------------------------------ # the actual dimension name for x is the last in the new.dims list dimx = new.dims[-1] x = getattr(new, dimx) # the actual dimension name for y is the one before last in the new.dims list dimy = new.dims[-2] y = getattr(new, dimy) # ------------------------------------------------------------------------------------------------------------------ # Should we display only ROI region? # ------------------------------------------------------------------------------------------------------------------ if 'Processed' in selector: # in this case we make the selection new = new[y.roi[0]:y.roi[1], x.roi[0]:x.roi[1]] x = getattr(new, dimx) y = getattr(new, dimy) xsize = new.shape[-1] ysize = new.shape[-2] # figure setup # ------------------------------------------------------------------------------------------------------------------ fig = new._fig # should we use the previous figure? clear = kwargs.get('clear', True) dragmode = kwargs.get('dragmode', 'zoom') if fig is None or not isinstance(fig, go.Figure) or clear: fig = go.Figure() # set the layout layout = dict( title=name + nameadd, paper_bgcolor='rgba(0,0,0,0)', # transparent autosize=True, hovermode='closest', showlegend=False, clickmode='event+select', dragmode=dragmode, selectdirection='h', margin=dict(t=43, r=50), ) fig.update_layout(layout) if dragmode == 'select': fig.update_layout( paper_bgcolor='lightsalmon', annotations=[ dict( x=2, y=5, xref="x", yref="y", text="Mask selection mode ACTIVE", ax=0, ay=-40 ) ] ) # Other properties # ------------------------------------------------------------------------------------------------------------------ # colorbar = kwargs.get('colorbar', prefs.colorbar) cmap = kwargs.get('cmap', 'viridis') # viridis is the default setting, # so we assume that it must be overwritten here # except if style is grayscale which is a particular case. style = kwargs.get('style', prefs.style) if style and "grayscale" not in style and cmap == "viridis": if method in ['map', 'image']: cmap = kwargs.get('colormap', kwargs.get('cmap', prefs.colormap)) elif data_transposed: cmap = kwargs.get('colormap', kwargs.get('cmap', prefs.colormap_transposed)) elif method in ['surface']: cmap = kwargs.get('colormap', kwargs.get('cmap', prefs.colormap_surface)) else: cmap = kwargs.get('colormap', kwargs.get('cmap', prefs.colormap_stack)) # lw = kwargs.get('linewidth', kwargs.get('lw', # prefs.pen_linewidth)) # alpha = kwargs.get('calpha', prefs.contour_alpha) # antialiased = kwargs.get('antialiased', prefs.antialiased) # rcount = kwargs.get('rcount', prefs.rcount) # ccount = kwargs.get('ccount', prefs.ccount) number_x_labels = prefs.number_of_x_labels # number_y_labels = prefs.number_of_y_labels # ax.xaxis.set_major_locator(MaxNLocator(nbins=number_x_labels)) # ax.yaxis.set_major_locator(MaxNLocator(nbins=number_y_labels)) # x_locator = MaxNLocator(nbins=number_x_labels) # y_locator = MaxNLocator(nbins=number_y_labels) # if method not in ['surface']: # ax.xaxis.set_ticks_position('bottom') # ax.yaxis.set_ticks_position('left') # the next lines are to avoid multipliers in axis scale # formatter = ScalarFormatter(useOffset=False) # ax.xaxis.set_major_formatter(formatter) # ax.yaxis.set_major_formatter(formatter) # ------------------------------------------------------------------------------------------------------------------ # Set axis # ------------------------------------------------------------------------------------------------------------------ # set the abscissa axis # ------------------------------------------------------------------------------------------------------------------ # discrete_data = False if x is not None and (not x.is_empty or x.is_labeled): xdata = x.data if not np.any(xdata): if x.is_labeled: # discrete_data = True # take into account the fact that sometimes axis have just labels xdata = range(1, len(x.labels) + 1) # TODO it would be more convenient if the data attribute returned the correct values else: xdata = range(xsize) xl = [xdata[0], xdata[-1]] xl.sort() if xsize < number_x_labels + 1: # extend the axis so that the labels are not too close to the limits inc = abs(xdata[1] - xdata[0]) * .5 xl = [xl[0] - inc, xl[1] + inc] xlim = list(kwargs.get('xlim', xl)) # zoom? xlim.sort() xlim[-1] = min(xlim[-1], xl[-1]) xlim[0] = max(xlim[0], xl[0]) if kwargs.get('x_reverse', kwargs.get('reverse', x.reversed if x else False)): xlim.reverse() # xscale = kwargs.get("xscale", "linear") fig.update_layout( dict( xaxis=_make_axis('x', range=xlim, label=f'{x.alt_title} / {x.units:~P}', **kwargs), ) ) # set the ordinates axis # ------------------------------------------------------------------------------------------------------------------ # the actual dimension name is the second in the new.dims list dimy = new.dims[-2] y = getattr(new, dimy) ysize = new.shape[-2] if y is not None and (not y.is_empty or y.is_labeled): ydata = y.data if not np.any(ydata): if y.is_labeled: ydata = range(1, len(y.labels) + 1) else: ydata = range(ysize) yl = [ydata[0], ydata[-1]] yl.sort() # if ysize < number_y_labels + 1: # # extend the axis so that the labels are not too close to the limits # inc = abs(ydata[1] - ydata[0]) * .5 # yl = [yl[0] - inc, yl[1] + inc] ylim = list(kwargs.get("ylim", yl)) ylim.sort() ylim[-1] = min(ylim[-1], yl[-1]) ylim[0] = max(ylim[0], yl[0]) # yscale = kwargs.get("yscale", "linear") fig.update_layout( dict( yaxis=_make_axis('y', label=f'{new.title} / {new.units:~P}', **kwargs), ) ) zoomreset = kwargs.get('zoomreset', None) uirevision = f'{new} {zoomreset}' fig.update_layout( dict( uirevision=uirevision, ) ) # Data # colorscale amp = 0 mi = np.ma.min(y.data) ma = np.ma.max(y.data) if kwargs.get('reduce_range', True): amp = (ma - mi) / 20. if kwargs.get('extrema', True): vmin, vmax = mi - amp, ma + amp else: vmin, vmax = -ma - amp, ma + amp # Here I am using matplotlib to find the color map # because I did not find the way to do this easily using plotly) colorscale.normalize(vmin, vmax, cmap=cmap, rev=False) # DATA data = [] optimisation = kwargs.get('optimisation', 0) offset = getattr(new, dimx).offset for trace in _compress(new[::-1], optimisation): name = f'{getattr(trace, dimy).values:~P}' # - dataset.y.offset_value:~P}' color = colorscale.rgba(getattr(trace, dimy).data) # , offset=yoffset) trace = trace.squeeze() x = getattr(trace, dimx).data if trace.mask is not None and np.any(trace.mask): z = trace.data z[trace.mask] = np.NaN else: z = trace.data y_string = f'{getattr(new, dimy).alt_title}:' + ' %{fullData.name} <br>' if getattr(new, dimy).size > 1 else '' data.append(dict(x=x, xaxis='x', y=z, yaxis='y', name=name, hoverlabel=dict( font_size=12, font_family="Rockwell" ), hovertemplate=f'{getattr(trace, dimx).alt_title}:' ' %{x:.2f} ' f'{getattr(trace, dimx).units:~P}' f'<br>' f'{y_string}' f'{trace.alt_title}:' ' %{y:.2f} ' f'{trace.units:~P}' '<extra></extra>', mode='lines', type='scattergl', connectgaps=False, line=dict( color=color, dash='solid', width=1.5), ) ) fig.add_traces(data) # show out of X ROI zone fullrange = getattr(new, dimx).limits roirange = getattr(new, dimx).roi x0, x1 = fullrange[0], roirange[0] - offset x2, x3 = fullrange[1], roirange[1] - offset fig.update_layout( shapes=[ dict( type="rect", # x-reference is assigned to the x-values xref="x", # y-reference is assigned to the plot paper [0,1] yref="paper", x0=x0, y0=0, x1=x1, y1=1, fillcolor="LightSalmon", opacity=0.2, layer="below", line_width=0, ), dict( type="rect", # x-reference is assigned to the x-values xref="x", # y-reference is assigned to the plot paper [0,1] yref="paper", x0=x2, y0=0, x1=x3, y1=1, fillcolor="LightSalmon", opacity=0.2, layer="below", line_width=0, ), ] ) return fig def _make_axis(axis, range=None, label=None, **kwargs): fontsize = kwargs.get('fontsize', 18) return dict( anchor='y' if axis == 'x' else 'x', domain=[0.0, 1.0], nticks=7, range=range, showgrid=True, side='bottom' if axis == 'x' else 'left', tickfont={ # 'family': 'Times', 'size': fontsize }, ticks='outside', title={ 'font': { # 'family': 'Times', 'color': '#000000', 'size': fontsize, }, 'text': label, }, type='linear', zeroline=False, linecolor='black', linewidth=1, mirror=True, ) def point_line_distance(x0, y0, x1, y1, x2, y2): return np.abs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1)) / np.sqrt( (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) def calc_distances(p, start=None, end=None): """ Parameters ---------- p : |NDDataset| """ dimx = p.dims[-1] x = getattr(p, dimx).data z = p.data # ny = z.shape[0] if start is None: start = 0 if end is None: end = x.size - 1 distances = np.zeros(z.shape) for i in range(start + 1, end): distances[i] = point_line_distance(x[i], z[i], x[start], z[start], x[end], z[end]) return distances def douglas_peucker(tolerance, p, mask, start, end, it): distances = calc_distances(p, start, end) more = distances > tolerance sum = np.count_nonzero(more) if sum > 0: maxindex = np.argmax(distances) mask[maxindex] = False m1 = douglas_peucker(tolerance, p, mask, start, maxindex, it + 1) m2 = douglas_peucker(tolerance, p, mask, maxindex, end, it + 1) mask = np.logical_and(mask, m1) mask = np.logical_and(mask, m2) else: for i in range(start + 1, end): if distances[i] <= tolerance: mask[i] = True return mask def simplify_douglas_peucker(tolerance, ds): # start by masking all the row of data except extremity new = ds.copy() new.mask = np.ones_like(ds, dtype='bool') new.mask[0] = False new.mask[-1] = False mask = douglas_peucker(tolerance, new, new.mask.copy(), 0, new.size - 1, 0) new.mask[:] = mask return new def _compress(ds, optimisation=None): """ reduce the number of spectra to display Parameters ---------- ds: |NDDataset| The dataset to simplify Returns ------- a list a (x,y) traces """ sizey, sizex = ds.shape # # find the closeness of each trace # # we always keep the first and the last if (optimisation == 0 and sizey < 100) or sizey < 5: return ds COUNT = { 0: 1000, 1: 500, 2: 150, 3: 30, 4: 5 }[optimisation] dd = np.sum(ds, axis=1) new = dd.copy() if new.size > 250: COUNT = COUNT / 4 TOLERANCE = np.max(calc_distances(dd)) / COUNT new = simplify_douglas_peucker(TOLERANCE, dd) print(np.count_nonzero(~new.mask), COUNT) keep = [] for i, b in enumerate(new.mask): if not b: keep.append(ds[i]) return keep if __name__ == '__main__': pass <file_sep>/spectrochempy/core/dataset/ndcomplex.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements a subclass of |NDArray| with complex/quaternion related attributes. """ __all__ = ['NDComplexArray', ] __dataset_methods__ = [] import itertools import textwrap import numpy as np from traitlets import validate, Bool from quaternion import as_float_array, as_quat_array from spectrochempy.core.dataset.ndarray import NDArray from spectrochempy.utils import (NOMASK, TYPE_FLOAT, TYPE_COMPLEX, typequaternion, as_quaternion, get_component, insert_masked_print) from spectrochempy.units import Quantity # ====================================================================================================================== # NDComplexArray # ====================================================================================================================== class NDComplexArray(NDArray): _interleaved = Bool(False) # .................................................................................................................. def __init__(self, data=None, **kwargs): """ This class provides the complex/quaternion related functionalities to |NDArray|. It is a subclass bringing complex and quaternion related attributes. Parameters ---------- data : array of complex number or quaternion. Data array contained in the object. The data can be a list, a tuple, a |ndarray|, a ndarray-like, a |NDArray| or any subclass of |NDArray|. Any size or shape of data is accepted. If not given, an empty |NDArray| will be inited. At the initialisation the provided data will be eventually casted to a numpy-ndarray. If a subclass of |NDArray| is passed which already contains some mask, labels, or units, these elements will be used to accordingly set those of the created object. If possible, the provided data will not be copied for `data` input, but will be passed by reference, so you should make a copy of the `data` before passing them if that's the desired behavior or set the `copy` argument to True. Other Parameters ---------------- dims : list of chars, optional. if specified the list must have a length equal to the number od data dimensions (ndim) and the chars must be taken among among x,y,z,u,v,w or t. If not specified, the dimension names are automatically attributed in this order. name : str, optional A user friendly name for this object. If not given, the automatic `id` given at the object creation will be used as a name. labels : array of objects, optional Labels for the `data`. labels can be used only for 1D-datasets. The labels array may have an additional dimension, meaning several series of labels for the same data. The given array can be a list, a tuple, a |ndarray|, a ndarray-like, a |NDArray| or any subclass of |NDArray|. mask : array of bool or `NOMASK`, optional Mask for the data. The mask array must have the same shape as the data. The given array can be a list, a tuple, or a |ndarray|. Each values in the array must be `False` where the data are *valid* and True when they are not (like in numpy masked arrays). If `data` is already a :class:`~numpy.ma.MaskedArray`, or any array object (such as a |NDArray| or subclass of it), providing a `mask` here will causes the mask from the masked array to be ignored. units : |Unit| instance or str, optional Units of the data. If data is a |Quantity| then `units` is set to the unit of the `data`; if a unit is also explicitly provided an error is raised. Handling of units use the `pint <https://pint.readthedocs.org/>`_ package. title : str, optional The title of the dimension. It will later be used for instance for labelling plots of the data. It is optional but recommended to give a title to each ndarray. dlabel : str, optional. Alias of `title`. meta : dict-like object, optional. Additional metadata for this object. Must be dict-like but no further restriction is placed on meta. author : str, optional. name(s) of the author(s) of this dataset. BNy default, name of the computer note where this dataset is created. description : str, optional. A optional description of the nd-dataset. A shorter alias is `desc`. history : str, optional. A string to add to the object history. copy : bool, optional Perform a copy of the passed object. Default is False. See Also -------- NDDataset : Object which subclass |NDArray| with the addition of coordinates. Examples -------- >>> from spectrochempy import NDComplexArray >>> myarray = NDComplexArray([1. + 0j, 2., 3.]) >>> myarray NDComplexArray: [complex128] unitless (size: 3) """ super().__init__(data=data, **kwargs) # .................................................................................................................. def implements(self, name=None): """ Utility to check if the current object implement `NDComplexArray`. Rather than isinstance(obj, NDComplexArrray) use object.implements('NDComplexArray'). This is useful to check type without importing the module """ if name is None: return 'NDComplexArray' else: return name == 'NDComplexArray' # ------------------------------------------------------------------------------------------------------------------ # validators # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @validate('_data') def _data_validate(self, proposal): # validation of the _data attribute # overrides the NDArray method data = proposal['value'] # cast to the desired type if self._dtype is not None: if self._dtype == data.dtype: pass # nothing more to do elif self._dtype not in [typequaternion] + list(TYPE_COMPLEX): data = data.astype(np.dtype(self._dtype), copy=False) elif self._dtype in TYPE_COMPLEX: data = self._make_complex(data) elif self._dtype == typequaternion: data = self._make_quaternion(data) elif data.dtype not in [typequaternion] + list(TYPE_COMPLEX): data = data.astype(np.float64, copy=False) # by default dta are float64 if the dtype is not fixed # return the validated data if self._copy: return data.copy() else: return data # ------------------------------------------------------------------------------------------------------------------ # read-only properties / attributes # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @property def has_complex_dims(self): """ bool - True if at least one of the `data` array dimension is complex (Readonly property). """ if self._data is None: return False return (self._data.dtype in TYPE_COMPLEX) or (self._data.dtype == typequaternion) # .................................................................................................................. @property def is_complex(self): """ bool - True if the 'data' are complex (Readonly property). """ if self._data is None: return False return self._data.dtype in TYPE_COMPLEX # .................................................................................................................. @property def is_quaternion(self): """ bool - True if the `data` array is hypercomplex (Readonly property). """ if self._data is None: return False return (self._data.dtype == typequaternion) # .................................................................................................................. @property def is_interleaved(self): """ bool - True if the `data` array is hypercomplex with interleaved data (Readonly property). """ if self._data is None: return False return self._interleaved # (self._data.dtype == typequaternion) # .................................................................................................................. @property def is_masked(self): """ bool - True if the `data` array has masked values (Readonly property). """ try: return super().is_masked except Exception as e: if self._data.dtype == typequaternion: return np.any(self._mask['I']) else: raise e # .................................................................................................................. @property def real(self): """ array - The array with real component of the `data` (Readonly property). """ new = self.copy() if not new.has_complex_dims: return new ma = new.masked_data if ma.dtype in TYPE_FLOAT: new._data = ma elif ma.dtype in TYPE_COMPLEX: new._data = ma.real elif ma.dtype == typequaternion: # get the scalar component # q = a + bi + cj + dk -> qr = a new._data = as_float_array(ma)[..., 0] else: raise TypeError('dtype %s not recognized' % str(ma.dtype)) if isinstance(ma, np.ma.masked_array): new._mask = ma.mask return new # .................................................................................................................. @property def imag(self): """ array - The array with imaginary component of the `data` (Readonly property). """ new = self.copy() if not new.has_complex_dims: return None ma = new.masked_data if ma.dtype in TYPE_FLOAT: new._data = np.zeros_like(ma.data) elif ma.dtype in TYPE_COMPLEX: new._data = ma.imag.data elif ma.dtype == typequaternion: # this is a more complex situation than for real component # get the imaginary component (vector component) # q = a + bi + cj + dk -> qi = bi+cj+dk as_float_array(ma)[..., 0] = 0 # keep only the imaginary component new._data = ma # .data else: raise TypeError('dtype %s not recognized' % str(ma.dtype)) if isinstance(ma, np.ma.masked_array): new._mask = ma.mask return new # .................................................................................................................. @property def RR(self): """ array - The array with real component in both dimension of hypercomplex 2D `data` (Readonly property). this is equivalent to the `real` property """ if not self.is_quaternion: raise TypeError('Not an hypercomplex array') return self.real # .................................................................................................................. @property def RI(self): """ array - The array with real-imaginary component of hypercomplex 2D `data` (Readonly property). """ if not self.is_quaternion: raise TypeError('Not an hypercomplex array') return self.component('RI') # .................................................................................................................. @property def IR(self): """ array - The array with imaginary-real component of hypercomplex 2D `data` (Readonly property). """ if not self.is_quaternion: raise TypeError('Not an hypercomplex array') return self.component('IR') # .................................................................................................................. @property def II(self): """ array - The array with imaginary-imaginary component of hypercomplex 2D data (Readonly property). """ if not self.is_quaternion: raise TypeError('Not an hypercomplex array') return self.component('II') # .................................................................................................................. @property def limits(self): """ list - range of the data """ if self.data is None: return None if self.data.dtype in TYPE_COMPLEX: return [self.data.real.min(), self.data.imag.max()] elif self.data.dtype == np.quaternion: data = as_float_array(self.data)[..., 0] return [data.min(), data.max()] else: return [self.data.min(), self.data.max()] # ------------------------------------------------------------------------------------------------------------------ # Public methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def component(self, select='REAL'): """ Take selected components of an hypercomplex array (RRR, RIR, ...) Parameters ---------- select : str, optional, default='REAL' if 'REAL', only real component in all dimensions will be selected. ELse a string must specify which real (R) or imaginary (I) component has to be selected along a specific dimension. For instance, a string such as 'RRI' for a 2D hypercomplex array indicated that we take the real component in each dimension except the last one, for which imaginary component is preferred. Returns ------- component component of the complex or hypercomplex array """ if not select: # no selection - returns inchanged return self new = self.copy() ma = self.masked_data ma = get_component(ma, select) if isinstance(ma, np.ma.masked_array): new._data = ma.data new._mask = ma.mask else: new._data = ma if hasattr(ma, 'mask'): new._mask = ma.mask else: new._mask = NOMASK return new # .................................................................................................................. def set_complex(self, inplace=False): """ Set the object data as complex. When nD-dimensional array are set to complex, we assume that it is along the first dimension. Two succesives rows are merged to form a complex rows. This means that the number of row must be even If the complexity is to be applied in other dimension, either transpose/swapdims your data before applying this function in order that the complex dimension is the first in the array. Parameters ---------- inplace : bool, optional, default=False Flag to say that the method return a new object (default) or not (inplace=True). Returns ------- out Same object or a copy depending on the ``inplace`` flag. See Also -------- set_quaternion, has_complex_dims, is_complex, is_quaternion """ if not inplace: # default is to return a new array new = self.copy() else: new = self # work inplace if new.has_complex_dims: # not necessary in this case, it is already complex return new new._data = new._make_complex(new._data) return new # .................................................................................................................. def set_quaternion(self, inplace=False): """ Set the object data as quaternion. Parameters ---------- inplace : bool, optional, default=False Flag to say that the method return a new object (default) or not (inplace=True). Returns ------- out Same object or a copy depending on the ``inplace`` flag. """ if not inplace: # default is to return a new array new = self.copy() else: new = self # work inplace if new.dtype != typequaternion: # not already a quaternion new._data = new._make_quaternion(new.data) return new set_hypercomplex = set_quaternion set_hypercomplex.__doc__ = 'Alias of set_quaternion' # .................................................................................................................. def transpose(self, *dims, inplace=False): """ Transpose the complex array. Parameters ---------- dims : int, str or tuple of int or str, optional, default=(0,) Dimension names or indexes along which the method should be applied. inplace : bool, optional, default=False Flag to say that the method return a new object (default) or not (inplace=True) Returns ------- transposed Same object or a copy depending on the ``inplace`` flag. """ new = super().transpose(*dims, inplace=inplace) if new.is_quaternion: # here if it is hypercomplex quaternion # we should interchange the imaginary component w, x, y, z = as_float_array(new._data).T q = as_quat_array(list(zip(w.T.flatten(), y.T.flatten(), x.T.flatten(), z.T.flatten()))) new._data = q.reshape(new.shape) return new def swapdims(self, dim1, dim2, inplace=False): """ Swap dimension the complex array. swapdims and swapaxes are alias. Parameters ---------- dims : int, str or tuple of int or str, optional, default=(0,) Dimension names or indexes along which the method should be applied. inplace : bool, optional, default=False Flag to say that the method return a new object (default) or not (inplace=True) Returns ------- transposed Same object or a copy depending on the ``inplace`` flag. """ new = super().swapdims(dim1, dim2, inplace=inplace) # we need also to swap the quaternion # WARNING: this work only for 2D - when swapdims is equivalent to a 2D transpose # TODO: implement something for any n-D array (n>2) if self.is_quaternion: # here if it is is_quaternion # we should interchange the imaginary component w, x, y, z = as_float_array(new._data).T q = as_quat_array(list(zip(w.T.flatten(), y.T.flatten(), x.T.flatten(), z.T.flatten()))) new._data = q.reshape(new.shape) return new # ------------------------------------------------------------------------------------------------------------------ # private methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def _str_shape(self): if self.is_empty: return ' size: 0\n' out = '' cplx = [False] * self.ndim if self.is_quaternion: cplx = [True, True] elif self.is_complex: cplx[-1] = True shcplx = (x for x in itertools.chain.from_iterable(list(zip(self.dims, self.shape, cplx)))) shape = (', '.join(['{}:{}{}'] * self.ndim)).format(*shcplx).replace('False', '').replace('True', '(complex)') size = self.size sizecplx = '' if not self.has_complex_dims else " (complex)" out += f' size: {size}{sizecplx}\n' if self.ndim < 2 else f' shape: ({shape})\n' return out # .................................................................................................................. def _str_value(self, sep='\n', ufmt=' {:~K}', header=" values: ... \n"): prefix = [''] if self.is_empty: return header + '{}'.format(textwrap.indent('empty', ' ' * 9)) if self.has_complex_dims: # we will display the different component separately if self.is_quaternion: prefix = ['RR', 'RI', 'IR', 'II'] else: prefix = ['R', 'I'] units = ufmt.format(self.units) if self.has_units else '' def mkbody(d, pref, units): # work around printing masked values with formatting ds = d.copy() if self.is_masked: dtype = self.dtype mask_string = f'--{dtype}' ds = insert_masked_print(ds, mask_string=mask_string) body = np.array2string(ds, separator=' ', prefix=pref) body = body.replace('\n', sep) text = ''.join([pref, body, units]) text += sep return text text = '' if 'I' not in ''.join(prefix): # case of pure real data (not hypercomplex) if self._data is not None: data = self.umasked_data if isinstance(data, Quantity): data = data.magnitude text += mkbody(data, '', units) else: for pref in prefix: if self._data is not None: data = self.component(pref).umasked_data if isinstance(data, Quantity): data = data.magnitude text += mkbody(data, pref, units) out = ' DATA \n' out += f' title: {self.title}\n' if self.title else '' out += header out += '\0{}\0'.format(textwrap.indent(text.strip(), ' ' * 9)) out = out.rstrip() # remove the trailings '\n' return out # .................................................................................................................. def _make_complex(self, data): if data.dtype in TYPE_COMPLEX: return data.astype(np.complex128) if data.shape[-1] % 2 != 0: raise ValueError("An array of real data to be transformed to complex must have an even number of columns!.") data = data.astype(np.float64) # to work the data must be in C order fortran = np.isfortran(data) if fortran: data = np.ascontiguousarray(data) data.dtype = np.complex128 # restore the previous order if fortran: data = np.asfortranarray(data) else: data = np.ascontiguousarray(data) self._dtype = None # reset dtype return data # .................................................................................................................. def _make_quaternion(self, data): if data.ndim % 2 != 0: raise ValueError("An array of data to be transformed to quaternion must be 2D.") if data.dtype not in TYPE_COMPLEX: if data.shape[1] % 2 != 0: raise ValueError( "An array of real data to be transformed to quaternion must have even number of columns!.") # convert to double precision complex data = self._make_complex(data) if data.shape[0] % 2 != 0: raise ValueError("An array data to be transformed to quaternion must have even number of rows!.") r = data[::2] i = data[1::2] # _data = as_quat_array(list(zip(r.real.flatten(), r.imag.flatten(), i.real.flatten(), i.imag.flatten()))) # _data = _data.reshape(r.shape) self._dtype = None # reset dtyep return as_quaternion(r, i) # ------------------------------------------------------------------------------------------------------------------ # special methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def __setitem__(self, items, value): super().__setitem__(items, value) # ====================================================================================================================== if __name__ == '__main__': pass # end of module <file_sep>/spectrochempy/core/dataset/npy.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, # Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in # the root directory = # ====================================================================================================================== """ In this module, we define basic functions adapted from numpy but able to handle our NDDataset objects """ __all__ = ['dot'] import numpy as np from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.utils import make_new_object # ............................................................................ def dot(a, b, strict=True, out=None): """ Return the dot product of two NDDatasets. This function is the equivalent of `numpy.dot` that takes NDDataset as input .. note:: Works only with 2-D arrays at the moment. Parameters ---------- a, b : masked_array_like Inputs arrays. strict : bool, optional Whether masked data are propagated (True) or set to 0 (False) for the computation. Default is False. Propagating the mask means that if a masked value appears in a row or column, the whole row or column is considered masked. out : masked_array, optional Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for `dot(a,b)`. This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. See Also -------- numpy.dot : Equivalent function for ndarrays. numpy.ma.dot : Equivalent function for masked ndarrays """ # if not a.implements('NDDataset'): # raise TypeError('A dataset of type NDDataset is ' # 'expected as a source of data, but an object' # ' of type {} has been provided'.format( # type(a).__name__)) # # if not b.implements('NDDataset'): # raise TypeError('A dataset of type NDDataset is ' # 'expected as a source of data, but an object' # ' of type {} has been provided'.format( # type(b).__name__)) # TODO: may be we can be less strict, and allow dot products with # different kind of objects, as far they are numpy-like arrays if not isinstance(a, NDDataset) and not isinstance(a, NDDataset): # must be between numpy object or something non valid. Let numpy # deal with this return np.dot(a, b) if not isinstance(a, NDDataset): # try to cast to NDDataset a = NDDataset(a) if not isinstance(b, NDDataset): # try to cast to NDDataset b = NDDataset(b) data = np.ma.dot(a.masked_data, b.masked_data) mask = data.mask data = data.data if a.coordset is not None: coordy = getattr(a, a.dims[0]) else: coordy = None if b.coordset is not None: coordx = getattr(b, b.dims[1]) else: coordx = None history = 'Dot product between %s and %s' % (a.name, b.name) # make the output # ------------------------------------------------------------------------------------------------------------------ new = make_new_object(a) new._data = data new._mask = mask new.set_coordset(y=coordy, x=coordx) new.history = history if a.unitless: new.units = b.units elif b.unitless: new.units = a.units else: new.units = a.units * b.units return new # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/tests/test_plotters/test_plot3D.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os from spectrochempy import NDDataset, Coord, show def test_plot2D_as_3D(): data = NDDataset.read_matlab(os.path.join('matlabdata', 'als2004dataset.MAT')) X = data[0] # X.plot_3D() X.plot_surface() X.set_coordset(y=Coord(title='elution time'), x=Coord(title='wavenumbers')) X.title = 'intensity' X.plot_surface() X.plot_surface(colorbar=True) show() pass # ============================================================================= if __name__ == '__main__': pass <file_sep>/spectrochempy/core/analysis/simplisma.py # -*- coding: utf-8 -*- # # ============================================================================= # Copyright (©) 2015-2021 LCS # Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT # See full LICENSE agreement in the root directory # ============================================================================= """ This module implement the SIMPLISMA class. """ __all__ = ['SIMPLISMA'] __dataset_methods__ = [] # ---------------------------------------------------------------------------- # imports # ---------------------------------------------------------------------------- import numpy as np import warnings from traitlets import HasTraits, Instance, Unicode from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.npy import dot from spectrochempy.core import info_, set_loglevel, INFO # ============================================================================ # class SIMPLISMA # ============================================================================ class SIMPLISMA(HasTraits): """ SIMPLe to use Interactive Self-modeling Mixture Analysis. This class performs a SIMPLISMA analysis of a 2D |NDDataset|. The algorithm is adapted from Windig's paper, Chemometrics and Intelligent Laboratory Systems, 36, 1997, 3-16. TODO : adapt to 3DDataset ? """ _St = Instance(NDDataset) _C = Instance(NDDataset) _X = Instance(NDDataset) _Pt = Instance(NDDataset) _s = Instance(NDDataset) _logs = Unicode def __init__(self, dataset, **kwargs): """ Parameters ---------- dataset : |NDDataset| A 2D dataset containing the data matrix (spectra in rows). interactive : bool, optional, default=False If True, the determination of purest variables is carried out interactively n_pc : int, optional, default=2 in non-interactive mode; 100 in interactive mode The maximum number of pure compounds. Used only for non interactive analysis (the default in interative mode (100) will never be reached in practice). tol : float, optional, default=0.1 The convergence criterion on the percent of unexplained variance. noise : float or int, optional, default=5 A correction factor (%) for low intensity variables (0 - no offset, 15 - large offset). verbose : bool, optional, default=True If True some information is given during the analysis. """ super().__init__() # ------------------------------------------------------------------------ # Utility functions # ------------------------------------------------------------------------ def figures_of_merit(X, maxPIndex, C, St, j): # return %explained variance and stdev of residuals when the jth compound is added C[:, j] = X[:, maxPIndex[j]] St[0:j + 1, :] = np.linalg.lstsq(C.data[:, 0:j + 1], X.data, rcond=None)[0] Xhat = dot(C[:, 0:j + 1], St[0:j + 1, :]) res = Xhat - X stdev_res = np.std(res) rsquare = 1 - np.linalg.norm(res) ** 2 / np.linalg.norm(X) ** 2 return rsquare, stdev_res def str_iter_summary(j, index, coord, rsquare, stdev_res, diff): # return formatted list of figure of merits at a given iteration string = '{:4} {:5} {:8.1f} {:10.4f} {:10.4f} '.format(j + 1, index, coord, stdev_res, rsquare) return string def get_x_data(X): if X.x is not None and not X.x.is_empty: # TODO what about labels? return X.x.data else: return np.arange(X.shape[-1]) # ------------------------------------------------------------------------ # Check data # ------------------------------------------------------------------------ X = dataset if len(X.shape) != 2: raise ValueError('For now, SIMPLISMA only handles 2D Datasets') if np.min(X.data) < 0: warnings.warn('SIMPLISMA does not handle easily negative values.') # TODO: check whether negative values should be set to zero or not. verbose = kwargs.get('verbose', True) if verbose: set_loglevel(INFO) interactive = kwargs.get('interactive', False) tol = kwargs.get('tol', 0.1) noise = kwargs.get('noise', 3) n_pc = kwargs.get('n_pc', 2) if n_pc < 2 or not isinstance(n_pc, int): raise ValueError('Oh you did not just... \'MA\' in simplisMA stands for Mixture Analysis. ' 'The number of pure compounds should be an integer larger than 2') if interactive: n_pc = 100 # ------------------------------------------------------------------------ # Core # ------------------------------------------------------------------------ if not interactive: logs = '*** Automatic SIMPL(I)SMA analysis *** \n' else: logs = '*** Interative SIMPLISMA analysis *** \n' logs += 'dataset: {}\n'.format(X.name) logs += ' noise: {:2} %\n'.format(noise) if not interactive: logs += ' tol: {:2} %\n'.format(tol) logs += ' n_pc: {:2}\n'.format(n_pc) logs += '\n' logs += '#iter index_pc coord_pc Std(res) R^2 \n' logs += '---------------------------------------------' info_(logs) logs += '\n' # Containers for returned objects and intermediate data # --------------------------------------------------- # purity 'spectra' (generally spectra if X is passed, # but could also be concentrations if X.T is passed) Pt = NDDataset.zeros((n_pc, X.shape[-1])) Pt.name = 'Purity spectra' Pt.set_coordset(y=Pt.y, x=X.x) Pt.y.title = '# pure compound' # weight matrix w = NDDataset.zeros((n_pc, X.shape[-1])) w.set_coordset(y=Pt.y, x=X.x) # Stdev spectrum s = NDDataset.zeros((n_pc, X.shape[-1])) s.name = 'Standard deviation spectra' s.set_coordset(y=Pt.y, x=X.x) # maximum purity indexes and coordinates maxPIndex = [0] * n_pc maxPCoordinate = [0] * n_pc # Concentration matrix C = NDDataset.zeros((X.shape[-2], n_pc)) C.name = 'Relative Concentrations' C.set_coordset(y=X.y, x=C.x) C.x.title = '# pure compound' # Pure component spectral profiles St = NDDataset.zeros((n_pc, X.shape[-1])) St.name = 'Pure compound spectra' St.set_coordset(y=Pt.y, x=X.x) # Compute Statistics # ------------------ sigma = np.std(X.data, axis=0) mu = np.mean(X.data, axis=0) alpha = (noise / 100) * np.max(mu.data) lamda = np.sqrt(mu ** 2 + sigma ** 2) p = sigma / (mu + alpha) # scale dataset Xscaled = X.data / np.sqrt(mu ** 2 + (sigma + alpha) ** 2) # COO dispersion matrix COO = (1 / X.shape[-2]) * np.dot(Xscaled.T, Xscaled) # Determine the purest variables j = 0 finished = False while not finished: # compute first purest variable and weights if j == 0: w[j, :] = lamda ** 2 / (mu ** 2 + (sigma + alpha) ** 2) s[j, :] = sigma * w[j, :] Pt[j, :] = p * w[j, :] # get index and coordinate of pure variable maxPIndex[j] = np.argmax(Pt[j, :].data) maxPCoordinate[j] = get_x_data(X)[maxPIndex[j]] # compute figures of merit rsquare0, stdev_res0 = figures_of_merit(X, maxPIndex, C, St, j) # add summary to log llog = str_iter_summary(j, maxPIndex[j], maxPCoordinate[j], rsquare0, stdev_res0, '') logs += llog + '\n' if verbose or interactive: print(llog) if interactive: # should plot purity and stdev, does not work for the moment # TODO: fix the code below # fig1, (ax1, ax2) = plt.subplots(2,1) # Pt[j, :].plot(ax=ax1) # ax1.set_title('Purity spectrum #{}'.format(j+1)) # ax1.axvline(maxPCoordinate[j], color='r') # s[j, :].plot(ax=ax2) # ax2.set_title('standard deviation spectrum #{}'.format(j+1)) # ax2.axvline(maxPCoordinate[j], color='r') # plt.show() ans = '' while ans.lower() not in ['a', 'c']: ans = input(' |--> (a) Accept, (c) Change: ') while ans.lower() != 'a': new = input(' |--> enter the new index (int) or variable value (float): ') try: new = int(new) maxPIndex[j] = new maxPCoordinate[j] = get_x_data(X)[maxPIndex[j]] except ValueError: try: new = float(new) maxPIndex[j] = np.argmin(abs(get_x_data(X) - new)) maxPCoordinate[j] = get_x_data(X)[maxPIndex[j]] except ValueError: print('Incorrect answer. Please enter a valid index or value') rsquare0, stdev_res0 = figures_of_merit(X, maxPIndex, C, St, j) llog = str_iter_summary(j, maxPIndex[j], maxPCoordinate[j], rsquare0, stdev_res0, '') logs += ' |--> changed pure variable #1' logs += llog + '\n' info_(llog) ans = input(' |--> (a) Accept, (c) Change: ') # ans was [a]ccept j += 1 if not interactive: j += 1 prev_stdev_res = stdev_res0 else: # compute jth purest variable for i in range(X.shape[-1]): Mji = np.zeros((j + 1, j + 1)) idx = [i] + maxPIndex[0:j] for line in range(j + 1): for col in range(j + 1): Mji[line, col] = COO[idx[line], idx[col]] w[j, i] = np.linalg.det(Mji) Pt[j:] = p * w[j, :] s[j, :] = sigma * w[j, :] # get index and coordinate of jth pure variable maxPIndex[j] = np.argmax(Pt[j, :].data) maxPCoordinate[j] = get_x_data(X)[maxPIndex[j]] # compute figures of merit rsquarej, stdev_resj = figures_of_merit(X, maxPIndex, C, St, j) diff = 100 * (stdev_resj - prev_stdev_res) / prev_stdev_res prev_stdev_res = stdev_resj # add summary to log llog = str_iter_summary(j, maxPIndex[j], maxPCoordinate[j], rsquarej, stdev_resj, diff) logs += llog + '\n' if verbose or interactive: info_(llog) if interactive: # TODO: I suggest to use jupyter widgets for the interactivity! # should plot purity and stdev, does not work for the moment # TODO: fix the code below # ax1.clear() # ax1.set_title('Purity spectrum #{}'.format(j+1)) # Pt[j, :].plot(ax=ax1) # for coord in maxPCoordinate[:-1]: # ax1.axvline(coord, color='g') # ax1.axvline(maxPCoordinate[j], color='r') # ax2.clear() # ax2.set_title('standard deviation spectrum #{}'.format(j+1)) # s[j, :].plot(ax=ax2) # for coord in maxPCoordinate[:-1]: # ax2.axvline(coord, color='g') # ax2.axvline(maxPCoordinate[j], color='r') # plt.show() ans = '' while ans.lower() not in ['a', 'c', 'r', 'f']: ans = input(' |--> (a) Accept and continue, (c) Change, (r) Reject, (f) Accept and finish: ') while ans.lower() == 'c': new = input(' |--> enter the new index (int) or variable value (float): ') try: new = int(new) maxPIndex[j] = new maxPCoordinate[j] = get_x_data(X)[maxPIndex[j]] except ValueError: try: new = float(new) maxPIndex[j] = np.argmin(abs(get_x_data(X) - new)) maxPCoordinate[j] = get_x_data(X)[maxPIndex[j]] except ValueError: print(' |--> Incorrect answer. Please enter a valid index or value') rsquarej, stdev_resj = figures_of_merit(X, maxPIndex, C, St, j) diff = 100 * (stdev_resj - prev_stdev_res) / prev_stdev_res prev_stdev_res + stdev_resj logs += f' |--> changed pure variable #{j + 1}\n' llog = str_iter_summary(j, maxPIndex[j], maxPCoordinate[j], rsquarej, stdev_resj, 'diff') logs += llog + '\n' info_(llog) info_(f'purest variable #{j + 1} set at index = {maxPIndex[j]} ; x = {maxPCoordinate[j]}') ans = input(' |--> (a) Accept and continue, (c) Change, (r) Reject, (f) Accept and stop: ') if ans.lower() == 'r': maxPCoordinate[j] = 0 maxPIndex[j] = 0 logs += f' |--> rejected pure variable #{j + 1}\n' j = j - 1 elif ans.lower() == 'a': j = j + 1 elif ans.lower() == 'f': finished = True j = j + 1 llog = (f'\n**** Interrupted by user at compound # {j} \n**** End of SIMPL(I)SMA analysis.') logs += llog + '\n' Pt = Pt[0:j, :] St = St[0:j, :] s = s[0:j, :] C = C[:, 0:j] # not interactive else: j = j + 1 if (1 - rsquarej) < tol / 100: llog = (f"\n**** Unexplained variance lower than 'tol' ({tol}%) \n" "**** End of SIMPL(I)SMA analysis.") logs += llog + '\n' Pt = Pt[0:j, :] St = St[0:j, :] s = s[0:j, :] C = C[:, 0:j] info_(llog) finished = True if j == n_pc: if not interactive: llog = (f"\n**** Reached maximum number of pure compounds 'n_pc' ({n_pc}) \n" "**** End of SIMPL(I)SMA analysis.") logs += llog + '\n' info_(llog) finished = True Pt.description = 'Purity spectra from SIMPLISMA:\n' + logs C.description = 'Concentration/contribution matrix from SIMPLISMA:\n' + logs St.description = 'Pure compound spectra matrix from SIMPLISMA:\n' + logs s.description = 'Standard deviation spectra matrix from SIMPLISMA:\n' + logs self._logs = logs self._X = X self._Pt = Pt self._C = C self._St = St self._s = s @property def X(self): """ The original dataset. """ return self._X @property def St(self): """ Spectra of pure compounds. """ return self._St @property def C(self): """ Intensities ('concentrations') of pure compounds in spectra. """ return self._C @property def Pt(self): """ Purity spectra. """ return self._Pt @property def s(self): """ Standard deviation spectra. """ return self._s @property def logs(self): """ Logs ouptut. """ return self._logs def reconstruct(self): """ Transform data back to the original space. The following matrix operation is performed: :math:`X'_{hat} = C'.S'^t` Returns ------- X_hat The reconstructed dataset based on the SIMPLISMA Analysis. """ # reconstruct from concentration and spectra profiles X_hat = dot(self.C, self.St) X_hat.description = 'Dataset reconstructed by SIMPLISMA\n' + self.logs X_hat.title = 'X_hat: ' + self.X.title return X_hat def plotmerit(self, **kwargs): """ Plots the input dataset, reconstructed dataset and residuals Parameters ---------- **kwargs : dict Plotting parameters Returns ------- ax subplot """ colX, colXhat, colRes = kwargs.get('colors', ['blue', 'green', 'red']) X_hat = self.reconstruct() res = self.X - X_hat ax = self.X.plot(label='$X$') ax.plot(X_hat.data.T, color=colXhat, label=r'$\hat{X}') ax.plot(res.data.T, color=colRes, label='Residual') ax.set_title('SIMPLISMA plot: ' + self.X.name) return ax # ============================================================================ if __name__ == '__main__': pass <file_sep>/spectrochempy/utils/misc.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Various methods and classes used in other part of the program """ import re import os import sys from operator import itemgetter from contextlib import contextmanager import functools from datetime import datetime, timezone import uuid import types import warnings import numpy as np from quaternion import as_float_array, as_quat_array __all__ = ["TYPE_INTEGER", "TYPE_COMPLEX", "TYPE_FLOAT", "TYPE_BOOL", "EPSILON", "INPLACE", 'typequaternion', 'make_func_from', "make_new_object", "getdocfrom", "dict_compare", 'htmldoc', "ignored", "is_iterable", "is_sequence", "is_number", "silence", "multisort", 'makestr', 'srepr', "spacing", 'largest_power_of_2', 'get_component', 'interleaved2quaternion', 'interleaved2complex', 'as_quaternion', 'quat_as_complex_array', 'get_n_decimals'] # # constants # TYPE_INTEGER = (int, np.int_, np.int32, np.int64, np.uint32, np.uint64) TYPE_FLOAT = (float, np.float_, np.float32, np.float64) TYPE_COMPLEX = (complex, np.complex_, np.complex64, np.complex128) TYPE_BOOL = (bool, np.bool, np.bool_) EPSILON = epsilon = np.finfo(float).eps "Minimum value before considering it as zero value" INPLACE = "INPLACE" "Flag used to specify inplace slicing" typequaternion = np.dtype(np.quaternion) def get_n_decimals(val, accuracy): if abs(val) > 0.0: nd = int(np.log10(abs(val) * accuracy)) else: return 3 if nd >= 0: nd = 1 else: nd = -nd + 1 return nd # ====================================================================================================================== # Private methods # ====================================================================================================================== def _codechange(code_obj, changes): code = types.CodeType names = ['co_argcount', 'co_nlocals', 'co_stacksize', 'co_flags', 'co_code', 'co_consts', 'co_names', 'co_varnames', 'co_filename', 'co_name', 'co_firstlineno', 'co_lnotab', 'co_freevars', 'co_cellvars'] if hasattr(code, 'co_kwonlyargcount'): names.insert(1, 'co_kwonlyargcount') if hasattr(code, 'co_posonlyargcount'): names.insert(1, 'co_posonlyargcount') values = [changes.get(name, getattr(code_obj, name)) for name in names] return code(*values) # ...................................................................................................................... class _DummyFile(object): """ A writeable object. """ def write(self, s): pass # ====================================================================================================================== # Public methods # ====================================================================================================================== def as_quaternion(*args): """ Recombine the arguments to produce a numpy array with quaternion dtype. Parameters ---------- *args : ndarray with dtype:float or complex The quaternion array components: If there is 4 components, then we assume it is the four compoents of the quaternion array: w, x, y, z. If there is only two, they are casted to complex and correspond respectively to w + i.x and y + j.z. Returns ------- """ if len(args) == 4: # we assume here that the for components have been provided w, x, y, z w, x, y, z = args if len(args) == 2: r, i = args w, x, y, z = r.real, r.imag, i.real, i.imag data = as_quat_array(list(zip(w.flatten(), x.flatten(), y.flatten(), z.flatten()))) return data.reshape(w.shape) def quat_as_complex_array(arr): """ Recombine the component of a quaternion array into a tuple of two complex array Parameters ---------- arr : quaternion ndarray The arr will be separated into (w + i.x) and (y + i.z) Returns ------- tuple Tuple of two complex array """ if not arr.dtype == np.quaternion: # no change return arr wt, xt, yt, zt = as_float_array(arr).T w, x, y, z = wt.T, xt.T, yt.T, zt.T return (w + 1j * x), (y + 1j * z) def dict_compare(d1, d2, check_equal_only=True): """ Compare two dictionaries Examples -------- >>> x = dict(a=1, b=2) >>> y = dict(a=2, b=2) >>> added, removed, modified, same = dict_compare(x, y, check_equal_only=False) >>> print(added, removed, modified, same) set() set() {'a'} {'b'} >>> dict_compare(x, y) False """ # from http://stackoverflow.com/questions/4527942/comparing-two-dictionaries-in-python # modified to account for the comparison of list objects d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = added.union(removed) for o in intersect_keys: if is_sequence(d1[o]): if not is_sequence(d2[o]) or len(d1[o]) != len(d2[o]): modified.add(o) else: # in principe we vae here two list of same length for i1, i2 in zip(d1[o], d2[o]): if np.any(i1 != i2): modified.add(o) else: if is_sequence(d2[o]) or d1[o] != d2[o]: modified.add(o) same = set(o for o in intersect_keys if o not in modified) if not check_equal_only: return added, removed, modified, same else: if modified or removed or added: return False return True # .................................................................................................................. def get_component(data, select='REAL'): """ Take selected components of an hypercomplex array (RRR, RIR, ...) Parameters ---------- data : ndarray select : str, optional, default='REAL' if 'REAL', only real component in all dimensions will be selected. Else a string must specify which real (R) or imaginary (I) component has to be selected along a specific dimension. For instance, a string such as 'RRI' for a 2D hypercomplex array indicated that we take the real component in each dimension except the last one, for which imaginary component is preferred. Returns ------- component A component of the complex or hypercomplex array. .. warning:: The definition is somewhat different from Bruker, as we order the component in the order of the dimensions in dataset: e.g., for dims = ['y','x'], 'IR' means that the `y` component is imaginary while the `x` is real. """ if not select: return data new = data.copy() if select == 'REAL': select = 'R' * new.ndim w = x = y = z = None if new.dtype == typequaternion: w, x, y, z = as_float_array(new).T w, x, y, z = w.T, x.T, y.T, z.T if select == 'R': new = (w + x * 1j) elif select == 'I': new = y + z * 1j elif select == 'RR': new = w elif select == 'RI': new = x elif select == 'IR': new = y elif select == 'II': new = z else: raise ValueError(f'something wrong: cannot interpret `{select}` for hypercomplex (quaternion) data!') elif new.dtype in TYPE_COMPLEX: w, x = new.real, new.imag if (select == 'R') or (select == 'RR'): new = w elif (select == 'I') or (select == 'RI'): new = x else: raise ValueError(f'something wrong: cannot interpret `{select}` for complex data!') else: warnings.warn(f'No selection was performed because datasets with complex data have no `{select}` component. ') return new # ...................................................................................................................... def getdocfrom(origin): def decorated(func): func.__doc__ = origin.__doc__ @functools.wraps(func) def wrapper(*args, **kwargs): response = func(*args, **kwargs) return response return wrapper return decorated # ...................................................................................................................... def gt_eps(arr): """lambda function to check that an array has at least some values greater than epsilon Parameters ----------- arr : array to check Returns -------- bool : results ot checking True means that at least some values are greater than epsilon """ return np.any(arr > EPSILON) # ...................................................................................................................... def htmldoc(text): """ format docstring in html for a nice display in IPython Parameters ---------- text : str The string to convert to html Returns ------- out : str the html string """ p = re.compile("^(?P<name>.*:)(.*)", re.MULTILINE) # To get the keywords html = p.sub(r'<b>\1</b>\2', text) html = html.replace('-', '') html = html.split('\n') while html[0].strip() == '': html = html[1:] # suppress initial blank lines for i in range(len(html)): html[i] = html[i].strip() if i == 0: html[i] = "<h3>%s</h3>" % html[i] html[i] = html[i].replace('Parameters', '<h4>Parameters</h4>') html[i] = html[i].replace('Properties', '<h4>Properties</h4>') html[i] = html[i].replace('Methods', '<h4>Methods</h4>') if html[i] != '': if "</h" not in html[i]: html[i] = html[i] + '<br/>' if not html[i].strip().startswith('<'): html[i] = "&nbsp;&nbsp;&nbsp;&nbsp;" + html[i] html = "".join(html) return html # ...................................................................................................................... try: from contextlib import ignored except ImportError: @contextmanager def ignored(*exceptions): """ A context manager for ignoring exceptions. Equivalent to:: try : <body> except exceptions : pass Examples -------- >>> import os >>> with ignored(OSError): ... os.remove('file-that-does-not-exist') """ try: yield except exceptions: pass # ...................................................................................................................... def interleaved2complex(data): """ Make a complex array from interleaved data """ return data[..., ::2] + 1j * data[..., 1::2] # ...................................................................................................................... def interleaved2quaternion(data): """ Make a complex array from interleaved data """ return data[..., ::2] + 1j * data[..., 1::2] # ...................................................................................................................... def is_iterable(arg): """ Determine if an object is iterable """ return hasattr(arg, "__iter__") # ...................................................................................................................... def is_number(x): try: if isinstance(x, np.ndarray): return False x + 1 return True except TypeError: return False # ...................................................................................................................... def is_sequence(arg): """ Determine if an object is iterable but is not a string """ return (not hasattr(arg, 'strip')) and hasattr(arg, "__iter__") # ...................................................................................................................... def largest_power_of_2(value): """ Find the nearest power of two equal to or larger than a value. Parameters ---------- value : int Value to find nearest power of two equal to or larger than. Returns ------- pw : int Power of 2. """ return int(pow(2, np.ceil(np.log(value) / np.log(2)))) # ...................................................................................................................... def make_func_from(func, first=None): """ Create a new func with its arguments from another func and a new signature """ code_obj = func.__code__ new_varnames = list(code_obj.co_varnames) if first: new_varnames[0] = first new_varnames = tuple(new_varnames) new_code_obj = _codechange(code_obj, changes={'co_varnames': new_varnames, }) modified = types.FunctionType(new_code_obj, func.__globals__, func.__name__, func.__defaults__, func.__closure__) modified.__doc__ = func.__doc__ return modified # ...................................................................................................................... def make_new_object(objtype): """ Make a new object of type obj Parameters ---------- objtype : the object type Returns ------- new : the new object of same type. """ new = type(objtype)() # new id and date new._id = "{}_{}".format(type(objtype).__name__, str(uuid.uuid1()).split('-')[0]) new._date = datetime.now(timezone.utc) return new # ...................................................................................................................... def makedirs(newdir): """ works the way a good mkdir should :) - already exists, silently complete - regular file in the way, raise an exception - parent directory(ies) does not exist, make them as well """ # from active recipes http://code.activestate.com/recipes/82465-a-friendly-mkdir/ newdir = os.path.expanduser(newdir) if os.path.isdir(newdir): pass elif os.path.isfile(newdir): raise OSError("a file with the same name as the desired " "dir, '%s', already exists." % newdir) else: head, tail = os.path.split(newdir) if head and not os.path.isdir(head): makedirs(head) # print "_mkdir %s" % repr(newdir) if tail: os.mkdir(newdir) # ...................................................................................................................... def makestr(li): """ make a string from a list of string """ if is_sequence(li): li = " ".join(map(str, li)) li = li.replace('$', '') li = li.replace(' ', r'\ ') li = r'$%s$' % li return li # ...................................................................................................................... def multisort(*args, **kargs): z = list(zip(*args)) z = sorted(z, key=itemgetter(kargs.get('index', 0))) return list(zip(*z)) def primefactors(n): from itertools import chain result = [] for i in chain([2], range(3, n + 1, 2)): s = 0 while n % i == 0: # a good place for mod n /= i s += 1 result.extend([i] * s) # avoid another for loop if n == 1: return result # ...................................................................................................................... @contextmanager def silence(): """ A context manager that silences sys.stdout and sys.stderr. """ old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = _DummyFile() sys.stderr = _DummyFile() yield sys.stdout = old_stdout sys.stderr = old_stderr # ...................................................................................................................... def spacing(arr): """ Return a scalar for the spacing in the one-dimensional input array (if it is uniformly spaced, else return an array of the different spacings Parameters ---------- arr : 1D np.array Returns ------- out : float or array """ spacings = np.diff(arr) # we need to take into account only the significative digits ( but round to some decimals doesn't work # for very small number # mantissa, twoexp = np.frexp(spacings) # mantissa = mantissa.round(6) # spacings = np.ldexp(mantissa, twoexp) # spacings = list(set(abs(spacings))) nd = get_n_decimals(spacings.max(), 1.0e-3) spacings = list(set(np.around(spacings, nd))) if len(spacings) == 1: # uniform spacing return spacings[0] else: return spacings # ...................................................................................................................... def srepr(arg): if is_sequence(arg): return '<' + ", ".join(srepr(x) for x in arg) + '>' return repr(arg) <file_sep>/spectrochempy/core/scripts/script.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import re import ast from traitlets import ( HasTraits, Unicode, validate, TraitError, Instance, Float, ) from spectrochempy.core.project.baseproject import AbstractProject from spectrochempy.core import error_ __all__ = ['Script', 'run_script', 'run_all_scripts'] class Script(HasTraits): _name = Unicode() _content = Unicode(allow_none=True) _priority = Float(min=0., max=100.) _parent = Instance(AbstractProject, allow_none=True) def __init__(self, name='unamed_script', content=None, parent=None, priority=50.): """ Executable scripts. The scripts are used in a project. Parameters ---------- name : str Name of the script. The name should be unique. content : str Content of sthe script. parent : instance of |Project| Parent project. priority: int Default=50. See Also -------- Project: Object containing |NDDataset|s, sub-|Project|s and |Scripts|. Examples -------- Make a script >>> import spectrochempy as scp >>> s = "set_loglevel(INFO)" >>> s = "info_('Hello')" >>> myscript = scp.Script("print_hello_info", s) Execute a script >>> scp.run_script(myscript) """ self.name = name self.content = content self.parent = parent self.priority = priority # ------------------------------------------------------------------------------------------------------------------ # special methods # ------------------------------------------------------------------------------------------------------------------ def __dir__(self): return ['name', 'content', 'parent'] def __call__(self, *args): return self.execute(*args) def __eq__(self, other): if self._content == other.content: return True return False def __ne__(self, other): return not self.__eq__(other) # ------------------------------------------------------------------------------------------------------------------ # properties # ------------------------------------------------------------------------------------------------------------------ @property def name(self): return self._name @name.setter def name(self, value): self._name = value @validate('_name') def _name_validate(self, proposal): pv = proposal['value'] if len(pv) < 2: raise TraitError('script name must have at least 2 characters') p = re.compile(r"^([^\W0-9]?[a-zA-Z_]+[\w]*)") if p.match(pv) and p.match(pv).group() == pv: return pv raise TraitError('Not a valid script name : only _ letters and numbers ' 'are valids. For the fist character, numbers are ' 'not allowed') @property def content(self): return self._content @content.setter def content(self, value): self._content = value @validate('_content') def _content_validate(self, proposal): pv = proposal['value'] if len(pv) < 1: # do not allow null but None raise TraitError("Script content must be non Null!") if pv is None: return try: ast.parse(pv) except Exception: raise return pv @property def parent(self): return self._parent @parent.setter def parent(self, value): self._parent = value # ------------------------------------------------------------------------------------------------------------------ # prublic methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def implements(self, name=None): """ Utility to check if the current object implement `Project`. Rather than isinstance(obj, Project) use object.implements('Project'). This is useful to check type without importing the module """ if name is None: return 'Script' else: return name == 'Script' def execute(self, localvars=None): co = 'from spectrochempy import *\n' \ 'import spectrochempy as scp\n' + self._content code = compile(co, '<string>', 'exec') if localvars is None: # locals was not passed, try to avoid missing values for name # such as 'project', 'proj', 'newproj'... # other missing name if they correspond to the parent project # will be subtitued latter upon exception localvars = locals() # localvars['proj']=self.parent # localvars['project']=self.parent try: exec(code, globals(), localvars) return except NameError as e: # most of the time, a script apply to a project # let's try to substitute the parent to the missing name regex = re.compile(r"'(\w+)'") s = regex.search(e.args[0]).group(1) localvars[s] = self.parent # lgtm [py/modification-of-locals] # TODO: check if this a real error or not (need to come # back on this later) try: exec(code, globals(), localvars) except NameError as e: error_(e + '. pass the variable `locals()` : this may solve ' 'this problem! ') def run_script(script, localvars=None): """ Execute a given project script in the current context. Parameters ---------- script : script instance The script to execute localvars : dict, optional If provided it will be used for evaluating the script. In general, it can be `localvrs`=``locals()``. Returns ------- output of the script if any """ return script.execute(localvars) def run_all_scripts(project): """ Execute all scripts in a project following their priority. Parameters ---------- project : project instance The project in which the scripts have to be executed """ # TODO: complete this run_all_script function project if __name__ == '__main__': pass <file_sep>/tests/test_dataset/test_ndmath.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # = # ====================================================================================================================== """ Tests for the ndmath module """ import numpy as np import pytest from pint.errors import (DimensionalityError) from quaternion import quaternion from spectrochempy.core import info_, error_ from spectrochempy.core.dataset.coord import Coord, LinearCoord from spectrochempy.core.dataset.coordset import CoordSet from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.ndmath import _unary_ufuncs, _binary_ufuncs, _comp_ufuncs from spectrochempy.units.units import ur, Quantity, Unit from spectrochempy.utils import MASKED from spectrochempy.utils.testing import assert_array_equal, assert_equal_units, assert_dataset_equal, RandomSeedContext from spectrochempy.utils.exceptions import CoordinateMismatchError import spectrochempy as scp typequaternion = np.dtype(np.quaternion) # UNARY MATHS # ----------- @pytest.mark.parametrize(('name', 'comment'), _unary_ufuncs().items()) def test_ndmath_unary_ufuncs_simple_data(nd2d, name, comment): nd1 = nd2d.copy() / 1.e+10 # divide to avoid some overflow in exp ufuncs # simple unitless NDDataset # -------------------------- assert nd1.unitless f = getattr(np, name) f(nd1) # assert isinstance(r, NDDataset) # NDDataset with units # --------------------- nd1.units = ur.absorbance f = getattr(np, name) # TODO: some ufunc suppress the units! see pint. skip = False # if name not in NDDataset.__remove_units__: # # try: # f(Quantity(1., nd1.units)).units # except TypeError as e: # error_(f"{name} :", e) # skip = True # except AttributeError: # if name in ['positive', 'fabs', 'cbrt', 'spacing', # 'signbit', 'isnan', 'isinf', 'isfinite', 'logical_not', # 'log2', 'log10', 'log1p', 'exp2', 'expm1']: # pass # already solved # else: # info_(f"\n =======> {name} remove units! \n") # except DimensionalityError as e: # error_(f"{name} :", e) # skip = True if not skip: try: f(nd1) # assert isinstance(r, NDDataset) nd1 = nd2d.copy() # reset nd # with units and mask nd1.units = ur.absorbance nd1[1, 1] = MASKED f(nd1) except DimensionalityError as e: error_(f"{name}: ", e) def test_bug_lost_dimensionless_units(): import os dataset = NDDataset.read_omnic(os.path.join('irdata', 'nh4y-activation.spg')) assert dataset.units == 'absorbance' dataset = dataset - 2. - 50. # artificially make negative some of the values assert dataset.units == 'absorbance' dataset = dataset.clip(-2., 2.) y = np.log2(dataset) y._repr_html_() # BINARY MATH # ------------ @pytest.mark.parametrize(('name', 'comment'), _binary_ufuncs().items()) def test_ndmath_binary_ufuncs_two_datasets(nd2d, name, comment): nd1 = nd2d.copy() nd2 = nd1.copy() * np.ones_like(nd1) * .01 # simple NDDataset # ----------------- f = getattr(np, name) r = f(nd1, nd2) assert isinstance(r, NDDataset) # NDDataset with units # ----------------------- nd1.units = ur.m nd2.units = ur.km f = getattr(np, name) r = f(nd1, nd2) assert isinstance(r, NDDataset) if name not in ['logaddexp', 'logaddexp2', 'true_divide', 'floor_divide', 'multiply', 'divide']: assert r.units == nd1.units # COMP Methods @pytest.mark.parametrize(('name', 'comment'), _comp_ufuncs().items()) def test_ndmath_comp_ufuncs_two_datasets(nd2d, name, comment): nd1 = nd2d.copy() nd2 = nd1.copy() + np.ones_like(nd1) * .001 # simple NDDataset # ----------------- f = getattr(np, name) r = f(nd1, nd2) assert isinstance(r, NDDataset) # NDDataset with units # ----------------------- nd1.units = ur.absorbance nd2.units = ur.absorbance f = getattr(np, name) r = f(nd1, nd2) assert isinstance(r, NDDataset) @pytest.mark.parametrize(('name', 'comment'), _binary_ufuncs().items()) def test_ndmath_binary_ufuncs_scalar(nd2d, name, comment): nd1 = nd2d.copy() nd2 = 2. # simple NDDataset # ----------------- f = getattr(np, name) r = f(nd1, nd2) assert isinstance(r, NDDataset) # NDDataset with units # ----------------------- nd1.units = ur.absorbance f = getattr(np, name) r = f(nd1, nd2) assert isinstance(r, NDDataset) if name not in ['logaddexp', 'logaddexp2', 'true_divide', 'floor_divide', ]: assert r.units == nd1.units # ---------------------------------------------------------------------------------------------------------------------- # non ufuncs # ---------------------------------------------------------------------------------------------------------------------- REDUCE_KEEPDIMS_METHODS = ['max', 'min', 'amax', 'amin', 'round', 'around', 'clip', 'cumsum'] REDUCE_KEEPUNITS_METHODS = ['sum', 'mean', 'std', 'ptp', ] REDUCE_METHODS = ['all', 'any', 'argmax', 'argmin', ] # test if a method is implemented @pytest.mark.parametrize('name', REDUCE_METHODS + REDUCE_KEEPDIMS_METHODS + REDUCE_KEEPUNITS_METHODS) def test_ndmath_classmethod_implementation(nd2d, name): nd = nd2d.copy() try: getattr(NDDataset, name) except AttributeError: info_('\n{} is not yet implemented'.format(name)) try: getattr(np.ma, name) getattr(np, name)(nd) except AttributeError: info_('\n{} is not a np.ma method'.format(name)) except TypeError as e: if 'required positional' in e.args[0]: pass else: raise TypeError(*e.args) def test_ndmath_absolute_of_quaternion(): na0 = np.array([[1., 2., 2., 0., 0., 0.], [1.3, 2., 2., 0.5, 1., 1.], [1, 4.2, 2., 3., 2., 2.], [5., 4.2, 2., 3., 3., 3.]]) nd = NDDataset(na0, dtype=quaternion) coords = CoordSet(np.linspace(-1, 1, 2), np.linspace(-10., 10., 3)) assert nd.shape == (2, 3) nd.set_coordset(**coords) np.abs(nd) # TODO: add more testings def test_unary_ops(): # UNARY_OPS = ['neg', 'pos', 'abs', 'invert'] d1 = NDDataset(np.ones((5, 5))) d2 = +d1 # pos assert isinstance(d2, NDDataset) assert np.all(d2.data == 1.) d2 = -d1 # neg assert isinstance(d2, NDDataset) assert np.all(d2.data == -1.) d3 = abs(d2) # abs assert isinstance(d3, NDDataset) assert np.all(d3.data == 1.) def test_unary_ops_with_units(): # UNARY_OPS = ['neg', 'pos', 'abs'] d1 = NDDataset(np.ones((5, 5)), units='m') d2 = +d1 # pos assert isinstance(d2, NDDataset) assert np.all(d2.data == 1.) assert d2.units == ur.m d2 = -d1 # neg assert isinstance(d2, NDDataset) assert np.all(d2.data == -1.) assert d2.units == ur.m d3 = abs(d2) # abs assert isinstance(d3, NDDataset) assert np.all(d3.data == 1.) assert d2.units == ur("m") def test_nddataset_add(): d1 = NDDataset(np.ones((5, 5)), name='d1') d2 = NDDataset(np.ones((5, 5)), name='d2') d3 = -d1 assert d3.name != d1 d3 = d1 * .5 + d2 assert isinstance(d3, NDDataset) assert np.all(d3.data == 1.5) def test_nddataset_add_with_numpy_array(): d1 = NDDataset(np.ones((5, 5))) d2 = np.ones((5, 5)) d3 = d1 * .5 + d2 assert isinstance(d3, NDDataset) assert np.all(d3.data == 1.5) # should commute! d3 = d2 + d1 * .5 assert isinstance(d3, NDDataset) assert np.all(d3.data == 1.5) def test_nddataset_add_inplace(): d1 = NDDataset(np.ones((5, 5))) d2 = NDDataset(np.ones((5, 5))) d1 += d2 * .5 assert np.all(d1.data == 1.5) def test_nddataset_add_mismatch_coords(): coord1 = Coord(np.arange(5.)) coord2 = Coord(np.arange(1., 5.5, 1.)) d1 = NDDataset(np.ones((5, 5)), coordset=[coord1, coord2]) d2 = NDDataset(np.ones((5, 5)), coordset=[coord2, coord1]) with pytest.raises(CoordinateMismatchError) as exc: d1 -= d2 assert str(exc.value).startswith('\nCoord.data attributes are not almost equal') with pytest.raises(CoordinateMismatchError) as exc: d1 += d2 assert str(exc.value).startswith( '\nCoord.data attributes are not almost equal') # TODO= make more tests like this for various functions def test_nddataset_add_mismatch_units(): d1 = NDDataset(np.ones((5, 5)), units='cm^2') d2 = NDDataset(np.ones((5, 5)), units='cm') with pytest.raises(DimensionalityError) as exc: d1 + d2 assert str(exc.value).startswith("Cannot convert from '[length]' to '[length] ** 2', " "Units must be compatible for the `add` operator") with pytest.raises(DimensionalityError) as exc: d1 += d2 assert str(exc.value).startswith("Cannot convert from '[length]' to '[length] ** 2', " "Units must be compatible for the `iadd` operator") def test_nddataset_add_units_with_different_scale(): d1 = NDDataset(np.ones((5, 5)), units='m') d2 = NDDataset(np.ones((5, 5)), units='cm') x = d1 + 1. * ur.cm assert x[0, 0].values == 1.01 * ur.m x = d1 + d2 assert x.data[0, 0] == 1.01 x = d2 + d1 assert x.data[0, 0] == 101. d1 += d2 assert d1.data[0, 0] == 1.01 d2 += d1 assert d2.data[0, 0] == 102. def test_nddataset_add_mismatch_shape(): d1 = NDDataset(np.ones((5, 5))) d2 = NDDataset(np.ones((6, 6))) with pytest.raises(ArithmeticError) as exc: d1 += d2 assert exc.value.args[0].startswith("operands could not be broadcast together") def test_nddataset_add_with_masks(): # numpy masked arrays mask the result of binary operations if the # mask of either operand is set. # Does NDData? ndd1 = NDDataset(np.array([1, 2])) ndd2 = NDDataset(np.array([2, 1])) result = ndd1 + ndd2 assert_array_equal(result.data, np.array([3, 3])) ndd1 = NDDataset(np.array([1, 2]), mask=np.array([True, False])) other_mask = ~ ndd1.mask ndd2 = NDDataset(np.array([2, 1]), mask=other_mask) result = ndd1 + ndd2 # The result should have all entries masked... assert result.mask.all() def test_nddataset_subtract(): d1 = NDDataset(np.ones((5, 5))) d2 = NDDataset(np.ones((5, 5)) * 2.) d3 = d1 - d2 assert np.all(d3.data == -1.) def test_nddataset_substract_with_numpy_array(): d1 = NDDataset(np.ones((5, 5))) d2 = np.ones((5, 5)) d3 = d1 * .5 - d2 assert isinstance(d3, NDDataset) assert np.all(d3.data == -0.5) # should commute! d3 = d2 - d1 * .5 assert isinstance(d3, NDDataset) assert np.all(d3.data == 0.5) def test_nddataset_binary_operation_with_other_1D(): coord1 = Coord(np.linspace(0., 10., 10)) coord2 = Coord(np.linspace(1., 5.5, 5)) d1 = NDDataset(np.random.random((10, 5)), coordset=[coord1, coord2]) d2 = d1[0] # this should work independantly of the value of the coordinates on dimension y d3 = d1 - d2 assert_array_equal(d3.data, d1.data - d2.data) def test_nddataset_subtract_mismatch_units(): d1 = NDDataset(np.ones((5, 5)), units='m') d2 = NDDataset(np.ones((5, 5)) * 2., units='m/s') with pytest.raises(DimensionalityError) as exc: d1 -= d2 assert str(exc.value) == "Cannot convert from '[length] / [time]' to '[length]', " \ "Units must be compatible for the `isub` operator" def test_nddataset_subtract_mismatch_shape(): d1 = NDDataset(np.ones((5, 5))) d2 = NDDataset(np.ones((6, 6)) * 2.) with pytest.raises(ArithmeticError) as exc: d1 -= d2 assert exc.value.args[0].startswith("operands could not be broadcast together") def test_nddataset_multiply_with_numpy_array(): d1 = NDDataset(np.ones((5, 5))) d2 = np.ones((5, 5)) * 2. d3 = d1 * d2 assert isinstance(d3, NDDataset) assert np.all(d3.data == 2.) # should commute! d3 = d2 * d1 assert isinstance(d3, NDDataset) assert np.all(d3.data == 2.) def test_nddataset_divide_with_numpy_array(): d1 = NDDataset(np.ones((5, 5))) d2 = np.ones((5, 5)) * 2. d3 = d1 / d2 assert isinstance(d3, NDDataset) assert np.all(d3.data == 0.5) # should commute! d3 = d2 / d1 assert isinstance(d3, NDDataset) assert np.all(d3.data == 2.) # first operand has units km, second has units m @pytest.mark.parametrize(('operation', 'result_units'), [('__add__', ur.km), ('__sub__', ur.km), ('__mul__', ur.km * ur.m), ('__truediv__', ur.km / ur.m)]) def test_ndmath_unit_conversion_operators(operation, result_units): in_km = NDDataset(np.array([1, 1]), units=ur.km) in_m = NDDataset(in_km.data * 1000, units=ur.m) operator_km = in_km.__getattribute__(operation) combined = operator_km(in_m) assert_equal_units(combined.units, result_units) @pytest.mark.parametrize(('unit1', 'unit2', 'op', 'result_units'), [(None, None, '__add__', None), (None, None, '__mul__', None), (None, ur.m, '__mul__', ur.m), (ur.dimensionless, None, '__mul__', ur.dimensionless), (ur.eV, ur.eV, '__add__', ur.eV), (ur.eV, ur.eV, '__sub__', ur.eV), (ur.eV, ur.eV, '__truediv__', ur.dimensionless), (ur.eV, ur.m, '__mul__', ur.m * ur.eV)]) def test_arithmetic_unit_calculation(unit1, unit2, op, result_units): ndd1 = NDDataset(np.array([1]), units=unit1) ndd2 = NDDataset(np.array([1]), units=unit2) ndd1_method = ndd1.__getattribute__(op) result = ndd1_method(ndd2) try: assert result.units == result_units except AssertionError: assert_equal_units(ndd1_method(ndd2).units, result_units) def test_simple_arithmetic_on_full_dataset(): # due to a bug in notebook with the following import os dataset = NDDataset.read_omnic(os.path.join('irdata', 'nh4y-activation.spg')) dataset - dataset[0] # suppress the first spectrum to all other spectra in the series def test_ndmath_and_api_methods(IR_dataset_1D, IR_dataset_2D): # CREATION _LIKE METHODS # ---------------------- # from a list x = [1, 2, 3] # _like as an API method ds = NDDataset(x).full_like(2.5, title='empty') ds = scp.full_like(x, 2) assert np.all(ds.data == np.full((3,), 2)) assert ds.implements('NDDataset') # _like as a classmethod ds = NDDataset.full_like(x, 2) assert np.all(ds.data == np.full((3,), 2)) assert ds.implements('NDDataset') # _like as an instance method ds = NDDataset(x).full_like(2) assert np.all(ds.data == np.full((3,), 2)) assert ds.implements('NDDataset') # _like as an instance method ds = NDDataset(x).empty_like(title='empty') assert ds.implements('NDDataset') assert ds.title == 'empty' # from an array x = np.array([1, 2, 3]) ds = NDDataset(x).full_like(2) assert np.all(ds.data == np.full((3,), 2)) assert ds.implements('NDDataset') # from a NDArray subclass with units x = NDDataset([1, 2, 3], units='km') ds = scp.full_like(x, 2) assert np.all(ds.data == np.full((3,), 2)) assert ds.implements('NDDataset') assert ds.units == ur.km ds1 = scp.full_like(ds, np.nan, dtype=np.double, units='m') assert ds1.units == Unit('m') # change of units is forced ds2 = scp.full_like(ds, 2, dtype=np.double, units='s') assert ds2.units == ur.s # other like creation functions nd = scp.empty_like(ds, dtype=np.double, units='m') assert str(nd) == 'NDDataset: [float64] m (size: 3)' assert nd.dtype == np.dtype(np.double) nd = scp.zeros_like(ds, dtype=np.double, units='m') assert str(nd) == 'NDDataset: [float64] m (size: 3)' assert np.all(nd.data == np.zeros((3,))) nd = scp.ones_like(ds, dtype=np.double, units='m') assert str(nd) == 'NDDataset: [float64] m (size: 3)' assert np.all(nd.data == np.ones((3,))) # FULL # ---- ds = NDDataset.full((6,), 0.1) assert ds.size == 6 assert str(ds) == 'NDDataset: [float64] unitless (size: 6)' # ZEROS # ----- ds = NDDataset.zeros((6,), units='km') assert ds.size == 6 assert str(ds) == 'NDDataset: [float64] km (size: 6)' # ONES # ---- ds = NDDataset.ones((6,)) ds = scp.full((6,), 0.1) assert ds.size == 6 assert str(ds) == 'NDDataset: [float64] unitless (size: 6)' ds = NDDataset.ones((6,), units='absorbance', dtype='complex128') assert ds.size == 3 assert str(ds) == 'NDDataset: [complex128] a.u. (size: 3)' assert ds[0].data == 1. + 1.j # LINSPACE # -------- c2 = Coord.linspace(1, 20, 200, units='m', name='mycoord') assert c2.name == 'mycoord' assert c2.size == 200 assert c2[-1].data == 20 assert c2[0].values == Quantity(1, 'm') # ARANGE # ------- c3 = Coord.arange(1, 20.0001, 1, units='s', name='mycoord') assert c3.name == 'mycoord' assert c3.size == 20 assert c3[-1].data == 20 assert c3[0].values == Quantity(1, 's') # EYE # ---- ds1 = scp.NDDataset.eye(2, dtype=int) assert str(ds1) == 'NDDataset: [float64] unitless (shape: (y:2, x:2))' ds = scp.eye(3, k=1, units='km') assert (ds.data == np.eye(3, k=1)).all() assert ds.units == ur.km # IDENTITY # -------- ds = scp.identity(3, units='km') assert (ds.data == np.identity(3, )).all() assert ds.units == ur.km # RANDOM # ------ ds = scp.random((3, 3), units='km') assert str(ds) == 'NDDataset: [float64] km (shape: (y:3, x:3))' # adding coordset c1 = Coord.linspace(1, 20, 200, units='m', name='axe_x') ds = scp.random((200,), units='km', coordset=scp.CoordSet(x=c1)) # DIAGONAL # -------- # extract diagonal nd = scp.full((2, 2), 0.5, units='s', title='initial') assert str(nd) == "NDDataset: [float64] s (shape: (y:2, x:2))" ndd = scp.diagonal(nd, title='diag') assert str(ndd) == 'NDDataset: [float64] s (size: 2)' assert ndd.units == Unit('s') cx = scp.Coord([0, 1]) cy = scp.Coord([2, 5]) nd = NDDataset.full((2, 2), 0.5, units='s', coordset=scp.CoordSet(cx, cy), title='initial') assert str(nd) == "NDDataset: [float64] s (shape: (y:2, x:2))" ndd = nd.diagonal(title='diag2') assert str(ndd) == 'NDDataset: [float64] s (size: 2)' assert ndd.units == Unit('s') assert ndd.title == 'diag2' cx = scp.Coord([0, 1, 2]) cy = scp.Coord([2, 5]) nd = NDDataset.full((2, 3), 0.5, units='s', coordset=scp.CoordSet(x=cx, y=cy), title='initial') assert str(nd) == "NDDataset: [float64] s (shape: (y:2, x:3))" ndd = nd.diagonal(title='diag3') assert str(ndd) == 'NDDataset: [float64] s (size: 2)' assert ndd.units == Unit('s') assert ndd.title == 'diag3' assert_array_equal(nd.x.data[:ndd.x.size], ndd.x.data) ndd = nd.diagonal(title='diag4', dim='y') assert str(ndd) == 'NDDataset: [float64] s (size: 2)' assert ndd.units == Unit('s') assert ndd.title == 'diag4' assert_array_equal(nd.y.data[:ndd.y.size], ndd.y.data) # DIAG # ---- ref = NDDataset(np.diag((3, 3.4, 2.3)), units='m', title='something') # Three forms should return the same NDDataset ds = scp.diag((3, 3.4, 2.3), units='m', title='something') assert_dataset_equal(ds, ref) ds = NDDataset.diag((3, 3.4, 2.3), units='m', title='something') assert_dataset_equal(ds, ref) ds = NDDataset((3, 3.4, 2.3)).diag(units='m', title='something') assert_dataset_equal(ds, ref) # and this too ds1 = NDDataset((3, 3.4, 2.3), units='s', title='another') ds = scp.diag(ds1, units='m', title='something') assert_dataset_equal(ds, ref) ds = ds1.diag(units='m', title='something') assert_dataset_equal(ds, ref) # BOOL : ALL and ANY # ------------------ ds = NDDataset([[True, False], [True, True]]) b = np.all(ds) assert not b b = scp.all(ds) assert not b b = ds.all() assert not b b = NDDataset.any(ds) assert b b = ds.all(dim='y') assert_array_equal(b, np.array([True, False])) b = ds.any(dim='y') assert_array_equal(b, np.array([True, True])) # ARGMAX, MAX # ----------- nd1 = IR_dataset_1D.copy() nd1[1290.:890.] = MASKED assert nd1.is_masked assert str(nd1) == 'NDDataset: [float64] a.u. (size: 5549)' idx = nd1.argmax() assert idx == 3122 mx = nd1.max() # alternative mx = scp.max(nd1) mx = NDDataset.max(nd1) assert mx == Quantity(3.8080601692199707, 'absorbance') mxk = nd1.max(keepdims=True) assert isinstance(mxk, NDDataset) assert str(mxk) == 'NDDataset: [float64] a.u. (size: 1)' assert mxk.values == mx # test on a 2D NDDataset nd2 = IR_dataset_2D.copy() nd2[:, 1290.:890.] = MASKED mx = nd2.max() # no axis specified assert mx == Quantity(3.8080601692199707, 'absorbance') mxk = nd2.max(keepdims=True) assert str(mxk) == 'NDDataset: [float64] a.u. (shape: (y:1, x:1))' nd2m = nd2.max('y') # axis selected ax = nd2m.plot() nd2[0].plot(ax=ax, clear=False) scp.show() nd2m2 = nd2.max('x') # axis selected nd2m2.plot() scp.show() nd2m = nd2.max('y', keepdims=True) assert nd2m.shape == (1, 5549) nd2m = nd2.max('x', keepdims=True) assert nd2m.shape == (55, 1) mx = nd2.min() # no axis specified assert mx == Quantity(-0.022955093532800674, 'absorbance') mxk = nd2.min(keepdims=True) assert str(mxk) == 'NDDataset: [float64] a.u. (shape: (y:1, x:1))' nd2m = nd2.min('y') # axis selected ax = nd2m.plot() nd2[0].plot(ax=ax, clear=False) scp.show() nd2m2 = nd2.min('x') # axis selected nd2m2.plot() scp.show() nd2m = nd2.min('y', keepdims=True) assert nd2m.shape == (1, 5549) nd2m = nd2.min('x', keepdims=True) assert nd2m.shape == (55, 1) # CLIP # ---- nd3 = nd2 - 2. assert nd3.units == nd2.units nd3c = nd3.clip(-.5, 1.) assert nd3c.max().m == 1. assert nd3c.min().m == -.5 # COORDMIN AND COORDMAX # --------------------- cm = nd2.coordmin() assert np.around(cm['x'], 3) == Quantity(1290.165, 'cm^-1') cm = nd2.coordmin(dim='y') assert cm.size == 1 cm = nd2.coordmax(dim='y') assert cm.size == 1 cm = nd2.coordmax(dim='x') assert cm.size == 1 # ABS # ---- nd2a = scp.abs(nd2) mxa = nd2a.min() assert mxa > 0 nd2a = NDDataset.abs(nd2) mxa = nd2a.min() assert mxa > 0 nd2a = np.abs(nd2) mxa = nd2a.min() assert mxa > 0 ndd = NDDataset([1., 2. + 1j, 3.]) val = np.abs(ndd) val = ndd[1] * 1.2 - 10. val = np.abs(val) # FROMFUNCTION # ------------ # 1D def func1(t, v): d = v * t return d time = Coord.linspace(0, 9, 10, ) distance = NDDataset.fromfunction(func1, v=134, coordset=CoordSet(t=time)) assert distance.dims == ['t'] assert_array_equal(distance.data, np.fromfunction(func1, (10,), v=134)) time = Coord.linspace(0, 90, 10, units='min') distance = NDDataset.fromfunction(func1, v=Quantity(134, 'km/hour'), coordset=CoordSet(t=time)) assert distance.dims == ['t'] assert_array_equal(distance.data, np.fromfunction(func1, (10,), v=134) * 10 / 60) # 2D def func2(x, y): d = x + 1 / y return d c0 = Coord.linspace(0, 9, 3) c1 = Coord.linspace(10, 20, 2) # implicit ordering of coords (y,x) distance = NDDataset.fromfunction(func2, coordset=CoordSet(c1, c0)) assert distance.shape == (2, 3) assert distance.dims == ['y', 'x'] # or equivalent distance = NDDataset.fromfunction(func2, coordset=[c1, c0]) assert distance.shape == (2, 3) assert distance.dims == ['y', 'x'] # explicit ordering of coords (y,x) # distance = NDDataset.fromfunction(func2, coordset=CoordSet(u=c0, v=c1)) assert distance.shape == (2, 3) assert distance.dims == ['v', 'u'] assert distance[0, 2].data == distance.u[2].data + 1. / distance.v[0].data # with units def func3(x, y): d = x + y return d c0u = Coord.linspace(0, 9, 3, units='km') c1u = Coord.linspace(10, 20, 2, units='m') distance = NDDataset.fromfunction(func3, coordset=CoordSet(u=c0u, v=c1u)) assert distance.shape == (2, 3) assert distance.dims == ['v', 'u'] assert distance[0, 2].values == distance.u[2].values + distance.v[0].values c0u = Coord.linspace(0, 9, 3, units='km') c1u = Coord.linspace(10, 20, 2, units='m^-1') distance = NDDataset.fromfunction(func2, coordset=CoordSet(u=c0u, v=c1u)) assert distance.shape == (2, 3) assert distance.dims == ['v', 'u'] assert distance[0, 2].values == distance.u[2].values + 1. / distance.v[0].values # FROMITER # -------- iterable = (x * x for x in range(5)) nit = scp.fromiter(iterable, float, units='km') assert str(nit) == 'NDDataset: [float64] km (size: 5)' assert_array_equal(nit.data, np.array([0, 1, 4, 9, 16])) # MEAN, AVERAGE # ----- nd = IR_dataset_2D.copy() m = scp.mean(nd) assert m == Quantity(np.mean(nd.data), "absorbance") m = scp.average(nd) assert m == Quantity(np.average(nd.data), "absorbance") mx = scp.mean(nd, keepdims=True) assert mx.shape == (1, 1) mxd = scp.mean(nd, dim='y') assert str(mxd) == 'NDDataset: [float64] a.u. (size: 5549)' assert str(mxd.x) == 'LinearCoord: [float64] cm^-1 (size: 5549)' def test_nddataset_fancy_indexing(): # numpy vs dataset rand = np.random.RandomState(42) x = rand.randint(100, size=10) # single value indexing dx = NDDataset(x) assert (dx[3].data, dx[7].data, dx[2].data) == (x[3], x[7], x[2]) # slice indexing assert_array_equal(dx[3:7].data, x[3:7]) # boolean indexingassert assert_array_equal(dx[x > 52].data, x[x > 52]) # fancy indexing ind = [3, 7, 4] assert_array_equal(dx[ind].data, x[ind]) ind = np.array([[3, 7], [4, 5]]) assert_array_equal(dx[ind].data, x[ind]) with RandomSeedContext(1234): a = np.random.random((3, 5)).round(1) c = (np.arange(3), np.arange(5)) nd = NDDataset(a, coordset=c) a = nd[[1, 0, 2]] a = nd[np.array([1, 0])] def test_coord_add_units_with_different_scale(): d1 = Coord.arange(3., units='m') d2 = Coord.arange(3., units='cm') x = d1 + 1. * ur.cm assert x.data[1] == 1.01 x = d1 + d2 assert x.data[1] == 1.01 x = d2 + d1 assert x.data[1] == 101. d1 += d2 assert d1.data[1] == 1.01 d2 += d1 assert d2.data[1] == 102. def test_linearcoord_add_units_with_different_scale(): d1 = LinearCoord.arange(3., units='m') d2 = LinearCoord.arange(3., units='cm') x = d1 + 1. * ur.cm assert np.around(x.data[1], 2) == 1.01 x = d1 + d2 assert np.around(x.data[1], 2) == 1.01 x = d2 + d1 assert np.around(x.data[1], 2) == 101. d1 += d2 assert np.around(d1.data[1], 2) == 1.01 d2 += d1 assert d2.data[1] == 102. def test_creation(): nd = scp.ones(5, units='km') assert str(nd) == 'NDDataset: [float64] km (size: 5)' nd = scp.ones((5,), dtype=np.dtype('int64'), mask=[True, False, False, False, True]) assert nd.dtype == np.dtype("int64") def test_from_function_docstring(): def func1(t, v): d = v * t return d time = scp.LinearCoord.arange(0, 60, 10, units='min') scp.fromfunction(func1, v=scp.Quantity(134, 'km/hour'), coordset=scp.CoordSet(t=time)) <file_sep>/docs/credits/citing.rst .. _citing: Citing |scpy| ========================================== When using |scpy| for your own work, you are kindly requested to cite it this way:: <NAME> & <NAME>, (2020) SpectroChemPy (Version 0.2). Zenodo. http://doi.org/10.5281/zenodo.3823841 <file_sep>/docs/gettingstarted/examples/analysis/readme.txt .. _analysis_examples-index: Example of the analysis package usage -------------------------------------- <file_sep>/requirements.txt # pip install -r requirements.txt pint colorama setuptools_scm traittypes orderedset quadprog brukeropusreader numpy-quaternion nmrglue <file_sep>/docs/gettingstarted/examples/read/plot_read_nmr_from_bruker.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Loading of experimental 1D NMR data =================================== In this example, we load a NMR dataset (in the Bruker format) and plot it. """ import spectrochempy as scp ################################################################################ # `datadir.path` contains the path to a default data directory. datadir = scp.preferences.datadir path = datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'topspin_1d' ################################################################################ # load the data in a new dataset ndd = scp.NDDataset.read_topspin(path, expno=1, remove_digital_filter=True) ################################################################################ # view it... scp.plot(ndd) ################################################################################ # Now load a 2D dataset path = datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'topspin_2d' ndd = scp.NDDataset.read_topspin(path, expno=1, remove_digital_filter=True) ################################################################################ # view it... # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/spectrochempy/utils/plots.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import matplotlib as mpl from matplotlib import pyplot as plt import plotly.graph_objects as go import numpy as np from spectrochempy.core.dataset.meta import Meta __all__ = ['cmyk2rgb', 'NBlack', 'NRed', 'NBlue', 'NGreen', 'figure', 'show', 'get_figure', # Plotly specific 'get_plotly_figure', 'colorscale'] # ............................................................................ # color conversion function def cmyk2rgb(C, M, Y, K): """CMYK to RGB conversion C,M,Y,K are given in percent. The R,G,B values are returned in the range of 0..1. """ C, Y, M, K = C / 100., Y / 100., M / 100., K / 100. # The red (R) color is calculated from the cyan (C) and black (K) colors: R = (1.0 - C) * (1.0 - K) # The green color (G) is calculated from the magenta (M) and black (K) colors: G = (1. - M) * (1. - K) # The blue color (B) is calculated from the yellow (Y) and black (K) colors: B = (1. - Y) * (1. - K) return (R, G, B) # Constants # ---------------------------------------------------------------------------------------------------------------------- # For color blind people, it is safe to use only 4 colors in graphs: # see http://jfly.iam.u-tokyo.ac.jp/color/ichihara_etal_2008.pdf # Black CMYK=0,0,0,0 # Red CMYK= 0, 77, 100, 0 % # Blue CMYK= 100, 30, 0, 0 % # Green CMYK= 85, 0, 60, 10 % NBlack = (0, 0, 0) NRed = cmyk2rgb(0, 77, 100, 0) NBlue = cmyk2rgb(100, 30, 0, 0) NGreen = cmyk2rgb(85, 0, 60, 10) # ............................................................................. def figure(preferences=Meta(), **kwargs): """ Method to open a new figure Parameters ---------- kwargs : any keywords arguments to be passed to the matplotlib figure constructor. preferences : Meta dictionary per object saved plot configuration """ return get_figure(preferences=preferences, **kwargs) # ............................................................................. def show(): """ Method to force the `matplotlib` figure display """ from spectrochempy import NO_DISPLAY if not NO_DISPLAY: if get_figure(clear=False): plt.show(block=True) # ............................................................................. def get_figure(**kwargs): """ Get the figure where to plot. Parameters ---------- clear : bool if False the last used figure is returned figsize : 2-tuple of floats, default: rcParams["figure.figsize"] (default: [6.4, 4.8]) Figure dimension (width, height) in inches. dpi : float, default: rcParams["figure.dpi"] (default: 100.0) Dots per inch. facecolor : default: rcParams["figure.facecolor"] (default: 'white') The figure patch facecolor. edgecolor : default: preferences.figure_edgecolor (default: 'white') The figure patch edge color. frameon : bool, default: preferences.figure_frameon (default: True) If False, suppress drawing the figure background patch. tight_layout : bool or dict, default: preferences.figure.autolayout (default: False) If False use subplotpars. If True adjust subplot parameters using tight_layout with default padding. When providing a dict containing the keys pad, w_pad, h_pad, and rect, the default tight_layout paddings will be overridden. constrained_layout : bool, default: preferences.figure_constrained_layout (default: False) If True use constrained layout to adjust positioning of plot elements. Like tight_layout, but designed to be more flexible. See Constrained Layout Guide for examples. preferences : Meta object, per object plot configuration Returns ------- matplotlib figure instance """ n = plt.get_fignums() clear = kwargs.get('clear', True) if not n or clear: # create a figure prefs = kwargs.pop('preferences', None) figsize = kwargs.get('figsize', prefs.figure_figsize) dpi = kwargs.get('dpi', prefs.figure_dpi) facecolor = kwargs.get('facecolor', prefs.figure_facecolor) edgecolor = kwargs.get('edgecolor', prefs.figure_edgecolor) frameon = kwargs.get('frameon', prefs.figure_frameon) tight_layout = kwargs.get('autolayout', prefs.figure_autolayout) # get the current figure (or the last used) fig = plt.figure(figsize=figsize) fig.set_dpi(dpi) fig.set_frameon(frameon) try: fig.set_edgecolor(edgecolor) except ValueError: fig.set_edgecolor(eval(edgecolor)) try: fig.set_facecolor(facecolor) except ValueError: try: fig.set_facecolor(eval(facecolor)) except ValueError: fig.set_facecolor('#' + eval(facecolor)) fig.set_dpi(dpi) fig.set_tight_layout(tight_layout) return fig # a figure already exists - if several we take the last return plt.figure(n[-1]) # FOR PLOTLY # ............................................................................. def get_plotly_figure(clear=True, fig=None, **kwargs): """ Get the figure where to plot. Parameters ---------- clear : bool if False the figure provided in the `fig` parameters is used. fig : plotly figure if provided, and clear is not True, it will be used for plotting kwargs : any keywords arguments to be passed to the plotly figure constructor. Returns ------- Plotly figure instance """ if clear or fig is None: # create a figure return go.Figure() # a figure already exists - if several we take the last return fig class colorscale: def normalize(self, vmin, vmax, cmap='viridis', rev=False, offset=0): """ """ if rev: cmap = cmap + '_r' _colormap = plt.get_cmap(cmap) _norm = mpl.colors.Normalize(vmin=vmin - offset, vmax=vmax - offset) self.scalarMap = mpl.cm.ScalarMappable(norm=_norm, cmap=_colormap) def rgba(self, z, offset=0): c = np.array(self.scalarMap.to_rgba(z.squeeze() - offset)) c[0:3] *= 255 c[0:3] = np.round(c[0:3].astype('uint16'), 0) return f'rgba{tuple(c)}' colorscale = colorscale() <file_sep>/docs/gettingstarted/examples/read/plot_read_IR_from_omnic.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Loading an IR (omnic SPG) experimental file ============================================ Here we load an experimental SPG file (OMNIC) and plot it. """ import spectrochempy as scp ################################################################################ # Loading and stacked plot of the original datadir = scp.preferences.datadir dataset = scp.NDDataset.read_omnic(datadir / 'irdata' / 'nh4y-activation.spg') dataset.plot_stack(style='paper'); ################################################################################ # change the unit of y axis, the y origin as well as the title of the axis dataset.y.to('hour') dataset.y -= dataset.y[0] dataset.y.title = 'acquisition time' dataset.plot_stack(); # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/tests/test_analysis/test_find_peaks.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import pytest def test_findpeaks(IR_dataset_1D): dataset = IR_dataset_1D peaks, properties = dataset[1800.0:1300.0].find_peaks(height=1.5, distance=50.0, width=0.0) assert len(peaks.x) == 2 assert properties['peak_heights'][0] == pytest.approx(2.267, 0.001) assert properties['widths'][0] == pytest.approx(38.7309, 0.001) <file_sep>/tests/test_readers_writers/test_labspec.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from pathlib import Path import spectrochempy as scp def test_read_labspec(): ramandir = Path('ramandata') scp.info_(ramandir) A = scp.read_labspec('Activation.txt', directory=ramandir) A.plot() A = scp.read_labspec('532nm-191216-Si 200mu.txt', directory=ramandir) A.plot() A = scp.read_labspec('serie190214-1.txt', directory=ramandir) A.plot(colorbar=True) A.plot_map(colorbar=True) A = scp.read_labspec('SMC1-Initial RT.txt', directory=ramandir) A.plot() B = scp.read(protocol='labspec', directory=ramandir) # this pack all spectra of the subdir directory B = scp.read_dir(directory=ramandir / 'subdir') B.plot() scp.show() <file_sep>/tests/test_dataset/test_ndarray.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from copy import copy, deepcopy from datetime import datetime, timezone import numpy as np import pytest from pint.errors import DimensionalityError from spectrochempy.core.dataset.ndarray import NDArray from spectrochempy.units import ur, Quantity from spectrochempy.utils import SpectroChemPyWarning, INPLACE, MASKED, TYPE_INTEGER, TYPE_FLOAT from spectrochempy.utils.testing import assert_equal, assert_array_equal, raises, catch_warnings # ---------------------------------------------------------------------------------------------------------------------- # NDARRAY INITIALIZATION # ---------------------------------------------------------------------------------------------------------------------- def test_ndarray_init(refarray, refmask, ndarray, ndarraymask): # initialisation with null array d0 = NDArray(description='testing ndarray') assert d0.implements('NDArray') assert d0.implements() == 'NDArray' assert isinstance(d0, NDArray) assert d0.is_empty assert d0.shape == () assert d0.id.startswith('NDArray') assert d0.name == d0.id assert d0.title == '<untitled>' assert d0.ndim == 0 assert d0.size is None assert not d0.is_masked assert d0.dtype is None assert d0.unitless assert not d0.dims assert not d0.meta assert hash(d0) is not None assert (repr(d0) == 'NDArray: empty (size: 0)') # assignement to basic write allowed properties d0.data = [1, 2, 3] # put some data assert_array_equal(d0.data, np.array([1, 2, 3])) assert d0.dtype in TYPE_INTEGER assert d0.date.date() == datetime.now(timezone.utc).date() d0.date = datetime(2005, 10, 12) d0.date = "25/12/2025" assert d0.date == datetime(2025, 12, 25, 0, 0) d0.name = 'xxxx' assert d0.name == 'xxxx' d0.title = 'yyyy' assert d0.title == "yyyy" d0.meta = [] d0.meta.something = "a_value" assert d0.meta.something == "a_value" assert d0[1].value == 2 # only a single element so we get a squeezed array d0.units = 'absorbance' assert d0.units == ur.absorbance assert d0[2] == 3 * ur.absorbance assert d0.dims == ['x'] # initialisation with a scalar quantity d1 = NDArray(25) assert d1.data == np.array(25) assert d1.data.dtype in TYPE_INTEGER d1 = NDArray(13. * ur.tesla) assert d1.data == np.array(13.) assert d1.data.dtype in TYPE_FLOAT assert d1.shape == () assert d1.ndim == 0 assert not d1.dims assert d1.units == 'tesla' assert d1.values == 13. * ur.tesla # initialisation with a 1D array quantity d2 = NDArray([13.] * ur.tesla) assert d2.data == np.array([13.]) assert d2.shape == (1,) assert d2.ndim == 1 assert d2.dims == ['x'] assert d2.units == 'tesla' assert d2.values == 13. * ur.tesla # initialisation with a 1D vector quantity d3 = NDArray([[13., 20.]] * ur.tesla) assert_array_equal(d3.data, np.array([[13., 20.]])) assert d3.shape == (1, 2) assert d3.ndim == 2 assert d3.dims == ['y', 'x'] assert d3.units == 'tesla' # initialisation with a sequence d4 = NDArray((2, 3, 4)) assert d4.shape == (3,) assert d4.size == 3 assert d4.dims == ['x'] assert not d4.is_masked # initialization with an array d5 = NDArray(refarray) assert d5.shape == refarray.shape assert d5.size == refarray.size assert not d5.is_masked # initialization with an NDArray object d6 = NDArray(ndarraymask) assert d6.title == '<untitled>' assert d6.shape == refarray.shape assert d6.dims == ['y', 'x'] assert d6.size == refarray.size assert_array_equal(d6.data, refarray) assert d6._data is ndarraymask._data # by default we do not copy # d6.data and ndarraym ask.data are however different due to the addition of un offset assert d6.is_masked assert_array_equal(d6.mask, refmask) assert d6.mask is ndarraymask.mask # no copy by default # initialization with an NDArray object with copy d7 = NDArray(ndarraymask, copy=True) assert_array_equal(d7.data, refarray) assert d7.data is not ndarraymask.data # by default we do not copy assert_array_equal(d7.mask, refmask) assert d7.mask is not ndarraymask.mask # no copy by default # initialisation with a sequence and a mask d0mask = NDArray([2, 3, 4, 5], mask=[1, 0, 0, 0], dtype='int64') assert d0mask.shape == (4,) assert d0mask.is_masked assert d0mask.mask.shape == d0mask.shape # initialisation with a sequence and a mask d1mask = NDArray([2., 3., 4., 5.1], mask=[1, 0, 0, 0]) assert d1mask.shape == (4,) assert d1mask.is_masked assert d1mask.mask.shape == d1mask.shape # dtype specified d8 = NDArray(ndarraymask, desc='with mask', dtype=np.int64) assert d8.shape == refarray.shape assert d8.data.dtype == np.int64 assert d8.dims == ['y', 'x'] assert d8.title == '<untitled>' assert d8.description == 'with mask' assert d8.desc == d8.description assert len(ndarraymask.history) == 1 # one line already in assert len(d8.history) == 2 # copy added # intialisation with only labels d9 = NDArray(labels='a b c d e f g h i j'.split(), title='labeled') assert d9.is_labeled # changing dims name d11 = NDArray(labels='a b c d e f g h i j'.split(), title='labeled', dims=['q'], author='Blake', history='Created from scratch') assert d11.dims == ['q'] assert d11.author == 'Blake' assert '[ a b ... i j]' in d11._repr_html_() # comparison def test_ndarray_copy(): d0 = NDArray(np.linspace(4000, 1000, 10), labels='a b c d e f g h i j'.split(), units='s', mask=False, title='wavelength') d0[5] = MASKED d1 = d0.copy() assert d1 is not d0 assert d1 == d0 assert d1.units == d0.units assert_array_equal(d1.labels, d0.labels) assert_array_equal(d1.mask, d0.mask) d0 = NDArray(np.linspace(4000, 1000, 10), labels=['a b c d e f g h i j'.split(), 'bc cd de ef ab fg gh hi ja ij'.split()], units='s', mask=False, title='wavelength') d0[5] = MASKED d1 = d0.copy() assert d1 is not d0 assert d1 == d0 assert d1.units == d0.units assert_array_equal(d1.labels, d0.labels) assert_array_equal(d1.mask, d0.mask) d2 = copy(d0) assert d2 == d0 d3 = deepcopy(d0) assert d3 == d0 def test_ndarray_sort(): # labels and sort d0 = NDArray(np.linspace(4000, 1000, 10), labels='a b c d e f g h i j'.split(), units='s', mask=False, title='wavelength') assert d0.is_labeled d1 = d0._sort() assert (d1.data[0] == 1000) # check inplace d2 = d0._sort(inplace=True) assert (d0.data[0] == 1000) assert d2 is d0 # check descend d0._sort(descend=True, inplace=True) assert (d0.data[0] == 4000) # check sort using label d3 = d0._sort(by='label', descend=True) assert (d3.labels[0] == 'j') # multilabels # add a row of labels to d0 d0.labels = 'bc cd de ef ab fg gh hi ja ij '.split() d1 = d0._sort() assert (d1.data[0] == 1000) assert_array_equal(d1.labels[0], ['j', 'ij']) d1._sort(descend=True, inplace=True) assert (d1.data[0] == 4000) assert_array_equal(d1.labels[0], ['a', 'bc']) d1 = d1._sort(by='label[1]', descend=True) assert np.all(d1.labels[0] == ['i', 'ja']) # other way d2 = d1._sort(by='label', pos=1, descend=True) assert np.all(d2.labels[0] == d1.labels[0]) def test_ndarray_methods(refarray, ndarray, ndarrayunit): ref = refarray nd = ndarray.copy() assert nd.data.size == ref.size assert nd.shape == ref.shape assert nd.size == ref.size assert nd.ndim == 2 assert nd.data[1, 1] == ref[1, 1] assert nd.dims == ['y', 'x'] assert nd.unitless # no units assert not nd.dimensionless # no unit so dimensionless has no sense with catch_warnings() as w: # try to change to an array with units nd.to('m') # should not change anything (but raise a warning) assert w[-1].category == SpectroChemPyWarning assert nd.unitless nd.units = 'm' assert nd.units == ur.meter nd1 = nd.to('km') assert nd.units != ur.kilometer # not inplace assert nd1.units == ur.kilometer nd.ito('m') assert nd.units == ur.meter # change of units - ok if it can be casted to the current one nd.units = 'cm' # cannot change to incompatible units with pytest.raises(TypeError): nd.units = 'radian' # we can force them nd.ito('radian', force=True) # check dimensionless and scaling assert 1 * nd.units == 1. * ur.dimensionless assert nd.units.dimensionless assert nd.dimensionless with raises(DimensionalityError): nd1 = nd1.ito('km/s') # should raise an error nd.units = 'm/km' assert nd.units.dimensionless assert nd.units.scaling == 0.001 nd.to(1 * ur.m, force=True) assert nd.dims == ['y', 'x'] # check units compatibility nd.ito('m', force=True) nd2 = ndarray.copy() assert nd2.dims == ['y', 'x'] nd2.units = 'km' assert nd.is_units_compatible(nd2) nd2.ito('radian', force=True) assert not nd.is_units_compatible(nd2) # check masking assert not nd.is_masked repr(nd) assert repr(nd).startswith('NDArray: ') nd[0] = MASKED assert nd.is_masked assert nd.dims == ['y', 'x'] # check len and size assert len(nd) == ref.shape[0] assert nd.shape == ref.shape assert nd.size == ref.size assert nd.ndim == 2 assert nd.dims == ['y', 'x'] # a vector is a 1st rank tensor. Internally (it will always be represented # as a 1D matrix. v = NDArray([[1., 2., 3.]]) assert v.ndim == 2 assert v.shape == (1, 3) assert v.dims == ['y', 'x'] assert_array_equal(v.data, np.array([[1., 2., 3.]])) vt = v.transpose() assert vt.shape == (3, 1) assert vt.dims == ['x', 'y'] assert_array_equal(vt.data, np.array([[1.], [2.], [3.]])) # test repr nd = ndarrayunit.copy() h, w = ref.shape assert nd.__repr__() == f"NDArray: [float64] m.s^-1 (shape: (y:{h}, x:{w}))" nd[1] = MASKED assert nd.is_masked # test repr_html assert '<table style=\'background:transparent\'>' in nd._repr_html_() # test iterations nd = ndarrayunit.copy() nd[1] = MASKED # force units to change np.random.seed(12345) ndd = NDArray(data=np.random.random((3, 3)), mask=[[True, False, False], [False, True, False], [False, False, True]], units='meters') with raises(Exception): ndd.to('second') ndd.to('second', force=True) # swapdims np.random.seed(12345) d = np.random.random((4, 3)) d3 = NDArray(d, units=ur.Hz, mask=[[False, True, False], [False, True, False], [False, True, False], [True, False, False]]) # with units & mask assert d3.shape == (4, 3) assert d3._data.shape == (4, 3) assert d3.dims == ['y', 'x'] d4 = d3.swapdims(0, 1) assert d4.dims == ['x', 'y'] assert d4.shape == (3, 4) assert d4._data.shape == (3, 4) # test iter for i, item in enumerate(ndd): assert item == ndd[i] ndz = NDArray() assert not list(item for item in ndz) assert str(ndz) == repr(ndz) == 'NDArray: empty (size: 0)' ################ # TEST SLICING # ################ def test_ndarray_slicing(refarray, ndarray): ref = refarray nd = ndarray.copy() assert not nd.is_masked assert nd.dims == ['y', 'x'] # slicing is different in scpy than with numpy. We always return # unsqueezed dimensions, except for array of size 1, which are considered as scalar nd1 = nd[0, 0] assert_equal(nd1.data, nd.data[0:1, 0:1]) assert nd1 is not nd[0, 0] assert nd1.ndim == 2 # array not reduced assert nd1.size == 1 assert nd1.shape == (1, 1) assert isinstance(nd1, NDArray) assert isinstance(nd1.data, np.ndarray) assert isinstance(nd1.values, TYPE_FLOAT) nd1b, id = nd.__getitem__((0, 0), return_index=True) assert nd1b == nd1 nd1a = nd[0, 0:2] assert_equal(nd1a.data, nd.data[0:1, 0:2]) assert nd1a is not nd[0, 0:2] assert nd1a.ndim == 2 assert nd1a.size == 2 assert nd1a.shape == (1, 2) assert isinstance(nd1a, NDArray) assert nd1a.dims == ['y', 'x'] # returning none if empty when slicing nd1b = nd[11:, 11:] assert nd1b is None # nd has been changed, restore it before continuing nd = ndarray.copy() nd2 = nd[7:10] assert_equal(nd2.data, nd.data[7:10]) assert not nd.is_masked nd3 = nd2[1] assert nd3.shape == (1, ref.shape[1]) assert nd3.dims == ['y', 'x'] nd4 = nd2[:, 1] assert nd4.shape == (3, 1) assert nd4.dims == ['y', 'x'] # squezzing nd5 = nd4.squeeze() assert nd5.shape == (3,) assert nd5.dims == ['y'] # set item nd[1] = 2. assert nd[1, 0] == 2 # set item mask nd[1] = MASKED assert nd.is_masked # boolean indexing nd = ndarray.copy() nd[nd.data > 0] # fancy indexing df = nd.data[[-1, 1]] ndf = nd[[-1, 1]] assert_array_equal(ndf.data, df) ndf = nd[[-1, 1], INPLACE] # TODO: check utility of this (I remember it should be related to setitem) assert_array_equal(ndf.data, df) # use with selection from other numpy functions am = np.argmax(nd.data, axis=1) assert_array_equal(am, np.array([7, 3])) amm = nd.data[..., am] assert_array_equal(nd[..., am].data, amm) def test_dim_names_specified(ndarray): nd = ndarray.copy() assert not nd.is_masked assert nd.dims == ['y', 'x'] # set dim names nd.dims = ['t', 'y'] assert nd.dims == ['t', 'y'] assert nd.dims == ['t', 'y'] def test_ndarray_slice_labels(): # slicing only-label array d0 = NDArray(labels='a b c d e f g h i j'.split(), title='labelled') assert d0.is_labeled assert d0.ndim == 1 assert d0.shape == (10,) assert d0[1].labels == ['b'] assert d0[1].values == 'b' assert d0['b'].values == 'b' assert d0['c':'d'].shape == (2,) assert_array_equal(d0['c':'d'].values, np.array(['c', 'd'])) def test_ndarray_issue_23(): nd = NDArray(np.ones((10, 10))) assert nd.shape == (10, 10) assert nd.dims == ['y', 'x'] # slicing nd1 = nd[1] assert nd1.shape == (1, 10) assert nd1.dims == ['y', 'x'] # transposition ndt = nd1.T assert ndt.shape == (10, 1) assert ndt.dims == ['x', 'y'] # squeezing nd2 = nd1.squeeze() assert nd2.shape == (10,) assert nd2.dims == ['x'] nd = NDArray(np.ones((10, 10, 2))) assert nd.shape == (10, 10, 2) assert nd.dims == ['z', 'y', 'x'] # slicing nd1 = nd[:, 1] assert nd1.shape == (10, 1, 2) assert nd1.dims == ['z', 'y', 'x'] # transposition ndt = nd1.T assert ndt.shape == (2, 1, 10) assert ndt.dims == ['x', 'y', 'z'] # squeezing nd2 = nd1.squeeze() assert nd2.shape == (10, 2) assert nd2.dims == ['z', 'x'] # Bugs Fixes def test_ndarray_bug_13(ndarrayunit): nd = ndarrayunit[0] assert isinstance(nd[0], NDArray) # reproduce our bug (now solved) nd[0] = Quantity('10 cm.s^-1') with pytest.raises(DimensionalityError): nd[0] = Quantity('10 cm') <file_sep>/docs/userguide/importexport/import.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.0 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Import Data # # This tutorial shows how to import data in **SpectroChemPy (SCPy)**. # # First, let's ``import spectrochempy as scp`` in the current # namespace, so that all spectrochempy commands will be called as ```scp.method(<method parameters>)```. # %% import spectrochempy as scp # %% [markdown] # ## Dialog boxes # # Retrieving Files and Directories, in day-to-day work is often made through Dialog Boxes. While we do not recommend # this procedure for advanced usage (see below), it is quite easy to do that with SCPy. To do so, we can use the # `read` function which open a dialog, allowing the selection of data file form various origin. By default, # the native SCPy type of data is proposed (file suffix: `.scp`). The desired type of files to display can be choosen # in a dropdown field. # %% X = scp.read() # %% [markdown] # The dialog box such as shown in this image: # # <center><img id='drawings' width='600px' src='./images/read.png'></img></center> # # The dialog Box allows selecting the file which data will be loaded in the variable `X`. Try for instance to run the # cell below, and select an omnic spg datafile (select the .spg extension), which you can find in the `irdata` # directory. # # <div class='alert alert-warning'> # <b>Tip</b> # # the dialog box does not necessarily pops up in the foreground: check your task bar ! # </div> # # Printing the returned NDDataset object X should read like this, with indication of the dataset `shape`, *i.e., # * the `y` and `x` dimension sizes: # %% print(X) # %% [markdown] # The size of the `y` and `x` dimension will depend, of course, of the file that you have selected ! If you did not # select any file (*e.g.,* by pressing 'cancel' in th Dialog Box, the result will be `None`, as nothing has been loaded # in `X`. # # <div class='alert alert-info'> # <b>Note</b> # # By default the Dialog Box opens in the last directory you have used. However if a directory path is specified, # the dialog should open from this diectory. # </div> # %% scp.read_omnic('irdata/subdir') # %% [markdown] # See below for more information # # - At the time of writing this tutorial (SpectroChemPy v.0.1.23), the following commands will behave similarly: # - `read` to open any kind of recognised data files based on the file suffix (e.g., *.spg, etc...) # - `read_omnic` to open omnic (spa and spg) files # - `read_opus` to open Bruker Opus (*.0, ...) files # - `read_labspec` to open LABSPEC6 files - this assume they have been exported as *.txt files # - `read_topspin` to open Bruker Topspin NMR files # - `read_csv` to open csv files # - `read_jcamp` to open an IR JCAMP-DX datafile # - `read_matlab` to open MATLAB (.mat) files including Eingenvector's Dataset objects # # # - Additionaly # - `read_dir` to open readable files in a directory # # # - The list of readers available will hopefully increase in future **SCPy** releases:-) # # If successful, the output of the above cell should read something like # # Out[2] NDDataset: [float64] a.u. (shape: (y:2, x:5549)) # %% [markdown] # ## Import with explicit directory or file pathnames # # While the use of Dialog Box seems at first 'user-friendly', you will probably experience that this is often **NOT** # efficient because you will have to select the file *each time* the notebook (or the script) is run... Hence, the # above commands can be used with the indication of the path to a directory, and/or to a filename. # # If only a directory is indicated, the dialog box will open in this directory. # # Note that on Windows the path separator is a backslash `\`. However, in many contexts, # backslash is also used as an escape character in order to represent non-printable characters. To avoid problems, # either it has to be escaped itself, a double backslash or one can also use raw string literals # to represent Windows paths. These are string literals that have an `r` prepended to them. In raw string literals # the `\` represents a literal backslash: `r'C:\users\Brian'`: # # For instance, on Windows systems, the two following commands are fully equivalent: # # ```ipython3 # X = scp.read_omnic(directory='C:\\users\\Brian') # ``` # # or # # ```ipython3 # X = scp.read_omnic(directory=r'C:\users\Brian') # ``` # # and will open the dialog box at the root directory of the `C:` drive. # # You can avoid using the form `\\` or the use of raw strings by using conventional slash `/`. In python # they play the path separator role, as well in Windows than in other unix-based system (Linux, OSX, ...) # # ```ipython3 # X = scp.read_omnic(directory='C:/users/Brian') # ``` # %% [markdown] # If a `filename` is passed in argument, like here: # ```ipython3 # X = scp.read_omnic('wodger.spg', directory='C:/') # ``` # then SpectroChemPy will attempt opening a file named `wodger.spg` supposedly located in `C:\`. # # # Imagine now that the file of interest is actually located in `C:\users\Brian\s\Life`. The following # commands are all equivalent and will allow opening the file: # # - using only the full pathname of the file: # ```ipython3 # X = scp.read_omnic('C:/users/Brian/s/Life/wodger.spg') # ``` # # - or using a combination of directory and file pathnames: # ```ipython3 # X = scp.read_omnic('wodger.spg', directory='C:/users/Brian/s/Life' # X = scp.read_omnic('Life/wodger.spg', directory='C:/users/Brian/s') # ``` # # - etc... # %% [markdown] # ### A good practice: use relative paths # # The above directives require explicitly writing the absolute pathnames, which are virtually always computer specific. # If, for instance, Brian has a project organised in a folder (`s`) with a directory dedicated to input data (`Life`) # and a notebook for preprocessing (`welease.ipynb`) as illustrate below: # # ``` # C:\users # | +-- Brian # | | +-- s # | | | +-- Life # | | | | +-- wodger.spg # | | | +-- welease.ipynb # # ``` # # Then running this project in John's Linux computer (e.g. in `\home\john\s_copy`) will certainly result in execution # errors if absolute paths are used in the notebook: # ```text # OSError: Can't find this filename C:\users\Brian\s\life\wodger.spg # ``` # In this respect, a good practice consists in using relative pathnames in scripts and notebooks. # Fortunately, SpectroChemPy readers use relative paths. If the given path is not absolute, then SpectroChemPy will # search in the current directory. Hence the opening of the `spg` file from scripts in `welease.ipynb` can be made # by the command: # ```ipython3 # X = scp.read_omnic('Life/wodger.spg') # ``` # or: # ```ipython3 # X = scp.read_omnic('wodger.spg', directory='Life') # ``` # # ### Good practice: use `os` or `pathlib` modules # # In python, working with pathnames is classically done with dedicated modules such as `os` or `pathlib` python modules. # With `os` we mention the following methods that can be particularly useful: # # ```ipython3 # import os # os.getcwd() # returns the absolute path of the current working directory preferences.datadir # os.path.expanduser("~") # returns the home directory of the user # os.path.join('path1','path2','path3', ...) # intelligently concatenates path components # # using the system seprator (`/`or `\\`) # ``` # # Using `Pathlib` is even simpler: # ```ipython3 # from pathlib import Path # Path.cwd() # returns the absolute path of the current working directory # Path.home() # returns the home directory of the user # Path('path1') / 'path2' / 'path3' / '...' # intelligently concatenates path components # ``` # # The interested readers will find more details on the use of these modules here: # - [os - Miscellaneous operating system interfaces](https://docs.python.org/3/library/os.html) # - [pathlib — Object-oriented filesystem paths](https://docs.python.org/3/library/pathlib.html) # # ## Another default search directory: `datadir` # # Spectrochempy also comes with the definition of a second default directory path where to look at the data: # the `datadir` directory. It is defined in the variable `preferences.datadir` which is imported at the same # time as spectrochempy. By default, `datadir` points in the 'scp_data\testdata' folder of SpectroChemPy: # %% DATADIR = scp.preferences.datadir DATADIR # %% [markdown] # DATADIR is already a pathlib object and so can be used easily # %% X = scp.read_omnic(DATADIR / 'wodger.spg') # %% [markdown] # It can be set to another pathname *permanently* (i.e., even after computer restart) by a new assignment: # # ```ipython3 # scp.preferences.datadir = 'C:/users/Brian/s/Life' # ``` # # This will change the default value in the SCPy preference file located in the hidden folder # `.spectrochempy/` at the root of the user home directory. # # Finally, by default, the import functions used in Sepctrochempy will search the data files using this order of # precedence: # # 1. try absolute path # 2. try in current working directory # 3. try in `datadir` # 4. if none of these works: generate an OSError (file or directory not found) # # %% [markdown] # ## File selector widget # %% [markdown] # A widget is provided to help with the selection of file names or directory. # # %% datadir = scp.preferences.datadir fs = scp.FileSelector(path=datadir, filters=['spg', 'spa']) fs # %% [markdown] # After validation of the selection, one can read the path and name of the selected files. # %% fs.value, fs.path, fs.fullpath <file_sep>/docs/userguide/units/units.py # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # Units & Quantities # %% [markdown] # Spectrochempy can do calculations with units - it uses [pint](https://pint.readthedocs.io) to define and perform # operation on data with units. # %% from spectrochempy import * # noqa: F403 # %% [markdown] # ## Create quantities # # to create quantity, use for instance, one of the following expression: # %% Quantity('10.0 cm^-1') # %% Quantity(1.0, 'cm^-1/hour') # %% Quantity(10.0, ur.cm / ur.km) # %% [markdown] # or may be (?) simpler, # %% 10.0 * ur.meter / ur.gram / ur.volt # %% [markdown] # `ur` stands for **unit registry**, which handle many type of units # (and conversion between them) # %% [markdown] # ## Do arithmetics with units # %% a = 900 * ur.km b = 4.5 * ur.hours a / b # %% [markdown] # Such calculations can also be done using the following syntax, using a string expression # %% Quantity("900 km / (8 hours)") # %% [markdown] # ## Convert between units # %% c = a / b c.to('cm/s') # %% [markdown] # We can make the conversion *inplace* using *ito* instead of *to* # %% c.ito('m/s') c # %% [markdown] # ## Do math operations with consistent units # %% x = 10 * ur.radians np.sin(x) # %% [markdown] # Consistency of the units are checked! # %% x = 10 * ur.meters np.sqrt(x) # %% [markdown] # but this is wrong... # %% x = 10 * ur.meters try: np.cos(x) except DimensionalityError as e: error_(e) # %% [markdown] # Units can be set for NDDataset data and/or Coordinates # %% ds = NDDataset([1., 2., 3.], units='g/cm^3', title='concentration') ds # %% ds.to('kg/m^3') # %% [markdown] # One can do transparent calculation using the units # %% volume = Quantity("2 m^3") ds1 = ds * volume ds1 # %% ds1 / ds <file_sep>/spectrochempy/core/dataset/ndarray.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # = # ====================================================================================================================== """ This module implements the base |NDArray| class. """ __all__ = ['NDArray'] import copy as cpy from datetime import datetime, timezone import warnings import re import textwrap import uuid import itertools from traitlets import (List, Unicode, Instance, Bool, Union, CFloat, Integer, CInt, HasTraits, default, validate, observe, All) from pint.errors import DimensionalityError import numpy as np from traittypes import Array from spectrochempy.units import Unit, ur, Quantity, set_nmr_context from spectrochempy.core import info_, error_, print_ from spectrochempy.core.dataset.meta import Meta from spectrochempy.utils import (TYPE_INTEGER, TYPE_FLOAT, MaskedConstant, MASKED, NOMASK, INPLACE, is_sequence, is_number, numpyprintoptions, spacing, insert_masked_print, SpectroChemPyWarning, make_new_object, convert_to_html, get_user_and_node) # ====================================================================================================================== # constants # ====================================================================================================================== DEFAULT_DIM_NAME = list('xyzuvwpqrstijklmnoabcdefgh')[::-1] # ====================================================================================================================== # Printing settings # ====================================================================================================================== numpyprintoptions() # ====================================================================================================================== # The basic NDArray class # ====================================================================================================================== # noinspection PyPep8Naming class NDArray(HasTraits): # hidden properties # array definition _id = Unicode() _name = Unicode() _title = Unicode(allow_none=True) _data = Array(allow_none=True) _dtype = Instance(np.dtype, allow_none=True) _dims = List(Unicode()) _mask = Union((Bool(), Array(Bool()), Instance(MaskedConstant))) _labels = Array(allow_none=True) _units = Instance(Unit, allow_none=True) # region of interest _roi = List(allow_none=True) # dates _date = Instance(datetime) _modified = Instance(datetime) # metadata _author = Unicode() _description = Unicode() _origin = Unicode() _history = List(Unicode(), allow_none=True) _meta = Instance(Meta, allow_none=True) # for linear data generation _offset = Union((CFloat(), CInt(), Instance(Quantity)), ) _increment = Union((CFloat(), CInt(), Instance(Quantity)), ) _size = Integer(0) _linear = Bool(False) # metadata # Basic NDArray setting _copy = Bool(False) # by default we do not copy the data # which means that if the same numpy array # is used for too different NDArray, they # will share it. _labels_allowed = Bool(True) # Labels are allowed for the data, if the # data are 1D only (they will essentially # serve as coordinates labelling. # other settings _text_width = Integer(120) _html_output = Bool(False) # .................................................................................................................. def __init__(self, data=None, **kwargs): """ The basic |NDArray| object. The |NDArray| class is an array (numpy |ndarray|-like) container, usually not intended to be used directly, as its basic functionalities may be quite limited, but to be subclassed. Indeed, both the classes |NDDataset| and |Coord| which respectively implement a full dataset (with coordinates) and the coordinates in a given dimension, are derived from |NDArray| in |scpy|. The key distinction from raw numpy |ndarray| is the presence of optional properties such as dimension names, labels, masks, units and/or extensible metadata dictionary. Parameters ---------- data : array of floats Data array contained in the object. The data can be a list, a tuple, a |ndarray|, a ndarray-like, a |NDArray| or any subclass of |NDArray|. Any size or shape of data is accepted. If not given, an empty |NDArray| will be inited. At the initialisation the provided data will be eventually casted to a numpy-ndarray. If a subclass of |NDArray| is passed which already contains some mask, labels, or units, these elements will be used to accordingly set those of the created object. If possible, the provided data will not be copied for `data` input, but will be passed by reference, so you should make a copy of the `data` before passing them if that's the desired behavior or set the `copy` argument to True. Other Parameters ---------------- dtype : str or dtype, optional, default=np.float64 If specified, the data will be casted to this dtype, else the data will be casted to float64. dims : list of chars, optional. if specified the list must have a length equal to the number od data dimensions (ndim) and the chars must be taken among among x,y,z,u,v,w or t. If not specified, the dimension names are automatically attributed in this order. name : str, optional A user friendly name for this object. If not given, the automatic `id` given at the object creation will be used as a name. labels : array of objects, optional Labels for the `data`. labels can be used only for 1D-datasets. The labels array may have an additional dimension, meaning several series of labels for the same data. The given array can be a list, a tuple, a |ndarray|, a ndarray-like, a |NDArray| or any subclass of |NDArray|. mask : array of bool or `NOMASK`, optional Mask for the data. The mask array must have the same shape as the data. The given array can be a list, a tuple, or a |ndarray|. Each values in the array must be `False` where the data are *valid* and True when they are not (like in numpy masked arrays). If `data` is already a :class:`~numpy.ma.MaskedArray`, or any array object (such as a |NDArray| or subclass of it), providing a `mask` here will causes the mask from the masked array to be ignored. units : |Unit| instance or str, optional Units of the data. If data is a |Quantity| then `units` is set to the unit of the `data`; if a unit is also explicitly provided an error is raised. Handling of units use the `pint <https://pint.readthedocs.org/>`_ package. title : str, optional The title of the dimension. It will later be used for instance for labelling plots of the data. It is optional but recommended to give a title to each ndarray. dlabel : str, optional. Alias of `title`. meta : dict-like object, optional. Additional metadata for this object. Must be dict-like but no further restriction is placed on meta. author : str, optional. name(s) of the author(s) of this dataset. BNy default, name of the computer note where this dataset is created. description : str, optional. A optional description of the nd-dataset. A shorter alias is `desc`. history : str, optional. A string to add to the object history. copy : bool, optional Perform a copy of the passed object. Default is False. See Also -------- NDDataset : Object which subclass |NDArray| with the addition of coordinates. Coord : Explicit coordinates object. LinearCoord : Implicit coordinates objet. Examples -------- >>> import spectrochempy as scp >>> myarray = scp.NDArray([1., 2., 3.]) """ # creation date self._date = datetime.now(timezone.utc) # by default, we try to keep a reference to the data, not copy them self._copy = kwargs.pop('copy', False) # dtype = kwargs.pop('dtype', None) if dtype is not None: self._dtype = np.dtype(dtype) self._linear = kwargs.pop('linear', False) self._increment = kwargs.pop('increment', 1.0) self._offset = kwargs.pop('offset', 0.0) self._size = kwargs.pop('size', 0) self._accuracy = kwargs.pop('accuracy', None) if data is not None: self.data = data if data is None or self.data is None: self._data = None self._dtype = None # default if self._labels_allowed: self.labels = kwargs.pop('labels', None) self.title = kwargs.pop('title', self.title) mask = kwargs.pop('mask', NOMASK) if mask is not NOMASK: self.mask = mask if 'dims' in kwargs.keys(): self.dims = kwargs.pop('dims') self.units = kwargs.pop('units', None) self.meta = kwargs.pop('meta', None) self.name = kwargs.pop('name', None) self.description = kwargs.pop('description', kwargs.pop('desc', "")) author = kwargs.pop('author', get_user_and_node()) if author: try: self.author = author except AttributeError: pass history = kwargs.pop('history', None) if history is not None: try: self.history = history except AttributeError: pass self._modified = self._date # ------------------------------------------------------------------------------------------------------------------ # special methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def __copy__(self): return self.copy(deep=False) # .................................................................................................................. def __deepcopy__(self, memo=None): return self.copy(deep=True, memo=memo) # .................................................................................................................. def __dir__(self): return ['data', 'dims', 'mask', 'labels', 'units', 'meta', 'title', 'name', 'origin', 'roi', 'author', 'description', 'history', 'linear', 'offset', 'increment'] # .................................................................................................................. def __eq__(self, other, attrs=None): eq = True if not isinstance(other, NDArray): # try to make some assumption to make useful comparison. if isinstance(other, Quantity): otherdata = other.magnitude otherunits = other.units elif isinstance(other, (float, int, np.ndarray)): otherdata = other otherunits = False else: # pragma: no cover return False if not self.has_units and not otherunits: eq = np.all(self._data == otherdata) elif self.has_units and otherunits: eq = np.all(self._data * self._units == otherdata * otherunits) else: # pragma: no cover return False return eq if attrs is None: attrs = self.__dir__() for attr in ['name', 'history']: if attr in attrs: attrs.remove(attr) for attr in attrs: if attr != 'units': sattr = getattr(self, f'_{attr}') if hasattr(other, f'_{attr}'): oattr = getattr(other, f'_{attr}') # to avoid deprecation warning issue for unequal array if (sattr is None and oattr is not None): return False if (oattr is None and sattr is not None): return False if hasattr(oattr, 'size') and hasattr(sattr, 'size') and oattr.size != sattr.size: # particular case of mask if attr != 'mask': return False else: if other.mask != self.mask: return False eq &= np.all(sattr == oattr) if not eq: return False else: return False else: # no unit and dimensionless are supposed equals sattr = self._units if sattr is None: sattr = ur.dimensionless if hasattr(other, '_units'): oattr = other._units if oattr is None: oattr = ur.dimensionless eq &= np.all(sattr == oattr) if not eq: # debug_(f"attributes `{attr}` are not equals or one is missing: \n{sattr} != {oattr}") return False else: return False return eq # .................................................................................................................. def __getitem__(self, items, return_index=False): if isinstance(items, list): # Special case of fancy indexing items = (items,) # choose, if we keep the same or create new object inplace = False if isinstance(items, tuple) and items[-1] == INPLACE: items = items[:-1] inplace = True # Eventually get a better representation of the indexes keys = self._make_index(items) # init returned object if inplace: new = self else: new = self.copy() # slicing by index of all internal array if new.data is not None: udata = new.masked_data[keys] if new.linear: # if self.increment > 0: # new._offset = udata.min() # else: # new._offset = udata.max() new._size = udata.size if new._size > 1: inc = np.diff(udata) variation = (inc.max() - inc.min()) / udata.ptp() if variation < 1.0e-5: new._increment = np.mean(inc) # np.round(np.mean( # inc), 5) new._offset = udata[0] new._data = None new._linear = True else: new._linear = False else: new._linear = False if not new.linear: new._data = np.asarray(udata) if self.is_labeled: # case only of 1D dataset such as Coord new._labels = np.array(self._labels[keys]) if new.is_empty: error_(f"Empty array of shape {new._data.shape} resulted from slicing.\n" f"Check the indexes and make sure to use floats for location slicing") new = None elif (self.data is not None) and hasattr(udata, 'mask'): new._mask = udata.mask else: new._mask = NOMASK # for all other cases, # we do not needs to take care of dims, as the shape is not reduced by # this operation. Only a subsequent squeeze operation will do it if not return_index: return new else: return new, keys # .................................................................................................................. def __hash__(self): # all instance of this class has same hash, so they can be compared return hash((type(self), self.shape, self._units)) # .................................................................................................................. def __iter__(self): # iterate on the first dimension if self.ndim == 0: error_('iteration over a 0-d array is not possible') return None for n in range(len(self)): yield self[n] # .................................................................................................................. def __len__(self): # len of the last dimension if not self.is_empty: return self.shape[0] else: return 0 # .................................................................................................................. def __ne__(self, other, attrs=None): return not self.__eq__(other, attrs) # .................................................................................................................. def __repr__(self): out = f"{self._repr_value().strip()} ({self._repr_shape().strip()})" out = out.rstrip() return out # .................................................................................................................. def __setitem__(self, items, value): if self.linear: error_('Linearly define array are readonly') return keys = self._make_index(items) if isinstance(value, (bool, np.bool_, MaskedConstant)): # the mask is modified, not the data if value is MASKED: value = True if not np.any(self._mask): self._mask = np.zeros(self._data.shape).astype(np.bool_) self._mask[keys] = value return elif isinstance(value, Quantity): # first convert value to the current units value.ito(self.units) # self._data[keys] = np.array(value.magnitude, subok=True, copy=self._copy) value = np.array(value.magnitude, subok=True, copy=self._copy) if self._data.dtype == np.dtype(np.quaternion) and np.isscalar(value): # sometimes do not work directly : here is a work around self._data[keys] = np.full_like(self._data[keys], value).astype(np.dtype(np.quaternion)) else: self._data[keys] = value # .................................................................................................................. def __str__(self): return repr(self) # ------------------------------------------------------------------------------------------------------------------ # private methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @observe(All) def _anytrait_changed(self, change): # ex: change { # 'owner': object, # The HasTraits instance # 'new': 6, # The new value # 'old': 5, # The old value # 'name': "foo", # The name of the changed trait # 'type': 'change', # The event type of the notification, usually 'change' # } if change['name'] in ["_date", "_modified", "trait_added"]: return if change.name in ['_linear', '_increment', '_offset', '_size']: if self._linear: self._linearize() return # all the time -> update modified date self._modified = datetime.now(timezone.utc) return # .................................................................................................................. def _argsort(self, by='value', pos=None, descend=False): # found the indices sorted by values or labels if by == 'value': args = np.argsort(self.data) elif 'label' in by and not self.is_labeled: # by = 'value' # pos = None warnings.warn('no label to sort, use `value` by default', SpectroChemPyWarning) args = np.argsort(self.data) elif 'label' in by and self.is_labeled: labels = self._labels if len(self._labels.shape) > 1: # multidimensional labels if not pos: pos = 0 # try to find a pos in the by string pattern = re.compile(r"label\[(\d)]") p = pattern.search(by) if p is not None: pos = int(p[1]) labels = self._labels[..., pos] args = np.argsort(labels) else: # by = 'value' warnings.warn('parameter `by` should be set to `value` or `label`, use `value` by default', SpectroChemPyWarning) args = np.argsort(self.data) if descend: args = args[::-1] return args # .................................................................................................................. def _cstr(self): out = f"{self._str_value()}\n{self._str_shape()}" out = out.rstrip() return out # .................................................................................................................. @default('_data') def _data_default(self): return None # .................................................................................................................. @validate('_data') def _data_validate(self, proposal): # validation of the _data attribute data = proposal['value'] # cast to the desired type if self._dtype is not None: data = data.astype(np.dtype(self._dtype, copy=False)) # return the validated data if self._copy: return data.copy() else: return data # .................................................................................................................. @default('_dims') def _dims_default(self): return DEFAULT_DIM_NAME[-self.ndim:] # .................................................................................................................. def _get_dims_from_args(self, *dims, **kwargs): # utility function to read dims args and kwargs # sequence of dims or axis, or `dim`, `dims` or `axis` keyword are accepted # check if we have arguments if not dims: dims = None # Check if keyword dims (or synonym axis) exists axis = kwargs.pop('axis', None) kdims = kwargs.pop('dims', kwargs.pop('dim', axis)) # dim or dims keyword if kdims is not None: if dims is not None: warnings.warn('the unamed arguments are interpreted as `dims`. But a named argument `dims` or `axis`' '(DEPRECATED) has been specified. \nThe unamed arguments will thus be ignored.', SpectroChemPyWarning) dims = kdims if dims is not None and not isinstance(dims, list): if isinstance(dims, tuple): dims = list(dims) else: dims = [dims] if dims is not None: for i, item in enumerate(dims[:]): if item is not None and not isinstance(item, str): item = self.dims[item] dims[i] = item if dims is not None and len(dims) == 1: dims = dims[0] return dims # .................................................................................................................. def _get_dims_index(self, dims): # get the index(es) corresponding to the given dim(s) which can be expressed as integer or string if dims is None: return if is_sequence(dims): if np.all([d is None for d in dims]): return else: dims = [dims] axis = [] for dim in dims: if isinstance(dim, TYPE_INTEGER): axis.append(dim) # nothing else to do elif isinstance(dim, str): if dim not in self.dims: raise ValueError(f"Error: Dimension `{dim}` is not recognized " f"(not in the dimension's list: {self.dims}).") id = self.dims.index(dim) axis.append(id) else: raise TypeError(f'Dimensions must be specified as string or integer index, but a value of type ' f'{type(dim)} has been passed (value:{dim})!') for i, item in enumerate(axis): # convert to positive index if item < 0: axis[i] = self.ndim + item axis = tuple(axis) return axis # .................................................................................................................. def _get_slice(self, key, dim): info = None if not isinstance(key, slice): # integer or float start = key if not isinstance(key, TYPE_INTEGER): start = self._loc2index(key, dim) if isinstance(start, tuple): start, info = start if start is None: return slice(None) else: if key < 0: # reverse indexing axis, dim = self.get_axis(dim) start = self.shape[axis] + key stop = start + 1 # in order to keep an non squeezed slice return slice(start, stop, 1) else: start, stop, step = key.start, key.stop, key.step if start is not None and not isinstance(start, TYPE_INTEGER): start = self._loc2index(start, dim) if isinstance(start, tuple): start, info = start if stop is not None and not isinstance(stop, TYPE_INTEGER): stop = self._loc2index(stop, dim) if isinstance(stop, tuple): stop, info = stop if start is not None and stop < start: start, stop = stop, start if stop != start: stop = stop + 1 # to include last loc or label index if step is not None and not isinstance(step, (int, np.int_, np.int64)): raise NotImplementedError( 'step in location slicing is not yet possible.') # TODO: we have may be a special case with # datetime # step = 1 if step is None: step = 1 if start is not None and stop is not None and start == stop and info is None: stop = stop + 1 # to include last index newkey = slice(start, stop, step) return newkey # .................................................................................................................. @default('_id') def _id_default(self): # a unique id return f"{type(self).__name__}_{str(uuid.uuid1()).split('-')[0]}" @default('_increment') def _increment_default(self): return 1.0 # .................................................................................................................. @default('_labels') def _labels_default(self): return None # .................................................................................................................. def _linearize(self): if not self.linear or self._data is None: return self._linear = False # to avoid action of the observer if self._squeeze_ndim > 1: error_("Linearization is only implemented for 1D data") return data = self._data.squeeze() # try to find an increment if data.size > 1: inc = np.diff(data) variation = (inc.max() - inc.min()) / data.ptp() if variation < 1.0e-5: self._increment = data.ptp() / (data.size - 1) * np.sign( inc[0]) # np.mean(inc) # np.round(np.mean(inc), 5) self._offset = data[0] self._size = data.size self._data = None self._linear = True else: self._linear = False else: self._linear = False # .................................................................................................................. def _loc2index(self, loc, dim=None): # Return the index of a location (label or values such as coordinates) along a 1D array. # Do not apply for multidimensional arrays (ndim>1) if self.ndim > 1: raise NotImplementedError(f'not implemented for {type(self).__name__} objects which are not 1-dimensional ' f'(current ndim:{self.ndim})') if self.is_empty and not self.is_labeled: raise IndexError(f'Could not find this location: {loc} on an empty array') else: data = self.data if is_number(loc): # get the index of a given values error = None if np.all(loc > data.max()) or np.all(loc < data.min()): print_(f'This coordinate ({loc}) is outside the axis limits ({data.min()}-{data.max()}).\n' f'The closest limit index is returned') error = 'out_of_limits' index = (np.abs(data - loc)).argmin() # TODO: add some precision to this result if not error: return index else: return index, error elif is_sequence(loc): # TODO: is there a simpler way to do this with numpy functions index = [] for lo in loc: index.append((np.abs(data - lo)).argmin()) # TODO: add some precision to this result return index elif self.is_labeled: # TODO: look in all row of labels labels = self._labels indexes = np.argwhere(labels == loc).flatten() if indexes.size > 0: return indexes[0] else: raise IndexError(f'Could not find this label: {loc}') elif isinstance(loc, datetime): # not implemented yet raise NotImplementedError("datetime as location is not yet impemented") # TODO: date! else: raise IndexError(f'Could not find this location: {loc}') # .................................................................................................................. def _make_index(self, key): if isinstance(key, np.ndarray) and key.dtype == bool: # this is a boolean selection # we can proceed directly return key # we need to have a list of slice for each argument # or a single slice acting on the axis=0 if isinstance(key, tuple): keys = list(key) else: keys = [key, ] def ellipsisinkeys(keys): try: # Ellipsis if isinstance(keys[0], np.ndarray): return False test = Ellipsis in keys except ValueError as e: if e.args[0].startswith('The truth '): # probably an array of index (Fancy indexing) # should not happen any more with the test above test = False return test while ellipsisinkeys(keys): i = keys.index(Ellipsis) keys.pop(i) for j in range(self.ndim - len(keys)): keys.insert(i, slice(None)) if len(keys) > self.ndim: raise IndexError("invalid index") # pad the list with additional dimensions for i in range(len(keys), self.ndim): keys.append(slice(None)) for axis, key in enumerate(keys): # the keys are in the order of the dimension in self.dims! # so we need to get the correct dim in the coordinates lists dim = self.dims[axis] if is_sequence(key): # fancy indexing # all items of the sequence must be integer index keys[axis] = key else: keys[axis] = self._get_slice(key, dim) return tuple(keys) # .................................................................................................................. @default('_mask') def _mask_default(self): return NOMASK if self._data is None else np.zeros(self._data.shape).astype(bool) # .................................................................................................................. @validate('_mask') def _mask_validate(self, proposal): pv = proposal['value'] mask = pv if mask is None or mask is NOMASK: return mask # mask will be stored in F_CONTIGUOUS mode, if data are in this mode if not mask.flags['F_CONTIGUOUS'] and self._data.flags['F_CONTIGUOUS']: mask = np.asfortranarray(mask) # no more need for an eventual copy self._copy = False # no particular validation for now. if self._copy: return mask.copy() else: return mask # .................................................................................................................. @default('_meta') def _meta_default(self): return Meta() # .................................................................................................................. @default('_name') def _name_default(self): return "" # .................................................................................................................. @default('_offset') def _offset_default(self): return 0 # .................................................................................................................. def _repr_html_(self): return convert_to_html(self) # .................................................................................................................. def _repr_shape(self): if self.is_empty: return 'size: 0' out = '' shape_ = (x for x in itertools.chain.from_iterable(list(zip(self.dims, self.shape)))) shape = (', '.join(['{}:{}'] * self.ndim)).format(*shape_) size = self.size out += f'size: {size}' if self.ndim < 2 else f'shape: ({shape})' return out # .................................................................................................................. def _repr_value(self): numpyprintoptions(precision=4, edgeitems=0, spc=1, linewidth=120) prefix = type(self).__name__ + ': ' units = '' size = '' if not self.is_empty: if self.data is not None: dtype = self.dtype data = '' if self.implements('Coord') or self.implements('LinearCoord'): size = f" (size: {self.data.size})" units = ' {:~K}'.format(self.units) if self.has_units else ' unitless' else: # no data but labels lab = self.get_labels() data = f' {lab}' size = f" (size: {len(lab)})" dtype = 'labels' body = f"[{dtype}]{data}" else: size = '' body = 'empty' numpyprintoptions() return ''.join([prefix, body, units, size]) # .................................................................................................................. def _set_data(self, data): if data is None: return elif isinstance(data, NDArray) and data.linear: # Case of Linearcoord for attr in self.__dir__(): try: if attr in ['linear', 'offset', 'increment']: continue if attr == 'data': val = data.data else: val = getattr(data, f"_{attr}") if self._copy: val = cpy.deepcopy(val) setattr(self, f"_{attr}", val) except AttributeError: # some attribute of NDDataset are missing in NDArray pass try: self.history = f'Copied from object:{data.name}' except AttributeError: pass elif isinstance(data, NDArray): # init data with data from another NDArray or NDArray's subclass # No need to check the validity of the data # because the data must have been already # successfully initialized for the passed NDArray.data # debug_("init data with data from another NDArray object") for attr in self.__dir__(): try: val = getattr(data, f"_{attr}") if self._copy: val = cpy.deepcopy(val) setattr(self, f"_{attr}", val) except AttributeError: # some attribute of NDDataset are missing in NDArray pass try: self.history = f'Copied from object:{data.name}' except AttributeError: pass elif isinstance(data, Quantity): # debug_("init data with data from a Quantity object") self._data = np.array(data.magnitude, subok=True, copy=self._copy) self._units = data.units elif hasattr(data, 'mask'): # an object with data and mask attributes # debug_("mask detected - initialize a mask from the passed data") self._data = np.array(data.data, subok=True, copy=self._copy) if isinstance(data.mask, np.ndarray) and data.mask.shape == data.data.shape: self.mask = np.array(data.mask, dtype=np.bool_, copy=False) elif (not hasattr(data, 'shape') or not hasattr(data, '__getitem__') or not hasattr(data, '__array_struct__')): # debug_("Attempt to initialize data with a numpy-like array object") # Data doesn't look like a numpy array, try converting it to # one. Non-numerical input are converted to an array of objects. self._data = np.array(data, subok=True, copy=False) else: # debug_("numpy array detected - initialize data with a numpy array") data = np.array(data, subok=True, copy=self._copy) if data.dtype == np.object_: # likely None value data = data.astype(float) self._data = data if self.linear: # we try to replace data by only an offset and an increment self._linearize() # .................................................................................................................. def _sort(self, by='value', pos=None, descend=False, inplace=False): # sort an ndarray using data or label values args = self._argsort(by, pos, descend) if not inplace: new = self[args] else: new = self[args, INPLACE] return new # .................................................................................................................. @property def _squeeze_ndim(self): # The number of dimensions of the squeezed`data` array (Readonly property). if self.data is None and self.is_labeled: return 1 if self.data is None: return 0 else: return len([x for x in self.data.shape if x > 1]) # .................................................................................................................. def _str_shape(self): if self.is_empty: return ' size: 0\n' out = '' shape_ = (x for x in itertools.chain.from_iterable(list(zip(self.dims, self.shape)))) shape = (', '.join(['{}:{}'] * self.ndim)).format(*shape_) size = self.size out += f' size: {size}\n' if self.ndim < 2 else f' shape: ({shape})\n' return out # .................................................................................................................. def _str_value(self, sep='\n', ufmt=' {:~K}', header=' data: ... \n'): # prefix = [''] if self.is_empty and 'data: ...' not in header: return header + '{}'.format(textwrap.indent('empty', ' ' * 9)) elif self.is_empty: return '{}'.format(textwrap.indent('empty', ' ' * 9)) print_unit = True units = '' def mkbody(d, pref, units): # work around printing masked values with formatting ds = d.copy() if self.is_masked: dtype = self.data.dtype mask_string = f'--{dtype}' ds = insert_masked_print(ds, mask_string=mask_string) body = np.array2string(ds, separator=' ', prefix=pref) body = body.replace('\n', sep) text = ''.join([pref, body, units]) text += sep return text text = '' if not self.is_empty: if self.data is not None: data = self.umasked_data else: # no data but labels data = self.get_labels() print_unit = False if isinstance(data, Quantity): data = data.magnitude if print_unit: units = ufmt.format(self.units) if self.has_units else '' text += mkbody(data, '', units) out = '' # f' title: {self.title}\n' if self.title else '' text = text.strip() if '\n' not in text: # single line! out += header.replace('...', f'\0{text}\0') else: out += header out += '\0{}\0'.format(textwrap.indent(text, ' ' * 9)) out = out.rstrip() # remove the trailings '\n' return out # .................................................................................................................. @default('_title') def _title_default(self): return None @default('_roi') def _roi_default(self): return None # .................................................................................................................. @staticmethod def _uarray(data, units=None): # return the array or scalar with units # if data.size==1: # uar = data.squeeze()[()] # else: uar = data if units: return Quantity(uar, units) else: return uar # .................................................................................................................. @staticmethod def _umasked(data, mask): # This ensures that a masked array is returned. if not np.any(mask): mask = np.zeros(data.shape).astype(bool) data = np.ma.masked_where(mask, data) # np.ma.masked_array(data, mask) return data # ------------------------------------------------------------------------------------------------------------------ # Public Methods and Properties # ------------------------------------------------------------------------------------------------------------------ def asfortranarray(self): """ Make data and mask (ndim >= 1) laid out in Fortran order in memory. """ # data and mask will be converted to F_CONTIGUOUS mode if not self._data.flags['F_CONTIGUOUS']: self._data = np.asfortranarray(self._data) if self.is_masked: self._mask = np.asfortranarray(self._mask) def astype(self, dtype=None, **kwargs): """ Cast the data to a specified type. Parameters ---------- dtype : str or dtype typecode or data-type to which the array is cast. """ if not self.linear: self._data = self._data.astype(dtype, **kwargs) else: self._increment = np.array(self._increment).astype(dtype, **kwargs)[()] self._offset = np.array(self._offset).astype(dtype, **kwargs)[()] return self # ................................................................................................................. @property def author(self): """ str - creator of the array """ return self._author # .................................................................................................................. @author.setter def author(self, value): self._author = value # .................................................................................................................. def copy(self, deep=True, memo=None, keepname=False): """ Make a disconnected copy of the current object. Parameters ---------- deep : bool, optional If True a deepcopy is performed which is the default behavior. memo : Not used This parameter ensure compatibility with deepcopy() from the copy package. keepname : bool If True keep the same name for the copied object. Returns ------- object An exact copy of the current object. Examples -------- >>> import spectrochempy as scp >>> nd1 = scp.NDArray([1. + 2.j, 2. + 3.j]) >>> nd1 NDArray: [complex128] unitless (size: 2) >>> nd2 = nd1 >>> nd2 is nd1 True >>> nd3 = nd1.copy() >>> nd3 is not nd1 True """ if deep: do_copy = cpy.deepcopy else: do_copy = cpy.copy new = make_new_object(self) for attr in self.__dir__(): # do not use dir(self) as the order in __dir__ list is important try: _attr = do_copy(getattr(self, f"_{attr}")) setattr(new, f"_{attr}", _attr) except ValueError: # ensure that if deepcopy do not work, a shadow copy can be done _attr = do_copy(getattr(self, f"_{attr}")) setattr(new, f"_{attr}", _attr) # name must be changed if not keepname: new.name = "" # default return new # .................................................................................................................. @property def created(self): """ `Datetime` - creation date object """ return self._date # .................................................................................................................. @created.setter def created(self, date): self.date = date # .................................................................................................................. @property def data(self): """ |ndarray| - The `data` array. If there is no data but labels, then the labels are returned instead of data. """ if self._data is None and not self.linear: return None elif self.linear: data = np.arange(self.size) * self._increment + self._offset if hasattr(data, 'units'): data = data.m else: data = self._data return data # .................................................................................................................. @data.setter def data(self, data): # property.setter for data # note that a subsequent validation is done in _data_validate # NOTE: as property setter doesn't work with super(), # see https://stackoverflow.com/questions/10810369/python-super-and-setting-parent-class-property # we use an intermediate function that can be called from a subclass self._set_data(data) # .................................................................................................................. magnitude = data m = data # .................................................................................................................. @property def date(self): """ `Datetime` - creation date object - equivalent to the attribute `created` """ return self._date # .................................................................................................................. @date.setter def date(self, date): if isinstance(date, datetime): self._date = date elif isinstance(date, str): try: self._date = datetime.strptime(date, "%Y/%m/%d") except ValueError: self._date = datetime.strptime(date, "%d/%m/%Y") # ................................................................................................................. @property def description(self): """ str - Provides a description of the underlying data """ return self._description desc = description desc.__doc__ = """Alias to the description attribute""" # .................................................................................................................. @description.setter def description(self, value): self._description = value # .................................................................................................................. @property def dimensionless(self): """ bool - True if the `data` array is dimensionless (Readonly property). Notes ----- `Dimensionless` is different of `unitless` which means no unit. See Also -------- unitless, has_units """ if self.unitless: return False return self._units.dimensionless # .................................................................................................................. @property def dims(self): """ list - Names of the dimensions The name of the dimensions are 'x', 'y', 'z'.... depending on the number of dimension. """ ndim = self.ndim if ndim > 0: # if len(self._dims)< ndim: # self._dims = self._dims_default() dims = self._dims[:ndim] return dims else: return [] # .................................................................................................................. @dims.setter def dims(self, values): if isinstance(values, str) and len(values) == 1: values = [values] if not is_sequence(values) or len(values) != self.ndim: raise ValueError(f'a sequence of chars with a length of {self.ndim} is expected, but `{values}` ' f'has been provided') for value in values: if value not in DEFAULT_DIM_NAME: raise ValueError(f"{value} value is not admitted. Dimension's name must be among " f"{DEFAULT_DIM_NAME[::-1]}.") self._dims = tuple(values) # .................................................................................................................. @property def dtype(self): """ numpy dtype - data type """ if self.is_empty: self._dtype = None else: self._dtype = self.data.dtype return self._dtype # .................................................................................................................. def get_axis(self, *args, **kwargs): """ Helper function to determine an axis index whatever the syntax used (axis index or dimension names) Parameters ---------- dim, axis, dims : str, int, or list of str or index. The axis indexes or dimensions names - they can be specified as argument or using keyword 'axis', 'dim' or 'dims'. negative_axis : bool, optional, default=False. If True a negative index is returned for the axis value (-1 for the last dimension, etc...). allows_none : bool, optional, default=False If True, if input is none then None is returned. only_first : bool, optional, default: True By default return only information on the first axis if dim is a list Else, return an list for axis and dims information Returns ------- axis : int The axis indexes dim : str The axis name """ # handle the various syntax to pass the axis dims = self._get_dims_from_args(*args, **kwargs) axis = self._get_dims_index(dims) allows_none = kwargs.get('allows_none', False) if axis is None and allows_none: return None, None if isinstance(axis, tuple): axis = list(axis) if not isinstance(axis, list): axis = [axis] dims = axis[:] for i, a in enumerate(axis[:]): # axis = axis[0] if axis else self.ndim - 1 # None if a is None: a = self.ndim - 1 if kwargs.get('negative_axis', False): if a >= 0: a = a - self.ndim axis[i] = a dims[i] = self.dims[a] only_first = kwargs.pop('only_first', True) if len(dims) == 1 and only_first: dims = dims[0] axis = axis[0] return axis, dims # .................................................................................................................. def get_labels(self, level=0): """Get the labels at a given level Used to replace `data` when only labels are provided, and/or for labeling axis in plots Parameters ---------- level : int, optional, default:0 Returns ------- |ndarray| The labels at the desired level or None """ if not self.is_labeled: return None if level > self.labels.ndim - 1: warnings.warn("There is no such level in the existing labels", SpectroChemPyWarning) return None if self.labels.ndim > 1: return self.labels[level] else: return self._labels # .................................................................................................................. @property def has_data(self): """ bool - True if the `data` array is not empty and size > 0. (Readonly property). """ if ((self.data is None) or (self.data.size == 0)): return False return True # .................................................................................................................. @property def has_defined_name(self): """ bool - True is the name has been defined """ return not (self.name == self.id) # .................................................................................................................. @property def has_units(self): """ bool - True if the `data` array have units (Readonly property). See Also -------- unitless, dimensionless """ if self._units: if not str(self.units).strip(): return False return True return False # .................................................................................................................. @property def history(self): """ List of strings - Describes the history of actions made on this array """ return self._history # .................................................................................................................. @history.setter def history(self, value): self._history.append(value) # .................................................................................................................. @property def id(self): """ str - Object identifier (Readonly property). """ return self._id # .................................................................................................................. @property def imag(self): return None # .................................................................................................................. def implements(self, name=None): """ Utility to check if the current object implement `NDArray`. Rather than isinstance(obj, NDArrray) use object.implements('NDArray'). This is useful to check type without importing the module """ if name is None: return 'NDArray' else: return name == 'NDArray' # .................................................................................................................. @property def increment(self): return self._increment @increment.setter def increment(self, val): if isinstance(val, Quantity): if self.has_units: val.ito(self.units) val = val.m else: self.units = val.units val = val.m self._increment = val @property def increment_value(self): increment = self.increment if self.units: return Quantity(increment, self._units) else: return increment # .................................................................................................................. @property def is_float(self): """ bool - True if the `data` are real values (Readonly property). """ if self.data is None: return False return self.data.dtype in TYPE_FLOAT # .................................................................................................................. @property def is_integer(self): """ bool - True if the `data` are integer values (Readonly property). """ if self.data is None: return False return self.data.dtype in TYPE_INTEGER # .................................................................................................................. @property def is_1d(self): """ bool - True if the `data` array has only one dimension """ return self.ndim == 1 # .................................................................................................................. @property def is_empty(self): """ bool - True if the `data` array is empty or size=0, and if no label are present (Readonly property). """ if not self.linear and ((self._data is None) or (self._data.size == 0)) and not self.is_labeled: return True return False # .................................................................................................................. @property def is_labeled(self): """ bool - True if the `data` array have labels (Readonly property). """ # label cannot exists (for now for nD dataset - only 1D dataset, such # as Coord can be labelled. if self._data is not None and self.ndim > 1: return False if self._labels is not None and np.any(self.labels != ''): return True else: return False # .................................................................................................................. @property def linear(self): """ bool - flag to specify if the data can be constructed using a linear variation """ return self._linear @linear.setter def linear(self, val): self._linear = val # it val is true this provoque the linearization ( # see observe) # if val and self._data is not None: # # linearisation of the data, if possible # self._linearize() # .................................................................................................................. @property def is_masked(self): """ bool - True if the `data` array has masked values (Readonly property). """ if isinstance(self._mask, np.ndarray): return np.any(self._mask) elif self._mask == NOMASK or self._mask is None: return False elif isinstance(self._mask, (np.bool_, bool)): return self._mask return False # .................................................................................................................. def is_units_compatible(self, other): """ Check the compatibility of units with another object Parameters ---------- other : |ndarray| The ndarray object for which we want to compare units compatibility Returns ------- result True if units are compatible Examples -------- >>> from spectrochempy import * >>> nd1 = NDDataset([1.+2.j,2.+ 3.j], units='meters') >>> nd1 NDDataset: [complex128] m (size: 2) >>> nd2 = NDDataset([1.+2.j,2.+ 3.j], units='seconds') >>> nd1.is_units_compatible(nd2) False >>> nd1.ito('minutes', force=True) >>> nd1.is_units_compatible(nd2) True >>> nd2[0].values * 60. == nd1[0].values True """ try: other.to(self.units, inplace=False) except DimensionalityError: return False return True # .................................................................................................................. @property def itemsize(self): """ numpy itemsize - data type size """ if self.data is None: return None return self.data.dtype.itemsize # .................................................................................................................. @property def iterdims(self): return list(range(self.ndim)) # .................................................................................................................. def ito(self, other, force=False): """ Inplace scaling of the current object data to different units. (same as `to` with inplace= True). Parameters ---------- other : |Unit|, |Quantity| or str Destination units. force : bool, optional, default=`False` If True the change of units is forced, even for incompatible units See Also -------- to : Rescaling of the current object data to different units to_base_units : Rescaling of the current object data to different units ito_base_units : Inplace rescaling of the current object data to different units to_reduced_units : Rescaling to reduced units. ito_reduced_units : Rescaling to reduced units. """ self.to(other, inplace=True, force=force) # .................................................................................................................. def ito_base_units(self): """ Inplace rescaling to base units. See Also -------- to : Rescaling of the current object data to different units ito : Inplace rescaling of the current object data to different units to_base_units : Rescaling of the current object data to different units to_reduced_units : Rescaling to redunced units. ito_reduced_units : Inplace rescaling to reduced units. """ self.to_base_units(inplace=True) # .................................................................................................................. def ito_reduced_units(self): """ Quantity scaled in place to reduced units, inplace. Scaling to reduced units means, one unit per dimension. This will not reduce compound units (e.g., 'J/kg' will not be reduced to m**2/s**2) See Also -------- to : Rescaling of the current object data to different units ito : Inplace rescaling of the current object data to different units to_base_units : Rescaling of the current object data to different units ito_base_units : Inplace rescaling of the current object data to different units to_reduced_units : Rescaling to reduced units. """ self.to_reduced_units(inplace=True) # .................................................................................................................. @property def labels(self): """ |ndarray| (str) - An array of labels for `data`. An array of objects of any type (but most generally string), with the last dimension size equal to that of the dimension of data. Note that's labelling is possible only for 1D data. One classical application is the labelling of coordinates to display informative strings instead of numerical values. """ return self._labels # .................................................................................................................. @labels.setter def labels(self, labels): if labels is None: return if self.ndim > 1: warnings.warn('We cannot set the labels for multidimentional data - Thus, these labels are ignored', SpectroChemPyWarning) else: # make sure labels array is of type np.ndarray or Quantity arrays if not isinstance(labels, np.ndarray): labels = np.array(labels, subok=True, copy=True).astype(object, copy=False) if not np.any(labels): # no labels return else: if (self.data is not None) and (labels.shape[0] != self.shape[0]): # allow the fact that the labels may have been passed in a transposed array if labels.ndim > 1 and (labels.shape[-1] == self.shape[0]): labels = labels.T else: raise ValueError(f"labels {labels.shape} and data {self.shape} shape mismatch!") if np.any(self._labels): info_(f"{type(self).__name__} is already a labeled array.\nThe explicitly provided labels will " f"be appended to the current labels") labels = labels.squeeze() self._labels = self._labels.squeeze() if self._labels.ndim > 1: self._labels = self._labels.T self._labels = np.vstack((self._labels, labels)).T else: if self._copy: self._labels = labels.copy() else: self._labels = labels # .................................................................................................................. @property def limits(self): """list - range of the data""" if self.data is None: return None return [self.data.min(), self.data.max()] # .................................................................................................................. @property def mask(self): """ |ndarray| (bool) - Mask for the data """ if not self.is_masked: return NOMASK return self._mask # .................................................................................................................. @mask.setter def mask(self, mask): if mask is NOMASK or mask is MASKED: pass elif isinstance(mask, (np.bool_, bool)): if not mask: mask = NOMASK else: mask = MASKED else: # from now, make sure mask is of type np.ndarray if it provided if not isinstance(mask, np.ndarray): mask = np.array(mask, dtype=np.bool_) if not np.any(mask): # all element of the mask are false mask = NOMASK elif mask.shape != self.shape: raise ValueError(f"mask {mask.shape} and data {self.shape} shape mismatch!") # finally set the mask of the object if isinstance(mask, MaskedConstant): self._mask = NOMASK if self.data is None else np.ones(self.shape).astype(bool) else: if np.any(self._mask): # this should happen when a new mask is added to an existing one # mask to be combined to an existing one info_(f"{type(self).__name__} is already a masked array.\n The new mask will be combined with the " f"current array's mask.") self._mask |= mask # combine (is a copy!) else: if self._copy: self._mask = mask.copy() else: self._mask = mask # .................................................................................................................. @property def masked_data(self): """ |ma.ndarray| - The actual masked `data` array (Readonly property). """ if self.is_masked and not self.is_empty: return self._umasked(self.data, self.mask) else: return self.data # .................................................................................................................. @property def meta(self): """ |Meta| - Additional metadata. """ return self._meta # .................................................................................................................. @meta.setter def meta(self, meta): if meta is not None: self._meta.update(meta) # .................................................................................................................. @property def modified(self): """ `Datetime` object - Date of modification (readonly property). """ return self._modified # .................................................................................................................. @property def name(self): """ str - An user friendly name. When the name is not provided, the `id` of the object is retruned instead """ if self._name: return self._name else: return self._id # .................................................................................................................. @name.setter def name(self, name): if name: if self._name: # debug_("Overwriting current name") pass self._name = name # .................................................................................................................. @property def ndim(self): """ int - The number of dimensions of the `data` array (Readonly property). """ if self.linear: return 1 if self.data is None and self.is_labeled: return 1 if not self.size: return 0 else: return self.data.ndim # .................................................................................................................. @property def offset(self): return self._offset @offset.setter def offset(self, val): if isinstance(val, Quantity): if self.has_units: val.ito(self.units) val = val.m else: self.units = val.units val = val.m self._offset = val @property def offset_value(self): offset = self.offset if self.units: return Quantity(offset, self._units) else: return offset # .................................................................................................................. @property def origin(self): """ str - origin of the data """ return self._origin # .................................................................................................................. @origin.setter def origin(self, origin): self._origin = origin @property def real(self): return self # .................................................................................................................. def remove_masks(self): """ Remove all masks previously set on this array """ self._mask = NOMASK # .................................................................................................................. @property def roi(self): """list - region of interest (ROI) limits""" if self._roi is None: self._roi = self.limits return self._roi @roi.setter def roi(self, val): self._roi = val @property def roi_values(self): if self.units is None: return list(np.array(self.roi)) else: return list(self._uarray(self.roi, self.units)) # .................................................................................................................. @property def shape(self): """ tuple on int - A tuple with the size of each dimensions (Readonly property). The number of `data` element on each dimensions (possibly complex). For only labelled array, there is no data, so it is the 1D and the size is the size of the array of labels. """ if self.linear: return (self._size,) if self.data is None and self.is_labeled: return (self.labels.shape[0],) elif self.data is None: return () else: return self.data.shape # .................................................................................................................. @property def size(self): """ int - Size of the underlying `data` array (Readonly property). The total number of data element (possibly complex or hypercomplex in the array). """ if self._data is None and self.is_labeled: return self.labels.shape[-1] elif self._data is None: if self.linear: # the provided size is returned i or its default return self._size return None else: return self._data.size # .................................................................................................................. @property def spacing(self): # return a scalar for the spacing of the coordinates (if they are uniformly spaced, # else return an array of the differents spacings if self.linear: return self.increment * self.units return spacing(self.data) * self.units # .................................................................................................................. def squeeze(self, *dims, inplace=False, return_axis=False, **kwargs): """ Remove single-dimensional entries from the shape of an array. Parameters ---------- dims : None or int or tuple of ints, optional Selects a subset of the single-dimensional entries in the shape. If a dimension (dim) is selected with shape entry greater than one, an error is raised. Returns ------- squeezed : same object type The input array, but with all or a subset of the dimensions of length 1 removed. Raises ------ ValueError If `dims` is not `None`, and the dimension being squeezed is not of length 1 """ if inplace: new = self else: new = self.copy() dims = self._get_dims_from_args(*dims, **kwargs) if not dims: s = np.array(new.shape) dims = np.argwhere(s == 1).squeeze().tolist() axis = self._get_dims_index(dims) if axis is None: # nothing to squeeze return new, axis # recompute new dims for i in axis[::-1]: del new._dims[i] # performs all required squeezing new._data = new._data.squeeze(axis=axis) if self.is_masked: new._mask = new._mask.squeeze(axis=axis) if return_axis: # in case we need to know which axis has been squeezed return new, axis return new # .................................................................................................................. def swapdims(self, dim1, dim2, inplace=False): """ Interchange two dims of a NDArray. Parameters ---------- dim1 : int or str First dimension index dim2 : int Second dimension index inplace : bool, optional, default=`False` Flag to say that the method return a new object (default) or not (inplace=True) Returns ------- swaped_array See Also -------- transpose """ if not inplace: new = self.copy() else: new = self if self.ndim < 2: # cannot swap axe for 1D data return new i0, i1 = axis = self._get_dims_index([dim1, dim2]) new._data = np.swapaxes(new._data, *axis) new._dims[i1], new._dims[i0] = self._dims[i0], self._dims[i1] # all other arrays, except labels have also to be swapped to reflect # changes of data ordering. # labels are presents only for 1D array, so we do not have to swap them if self.is_masked: new._mask = np.swapaxes(new._mask, *axis) new._meta = new._meta.swap(*axis, inplace=False) return new swapaxes = swapdims swapaxes.__doc__ = 'Alias of `swapdims`' # .................................................................................................................. @property def T(self): """ |NDArray| - Transposed array. The same object is returned if `ndim` is less than 2. """ return self.transpose() # .................................................................................................................. @property def title(self): """ str - An user friendly title. When the title is provided, it can be used for labeling the object, e.g., axe title in a matplotlib plot. """ if self._title: return self._title else: return "<untitled>" @title.setter def title(self, title): if title: self._title = title # .................................................................................................................. def to(self, other, inplace=False, force=False): """ Return the object with data rescaled to different units. Parameters ---------- other : |Quantity| or str. Destination units. inplace : bool, optional, default=`False` Flag to say that the method return a new object (default) or not (inplace=True) force : bool, optional, default=False If True the change of units is forced, even for incompatible units Returns ------- rescaled See Also -------- ito : Inplace rescaling of the current object data to different units to_base_units : Rescaling of the current object data to different units ito_base_units : Inplace rescaling of the current object data to different units to_reduced_units : Rescaling to reduced_units. ito_reduced_units : Inplace rescaling to reduced units. Examples -------- >>> np.random.seed(12345) >>> ndd = NDArray( data = np.random.random((3, 3)), ... mask = [[True, False, False], ... [False, True, False], ... [False, False, True]], ... units = 'meters') >>> print(ndd) NDArray: [float64] m (shape: (y:3, x:3)) We want to change the units to seconds for instance but there is no relation with meters, so an error is generated during the change >>> ndd.to('second') Traceback (most recent call last): ... pint.errors.DimensionalityError: Cannot convert from 'meter' ([length]) to 'second' ([time]) However, we can force the change >>> ndd.to('second', force=True) NDArray: [float64] s (shape: (y:3, x:3)) By default the conversion is not done inplace, so the original is not modified : >>> print(ndd) NDArray: [float64] m (shape: (y:3, x:3)) """ new = self.copy() if other is None: units = None if self.units is None: return new elif force: new._units = None if inplace: self._units = None return new elif isinstance(other, str): units = ur.Unit(other) elif hasattr(other, 'units'): units = other.units else: units = ur.Unit(other) if self.has_units: oldunits = self._units def _transform(new): # not a linear transform udata = (new.data * new.units).to(units) new._data = udata.m new._units = udata.units if new._roi is not None: roi = (np.array(new._roi) * self.units).to(units) new._roi = list(roi) if new._linear: # try to make it linear as well new._linearize() if not new._linear and new.implements('LinearCoord'): # can't be linearized -> Coord if inplace: raise Exception( 'A LinearCoord object cannot be transformed to a non linear coordinate `inplace`. ' 'Use to() instead of ito() and leave the `inplace` attribute to False') else: from spectrochempy import Coord new = Coord(new) return new try: if new.meta.larmor: # _origin in ['topspin', 'nmr'] set_nmr_context(new.meta.larmor) with ur.context('nmr'): new = _transform(new) # particular case of dimensionless units: absorbance and transmittance if oldunits in [ur.transmittance, ur.absolute_transmittance]: if units == ur.absorbance: udata = (new.data * new.units).to(units) new._data = -np.log10(udata.m) new._units = units if new.title.lower() == 'transmittance': new._title = 'absorbance' elif oldunits == ur.absorbance: if units in [ur.transmittance, ur.absolute_transmittance]: scale = Quantity(1., self._units).to(units).magnitude new._data = 10. ** -new.data * scale new._units = units if new.title.lower() == 'absorbance': new._title = 'transmittance' else: # change the title for spectrocopic units change new = _transform(new) if (oldunits.dimensionality in ['1/[length]', '[length]', '[length] ** 2 * [mass] / [time] ** 2'] and new._units.dimensionality == '1/[time]'): new._title = 'frequency' elif (oldunits.dimensionality in ['1/[time]', '[length] ** 2 * [mass] / [time] ** 2'] and new._units.dimensionality == '1/[length]'): new._title = 'wavenumber' elif (oldunits.dimensionality in ['1/[time]', '1/[length]', '[length] ** 2 * [mass] / [time] ** 2'] and new._units.dimensionality == '[length]'): new._title = 'wavelength' elif (oldunits.dimensionality in ['1/[time]', '1/[length]', '[length]'] and new._units.dimensionality == '[length] ** 2 * ' '[mass] / [time] ' '** 2'): new._title = 'energy' except DimensionalityError as exc: if force: new._units = units info_('units forced to change') else: raise exc else: if force: new._units = units else: warnings.warn("There is no units for this NDArray!", SpectroChemPyWarning) if inplace: self._data = new._data self._units = new._units self._offset = new._offset self._increment = new._increment self._title = new._title self._roi = new._roi self._linear = new._linear else: return new def to_base_units(self, inplace=False): """ Return an array rescaled to base units. Parameters ---------- inplace : bool If True the rescaling is done in place Returns ------- rescaled A rescaled array """ q = Quantity(1., self.units) q.ito_base_units() if not inplace: new = self.copy() else: new = self new.ito(q.units) if not inplace: return new def to_reduced_units(self, inplace=False): """ Return an array scaled in place to reduced units Reduced units means one unit per dimension. This will not reduce compound units (e.g., 'J/kg' will not be reduced to m**2/s**2), Parameters ---------- inplace : bool If True the rescaling is done in place Returns ------- rescaled A rescaled array """ q = Quantity(1., self.units) q.ito_reduced_units() if not inplace: new = self.copy() else: new = self new.ito(q.units) if not inplace: return new # .................................................................................................................. def transpose(self, *dims, inplace=False): """ Permute the dimensions of an array. Parameters ---------- *dims : list int or str Sequence of dimension indexes or names, optional. By default, reverse the dimensions, otherwise permute the dimensions according to the values given. If specified the list of dimension index or names must match the number of dimensions. inplace : bool, optional, default=`False` Flag to say that the method return a new object (default) or not (inplace=True) Returns ------- transpose A transposed array See Also -------- swapdims : Interchange two dimensions of an array. """ if not inplace: new = self.copy() else: new = self if self.ndim < 2: # cannot transpose 1D data return new if not dims or list(set(dims)) == [None]: dims = self.dims[::-1] axis = self._get_dims_index(dims) new._data = np.transpose(new._data, axis) if new.is_masked: new._mask = np.transpose(new._mask, axis) new._meta = new._meta.permute(*axis, inplace=False) new._dims = list(np.take(self._dims, axis)) return new # .................................................................................................................. @property def umasked_data(self): """ |Quantity| - The actual array with mask and unit (Readonly property). """ if self.data is None: return None return self._uarray(self.masked_data, self.units) # .................................................................................................................. @property def unitless(self): """ `bool` - True if the `data` does not have `units` (Readonly property). """ return not self.has_units # .................................................................................................................. @property def units(self): """ |Unit| - The units of the data. """ return self._units # .................................................................................................................. @units.setter def units(self, units): if units is None: return if isinstance(units, str): units = ur.Unit(units) elif isinstance(units, Quantity): raise TypeError("Units or string representation of unit is expected, not Quantity") if self.has_units and units != self._units: # first try to cast try: self.to(units) except Exception: raise TypeError(f"Provided units {units} does not match data units: {self._units}.\nTo force a change," f" use the to() method, with force flag set to True") self._units = units # .................................................................................................................. @property def values(self): """ |Quantity| - The actual values (data, units) contained in this object (Readonly property). """ if self.data is not None: if self.is_masked: data = self._umasked(self.masked_data, self.mask) if self.units: return Quantity(data, self.units) else: data = self._uarray(self.data, self.units) if self.size > 1: return data else: return data.squeeze()[()] elif self.is_labeled: return self._labels[()] @property def value(self): """ Alias of `values`. """ return self.values <file_sep>/docs/gettingstarted/examples/processing/plot_baseline_correction.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ NDDataset baseline correction ============================== In this example, we perform a baseline correction of a 2D NDDataset interactively, using the ``multivariate`` method and a ``pchip`` interpolation. """ ############################################################################### # As usual we start by importing the useful library, and at least the # spectrochempy library. import spectrochempy as scp ############################################################################### # Load data: nd = scp.NDDataset.read_omnic('irdata/nh4y-activation.spg') ############################################################################### # Do some slicing to keep only the interesting region: ndp = (nd - nd[-1])[:, 1291.0:5999.0] # Important: notice that we use floating point number # integer would mean points, not wavenumbers! ############################################################################### # Define the BaselineCorrection object: ibc = scp.BaselineCorrection(ndp) ############################################################################### # Launch the interactive view, using the `BaselineCorrection.run` method: ranges = [[1556.30, 1568.26], [1795.00, 1956.75], [3766.03, 3915.81], [4574.26, 4616.04], [4980.10, 4998.01], [5437.52, 5994.70]] # predefined ranges span = ibc.run(*ranges, method='multivariate', interpolation='pchip', npc=5, zoompreview=3) ############################################################################### # Print the corrected dataset: print(ibc.corrected) _ = ibc.corrected.plot() # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) "" <file_sep>/tests/test_readers_writers/test_exporter.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from pathlib import Path import pytest import spectrochempy as scp from spectrochempy import NDDataset, preferences as prefs from spectrochempy.utils import pathclean, testing irdatadir = pathclean(prefs.datadir) / "irdata" cwd = Path.cwd() # ...................................................................................................................... def test_write(): nd = scp.read_omnic('irdata/nh4y-activation.spg') # API write methods needs an instance of a NDDataset as the first argument with pytest.raises(TypeError): scp.write() # the simplest way to save a dataset, is to use the function write with a filename as argument filename = nd.write('essai.scp') assert filename == cwd / 'essai.scp' nd2 = NDDataset.load(filename) testing.assert_dataset_equal(nd2, nd) filename.unlink() # if the filename is omitted, the a dialog is opened to select a name (and a protocol) filename = nd.write() assert filename is not None assert filename.stem == nd.name assert filename.suffix == '.scp' filename.unlink() # # a write protocole can be specified # filename = nd.write(protocole='json') # assert filename is not None # assert filename.stem == nd.name # assert filename.suffix == '.json' # filename.unlink() irdatadir = pathclean(prefs.datadir) / "irdata" for f in ['essai.scp', 'nh4y-activation.scp']: if (irdatadir / f).is_file(): (irdatadir / f).unlink() # EOF <file_sep>/tests/test_dataset/test_issues_dataset.py # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import os import numpy as np from spectrochempy import read_omnic from spectrochempy.units import ur typequaternion = np.dtype(np.quaternion) # ====================================================================================================================== def test_fix_issue_20(): # Description of bug #20 # ----------------------- # X = read_omnic(os.path.join('irdata', 'CO@Mo_Al2O3.SPG')) # # # slicing a NDDataset with an integer is OK for the coord: # X[:,100].x # Out[4]: Coord: [float64] cm^-1 # # # but not with an integer array : # X[:,[100, 120]].x # Out[5]: Coord: [int32] unitless # # # on the other hand, the explicit slicing of the coord is OK ! # X.x[[100,120]] # Out[6]: Coord: [float64] cm^-1 X = read_omnic(os.path.join('irdata', 'CO@Mo_Al2O3.SPG')) assert X.__str__() == 'NDDataset: [float64] a.u. (shape: (y:19, x:3112))' # slicing a NDDataset with an integer is OK for the coord: assert X[:, 100].x.__str__() == 'LinearCoord: [float64] cm^-1 (size: 1)' # The explicit slicing of the coord is OK ! assert X.x[[100, 120]].__str__() == 'LinearCoord: [float64] cm^-1 (size: 2)' # slicing the NDDataset with an integer array is also OK (fixed #20) assert X[:, [100, 120]].x.__str__() == X.x[[100, 120]].__str__() def test_fix_issue_58(): X = read_omnic(os.path.join('irdata', 'CO@Mo_Al2O3.SPG')) X.y = X.y - X.y[0] # subtract the acquisition timestamp of the first spectrum X.y = X.y.to('minute') # convert to minutes assert X.y.units == ur.minute X.y += 2 # add 2 minutes assert X.y.units == ur.minute assert X.y[0].data == [2] # check that the addition is correctly done 2 min def test_fix_issue_186(): import spectrochempy as scp da = scp.read_omnic(os.path.join('irdata', 'nh4y-activation.spg')) da -= da.min() da.plot() scp.show() dt = da.to('transmittance') dt.plot() scp.show() dt.ito('absolute_transmittance') dt.plot() scp.show() da = dt.to('absorbance') da.plot() scp.show() dt.ito('transmittance') dt.plot() scp.show() da = dt.to('absorbance') da.plot() scp.show() <file_sep>/spectrochempy/application.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module define the `application` on which the API rely. It also define the default application preferences and IPython magic functions. """ __all__ = [] import re import sys import logging import subprocess import datetime import warnings import pprint import json from os import environ from pathlib import Path import threading from pkg_resources import parse_version, get_distribution, DistributionNotFound import requests from setuptools_scm import get_version from traitlets.config.configurable import Config from traitlets.config.application import Application from traitlets import Bool, Unicode, List, Integer, Union, HasTraits, Instance, default, observe from traitlets.config.manager import BaseJSONConfigManager import matplotlib as mpl from matplotlib import pyplot as plt from IPython import get_ipython from IPython.core.interactiveshell import InteractiveShell from IPython.core.magic import (Magics, magics_class, line_cell_magic) from IPython.core.magics.code import extract_symbols from IPython.core.error import UsageError from IPython.utils.text import get_text_list from IPython.display import publish_display_data, clear_output from jinja2 import Template from spectrochempy.utils import MetaConfigurable, pathclean, get_pkg_path from .matplotlib_preferences import MatplotlibPreferences # set the default style plt.style.use(['classic']) # ---------------------------------------------------------------------------------------------------------------------- # Log levels # ---------------------------------------------------------------------------------------------------------------------- DEBUG = logging.DEBUG INFO = logging.INFO WARNING = logging.WARNING ERROR = logging.ERROR CRITICAL = logging.CRITICAL # ---------------------------------------------------------------------------------------------------------------------- # logo / copyright display # ---------------------------------------------------------------------------------------------------------------------- def display_info_string(**kwargs): _template = """ {{widgetcss}} <table><tr><td> {% if logo %} <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAAlw SFlzAAAJOgAACToB8GSSSgAAAetpVFh0WE1MOmNvbS5hZG9iZS54b<KEY>Onht<KEY> bWV0YS8iIH<KEY> <KEY> <KEY> <KEY> <KEY> <KEY>Dp4bXBtZXRhPgqNQaNYAAAGiUlE QVRIDY1We4xU1Rn/3XPuYx47u8<KEY> IhKq76sKPUdF9NW/LSqfSn6vjv8C45H/6FSgvZQAAAAASUVORK5CYII=' style='height:25px; border-radius:12px; display:inline-block; float:left; vertical-align:middle'></img> {% endif %} </td><td> {% if message %} &nbsp;&nbsp;<span style='font-size:12px'>{{ message }}</span> {% endif %} </td></tr></table> </div> """ clear_output() logo = kwargs.get('logo', True) message = kwargs.get('message', 'info ') template = Template(_template) html = template.render({'logo': logo, 'message': message.strip().replace('\n', '<br/>')}) publish_display_data(data={'text/html': html}) # ---------------------------------------------------------------------------------------------------------------------- # Version # ---------------------------------------------------------------------------------------------------------------------- try: __release__ = get_distribution('spectrochempy').version.split('+')[0] "Release version string of this package" except DistributionNotFound: # pragma: no cover # package is not installed __release__ = '--not set--' try: __version__ = get_version(root='..', relative_to=__file__) "Version string of this package" except LookupError: # pragma: no cover __version__ = __release__ # ............................................................................ def _get_copyright(): current_year = datetime.date.today().year copyright = '2014-{}'.format(current_year) copyright += ' - A.Travert & C.Fernandez @ LCS' return copyright __copyright__ = _get_copyright() "Copyright string of this package" # ............................................................................. def _get_release_date(): return subprocess.getoutput("git log -1 --tags --date='short' --format='%ad'") __release_date__ = _get_release_date() "Last release date of this package" def _check_for_updates(cls): # Get version conda_url = "https://anaconda.org/spectrocat/spectrochempy/files" try: response = requests.get(conda_url) except requests.exceptions.RequestException: return None regex = r"\/\d{1,2}\.\d{1,2}\.\d{1,2}\/download\/noarch" \ r"\/spectrochempy-(\d{1,2}\.\d{1,2}\.\d{1,2})\-(dev\d{1,2}|stable).tar.bz2" matches = re.finditer(regex, response.text, re.MULTILINE) vavailables = [] for matchNum, match in enumerate(matches): v = match[1] if match[2] == 'stable': vavailables.append(v) old = parse_version(__version__) new_version = None for key in vavailables: new = parse_version(key) if new > old: new_version = key fi = Path.home() / ".scpy_update" if new_version: fi.write_text(f"\n\n\tYou are running SpectrocChemPy-{__version__} but version {new_version} is available." f"\n\tPlease consider updating for bug fixes and new features! ") else: if fi.exists(): fi.unlink() CHECK_UPDATE = threading.Thread(target=_check_for_updates, args=(1,)) CHECK_UPDATE.start() # other info # ............................................................................ __url__ = "http://www.spectrochempy.fr" "URL for the documentation of this package" __author__ = "<NAME> & <NAME> @LCS" "First authors(s) of this package" __contributor__ = "" "contributor(s) to this package" __license__ = "CeCILL-B license" "Licence of this package" # .................................................................................................................. def _find_or_create_spectrochempy_dir(): directory = Path.home() / '.spectrochempy' if not directory.exists(): directory.mkdir(exist_ok=True) elif directory.is_file(): msg = 'Intended SpectroChemPy directory `{0}` is ' \ 'actually a file.' raise IOError(msg.format(directory)) return directory # ====================================================================================================================== # Magic ipython function # ====================================================================================================================== @magics_class class SpectroChemPyMagics(Magics): """ This class implements the addscript ipython magic function. """ @line_cell_magic def addscript(self, pars='', cell=None): """ This works both as **%addscript** and as **%%addscript** This magic command can either take a local filename, element in the namespace or history range (see %history), or the current cell content Usage: %addscript -p project n1-n2 n3-n4 ... n5 .. n6 ... or %%addscript -p project ...code lines ... Options: -p <string> Name of the project where the script will be stored. If not provided, a project with a standard name : `proj` is searched. -o <string> script name -s <symbols> Specify function or classes to load from python source. -a append to the current script instead of overwriting it. -n search symbol in the current namespace Examples -------- .. sourcecode:: ipython In[1]: %addscript myscript.py In[2]: %addscript 7-27 In[3]: %addscript -s MyClass,myfunction myscript.py In[4]: %addscript MyClass In[5]: %addscript mymodule.myfunction """ opts, args = self.parse_options(pars, 'p:o:s:n:a') # append = 'a' in opts # mode = 'a' if append else 'w' search_ns = 'n' in opts if not args and not cell and not search_ns: # pragma: no cover raise UsageError('Missing filename, input history range, ' 'or element in the user namespace.\n ' 'If no argument are given then the cell content ' 'should ' 'not be empty') name = 'script' if 'o' in opts: name = opts['o'] proj = 'proj' if 'p' in opts: proj = opts['p'] if proj not in self.shell.user_ns: # pragma: no cover raise ValueError('Cannot find any project with name `{}` in the ' 'namespace.'.format(proj)) # get the proj object projobj = self.shell.user_ns[proj] contents = "" if search_ns: contents += "\n" + self.shell.find_user_code(opts['n'], search_ns=search_ns) + "\n" args = " ".join(args) if args.strip(): contents += "\n" + self.shell.find_user_code(args, search_ns=search_ns) + "\n" if 's' in opts: # pragma: no cover try: blocks, not_found = extract_symbols(contents, opts['s']) except SyntaxError: # non python code logging.error("Unable to parse the input as valid Python code") return if len(not_found) == 1: warnings.warn('The symbol `%s` was not found' % not_found[0]) elif len(not_found) > 1: warnings.warn('The symbols %s were not found' % get_text_list(not_found, wrap_item_with='`')) contents = '\n'.join(blocks) if cell: contents += "\n" + cell # import delayed to avoid circular import error from spectrochempy.core.scripts.script import Script script = Script(name, content=contents) projobj[name] = script return "Script {} created.".format(name) # @line_magic # def runscript(self, pars=''): # """ # # # """ # opts, # args = self.parse_options(pars, '') # # if # not args: # raise UsageError('Missing script # name') # # # return args # ====================================================================================================================== # DataDir class # ====================================================================================================================== class DataDir(HasTraits): """ A class used to determine the path to the testdata directory. """ path = Instance(Path) @default('path') def _get_path_default(self, **kwargs): super().__init__(**kwargs) # create a directory testdata in .spectrochempy to avoid an error if the following do not work path = _find_or_create_spectrochempy_dir() / 'testdata' path.mkdir(exist_ok=True) # try to use the conda installed testdata (spectrochempy_data package) try: conda_env = environ['CONDA_PREFIX'] path = Path(conda_env) / 'share' / 'spectrochempy_data' / 'testdata' if not path.exists(): path = Path( conda_env) / 'share' / 'spectrochempy_data' # depending on the version of spectrochempy_data except KeyError: pass return path def listing(self): """ Create a str representing a listing of the testdata folder. Returns ------- listing : str Display of the datadir content """ strg = f'{self.path.name}\n' # os.path.basename(self.path) + "\n" def _listdir(s, initial, ns): ns += 1 for f in pathclean(initial).glob('*'): # glob.glob(os.path.join(initial, '*')): fb = f.name # os.path.basename(f) if fb.startswith('.'): continue if not fb.startswith('acqu') and not fb.startswith('pulse') and fb not in ['ser', 'fid']: s += " " * ns + "|__" + "%s\n" % fb if f.is_dir(): s = _listdir(s, f, ns) return s return _listdir(strg, self.path, -1) @classmethod def class_print_help(cls): # to work with --help-all """""" # TODO: make some useful help def __str__(self): return self.listing() def _repr_html_(self): # _repr_html is needed to output in notebooks return self.listing().replace('\n', '<br/>').replace(" ", "&nbsp;") # ====================================================================================================================== # General Preferences # ====================================================================================================================== class GeneralPreferences(MetaConfigurable): """ Preferences that apply to the |scpy| application in general They should be accessible from the main API """ name = Unicode('GeneralPreferences') description = Unicode('General options for the SpectroChemPy application') updated = Bool(False) # ------------------------------------------------------------------------------------------------------------------ # Gonfiguration entries # ------------------------------------------------------------------------------------------------------------------ databases = Union((Instance(Path), Unicode()), help='Directory where to look for database files such as csv').tag( config=True, type="folder") datadir = Union((Instance(Path), Unicode()), help='Directory where to look for data by default').tag(config=True, type="folder") show_info_on_loading = Bool(True, help='Display info on loading').tag(config=True) use_qt = Bool(False, help='Use QT for dialog instead of TK wich is the default. ' 'If True the PyQt libraries must be installed').tag(config=True) # .................................................................................................................. @default('databases') def _get_databases_default(self): # the spectra path in package data return Path(get_pkg_path('databases', 'scp_data')) # .................................................................................................................. @default('datadir') def _get_default_datadir(self): return self.parent.datadir.path # .................................................................................................................. @observe('datadir') def _datadir_changed(self, change): self.parent.datadir.path = pathclean(change['new']) # .................................................................................................................. @property def log_level(self): """ int - logging level """ return self.parent.log_level # .................................................................................................................. @log_level.setter def log_level(self, value): if isinstance(value, str): value = getattr(logging, value, None) if value is None: warnings.warn('Log level not changed: invalid value given\n' 'string values must be DEBUG, INFO, WARNING, ' 'or ERROR') self.parent.log_level = value # .................................................................................................................. def __init__(self, **kwargs): super().__init__(jsonfile='GeneralPreferences', **kwargs) # ====================================================================================================================== class DatasetPreferences(MetaConfigurable): """ Per nddataset preferences """ name = Unicode('DatasetPreferences') description = Unicode('Options for datasets') updated = Bool(False) # ------------------------------------------------------------------------------------------------------------------ # Configuration entries # ------------------------------------------------------------------------------------------------------------------ csv_delimiter = Unicode(',', help='CSV data delimiter').tag(config=True) # .................................................................................................................. def __init__(self, **kwargs): super(DatasetPreferences, self).__init__(jsonfile='DatasetPreferences', **kwargs) # ====================================================================================================================== class ProjectPreferences(MetaConfigurable): """ Project preferences """ name = Unicode('ProjectPreferences') description = Unicode('Options for projects') updated = Bool(False) # ------------------------------------------------------------------------------------------------------------------ # Configuration entries # ------------------------------------------------------------------------------------------------------------------ autoload_project = Bool(False, help='Automatic loading of the last project at startup').tag(config=True) autosave_projects = Bool(False, help='Automatic saving of the current project').tag(config=True) project_directory = Unicode(help='Directory where projects are stored by default').tag(config=True, type='folder') show_close_dialog = Bool(True, help='Display the close project dialog project changing or on application exit').tag( config=True) @default('project_directory') def _get_default_project_directory(self): # Determines the SpectroChemPy project directory name and creates the directory if it doesn't exist. # This directory is typically ``$HOME/spectrochempy/projects``, but if the SCP_PROJECTS_HOME environment # variable is set and the `$SCP_PROJECTS_HOME` directory exists, it will be that directory. # If neither exists, the former will be created. # first look for SCP_PROJECTS_HOME pscp = Path(environ.get('SCP_PROJECTS_HOME')) if pscp.exits(): return pscp pscp = Path.home() / '.spectrochempy' / 'projects' if not pscp.exists(): pscp.mkdir(exist_ok=True) elif pscp.is_file(): raise IOError('Intended Projects directory is actually a file.') return pscp # .................................................................................................................. def __init__(self, **kwargs): super().__init__(jsonfile='ProjectPreferences', **kwargs) # ====================================================================================================================== # Application # ====================================================================================================================== class SpectroChemPy(Application): """ This class SpectroChemPy is the main class, containing most of the setup, configuration and more. """ icon = Unicode('scpy.png') "Icon for the application" running = Bool(False) "Running status of the |scpy| application" name = Unicode('SpectroChemPy') "Running name of the application" description = Unicode('SpectroChemPy is a framework for processing, analysing and modelling Spectroscopic data for ' 'Chemistry with Python.') "Short description of the |scpy| application" long_description = Unicode() "Long description of the |scpy| application" @default('long_description') def _get_long_description(self): desc = """ Welcome to <strong>SpectroChemPy</strong> Application<br><br> <p><strong>SpectroChemPy</strong> is a framework for processing, analysing and modelling <strong>Spectro</>scopic data for <strong>Chem</strong>istry with <strong>Py</strong>thon. It is a cross platform software, running on Linux, Windows or OS X.</p><br><br> <strong>version:</strong> {version}<br> <strong>Authors:</strong> {authors}<br> <strong>License:</strong> {license}<br> <div class='warning'> SpectroChemPy is still experimental and under active development. Its current design and functionalities are subject to major changes, reorganizations, bugs and crashes!!!. Please report any issues to the <a url='https://redmine.spectrochempy.fr/projects/spectrochempy/issues'>Issue Tracker<a> </div><br><br> When using <strong>SpectroChemPy</strong> for your own work, you are kindly requested to cite it this way: <pre><NAME> & <NAME>, SpectroChemPy, a framework for processing, analysing and modelling of Spectroscopic data for Chemistry with Python https://www.spectrochempy.fr, (version {version}) Laboratoire Catalyse and Spectrochemistry, ENSICAEN/University of Caen/CNRS, 2019 </pre></p>""".format(version=__release__, authors=__author__, license=__license__) return desc # ------------------------------------------------------------------------------------------------------------------ # Configuration parameters # ------------------------------------------------------------------------------------------------------------------ # Config file setting # ------------------------------------------------------------------------------------------------------------------ _loaded_config_files = List() reset_config = Bool(False, help='Should we restore a default configuration ?').tag(config=True) """Flag: True if one wants to reset settings to the original config defaults""" config_file_name = Unicode(None, help="Configuration file name").tag(config=True) """Configuration file name""" @default('config_file_name') def _get_config_file_name_default(self): return str(self.name).lower() + '_cfg' config_dir = Instance(Path, help="Set the configuration directory location").tag(config=True) """Configuration directory""" @default('config_dir') def _get_config_dir_default(self): return self.get_config_dir() config_manager = Instance(BaseJSONConfigManager) @default('config_manager') def _get_default_config_manager(self): return BaseJSONConfigManager(config_dir=str(self.config_dir)) log_format = Unicode("%(highlevel)s %(message)s", help="The Logging format template", ).tag(config=True) debug = Bool(True, help='Set DEBUG mode, with full outputs').tag(config=True) """Flag to set debugging mode""" info = Bool(False, help='Set INFO mode, with msg outputs').tag(config=True) """Flag to set info mode""" quiet = Bool(False, help='Set Quiet mode, with minimal outputs').tag(config=True) """Flag to set in fully quite mode (even no warnings)""" nodisplay = Bool(False, help='Set NO DISPLAY mode, i.e., no graphics outputs').tag(config=True) """Flag to set in NO DISPLAY mode """ last_project = Unicode('', help='Last used project').tag(config=True, type='project') """Last used project""" @observe('last_project') def _last_project_changed(self, change): if change.name in self.traits(config=True): self.config_manager.update(self.config_file_name, {self.__class__.__name__: {change.name: change.new, }}) show_config = Bool(help="Dump configuration to stdout at startup").tag(config=True) @observe('show_config') def _show_config_changed(self, change): if change.new: self._save_start = self.start self.start = self.start_show_config show_config_json = Bool(help="Dump configuration to stdout (as JSON)").tag(config=True) @observe('show_config_json') def _show_config_json_changed(self, change): self.show_config = change.new test = Bool(False, help='test flag').tag(config=True) """Flag to set the application in testing mode""" port = Integer(7000, help='Dash server port').tag(config=True) """Dash server port""" # Command line interface # ------------------------------------------------------------------------------------------------------------------ aliases = dict(test='SpectroChemPy.test', project='SpectroChemPy.last_project', f='SpectroChemPy.startup_filename', port='SpectroChemPy.port', ) flags = dict(debug=({'SpectroChemPy': {'log_level': DEBUG}}, "Set log_level to DEBUG - most verbose mode"), info=({'SpectroChemPy': {'log_level': INFO}}, "Set log_level to INFO - verbose mode"), quiet=({'SpectroChemPy': {'log_level': ERROR}}, "Set log_level to ERROR - no verbosity at all"), nodisplay=({'SpectroChemPy': {'nodisplay': True}}, "Set NO DISPLAY mode to true - no graphics at all"), reset_config=({'SpectroChemPy': {'reset_config': True}}, "Reset config to default"), show_config=( {'SpectroChemPy': {'show_config': True, }}, "Show the application's configuration (human-readable " "format)"), show_config_json=( {'SpectroChemPy': {'show_config_json': True, }}, "Show the application's configuration (json " "format)"), ) classes = List([GeneralPreferences, DatasetPreferences, ProjectPreferences, MatplotlibPreferences, DataDir, ]) # ------------------------------------------------------------------------------------------------------------------ # Initialisation of the application # ------------------------------------------------------------------------------------------------------------------ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.logs = self.log # we change the noame in order to avoid latter conflict with numpy.log self.initialize() def initialize(self, argv=None): """ Initialisation function for the API applications Parameters ---------- argv : List, [optional]. List of configuration parameters. """ # parse the argv # -------------------------------------------------------------------- # if we are running this under ipython and jupyter notebooks # deactivate potential command line arguments # (such that those from jupyter which cause problems here) self.logs.debug('initialization of SpectroChemPy') IN_IPYTHON = False if InteractiveShell.initialized(): IN_IPYTHON = True self.logs.debug("scpy command line arguments are: %s" % " ".join(sys.argv)) if not IN_IPYTHON: # remove argument not known by spectrochempy if 'make.py' in sys.argv[0] or 'pytest' in sys.argv[0]: # building docs options = [] for item in sys.argv[:]: for k in list(self.flags.keys()): if item.startswith("--" + k) or k in ['--help', '--help-all']: options.append(item) continue for k in list(self.aliases.keys()): if item.startswith("-" + k) or k in ['h', ]: options.append(item) self.parse_command_line(options) else: self.parse_command_line(sys.argv) # Get preferences from the config file and init everything # --------------------------------------------------------------------- self._init_all_preferences() # we catch warnings and error for a ligther display to the end-user. # except if we are in debugging mode # warning handler # -------------------------------------------------------------------- def send_warnings_to_log(message, category): self.logs.warning(f'{category.__name__} - {message}') return warnings.showwarning = send_warnings_to_log # exception handler # -------------------------------------------------------------------- if IN_IPYTHON: ip = get_ipython() def _custom_exc(shell, etype, evalue, tb, tb_offset=None): if self.log_level == logging.DEBUG: shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset) else: self.logs.error(f"{etype.__name__}: {evalue}") ip.set_custom_exc((Exception,), _custom_exc) # load our custom magic extensions # -------------------------------------------------------------------- if ip is not None: ip.register_magics(SpectroChemPyMagics) def _init_all_preferences(self): # Get preferences from the config file # --------------------------------------------------------------------- if not self.config: self.config = Config() configfiles = [] if self.config_file_name: config_file = self.config_dir / self.config_file_name configfiles.append(config_file) lis = self.config_dir.iterdir() for f in lis: if f.suffix == '.json': jsonname = self.config_dir / f if self.reset_config or f == 'MatplotlibPreferences.json': # remove the user json file to reset to defaults jsonname.unlink() else: configfiles.append(jsonname) for cfgname in configfiles: self.load_config_file(cfgname) if cfgname not in self._loaded_config_files: self._loaded_config_files.append(cfgname) # Eventually write the default config file # -------------------------------------- self._make_default_config_file() self.datadir = DataDir(config=self.config) self.preferences = GeneralPreferences(config=self.config, parent=self) self.dataset_preferences = DatasetPreferences(config=self.config, parent=self) self.project_preferences = ProjectPreferences(config=self.config, parent=self) self.matplotlib_preferences = MatplotlibPreferences(config=self.config, parent=self) # .................................................................................................................. def get_config_dir(self): """ Determines the SpectroChemPy configuration directory name and creates the directory if it doesn't exist. This directory is typically ``$HOME/.spectrochempy/config``, but if the SCP_CONFIG_HOME environment variable is set and the ``$SCP_CONFIG_HOME`` directory exists, it will be that directory. If neither exists, the former will be created. Returns ------- config_dir : str The absolute path to the configuration directory. """ # first look for SCP_CONFIG_HOME scp = environ.get('SCP_CONFIG_HOME') if scp is not None and Path(scp).exists(): return Path(scp) config = _find_or_create_spectrochempy_dir() / 'config' if not config.exists(): config.mkdir(exist_ok=True) return config def start_show_config(self, **kwargs): """start function used when show_config is True""" config = self.config.copy() # exclude show_config flags from displayed config for cls in self.__class__.mro(): if cls.__name__ in config: cls_config = config[cls.__name__] cls_config.pop('show_config', None) cls_config.pop('show_config_json', None) if self.show_config_json: json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr) # add trailing newlines sys.stdout.write('\n') print() return self._start() if self._loaded_config_files: print("Loaded config files:") for f in self._loaded_config_files: print(' ' + f) print() for classname in sorted(config): class_config = config[classname] if not class_config: continue print(classname) pformat_kwargs = dict(indent=4) if sys.version_info >= (3, 4): # use compact pretty-print on Pythons that support it pformat_kwargs['compact'] = True for traitname in sorted(class_config): value = class_config[traitname] print(' .{} = {}'.format(traitname, pprint.pformat(value, **pformat_kwargs), )) print() # now run the actual start function return self._start() # ------------------------------------------------------------------------------------------------------------------ # start the application # ------------------------------------------------------------------------------------------------------------------ def start(self): """ Start the |scpy| API All configuration must have been done before calling this function """ # print(f'{sys.argv}') return self._start() # ------------------------------------------------------------------------------------------------------------------ # Private methods # ------------------------------------------------------------------------------------------------------------------ def _start(self): debug = self.logs.debug if self.running: debug('API already started. Nothing done!') return self.logs.debug("show info on loading %s" % self.preferences.show_info_on_loading) if self.preferences.show_info_on_loading: info_string = "SpectroChemPy's API - v.{}\n" \ "© Copyright {}".format(__version__, __copyright__) ip = get_ipython() if ip is not None and "TerminalInteractiveShell" not in str(ip): display_info_string(message=info_string.strip()) else: if "/bin/scpy" not in sys.argv[0]: # deactivate for console scripts print(info_string.strip()) # force update of rcParams for rckey in mpl.rcParams.keys(): key = rckey.replace('_', '__').replace('.', '_').replace('-', '___') try: mpl.rcParams[rckey] = getattr(self.matplotlib_preferences, key) except ValueError: mpl.rcParams[rckey] = getattr(self.matplotlib_preferences, key).replace('\'', '') except AttributeError: # print(f'{e} -> you may want to add it to MatplotlibPreferences.py') pass self.matplotlib_preferences.set_latex_font(self.matplotlib_preferences.font_family) self.running = True debug('MPL backend: {}'.format(mpl.get_backend())) # display needs for update # time.sleep(1) fi = Path.home() / ".scpy_update" if fi.exists(): try: msg = fi.read_text() self.logs.warning(msg) except Exception: pass return True # .................................................................................................................. def _make_default_config_file(self): """auto generate default config file.""" fname = self.config_dir / self.config_file_name fname = fname.with_suffix('.py') if not fname.exists() or self.reset_config: s = self.generate_config_file() self.logs.info("Generating default config file: %r" % fname) with open(fname, 'w') as f: f.write(s) # ------------------------------------------------------------------------------------------------------------------ # Events from Application # ------------------------------------------------------------------------------------------------------------------ @observe('log_level') def _log_level_changed(self, change): self.log_format = '%(message)s' if change.new == DEBUG: self.log_format = '[%(filename)s-%(funcName)s %(levelname)s] %(' \ 'message)s' self.logs._cache = {} self.logs.level = self.log_level for handler in self.logs.handlers: handler.level = self.log_level self.logs.info("changed default log_level to {}".format(logging.getLevelName(change.new))) # ====================================================================================================================== if __name__ == "__main__": pass <file_sep>/tests/test_processors/test_concatenate.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy.core.processors.concatenate import concatenate, stack from spectrochempy.units import ur from spectrochempy.core.dataset.coord import Coord from spectrochempy.utils.testing import assert_dataset_almost_equal def test_concatenate(IR_dataset_2D): dataset = IR_dataset_2D # print(dataset) s1 = dataset[:, -10:] s2 = dataset[:, :-10] # specify axis dim = 'x' s = concatenate(s1, s2, dims=dim) assert s.units == s1.units assert s.shape[-1] == (s1.shape[-1] + s2.shape[-1]) assert s.x.size == (s1.x.size + s2.x.size) assert s.x != dataset.x s = s.sort(dims=dim, descend=True) # assert_dataset_almost_equal(s.x, Coord(dataset.x, linear=False), decimal=3) # default concatenation in the last dimensions s = concatenate(s1, s2) assert s.units == s1.units assert s.shape[-1] == (s1.shape[-1] + s2.shape[-1]) assert s.x.size == (s1.x.size + s2.x.size) assert s.x != dataset.x s = s.sort(descend=True) # assert_dataset_almost_equal(s.x, Coord(dataset.x, linear=False), decimal=3) s1 = dataset[:10] s2 = dataset[20:] # check with derived units s1.to(ur.m, force=True) s2.to(ur.dm, force=True) s = concatenate(s1, s2, dim=0) assert s.units == s1.units assert s.shape[0] == (s1.shape[0] + s2.shape[0]) assert s.y.size == (s1.y.size + s2.y.size) s = s.sort(dim='y') s.plot() # second syntax s = s1.concatenate(s2, dim=0) assert s.units == s1.units assert s.shape[0] == (s1.shape[0] + s2.shape[0]) assert s.y.size == (s1.y.size + s2.y.size) # third syntax s = concatenate((s1, s2), dim=0) assert s.units == s1.units assert s.shape[0] == (s1.shape[0] + s2.shape[0]) assert s.y.size == (s1.y.size + s2.y.size) # concatenation in the first dimenson using stack s = stack(s1, s2) assert s.units == s1.units assert s.shape[0] == (s1.shape[0] + s2.shape[0]) assert s.y.size == (s1.y.size + s2.y.size) # Stacking of datasets: # for nDimensional datasets (with the same shape), a new dimension is added ss = concatenate(s.copy(), s.copy(), force_stack=True) # make a copy of s # (dataset cannot be concatenated to itself!) assert ss.shape == (2, 45, 5549) # If one of the dimensions is of size one, then this dimension is removed before stacking s0 = s[0] s1 = s[1] ss = s0.concatenate(s1, force_stack=True) assert s0.shape == (1, 5549) assert ss.shape == (2, 5549) # stack squeezed nD dataset s0 = s[0].copy().squeeze() assert s0.shape == (5549,) s1 = s[1].squeeze() assert s1.shape == (5549,) ss = concatenate(s0, s1, force_stack=True) assert ss.shape == (2, 5549) def test_bug_243(): import spectrochempy as scp D = scp.zeros((10, 100)) x = scp.LinearCoord(offset=0.0, increment=1.0, size=100) y = scp.LinearCoord(offset=0.0, increment=1.0, size=10) D.set_coordset(x=x, y=y) D1 = D[:, 0.:10.] D2 = D[:, 20.:40.] D12 = scp.concatenate(D1, D2, axis=1) # D2.x.data[-1] is 40., as expected, but not D12.x.data[-1]: assert D12.x.data[-1] == D2.x.data[-1] <file_sep>/tests/test_database/test_isotopes.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy import Isotopes, ur def test_isotopes(): isotope = Isotopes('129Xe') assert (isotope.name == 'xenon') assert (isotope.spin == 1 / 2) assert (isotope.symbol == 'Xe') isotope.nucleus = '27Al' # we change the isotope`inplace` assert (isotope.name == 'aluminium') assert (isotope.spin == 5 / 2) assert (isotope.symbol == 'Al') assert isinstance(isotope.H_2, Isotopes) assert round(isotope.H_2.Q, 2) == 2.86 * ur.millibarn assert round(isotope.H_1.gamma * 9.4 * ur.tesla, 0) == 400 * ur.MHz <file_sep>/docs/userguide/introduction/mdcheatsheet.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # cell_metadata_filter: -all # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # Markdown Cheat Sheet # %% [markdown] # Copied and adapted # from __[this guide](https://www.ibm.com/support/knowledgecenter/en/SSGNPV_2.0.0/dsx/markd-jupyter.html)__! # # This Markdown cheat sheet provides a quick overview of all the Markdown syntax elements to format Markdown cells in # Jupyter notebooks. # %% [markdown] # ## Headings # %% [markdown] # Use the number sign (#) followed by a blank space for notebook titles and section headings, e.g.: # ```md # # for titles # ## for major headings # ### for subheadings # #### for 4th level subheading # ``` # %% [markdown] # ## Emphasis # %% [markdown] # Use the surroundig _ or * to emphasize text, e.g.: # ``` # Bold text: `__string___ or **string**` # Italic text: `_string_ or *string` # ``` # %% [markdown] # ## Mathematical symbols # %% [markdown] # Surround mathematical symbols with a dollar sign (\$), for example: # ``` # $ \lambda = \sqrt{2*\pi} $ # ``` # gives $ \lambda = \sqrt{2*\pi} $ # %% [markdown] # ## Monospace font # %% [markdown] # Surround text with a grave accent (\`) also called a back single quotation mark, for example: # ``` # `string` # ``` # You can use the monospace font for `file paths`, `file names`,`message text`... # %% [markdown] # ## Line breaks # %% [markdown] # Sometimes markdown doesn’t make line breaks when you want them. To force a linebreak, use the following code: `<br>` # %% [markdown] # ## Indenting # %% [markdown] # Use the greater than sign (>) followed by a space, for example: # ``` # > Text that will be indented when the Markdown is rendered. # Any subsequent text is indented until the next carriage return. # ``` # %% [markdown] # ## Bullets # %% [markdown] # To create a circular bullet point, use one of the following methods. Each bullet point must be on its own line. # # - A hyphen (-) followed by one or two spaces, for example: # # ``` # - Bulleted item # ``` # # - A space, a hyphen (-) and a space, for example: # # ``` # - Bulleted item # ``` # # * An asterisk (*) followed by one or two spaces, for example: # # ``` # * Bulleted item # ``` # # To create a sub bullet, press Tab before entering the bullet point using one of the methods described above. For # example: # # ``` # - Main bullet point # - Sub bullet point # ``` # %% [markdown] # ## Numbered lists # %% [markdown] # To create a numbered list, enter 1. followed by a space, for example: # ``` # 1. Numbered item # 1. Numbered item # ``` # For simplicity, you use 1. before each entry. The list will be numbered correctly when you run the cell. # # To create a substep, press Tab before entering the numbered item, for example: # ``` # 1. Numbered item # 1. Substep # ``` # %% [markdown] # ## Colored note boxes # %% [markdown] # Use one of the following <div> tags to display text in a colored box. # # **Restriction**: # Not all Markdown code displays correctly within <div> tags, so review your colored boxes carefully. # For example, to make a word bold, surround it with the HTML code for bold (<b>text</b> instead of the Markdown code. # # The color of the box is determined by the alert type that you specify: # # * Blue boxes (alert-info) # * Yellow boxes (alert-warning) # * Green boxes (alert-success) # * Red boxes (alert-danger) # # ``` # <div class="alert alert-block alert-info"> # <b>Tip:</b> For example use blue boxes to highlight a tip. # If it’s a note, you don’t have to include the word “Note”. # </div> # ``` # # <div class="alert alert-block alert-info"> # <b>Tip:</b> For example use blue boxes to highlight a tip. # If it’s a note, you don’t have to include the word “Note”. # </div> # %% [markdown] # ## Graphics # %% [markdown] # You can attach image files directly to a notebook in Markdown cells by dragging and dropping it into the cell. # To add images to other types of cells, you must use a graphic that is hosted on the web and use the following code # to insert the graphic: # ``` # <img src="url.gif" alt="Alt text that describes the graphic" title="Title text" /> # # ``` # <img src="images/scpy.png" alt="Alt text that describes the graphic" width=100 title="Title text" /> # # **Restriction** # You cannot add captions to graphics. # %% [markdown] # ## Geometric shapes # Use &# followed by the decimal or hex reference number for the shape, for example: # ``` # &#reference_number; # ``` # e.g., `&#9664;`: &#9664; # # For a list of reference numbers, see __[UTF-8 Geometric shapes](https://en.wikipedia.org/wiki/Geometric_Shapes)__. # %% [markdown] # ## Horizontal lines # On a new line, enter three asterisks: ``***`` # *** # %% [markdown] # ## Internal links # To link to a section within your notebook, use the following code: # ``` # [Section title](#section-title) # ``` # # For the text inside the parentheses, replace any spaces and special characters with a hyphen. For example, # if your section is called `processing_functions`, you'd enter: # ``` # [processing_functions](#processing_functions) # ``` # [processing_functions](#processing_functions) # # Alternatively, you can add an ID above the section: # ``` # <a id="section_ID"></a> # ``` # # **Important** # Each ID in the notebook must be unique. # # To link to a section that has an ID, use the following code: # [Section title](#section_ID) # # %% [markdown] # ## External links # %% [markdown] # To link to an external site, use the following code: # __[link text](http://url)__ # Surround the link with two underscores (_) on each side # %% <file_sep>/spectrochempy/core/plotters/plot3d.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module should be able to handle a large set of plot types. """ __all__ = ['plot_3D'] __dataset_methods__ = [] # from spectrochempy.core import project_preferences # import matplotlib.pyplot as plt # import matplotlib as mpl # import numpy as np # ============================================================================= # nddataset plot3D functions # ============================================================================= def plot_3D(dataset, **kwargs): raise NotImplementedError('Not implemented') # """ # 3D Plots of NDDatasets # # Parameters # ---------- # dataset: :class:`~spectrochempy.ddataset.nddataset.NDDataset` to plot # # data_only: `bool` [optional, default=`False`] # # Only the plot is done. No addition of axes or label specifications # (current if any or automatic settings are kept. # # method: str [optional among ``surface``, ... (other to be implemented)..., default=``surface``] # # style: str, optional, default='notebook' # Matplotlib stylesheet (use `available_style` to get a list of available # styles for plotting # # reverse: `bool` or None [optional, default=None # In principle, coordinates run from left to right, except for wavenumbers # (e.g., FTIR spectra) or ppm (e.g., NMR), that spectrochempy # will try to guess. But if reverse is set, then this is the # setting which will be taken into account. # # x_reverse: `bool` or None [optional, default=None # # kwargs: additional keywords # # {} # # """.format(dataset._general_parameters_doc_) # # # get all plot preferences # # ------------------------ # # prefs = dataset.preferences # if not prefs.style: # # not yet set, initialize with default project preferences # prefs.update(project_preferences.to_dict()) # # # If we are in the GUI, we will plot on a widget: but which one? # # --------------------------------------------------------------- # # # # widget = kwargs.get('widget', None) # # if widget is not None: # if hasattr(widget, 'implements') and widget.implements('PyQtGraphWidget'): # # let's go to a particular treament for the pyqtgraph plots # kwargs['use_mpl'] = use_mpl = False # # we try to have a commmon interface for both plot library # kwargs['ax'] = ax = widget # return qt_plot_1D(dataset, **kwargs) # else: # # this must be a matplotlibwidget # kwargs['use_mpl'] = use_mpl = True # fig = widget.fig # kwargs['ax'] = ax = fig.gca() # # # method of plot # # ------------ # # method = kwargs.get('method', prefs.method_3D) # # data_only = kwargs.get('data_only', False) # new = dataset.copy() # # # figure setup # # ------------ # # ax = plt.axes(projection='3d') # # # Other properties # # ------------------ # # colorbar = kwargs.get('colorbar', project_preferences.colorbar) # # cmap = mpl.rcParams['image.cmap'] # # # viridis is the default setting, # # so we assume that it must be overwritten here # # except if style is grayscale which is a particular case. # styles = kwargs.get('style', project_preferences.style) # # if styles and not "grayscale" in styles and cmap == "viridis": # # if method in ['surface']: # cmap = colormap = kwargs.get('colormap', # kwargs.get('cmap', project_preferences.colormap_surface)) # else: # # other methods to be implemented # pass # # lw = kwargs.get('linewidth', kwargs.get('lw', # project_preferences.pen_linewidth)) # # antialiased = kwargs.get('antialiased', project_preferences.antialiased) # # rcount = kwargs.get('rcount', project_preferences.rcount) # # ccount = kwargs.get('ccount', project_preferences.ccount) # # if method == 'surface': # X, Y = np.meshgrid(new.x.data, new.y.data) # Z = dataset.data # # # Plot the surface. # surf = ax.plot_surface(X, Y, Z, cmap=cmap, # linewidth=lw, antialiased=antialiased, # rcount=rcount, ccount=ccount) # if not data_only: # ax.set_xlabel(new.x.title) # ax.set_ylabel(new.y.title) # ax.set_zlabel(new.title) # # return ax <file_sep>/spectrochempy/core/dataset/ndio.py # -*- coding: utf-8 -*- # ============================================================================== # Copyright (©) 2015-2020 # LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT # See full LICENSE agreement in the root directory # ============================================================================== """ This module define the class |NDIO| in which input/output standard methods for a |NDDataset| are defined. """ __all__ = ['NDIO', 'SCPY_SUFFIX'] import io import json import pathlib import numpy as np from numpy.lib.npyio import zipfile_factory from traitlets import HasTraits, Instance, Union, Unicode from spectrochempy.core.dataset.coord import Coord, LinearCoord from spectrochempy.core import debug_ from spectrochempy.utils import (SpectroChemPyException, pathclean, check_filenames, ScpFile, check_filename_to_save, json_serialiser, TYPE_BOOL, ) SCPY_SUFFIX = {'NDDataset': '.scp', 'Project': '.pscp'} # ---------------------------------------------------------------------------------------------------------------------- # Utilities # ---------------------------------------------------------------------------------------------------------------------- # ====================================================================================================================== # Class NDIO to handle I/O of datasets # ====================================================================================================================== class NDIO(HasTraits): """ Import/export interface from |NDDataset| This class is used as basic import/export interface of the |NDDataset|. """ _filename = Union((Instance(pathlib.Path), Unicode()), allow_none=True) @property def directory(self): """ `Pathlib` object - current directory for this dataset ReadOnly property - automaticall set when the filename is updated if it contains a parent on its path """ if self._filename: return pathclean(self._filename).parent else: return None @property def filename(self): """ `Pathlib` object - current filename for this dataset. """ if self._filename: return self._filename.stem + self.suffix else: return None @filename.setter def filename(self, val): self._filename = pathclean(val) @property def filetype(self): klass = self.implements() return [f'SpectroChemPy {klass} file (*{SCPY_SUFFIX[klass]})'] @property def suffix(self): """ filename suffix Read Only property - automatically set when the filename is updated if it has a suffix, else give the default suffix for the given type of object. """ if self._filename and self._filename.suffix: return self._filename.suffix else: klass = self.implements() return SCPY_SUFFIX[klass] # ------------------------------------------------------------------------------------------------------------------ # Special methods # ------------------------------------------------------------------------------------------------------------------ def __dir__(self): return ['filename', ] # ------------------------------------------------------------------------------------------------------------------ # Public methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def save(self, **kwargs): """ Save the current object in SpectroChemPy format. Default extension is *.scp for |NDDataset|'s and *.pscp for |Project|'s. See Also --------- save_as : save current object with a different name and/or directory write : export current object to different format Examples --------- read some data from an OMNIC file >>> import spectrochempy as scp >>> nd = scp.read_omnic('wodger.spg') >>> assert nd.name == 'wodger' write it in SpectroChemPy format (.scp) (return a `pathlib` object) >>> filename = nd.save() check the existence of the scp fie >>> assert filename.is_file() >>> assert filename.name == 'wodger.scp' Remove this file >>> filename.unlink() """ # by default we save the file in the self.directory and with the # name + suffix depending # on the current object type if self.directory is None: filename = pathclean('.') / self.name self.filename = filename # <- this will set self.directory too. filename = self.directory / self.name default_suffix = SCPY_SUFFIX[self.implements()] filename = filename.with_suffix(default_suffix) if not filename.exists() and kwargs.get('confirm', True): # never saved kwargs['caption'] = f'Save the current {self.implements()} as ... ' return self.save_as(filename, **kwargs) # was already saved previously with this name, # in this case we do not display a dialog and overwrite the same file self.name = filename.stem return self.dump(filename, **kwargs) # .................................................................................................................. def save_as(self, filename='', **kwargs): """ Save the current |NDDataset| in SpectroChemPy format (*.scp) Parameters ---------- filename : str The filename of the file where to save the current dataset directory : str, optional If specified, the given `directory` and the `filename` will be appended. Examples --------- read some data from an OMNIC file >>> import spectrochempy as scp >>> nd = scp.read_omnic('wodger.spg') >>> assert nd.name == 'wodger' write it in SpectroChemPy format (.scp) (return a `pathlib` object) >>> filename = nd.save_as('new_wodger') check the existence of the scp fie >>> assert filename.is_file() >>> assert filename.name == 'new_wodger.scp' Remove this file >>> filename.unlink() Notes ----- adapted from :class:`numpy.savez` See Also --------- save : save current dataset write : export current dataset to different format """ if filename: # we have a filename # by default it use the saved directory filename = pathclean(filename) if self.directory and self.directory != filename.parent: filename = self.directory / filename else: filename = self.directory # suffix must be specified which correspond to the type of the # object to save default_suffix = SCPY_SUFFIX[self.implements()] filename = filename.with_suffix(default_suffix) kwargs['filetypes'] = self.filetype kwargs['caption'] = f'Save the current {self.implements()} as ... ' filename = check_filename_to_save(self, filename, save_as=True, **kwargs) if filename: self.filename = filename return self.dump(filename, **kwargs) # .................................................................................................................. @classmethod def load(cls, filename, **kwargs): """ open a data from a '*.scp' file. It's a class method, that can be used directly on the class, without prior opening of a class instance. Parameters ---------- filename : `str`, `pathlib` or `file` objects The name of the file to read (or a file objects. content : str, optional The optional content of the file(s) to be loaded as a binary string kwargs : optional keyword parameters. Any additional keyword(s) to pass to the actual reader. Examples -------- >>> import spectrochempy as scp >>> nd1 = scp.read('irdata/nh4y-activation.spg') >>> f = nd1.save() >>> f.name 'nh4y-activation.scp' >>> nd2 = scp.load(f) Notes ----- adapted from `numpy.load` See Also -------- read : import dataset from various orgines save : save the current dataset """ content = kwargs.get('content', None) if content: fid = io.BytesIO(content) else: # be sure to convert filename to a pathlib object with the # default suffix filename = pathclean(filename) suffix = cls().suffix filename = filename.with_suffix(suffix) if kwargs.get('directory', None) is not None: filename = pathclean(kwargs.get('directory')) / filename if not filename.exists(): filename = check_filenames(filename, **kwargs)[0] fid = open(filename, 'rb') # get zip file try: obj = ScpFile(fid) except FileNotFoundError: raise SpectroChemPyException(f"File {filename} doesn't exist!") except Exception as e: if str(e) == 'File is not a zip file': raise SpectroChemPyException("File not in 'scp' format!") raise SpectroChemPyException("Undefined error!") js = obj[obj.files[0]] if kwargs.get('json', False): return js new = cls.loads(js) fid.close() if filename: filename = pathclean(filename) new._filename = filename new.name = filename.stem return new def dumps(self, encoding=None): debug_('Dumps') js = json_serialiser(self, encoding=encoding) return json.dumps(js, indent=2) @classmethod def loads(cls, js): from spectrochempy.core.project.project import Project from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.scripts.script import Script # ......................... def item_to_attr(obj, dic): for key, val in dic.items(): try: if 'readonly' in dic.keys() and key in ['readonly', 'name']: # case of the meta and preferences pass elif hasattr(obj, f'_{key}'): # use the hidden attribute if it exists key = f'_{key}' if val is None: pass elif key in ['_meta', '_preferences']: setattr(obj, key, item_to_attr(getattr(obj, key), val)) elif key in ['_coordset']: _coords = [] for v in val['coords']: if 'data' in v: _coords.append(item_to_attr(Coord(), v)) else: _coords.append(item_to_attr(LinearCoord(), v)) if val['is_same_dim']: obj.set_coordset(_coords) else: coords = dict((c.name, c) for c in _coords) obj.set_coordset(coords) obj._name = val['name'] obj._references = val['references'] elif key in ['_datasets']: # datasets = [item_to_attr(NDDataset(name=k), # v) for k, v in val.items()] datasets = [item_to_attr(NDDataset(), js) for js in val] obj.datasets = datasets elif key in ['_projects']: projects = [item_to_attr(Project(), js) for js in val] obj.projects = projects elif key in ['_scripts']: scripts = [item_to_attr(Script(), js) for js in val] obj.scripts = scripts elif key in ['_parent']: # automatically set pass else: if isinstance(val, TYPE_BOOL) and key == '_mask': val = np.bool_(val) setattr(obj, key, val) except Exception as e: raise TypeError(f'for {key} {e}') return obj new = item_to_attr(cls(), js) return new # .................................................................................................................. def dump(self, filename, **kwargs): """ Save the current object into compressed native spectrochempy format Parameters ---------- filename: str of `pathlib` object File name where to save the current object. Extension """ # Stage data in a temporary file on disk, before writing to zip. import zipfile import tempfile zipf = zipfile_factory(filename, mode="w", compression=zipfile.ZIP_DEFLATED) _, tmpfile = tempfile.mkstemp(suffix='-spectrochempy') tmpfile = pathclean(tmpfile) js = self.dumps(encoding='base64') tmpfile.write_bytes(js.encode('utf-8')) zipf.write(tmpfile, arcname=f'{self.name}.json') tmpfile.unlink() zipf.close() self.filename = filename self.name = filename.stem return filename # ====================================================================================================================== if __name__ == '__main__': pass # EOF <file_sep>/docs/gettingstarted/examples/readme.txt .. _examples-index: ################### Example's gallery ################### Many examples on the use of the API can be found in this gallery. Notebook and standalone python scripts can be downloaded using the link at the bottom of each example. .. contents:: Table of Contents :local: :depth: 3 <file_sep>/docs/userguide/processing/baseline.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Baseline corrections # # This tutorial shows how to make baseline corrections with spectrochempy. # As prerequisite, the user is expected to have read the [Import](../import_export/import.ipynb) # and [Import IR](../import_export/importIR.ipynb) tutorials. # %% import spectrochempy as scp # %% [markdown] # Now let's import and plot a typical IR dataset which wase recorded during the removal of ammonia from a NH4-Y zeolite: # %% X = scp.read_omnic("irdata/nh4y-activation.spg") X[:, 1290.:890.] = scp.MASKED # %% [markdown] # After setting some plotting preferences and plot it # %% prefs = X.preferences prefs.figure.figsize = (7, 3) prefs.colormap = 'magma' _ = X.plot() # %% [markdown] # ## Background subtraction # # Often, particularly for surface species, the baseline is first corrected by subtracting a reference spectrum. In this # example, it could be, for instance, the last spectrum (index -1). Hence: # %% Xdiff = X - X[-1] _ = Xdiff.plot() # %% [markdown] # ## Detrend # # Other simple baseline corrections - often use in preprocessing prior chemometric analysis - constist in shifting # the spectra or removing a linear trend. This is done using the detrend() method, which is a wrapper of the [ # detrend() method](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.detrend.html) from the [ # scipy.signal](https://docs.scipy.org/doc/scipy/reference/signal.html) module to which we refer the interested reader. # %% [markdown] # ### Linear trend # Subtract the linear trend of each spectrum (type='linear', default) # %% _ = X.detrend().plot() # %% [markdown] # ### Constant trend # Subtract the average absorbance to each spectrum # %% _ = X.detrend(type='constant').plot() # %% [markdown] # ## Automatic linear baseline correction `abc` # %% [markdown] # When the baseline to remove is a simple linear correction, one can use ``abc``. # This perform an automatic baseline correction. # %% _ = scp.abc(X).plot() # %% [markdown] # ## Advanced baseline correction # # 'Advanced' baseline correction basically consists for the user to choose: # # - spectral ranges which s/he considers as belonging to the base line - the type of polynomial(s) used to model the # baseline in and between these regions (keyword: `interpolation`) - the method used to apply the correction to # spectra: sequentially to each spectrum, or using a multivariate approach (keyword: `method`). # # ### Range selection # # Each spectral range is defined by a list of two values indicating the limits of the spectral ranges, e.g. `[4500., # 3500.]` to # select the 4500-3500 cm$^{-1}$ range. Note that the ordering has no importance and using `[3500.0, 4500.]` would # lead to exactly the same result. It is also possible to formally pick a single wavenumber `3750.`. # # The first step is then to select the verious regions that we expect to belong to the baseline # %% ranges = [5900.0, 5400.0], 4550., [4500., 4000.], [2100., 2000.0], [1550., 1555.] # %% [markdown] # After selection of the baseline ranges, the baseline correction can be made using a sequence of 2 commands: # # 1. Initialize an instance of BaselineCorrection # %% blc = scp.BaselineCorrection(X) # %% [markdown] # 2. compute baseline other the ranges # %% Xcorr = blc.compute(ranges) Xcorr # %% [markdown] # * plot the result (blc.corrected.plot() would lead to the same result) # %% _ = Xcorr.plot() # %% [markdown] # ### Interpolation method # # # The previous correction was made using the default parameters for the interpolation ,i.e. an interpolation using # cubic Hermite spline interpolation: `interpolation='pchip'` (`pchip` stands for **P**iecewise **C**ubic **H**ermite # **I**nterpolating **P**olynomial). This option triggers the use of [scipy.interpolate.PchipInterpolator()]( # https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.PchipInterpolator.html) to which we refer # the interested readers. The other interpolation method is the classical polynomial interpolation # (`interpolation='polynomial'`) in which case the order can also be set (e.g. `order=3`, the default value being 6). # In this case, the base methods used for the interpolation are those of the [polynomial module]( # https://numpy.org/doc/stable/reference/routines.polynomials.polynomial.html) of spectrochempy, in particular the # [polyfit()](https://numpy.org/doc/stable/reference/generated/numpy.polynomial.polynomial.polyfit.html#numpy # .polynomial.polynomial.polyfit) method. # # For instance: # %% [markdown] # First, we put the ranges in a list # %% ranges = [[5900.0, 5400.0], [4000., 4500.], [2100., 2000.0], [1550., 1555.]] # %% [markdown] # <div class='alert alert-warning'> # <b>Warning</b> # # if you use a tuple to define the sequences of ranges: # # ```ipython3 # ranges = [5900.0, 5400.0], [4000., 4500.], [2100., 2000.0], [1550., 1555.] # ``` # # or # # ```ipython3 # ranges = ([5900.0, 5400.0], [4000., 4500.], [2100., 2000.0], [1550., 1555.]) # ``` # # then you can call `compute` by directly pass the ranges tuple, or you can unpack it as below. # # ```ipython3 # blc.compute(ranges, ....) # ``` # # # if you you use a list instead of tuples: # # ```ipython3 # ranges = [[5900.0, 5400.0], [4000., 4500.], [2100., 2000.0], [1550., 1555.]] # ``` # # then you **MUST UNPACK** the element when calling `compute`: # # ```ipython3 # blc.compute(*ranges, ....) # ``` # # # </div> # %% blc = scp.BaselineCorrection(X) blc.compute(*ranges, interpolation='polynomial', order=6) # %% [markdown] # The `corrected` attribute contains the corrected NDDataset. # %% _ = blc.corrected.plot() # %% [markdown] # ### Multivariate method # # The `method` option defines whether the selected baseline regions of the spectra should be taken 'as is' # this is the default `method='sequential'`), or modeled using a multivariate approach (`method='multivariate'`). # # The `'multivariate'` option is useful when the signal‐to‐noise ratio is low and/or when the baseline changes in # various regions of the spectrum are correlated. It constist in (i) modeling the baseline regions by a principal # component analysis (PCA), (ii) interpolate the loadings of the first principal components over the whole spectral # and (iii) modeling the spectra baselines from the product of the PCA scores and the interpolated loadings. # (for detail: see [Vilmin et al. Analytica Chimica Acta 891 (2015)](dx.doi.org/10.1016/j.aca.2015.06.006). # # If this option is selected, the user should also choose `npc`, the number of principal components used to model the # baseline. In a sense, this parameter has the same role as the `order` parameter, except tha it will affect how well # the baseline fits the selected regions, but on *both dimensions: wavelength and acquision time*. In particular a # large value of `npc` will lead to an overfit of baseline variation with time and will lead to the same result as the # `sequential` method while a too small `value` would miss important pricipal component underlying the baseline change # over time. Typical optimum values are `npc=2` or `npc=3` (see Exercises below). # %% blc = scp.BaselineCorrection(X) blc.compute(*ranges, interpolation='pchip', method='multivariate', npc=2) _ = blc.corrected.plot() # %% [markdown] # ### Code snippet for 'advanced' baseline correction # The following code in which the user can change any of the parameters and look at the changes after re-running # the cell: # %% # user defined parameters # ----------------------- ranges = [5900.0, 5400.0], [4000., 4500.], 4550., [2100., 2000.0], [1550., 1555.], [1250.0, 1300.], [800., 850.] interpolation = 'pchip' # choose 'polynomial' or 'pchip' order = 5 # only used for 'polynomial' method = 'sequential' # choose 'sequential' or 'multivariate' npc = 3 # only used for 'multivariate' # code: compute baseline, plot original and corrected NDDatasets and ranges # ------------------------------------------------------------------------- blc = scp.BaselineCorrection(X) Xcorr = blc.compute(*ranges, interpolation=interpolation, order=order, method=method, npc=npc) axes = scp.multiplot([X, Xcorr], labels=['Original', 'Baseline corrected'], sharex=True, nrow=2, ncol=1, figsize=(7, 6), dpi=96) blc.show_regions(axes['axe21']) # %% [markdown] # <div class='alert alert-info'> # <b>Exercises</b> # # **basic:** # - write commands to subtract (i) the first spectrum from a dataset and (ii) the mean spectrum from a dataset # - write a code to correct the baseline of the last 10 spectra of the above dataset in the 4000-3500 cm$^{-1}$ range # # **intermediate:** # - what would be the parameters to use in 'advanced' baseline correction to mimic 'detrend' ? Write a code to check # your answer. # # **advanced:** # - simulate noisy spectra with baseline drifts and compare the performances of `multivariate` vs `sequential` methods # </div> <file_sep>/docs/gettingstarted/examples/analysis/plot_pca_iris.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ PCA analysis example --------------------- In this example, we perform the PCA dimensionality reduction of the classical ``iris`` dataset. """ import spectrochempy as scp import sys ############################################################ # Upload a dataset form a distant server try: dataset = scp.download_IRIS() except (IOError, OSError): print('Could not load The IRIS dataset. Finishing here.') sys.exit(0) ############################################################## # Create a PCA object pca = scp.PCA(dataset, centered=True) ############################################################## # Reduce the dataset to a lower dimensionality (number of # components is automatically determined) S, LT = pca.reduce(n_pc='auto') print(LT) ############################################################### # Finally, display the results graphically # # ScreePlot _ = pca.screeplot() ######################################################################################################################## # ScorePlot of 2 PC's _ = pca.scoreplot(1, 2, color_mapping='labels') ######################################################################################################################## # or in 3D for 3 PC's _ = pca.scoreplot(1, 2, 3, color_mapping='labels') # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/spectrochempy/core/analysis/svd.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements the Singular Value Decomposition (SVD) class. """ __all__ = ['SVD'] __dataset_methods__ = [] from traitlets import HasTraits, Instance import numpy as np from spectrochempy.core.dataset.coord import Coord from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.ndarray import MASKED # ---------------------------------------------------------------------------------------------------------------------- class SVD(HasTraits): """ Performs a Singular Value Decomposition of a dataset. The SVD is commonly written as :math:`X = U \\Sigma V^{T}`. This class has the attributes : U, s = diag(S) and VT=V :math:`^T`. If the dataset contains masked values, the corresponding ranges are ignored in the calculation. """ U = Instance(NDDataset, allow_none=True) """|NDDataset| - Contains the left unitary matrix. Its shape depends on `full_matrices`""" s = Instance(NDDataset) """|NDDataset| - Vector of singular values""" VT = Instance(NDDataset, allow_none=True) """|NDDataset| - Contains a transpose matrix of the Loadings. Its shape depends on `full_matrices`""" def __init__(self, dataset, full_matrices=False, compute_uv=True): """ Parameters ----------- dataset : |NDDataset| object The input dataset has shape (M, N). M is the number of observations (for examples a series of IR spectra) while N is the number of features (for example the wavenumbers measured in each IR spectrum). full_matrices : bool, optional, default=False. If False , U and VT have the shapes (M, k) and (k, N), respectively, where k = min(M, N). Otherwise the shapes will be (M, M) and (N, N), respectively. compute_uv : bool, optional, default: True. Whether or not to compute U and VT in addition to s. Examples -------- >>> import spectrochempy as scp >>> dataset = scp.read('irdata/nh4y-activation.spg') >>> svd = SVD(dataset) >>> print(svd.ev.data) [1.185e+04 634 ... 0.001089 0.000975] >>> print(svd.ev_cum.data) [ 94.54 99.6 ... 100 100] >>> print(svd.ev_ratio.data) [ 94.54 5.059 ... 8.687e-06 7.779e-06] """ self._compute_uv = compute_uv # check if we have the correct input # ---------------------------------- X = dataset if isinstance(X, NDDataset): # As seen below, we cannot performs SVD on the masked array # so let's take the ndarray only. # Warning: we need to take the hidden values, to handle the # case of dim 1 axis. Of course, svd will work only for real # data, not complex or hypercomplex. data = X._data M, N = X._data.shape units = X.units else: raise TypeError(f'A dataset of type NDDataset is expected as a dataset of data, but an object of type' f' {type(X).__name__} has been provided') # Retains only valid rows and columns # ----------------------------------- # unfortunately, the present SVD implementation in linalg library # doesn't support numpy masked arrays as input. So we will have to # remove the masked values ourselves # the following however assumes that entire rows or columns are masked, # not only some individual data (if this is what you wanted, this # will fail) if np.any(X._mask): masked_columns = np.all(X._mask, axis=-2) masked_rows = np.all(X._mask, axis=-1) else: masked_columns = np.zeros(X._data.shape[-1], dtype=bool) masked_rows = np.zeros(X._data.shape[-2], dtype=bool) data = data[:, ~ masked_columns] data = data[~ masked_rows] # Performs the SVD # ---------------- if data.size == 0 and np.product(data.shape[-2:]) == 0: raise np.linalg.LinAlgError("Arrays cannot be empty. You may " "want to check the masked data. ") res = np.linalg.svd(data, full_matrices, compute_uv) if compute_uv: U, s, VT = res else: s = res # Returns the diagonal sigma matrix as a NDDataset object # ------------------------------------------------------- s = NDDataset(s) s.title = 'Singular values of ' + X.name s.name = 'sigma' s.history = 'Created by SVD \n' s.description = ( 'Vector of singular values obtained by SVD ' 'decomposition of ' + X.name) self.s = s if compute_uv: # Put back masked columns in VT # ------------------------------ # Note that it is very important to use here the ma version of zeros # array constructor KV = VT.shape[0] if np.any(masked_columns): Vtemp = np.ma.zeros((KV, N)) # note np.ma, not np. Vtemp[:, ~ masked_columns] = VT Vtemp[:, masked_columns] = MASKED VT = Vtemp # Put back masked rows in U # ------------------------- KU = U.shape[1] if np.any(masked_rows): Utemp = np.ma.zeros((M, KU)) Utemp[~ masked_rows] = U Utemp[masked_rows] = MASKED U = Utemp # Sign correction to ensure deterministic output from SVD. # This doesn't work will full_matrices=True. if not full_matrices: U, VT = self._svd_flip(U, VT) # Returns U as a NDDataset object # -------------------------------- U = NDDataset(U) U.name = 'U' U.title = 'left singular vectors of ' + X.name U.set_coordset(x=Coord(labels=['#%d' % (i + 1) for i in range(KU)], title='Components'), y=X.y) U.description = 'left singular vectors of ' + X.name U.history = 'Created by SVD \n' # Returns the loadings (VT) as a NDDataset object # ------------------------------------------------ VT = NDDataset(VT) VT.name = 'V.T' VT.title = 'Loadings (V.t) of ' + X.name VT.set_coordset(x=X.x, y=Coord(labels=['#%d' % (i + 1) for i in range(KV)], title='Components')) VT.description = ( 'Loadings obtained by singular value decomposition of ' + X.name) VT.history = (str(VT.modified) + ': Created by SVD \n') # loadings keep the units of the original data VT.units = units self.U = U self.VT = VT else: self.U = None self.VT = None # ------------------------------------------------------------------------------------------------------------------ # special methods # ------------------------------------------------------------------------------------------------------------------ def __repr__(self): if self._compute_uv: return '<svd: U%s, s(%s), VT%s>' % ( self.U.shape, self.s.size, self.VT.shape) else: return '<svd: s(%s), U, VT:not computed>' % (self.s.size,) # ------------------------------------------------------------------------------------------------------------------ # Properties # ------------------------------------------------------------------------------------------------------------------ @property def sv(self): """|NDDataset|, Singular values""" size = self.s.size sv = self.s.copy() sv.name = 'sv' sv.title = 'Singular values' sv.set_coordset(Coord(None, labels=['#%d' % (i + 1) for i in range(size)], title='Components')) return sv @property def ev(self): """|NDDataset|, Explained variance""" size = self.s.size ev = self.s ** 2 / (size - 1) ev.name = 'ev' ev.title = 'Explained variance' ev.set_coordset(Coord(None, labels=['#%d' % (i + 1) for i in range(size)], title='Components')) return ev @property def ev_cum(self): """|NDDataset|, Cumulative Explained Variance""" ev_cum = np.cumsum(self.ev_ratio) ev_cum.name = 'ev_cum' ev_cum.title = 'Cumulative explained variance' ev_cum.units = 'percent' return ev_cum @property def ev_ratio(self): """|NDDataset|, Explained Variance per singular values""" ratio = self.ev * 100. / np.sum(self.ev) ratio.name = 'ev_ratio' ratio.title = 'Explained variance' ratio.units = 'percent' return ratio def _svd_flip(self, U, VT, u_based_decision=True): """ Sign correction to ensure deterministic output from SVD. Adjusts the columns of u and the rows of v such that the loadings in the columns in u that are largest in absolute value are always positive. Parameters ---------- u_based_decision : boolean, (default=True) If True, use the columns of u as the basis for sign flipping. Otherwise, use the rows of v. Notes ----- Copied and modified from scikit-learn.utils.extmath (BSD 3 Licence) """ if u_based_decision: # columns of U, rows of VT max_abs_cols = np.argmax(np.abs(U), axis=0) signs = np.sign(U[max_abs_cols, range(U.shape[1])]) U *= signs VT *= signs[:, np.newaxis] else: # rows of V, columns of U max_abs_rows = np.argmax(np.abs(VT), axis=1) signs = np.sign(VT[range(VT.shape[0]), max_abs_rows]) U *= signs VT *= signs[:, np.newaxis] return U, VT # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/spectrochempy/core/dataset/api.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, # Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in # the root directory = # ====================================================================================================================== from spectrochempy.utils import generate_api # generate api __all__ = generate_api(__file__) <file_sep>/docs/gettingstarted/examples/plotting/readme.txt .. _plotting_examples-index: Plotting dataset examples -------------------------- Example of how to plot datasets in SpectroChemPy <file_sep>/tests/test_readers_writers/test_read_dir.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== import spectrochempy as scp def test_read_dir(): A = scp.read_dir('irdata/subdir') assert A.shape == (4, 5549) C = scp.NDDataset.read_dir('matlabdata') assert isinstance(C, list) assert len(C) == 7 # seven matrices # The order in which .mat files are read/returned can change depending on python implementaion. # Skip the following assert for the moment # assert C[3].shape == (204, 96) A = scp.read_dir(directory='irdata/subdir') # open a dialog to eventually select # directory inside the specified one assert A.shape == (4, 5549) B = scp.read_dir('irdata/subdir', recursive=True) assert len(B) == 8 assert B.shape == (8, 5549) # no merging B = scp.read_dir(directory='irdata/subdir', recursive=True, merge=False) assert len(B) == 8 assert isinstance(B, list) C = scp.read_dir() assert C == A def test_read_dir_nmr(): D = scp.read_dir('nmrdata/bruker/tests/nmr', protocol='topspin') assert isinstance(D, list) Dl = [item.name for item in D] assert 'topspin_2d expno:1 procno:1 (SER)' in Dl assert 'topspin_1d expno:1 procno:1 (FID)' in Dl def test_read_dir_glob(): pass # EOF <file_sep>/tests/test_analysis/test_download.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy.core.readers.download import download_IRIS from spectrochempy.core.analysis.pca import PCA from spectrochempy.core import show def test_upload(): ds = download_IRIS() assert ds.shape == (150, 4) assert repr(ds[0]) == "NDDataset: [float64] cm (shape: (y:1, x:4))" ds.plot_stack() pca = PCA(ds, centered=True) L, S = pca.reduce() L.plot_stack() pca.screeplot() pca.scoreplot(1, 2, color_mapping='labels') show() <file_sep>/docs/userguide/processing/processing.rst .. _userguide.processing: Processing ********** .. toctree:: :maxdepth: 3 transformations math_operations slicing smoothing apodization td_baseline fourier interferogram fourier2d baseline interactive_baseline alignment <file_sep>/spectrochempy/core/processors/phasing.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ A collection of NMR spectral processing functions which operate on the last dimension (1) of 2D arrays. """ __all__ = ['pk', 'pk_exp'] __dataset_methods__ = __all__ import functools import numpy as np from spectrochempy.units import ur, Quantity from spectrochempy.core import error_ pi = np.pi # ====================================================================================================================== # Decorators # ====================================================================================================================== def _phase_method(method): @functools.wraps(method) def wrapper(dataset, **kwargs): # On which axis do we want to phase (get axis from arguments) axis, dim = dataset.get_axis(**kwargs, negative_axis=True) # output dataset inplace (by default) or not if not kwargs.pop('inplace', False): new = dataset.copy() # copy to be sure not to modify this dataset else: new = dataset swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) # must be done in place swaped = True # Get the coordinates for the last dimension x = new.coordset[dim] # check if the dimensionality is compatible with this kind of functions if x.unitless or x.dimensionless or x.units.dimensionality != '[time]': # extract inital phase from metadata def _check_units(par, default_units, inv=False): if not isinstance(par, Quantity): par *= Quantity(1., default_units) elif inv: if par == 0: return par par = 1. / (1. / par).to(default_units) else: par = par.to(default_units) return par # Set correct units for the parameters dunits = dataset.coordset[dim].units current = [new.meta.phc0[-1], new.meta.phc1[-1]] rel = kwargs.pop('rel', False) if rel: # relative phase current = [0, 0] kwargs['phc0'] = (_check_units(kwargs.get('phc0', 0), 'degree') - current[0]).magnitude kwargs['phc1'] = (_check_units(kwargs.get('phc1', 0), 'degree') - current[1]).magnitude kwargs['pivot'] = _check_units(kwargs.get('pivot', new.meta.pivot[-1]), dunits).magnitude kwargs['exptc'] = _check_units(kwargs.get('exptc', new.meta.get('exptc', [0] * new.ndim)[-1]), dunits, inv=True).magnitude if not new.meta.phased[-1]: # initial phase from topspin have not yet been used kwargs['phc0'] = -kwargs['phc0'] kwargs['phc1'] = -kwargs['phc1'] apod = method(new.data, **kwargs) new *= apod new.history = f'`{method.__name__}` applied to dimension `{dim}` with parameters: {kwargs}' if not new.meta.phased[-1]: new.meta.phased[-1] = True new.meta.phc0[-1] = 0 * ur.degree new.meta.phc1[-1] = 0 * ur.degree new.meta.exptc[-1] = 0 * (1 / dunits) else: if rel: new.meta.phc0[-1] += kwargs['phc0'] * ur.degree new.meta.phc1[-1] += kwargs['phc1'] * ur.degree else: new.meta.phc0[-1] = kwargs['phc0'] * ur.degree new.meta.phc1[-1] = kwargs['phc1'] * ur.degree # TODO: to do for exptc too! new.meta.exptc[-1] = kwargs['exptc'] * (1 / dunits) new.meta.pivot[-1] = kwargs['pivot'] * dunits else: # not (x.unitless or x.dimensionless or x.units.dimensionality != '[time]') error_('This method apply only to dimensions with [frequency] or [dimensionless] dimensionality.\n' 'Phase processing was thus cancelled') # restore original data order if it was swaped if swaped: new.swapdims(axis, -1, inplace=True) # must be done inplace return new return wrapper # ====================================================================================================================== # Public methods # ====================================================================================================================== @_phase_method def pk(dataset, phc0=0.0, phc1=0.0, exptc=0.0, pivot=0.0, **kwargs): """ Linear phase correction For multidimensional NDDataset, the phase is by default applied on the last dimension. Parameters ---------- dataset : nddataset Input dataset. phc0 : float or |Quantity|, optional, default=0 degree Zero order phase in degrees. phc1 : float or |Quantity|, optional, default=0 degree First order phase in degrees. exptc : float or |Quantity|, optional, default=0 us Exponential decay constant. If not 0, phc1 is ignored. pivot: float or |Quantity|, optional, default=0 in units of the x coordinate Units if any must be compatible with last dimension units Returns ------- phased Dataset. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x'. Specify on which dimension to apply the phase. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False. True for inverse phasing. inplace : bool, keyword parameter, optional, default=False. True if we make the transform inplace. If False, the function return a new dataset. See Also -------- ps_exp : Exponential Phase Correction pk : Automatic or manual phasing """ phc0 = pi * phc0 / 180. size = dataset.shape[-1] if exptc > 0.0: apod = np.exp(1.0j * (phc0 * np.exp(-exptc * (np.arange(size) - pivot) / size))) else: phc1 = pi * phc1 / 180. apod = np.exp(1.0j * (phc0 + (phc1 * (np.arange(size) - pivot) / size))) return apod def pk_exp(dataset, phc0=0.0, pivot=0.0, exptc=0.0, **kwargs): """ Exponential Phase Correction For multidimensional NDDataset, the phase is by default applied on the last dimension. Parameters ---------- dataset : nddataset Input dataset. phc0 : float or |Quantity|, optional, default=0 degree Zero order phase in degrees. exptc : float or |Quantity|, optional, default=0 us Exponential decay constant. Returns ------- phased Dataset. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x'. Specify on which dimension to apply the phase. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. inv : bool, keyword parameter, optional, default=False. True for inverse phasing. inplace : bool, keyword parameter, optional, default=False. True if we make the transform inplace. If False, the function return a new dataset. See Also -------- ps : Linear Phase Correction pk : Automatic or manual phasing """ return pk(dataset, phc0=phc0, phc1=0, pivot=pivot, exptc=exptc) # # TODO: work on pk (below a copy from MASAI) # @_phase_method # def _apk(source=None, options='', axis=-1): # """ # Automatic or manual phasing # # Parameters # ---------- # fit_phc1: bool, optional, default=False # also optimize first order phase if True # mode: String, optional, default='negmin' # method for automatic phase detection: 'negmin', 'entropy', ... # entropyd: int, optional, default=2 # order of derivation for method entropy # gamma: float, optional # relative weigth for method entropy error with respect to negmin # axis: optional, default=-1 # # """ # # options evaluation # parser = argparse.ArgumentParser(description='PK processing.', usage=""" # pk [-h] [--auto] [--fit_phc1] [--ediff EDIFF] # [--gamma GAMMA] [--select {standard,max,cols}] # [--threshold THRESHOLD] [--mode MODE] # [--optmode {simplex,hopping}] # [--bound_phc0 BOUND_PHC0] [--bound_phc1 BOUND_PHC1] # [--verbose] # [phases [phases ...]] # """) # # global data, par, interact # # phc0 = None # phc1 = None # # # positional arguments # parser.add_argument('phases', default=(phc0, phc1), nargs='*', type=float, help='zero and first order phase') # parser.add_argument('--pivot', '-pv', default=None, type=float, help='pivot position in spectral units') # parser.add_argument('--interactive', '-i', default=None, nargs='*', # help='Interative mode on selected section here to check phase') # parser.add_argument('--pos', default=(0,), nargs='*', type=float, # help='row or column position where to check phase') # parser.add_argument('--shifted', default=0.0, type=float, help="position of the top in units of time") # parser.add_argument('--exp', '-ex', action='store_true', help='perform an exponential phase correction') # parser.add_argument('--auto', '-a', action='store_true', help='set to automatic phase mode') # parser.add_argument('--fit_phc1', '-u1', action='store_true', help='use phc1 in automatic phasing', ) # parser.add_argument('--ediff', '-ef', default=1, type=int, # help='order of the derivative for entropy calculation', ) # parser.add_argument('--gamma', '-ga', default=1.0, type=float, help='weight', ) # parser.add_argument('--select', '-st', default='standard', choices=['standard', 'max', 'cols', 'pos'], # help='selection mode in automatic phasing', ) # parser.add_argument('--threshold', '-th', default=50.0, type=int, # help='default threshold for columns selection', ) # parser.add_argument('--mode', '-m', default='negmin+entropy', help="position of the top in units of time") # parser.add_argument('--optmode', '-om', default='simplex', choices=['simplex', 'hopping'], # help="method of optimisation") # parser.add_argument('--bound_phc0', '-bp0', default=360., type=float, help="phc0 boundary") # parser.add_argument('--bound_phc1', '-bp1', default=10., type=float, help="phc1 boundary") # parser.add_argument('--byrow', '-br', action='store_true', help='to phase each row separately for series or 2D') # parser.add_argument('--verbose', action='store_true', help='verbose flag') # # parser.add_argument('--absolute', action='store_true', help='absolute flag: take the absolute value of phases') # # args = parser.parse_args(options.split()) # # if not source: # return # # if source: # # if axis == -1 or axis == 1: # par = source.par # else: # par = source.par2 # # if not par.isfreq: # print('This source is not already transformed: are you sure this is what you want?') # # # set data depending on the axis # # data = source.data # if axis == 0: # # transpose temporarily the data for indirect dimension ft # data = data.T # # # get initial phase and pivot # # get the initial phase setting # if DEBUG: # print('Current phases for axis %d : %f,%f' % (axis, par.PHC0, par.PHC1)) # # phc0, phc1 = args.phases # # if phc0 is None and phc1 is None: # # phase were not given, read stored phase # args.phases = phc0, phc1 = par.PHC0, par.PHC1 # # # relative phases # phc0, phc1 = phc0 - par.PHC0, phc1 - par.PHC1 # # # absolute phases # par.PHC0, par.PHC1 = args.phases # # # phases to apply # args.phases = phc0, phc1 # # # read pivot # ppivot = args.pivot # if ppivot is None: # ppivot = par.pivot # par.pivot = ppivot # # # we need to transform into index # pivot = position2index(data, ppivot) # args.pivot = pivot # # if DEBUG: # print('Phases demanded for axis %d : %f,%f with pivot: %f' % (axis, par.PHC0, par.PHC1, ppivot)) # print('Actual phases for axis %d to apply: %f,%f with pivot: %f' % (axis, phc0, phc1, ppivot)) # # sw = source.par.SW_h # p_shifted = args.shifted = 0.360 * args.shifted * sw # time are in ms # # # if the correction is exponential we need a second parameter tc=phc1 # if args.exp: # args.fit_phc1 = True # # # INTERACTIVE MODE --------------------- # if args.interactive is not None: # # if DEBUG: # print('INTERACTIVE PHASING MODE') # # interact = args.interactive # if interact == []: # interact = ['0'] # # # interactive phasing # # ps0, ps1 = par.PHC0, par.PHC1 # # def phasing(ph0, ph1, pivot): # # global interact # # # set data depending on the axis # data = source.data.copy() # if axis == 0: # # transpose temporarily the data for indirect dimension ft # data = data.T # # if axis == -1 or axis == 1: # par = source.par # else: # par = source.par2 # # p0 = (ph0 - ps0) * np.pi / 180. # convert to radians # p1 = (ph1 - ps1) * np.pi / 180. # # size = data.shape[-1] # pivot_ = position2index(data, pivot) # apod = np.exp(1.0j * (p0 + (p1 * (np.arange(size) - pivot_) / size))) # data = apod * data # fig = pl.figure(figsize=(4, 2)) # ax = fig.add_subplot(1, 1, 1) # ax.set_xlim((data.columns.max(), data.columns.min())) # # if interact[0] == 'max': # i, j = np.unravel_index(np.abs(data.values).argmax(), data.values.shape) # # dat = data.values[i] # dat = getsection(data, i, width=1., axis=0) # ax.plot(data.columns, dat.values) # else: # for item in interact: # pos = float(item) # i = position2index(data.T, pos) # index of a row # dat = data.values[i] # ax.plot(data.columns, dat) # # ax.axvline(pivot, color='r', lw='.1') # ax.axhline(0, color='g', lw='.1') # pl.show() # # print('ph0: {} ph1: {} pivot: {} (PHC0: {}'.format(ph0, ph1, pivot, # par.PHC0) + '\nWARNING THESE PHASE VALUES ARE NOT ' # STORED IN THE SOURCE!' + '\nSo you must ' # 'use them in ' # 'another `pk` ' # 'command)') # # w = interactive(phasing, # ph0=FloatSlider(min=ps0 - 45, max=ps0 + 45, step=0.001, value=ps0, continuous_update=False), # ph1=FloatSlider(min=ps1 - 180, max=ps1 + 180, step=0.01, value=ps1, continuous_update=False), # pivot=FloatSlider(min=data.columns.min(), max=data.columns.max(), step=0.001, value=ppivot, # continuous_update=False)) # # output = w.children[-1] # display(w) # # return w # # # Manual mode ------------------------------ # # elif not args.auto: # # if DEBUG: # print('MANUAL PHASE MODE') # # # not interactive and not automatic leaves here... # data = ps(data.values, phc0, phc1 + p_shifted, pivot=pivot, # is_exp=args.exp) # this return an array not a dataframe # source.history.append('Manual phasing phc0:%.2f, phc1:%.2f, pivot:%.2f ' % (par.PHC0, par.PHC1, par.pivot)) # # # Automatic mode ------------------------------ # else: # if DEBUG: # print('AUTOMATIC PHASE MODE') # # # APK... # if args.select == 'cols' and source.is_2d and axis == 0: # ar = picking(source, args.threshold, index=True) # args.cols = zip(*ar)[1] # # if args.byrow and source.is_2d: # rows = [] # for index in range(data.index.size): # row = data.iloc[index:index + 1].values # row, phc0, phc1 = autophase(row, args) # row = row - basecorr(row) # rows.append(row) # # merge all rows to recreate data # data = np.vstack(rows) # else: # data, phc0, phc1 = autophase(data.values, args, par) # return an array not a dataframe # # atxt = '(not optimized)' if not args.fit_phc1 else '' # # sbyrow = 'byrow' if args.byrow else '' # source.history.append( # 'Auto-phasing %s: phc0 = %.3f, phc1%s = %.3f, pivot:%.2f' % (sbyrow, phc0, atxt, phc1, pivot)) # # store the new phases # par.PHC0, par.PHC1 = phc0, phc1 # # try: # data = data - basecorr(data) # except Exception: # pass # # # un-transpose the data if needed # if axis == 0: # data = data.T # # source.data = data # # # # # # autophase # # # def _checkin(ph, bp): # if ph < -bp: # ph = -bp # if ph > bp: # ph = bp # return ph # # # def _autophase(data, args, par): # """ # Automatic phasing of 1D or 2D spectra # """ # # dat = data.copy() # # # get parameters # # -------------- # phc0, phc1 = args.phases # pivot = args.pivot # is_exp = args.exp # verbose = args.verbose # # if DEBUG: # print('performing autophase') # # select = args.select # # if select == 'standard' or data.shape[0] == 1: # # select the first row # dat = dat[0] # select = 'standard' # # if select == 'max' and data.ndim > 1: # i, j = np.unravel_index(data.real.argmax(), data.shape) # dat = data[i] # # if select == 'cols' and data.ndim > 1: # l = [] # cols = args.cols # if verbose: # print('columns selected:', cols) # for col in cols: # i = int(col) # l.append(data[i]) # dat = np.vstack(l) # # # apkmode # # -------- # if DEBUG: # print('\nselect: ', select) # # mode = args.mode # ediff = args.ediff # gamma = args.gamma # optmode = args.optmode # p_shifted = args.shifted # # prepare the phase to optimized with bound # fp = FitParameters() # bp0 = args.bound_phc0 # bp1 = args.bound_phc1 # phc0 = _checkin(phc0, bp0) # # fixed is false # fp['phc0'] = phc0, -bp0, bp0, False # # fit_phc1 = args.fit_phc1 # phc1 = _checkin(phc1, bp1) # fixed = not fit_phc1 # fp['phc1'] = phc1, -bp1, bp1, fixed # # # optim # global ni, nas, spe, err, niter # ni = 0 # err = 0 # niter = 0 # # # internal error function ---------------------------------------------------------------------------------- # def _phase_error(p, s): # # global nas, spe, ni, err # # p0 = p['phc0'] # p1 = p['phc1'] # sc = s.copy() # sc = ps(sc, p0, p1 + p_shifted, pivot=pivot, is_exp=is_exp) # # # baseline correction # scp = sc - basecorr(sc) # # # Negative area minimization # nas = 0. # nam = 0. # if "negmin" in mode: # fm = scp[scp.real <= 0].real # fm = fm - np.min(fm) # nas = np.sum(fm ** 2) # # # normalisation # fp = scp.real # fp = fp - np.min(fm) # nas = nas * 100. / (np.sum(fp ** 2) + 1.e-30) # # # entropy minimization # spe = 0. # if 'entropy' in mode: # h = np.diff(scp.real, ediff) # h = np.abs(h) # h = abs(h / np.sum(np.abs(h))) + 1.e-30 # spe = -np.sum(h * np.log(h)) # ni += 1 # err = nas + spe * gamma # # return err # # # end _phase_error function ------------------------------------------------------------------------------------- # # # callback function-------------------------------------------------------- # def callback(x, f=None, accepted=None): # """ # callback print function # """ # global niter, err # return # # if f is not None: # hopping # pass # if f is None: # simplex # # display.clear_output(wait=True) # # msg = ("Iteration: %d (chi2: %.5f)" % (niter, err) + # ' Negative area (NA):%.3g Entropy (S) * gamma:%.3g' % ( # nas, spe * gamma)) # auto_close_message(msg, title='Information', time=.001) # # niter += 1 # # # end callback function --------------------------------------------------- # # # convergence is not insured depending on the starting values # fp, err1 = optimize(_phase_error, fp, args=[dat, ], method=optmode, callback=None) # nas_save = nas # spe_save = spe # fp_save = fp.copy() # # if optmode.upper() != 'HOPPING': # fp['phc0'] = (fp['phc0'] - 180.0) % 360.0, -bp0, bp0, False # ni = 0 # fp, err2 = optimize(_phase_error, fp, args=(dat,), method=optmode, callback=callback) # # # select the best # if err2 > err1: # fp = fp_save.copy() # nas = nas_save # spe = spe_save # # # extract results # phc0 = fp['phc0'] # phc1 = fp['phc1'] # # if verbose: # print('Phase:') # # if fit_phc1: # if verbose: # print('phc0: %.3f' % phc0) # print('phc1: %.3f' % phc1) # else: # if verbose: # print('phc0: %.3f' % phc0) # print('phc1: %.3f (not optimized)' % phc1) # # if verbose: # print('Negative area (NA):%.3g Entropy (S) * gamma:%.3g' % (nas, spe * gamma)) # # # apply to the original data and return # data = pk(data, phc0, phc1 + p_shifted, pivot=pivot, is_exp=is_exp) # return data, phc0, phc1 <file_sep>/docs/userguide/processing/transformations.py # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # Basic transformations # Let's show some SpectroChemPy features on a group of IR spectra # %% from spectrochempy import * # %% dataset = NDDataset.read_omnic('irdata/nh4y-activation.spg') dataset.y -= dataset.y[0] dataset.y.title = 'Time' dataset # %% prefs = dataset.preferences prefs.figure.figsize = (6, 3) prefs.colormap = 'Dark2' prefs.colorbar = True ax = dataset.plot() # %% [markdown] # ## Masking data # %% [markdown] # if we try to get for example the maximum of this dataset, we face a problem due to the saturation around # 1100 cm$^{-1}$. # %% dataset.max() # %% [markdown] # One way is to apply the max function to only a part of the spectrum (using [slicing](slicing)). Another way is to # mask the undesired data. # # Masking values in this case is straigthforward. Just set a value `masked` or True for those data you want to mask. # %% dataset[:, 1290.:890.] = MASKED # note that we specify floating values in order to sect wavenumbers, not index. # %% [markdown] # Here is a display the figure with the new mask # %% _ = dataset.plot_stack() # %% [markdown] # Now the max function return the maximum in the unmasked region, which is exactly what we wanted. # %% dataset.max() # %% [markdown] # To clear this mask, we can simply do: # %% dataset.remove_masks() _ = dataset.plot() # %% [markdown] # ## Transposition # %% [markdown] # Dataset can be transposed # %% dataset[:, 1290.:890.] = MASKED # we mask the unwanted colomns datasetT = dataset.T datasetT # %% [markdown] # As it can be observed the dimension `x`and `y`have been exchanged, *e.g.* the originalshape was **(x: 5549, y: 55)**, # and after transposition it is **(y:55, x:5549)**. # (the dimension names stay the same, but the index of the corresponding axis are exchanged). # %% [markdown] # Let's vizualize the result: # %% _ = datasetT.plot() # %% [markdown] # ## Changing units # %% [markdown] # Units of the data and coordinates can be changed, but only towards compatible units. For instance, data are in # absorbance units, which are dimensionless (**a.u**). So a dimensionless units such as **radian** is allowed, # even if in this case it maks very little sense. # %% dataset.units = 'radian' # %% _ = dataset.plot() # %% [markdown] # Trying to change it in 'meter' for instance, will generate an error! # %% try: dataset.to('meter') except DimensionalityError as e: error_(e) # %% [markdown] # If this is for some reasons something you want to do, you must for the change: # %% d = dataset.to('meter', force=True) print(d.units) # %% [markdown] # When units are compatible there is no problem to modify it. For instance, we can change the `y` dimension units ( # Time) to hours. Her we use the inplace transformation `ito`. # %% dataset.y.ito('hours') _ = dataset.plot() # %% [markdown] # See [Units and Quantities](../units/index.ipynb) for more details on these units operations <file_sep>/docs/userguide/introduction/introduction.py # --- # jupyter: # jupytext: # cell_metadata_json: true # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] {"slideshow": {"slide_type": "slide"}} # # Introduction # # The **SpectroChemPy** project was developed to provide advanced tools for processing and # analyzing spectroscopic data, initially for internal purposes in the # [LCS (https://www.lcs.ensicaen.fr)](https://www.lcs.ensicaen.fr). # # **SpectroChemPy** is essentially a library written in python language and which proposes objects (`NDDataset`, and # `Project`) to contain data, equipped with methods to analyze, transform or display # this data in a simple way by the user. # # The processed data are mainly spectroscopic data from techniques such as IR, Raman or NMR, but they are not limited # to this type of application, as any type of numerical data arranged in tabular form can generally serve as the main # input. # %% [markdown] {"slideshow": {"slide_type": "slide"}} # ## How to get started # # <div class='alert alert-info'> # <b>Note</b> # # We assume that the SpectroChemPy package has been correctly # installed. if is not the case, please go to [SpectroChemPy installation # procedure](../../gettingstarted/install/index.rst). # </div> # %% [markdown] {"nbsphinx-toctree": {"maxdepth": 3}, "slideshow": {"slide_type": "subslide"}} # [interface](interface.ipynb) # %% [markdown] {"slideshow": {"slide_type": "slide"}} # ## Loading the API # # Before using SpectroChemPy, we need to load the **API (Application Programming Interface)**: it exposes many # objects and functions. # # To load the API, you must import it using one of the following syntax. # # In the first syntax we load the library into a namespace called `scp` (you can choose whatever you want - except # something already in use): # %% import spectrochempy as scp # SYNTAX 1 nd = scp.NDDataset() # %% [markdown] # or in the second syntax, with a wild `*` import. # %% from spectrochempy import * nd = NDDataset() # %% [markdown] # With the second syntax, as often in python, the access to objects/functions can be greatly simplified. For example, # we can use "NDDataset" without a prefix instead of `scp.NDDataset` which is the first syntax) but there is always a # risk of overwriting some variables or functions already present in the namespace. # Therefore, the first syntax is generally highly recommended. # # Alternatively, you can also load only the onbjects and function required by your application: # # %% from spectrochempy import NDDataset nd = NDDataset() # %% [markdown] # If something goes wrong with during a cell execution, a ``traceback`` is displayed. # # For instance, the object or method ``toto`` does not exist in the API, so an error (**ImportError**) is generated # when trying to import this from the API. # # Here we catch the error with a conventional `try-except` structure # %% try: from spectrochempy import toto except ImportError as e: scp.error_("OOPS, THAT'S AN IMPORT ERROR! : %s" % e) # %% [markdown] # The error will stop the execution if not catched. # # This is a basic behavior of python : on way to avoid. stoppping the execution without displaying a message is : # %% try: from spectrochempy import toto # noqa: F811, F401 except Exception: pass # %% [markdown] # ## API Configuration # # Many options of the API can be set up # %% scp.set_loglevel(scp.INFO) # %% [markdown] # In the above cell, we have set the **log** level to display ``info`` messages, such as this one: # %% scp.info_('this is an info message!') scp.debug_('this is a debug message!') # %% [markdown] # Only the info message is displayed, as expected. # # If we change it to ``DEBUG``, we should get the two messages # %% scp.set_loglevel(scp.DEBUG) scp.info_('this is an info message!') scp.debug_('this is a debug message!') # %% [markdown] # Let's now come back to a standard level of message for the rest of the Tutorial. # %% scp.set_loglevel(scp.WARNING) scp.info_('this is an info message!') scp.debug_('this is a debug message!') # %% [markdown] # Many other configuration items will be further described when necessary in the other chapters. # %% [markdown] # ## Units # %% [markdown] # The objets **ur**, **Quantity** allows the manipulation of data with units, thanks to pint. (see [Units and # Quantities](../units/index.ipynb)) # # * **ur**: the unit registry # * **Quantity**: a scalar or an array with some units # %% from spectrochempy import ur # to simplify further writting ur.cm / ur.s # %% x = scp.Quantity(10., ur.cm / ur.s) x * 2. # %% import numpy as np xa = scp.Quantity(np.array((1, 2)), 'km') xa[1] * 2.5 # %% [markdown] # ## NDDataset, the main object # %% [markdown] # NDDataset is a python object, actually a container, which can represent most of your multidimensional spectroscopic # data. # # For instance, in the following we read data from a series of FTIR experiments, provided by the OMNIC software: # %% import os nd = NDDataset.read_omnic(os.path.join('irdata', 'nh4y-activation.spg')) # %% [markdown] # Note that for this example, we use data stored in a ``test`` directory. For your own usage, you probably have to # give the full pathname (see ... for the way to overcome this using `preferences` setting) # %% [markdown] # ### Display dataset information # %% [markdown] # Several ways are available to display the data we have jsut read and that are now stored in the dataset # # * **Printing** them, using the print function of python to get a short text version of the dataset information. # %% print(nd) # %% [markdown] # A much Longer (and colored) information text can be obtained using the spectrochempy provided ``print_`` function. # %% scp.print_(nd) # %% [markdown] # * **Displaying html**, inside a jupyter notebook, by just typing the name of the dataset (must be the last # instruction of a cell, however!) # %% nd # %% [markdown] # ### Plotting a dataset # # First, we can set some general plotting preferences for this dataset # %% prefs = nd.preferences prefs.reset() prefs.figure.figsize = (6, 3) # %% [markdown] # Let's plot first a 1D spectrum (for instance one row of nd) # %% row = nd[-1] _ = row.plot() # %% [markdown] # or a column ... # %% col = nd[:, 3500.] # note the indexing using wavenumber! _ = col.plot_scatter() # %% [markdown] # 2D plots can be also generated as stacked plot # %% _ = nd.plot(method='stack') # or nd.plot_stack() # %% [markdown] # or as an image plot: # %% prefs.colormap = 'magma' _ = nd.plot(method='image') # or nd.plot_image() # %% [markdown] # Note that as we plot wavenumbers as abcissa, by convention the coordinates direction is reversed. # # This can be changed by using the keyword argument `reversed = False`. # %% [markdown] # ### Processing a dataset # %% [markdown] # Some arithmetic can be performed on such dataset. Here is an example where we subtract one reference spectrum to # the whole nddataset that we have read above (`nd`). # %% [markdown] # Lets take, e.g., the last row as reference # %% ref = nd[0] _ = ref.plot() # %% [markdown] # Now suppress this ref spectrum to all other spectra of the whole dataset (additionally we mask the region of # saturation # %% prefs.colormap = 'jet' prefs.colorbar = True nds = nd - ref nds[:, 1290.:890.] = scp.MASKED _ = nds.plot_stack() # %% [markdown] # More details on available on available processing and analysis function will be given later in this user guide. # %% [markdown] # This was a short overview of the possibilities. To go further you can **Continue with ...** # %% [markdown] {"nbsphinx-toctree": {"maxdepth": 3}} # [Data structures](../objects.rst) <file_sep>/spectrochempy/core/analysis/mcrals.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements the MCRALS class. """ __all__ = ['MCRALS'] __dataset_methods__ = [] import numpy as np from traitlets import HasTraits, Instance, Dict, Unicode # from collections.abc import Iterable from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.analysis.pca import PCA from spectrochempy.core.dataset.npy import dot from spectrochempy.core import info_, set_loglevel, INFO class MCRALS(HasTraits): """ Performs MCR-ALS of a dataset knowing the initial C or St matrix. """ _X = Instance(NDDataset) _C = Instance(NDDataset, allow_none=True) _extC = Instance(NDDataset, allow_none=True) _extOutput = Instance(NDDataset, allow_none=True) _St = Instance(NDDataset, allow_none=True) _logs = Unicode _params = Dict() def __init__(self, dataset, guess, **kwargs): # lgtm [py/missing-call-to-init] """ Parameters ---------- dataset : |NDDataset| The dataset on which to perform the MCR-ALS analysis guess : |NDDataset| Initial concentration or spectra verbose : bool If set to True, prints a summary of residuals and residuals change at each iteration. default = False. In any case, the same information is returned in self.logs **kwargs : dict Optimization parameters : See Other Parameters. Other Parameters ---------------- tol : float, optional, default=0.1 Convergence criterion on the change of resisuals. (percent change of standard deviation of residuals). maxit : int, optional, default=50 Maximum number of ALS minimizations. maxdiv : int, optional, default=5. Maximum number of successive non-converging iterations. nonnegConc : list or tuple, default=Default [0, 1, ...] (only non-negative concentrations) Index of species having non-negative concentration profiles. For instance [0, 2] indicates that species #0 and #2 have non-negative conc profiles while species #1 can have negative concentrations. unimodConc : list or tuple, Default=[0, 1, ...] (only unimodal concentration profiles) index of species having unimodal concentrationsprofiles. closureConc : list or tuple, Default=None (no closure) Index of species subjected to a closure constraint. extConc: list or tuple, Default None (no external concentration). Index of species for which a concentration profile is provided by an external function. getExtlConc : callable An external function that will provide `n_ext` concentration profiles: getExtConc(C, extConc, ext_to_C_idx, *args) -> extC or getExtConc(C, extConc, ext_to_C_idx, *args) -> (extC, out2, out3, ...) where C is the current concentration matrix, *args are the parameters needed to completely specify the function, extC is a nadarray or NDDataset of shape (C.y, n_ext), and out1, out2, ... are supplementary outputs returned by the function (e.g. optimized rate parameters) args : tuple, optional. Extra arguments passed to the external function external_to_C_idx : array or tuple, Default=np.arange(next) Indicates the correspondence between the indexes of external chemical profiles and the columns of the C matrix. [1, None, 0] indicates that the first external profile is the second pure species (index 1). nonnegSpec : list or tuple, Default [1, ..., 1] (only non-negative spectra) Indicates species having non-negative spectra unimodSpec : list or tuple, Default [0, ..., 0] (no unimodal concentration profiles) Indicates species having unimodal spectra """ verbose = kwargs.pop('verbose', False) if verbose: set_loglevel(INFO) # Check initial data # ------------------------------------------------------------------------ initConc, initSpec = False, False if type(guess) is np.ndarray: guess = NDDataset(guess) X = dataset if X.shape[0] == guess.shape[0]: initConc = True C = guess.copy() C.name = 'Pure conc. profile, mcs-als of ' + X.name nspecies = C.shape[1] elif X.shape[1] == guess.shape[1]: initSpec = True St = guess.copy() St.name = 'Pure spectra profile, mcs-als of ' + X.name nspecies = St.shape[0] else: raise ValueError('the dimensions of initial concentration ' 'or spectra dataset do not match the data') ny, nx = X.shape # makes a PCA with same number of species Xpca = PCA(X).reconstruct(n_pc=nspecies) # Get optional parameters in kwargs or set them to their default # ------------------------------------------------------------------------ # TODO: make a preference file to set this kwargs # optimization tol = kwargs.get('tol', 0.1) maxit = kwargs.get('maxit', 50) maxdiv = kwargs.get('maxdiv', 5) # constraints on concentrations nonnegConc = kwargs.get('nonnegConc', np.arange(nspecies)) unimodConc = kwargs.get('unimodConc', np.arange(nspecies)) unimodTol = kwargs.get('unimodTol', 1.1) unimodMod = kwargs.get('unimodMod', 'strict') closureConc = kwargs.get('closureConc', None) if closureConc is not None: closureTarget = kwargs.get('closureTarget', np.ones(ny)) closureMethod = kwargs.get('closureMethod', 'scaling') monoDecConc = kwargs.get('monoDecConc', None) monoDecTol = kwargs.get('monoDecTol', 1.1) monoIncConc = kwargs.get('monoIncConc', None) monoIncTol = kwargs.get('monoIncTol', 1.1) externalConc = kwargs.get('externalConc', None) if externalConc is not None: external_to_C_idx = kwargs.get('external_to_C_idx', np.arange(nspecies)) if externalConc is not None: try: getExternalConc = kwargs.get('getExternalConc') except Exception: raise ValueError('A function must be given to get the external concentration profile(s)') external_to_C_idx = kwargs.get('external_to_C_idx', externalConc) args = kwargs.get('args', ()) # constraints on spectra nonnegSpec = kwargs.get('nonnegSpec', np.arange(nspecies)) normSpec = kwargs.get('normSpec', None) # TODO: add unimodal constraint on spectra # Compute initial spectra or concentrations (first iteration...) # ------------------------------------------------------------------------ if initConc: if C.coordset is None: C.set_coordset(y=X.y, x=C.x) St = NDDataset(np.linalg.lstsq(C.data, X.data, rcond=None)[0]) St.name = 'Pure spectra profile, mcs-als of ' + X.name St.title = X.title cy = C.x.copy() if C.x else None cx = X.x.copy() if X.x else None St.set_coordset(y=cy, x=cx) if initSpec: if St.coordset is None: St.set_coordset(y=St.y, x=X.x) Ct = np.linalg.lstsq(St.data.T, X.data.T, rcond=None)[0] C = NDDataset(Ct.T) C.name = 'Pure conc. profile, mcs-als of ' + X.name C.title = 'Concentration' cx = St.y.copy() if St.y else None cy = X.y.copy() if X.y else None C.set_coordset(y=cy, x=cx) change = tol + 1 stdev = X.std() # .data[0] niter = 0 ndiv = 0 logs = '*** ALS optimisation log***\n' logs += '#iter Error/PCA Error/Exp %change\n' logs += '---------------------------------------------------' info_(logs) while change >= tol and niter < maxit and ndiv < maxdiv: C.data = np.linalg.lstsq(St.data.T, X.data.T, rcond=None)[0].T niter += 1 # Force non-negative concentration # -------------------------------- if nonnegConc is not None: for s in nonnegConc: C.data[:, s] = C.data[:, s].clip(min=0) # Force unimodal concentration # ---------------------------- if unimodConc is not None: for s in unimodConc: maxid = np.argmax(C.data[:, s]) curmax = C.data[maxid, s] curid = maxid while curid > 0: curid -= 1 if C.data[curid, s] > curmax * unimodTol: if unimodMod == 'strict': C.data[curid, s] = C.data[curid + 1, s] if unimodMod == 'smooth': C.data[curid, s] = (C.data[curid, s] + C.data[ curid + 1, s]) / 2 C.data[curid + 1, s] = C.data[curid, s] curid = curid + 2 curmax = C.data[curid, s] curid = maxid while curid < ny - 1: curid += 1 if C.data[curid, s] > curmax * unimodTol: if unimodMod == 'strict': C.data[curid, s] = C.data[curid - 1, s] if unimodMod == 'smooth': C.data[curid, s] = (C.data[curid, s] + C.data[ curid - 1, s]) / 2 C.data[curid - 1, s] = C.data[curid, s] curid = curid - 2 curmax = C.data[curid, s] # Force monotonic increase # ------------------------ if monoIncConc is not None: for s in monoIncConc: for curid in np.arange(ny - 1): if C.data[curid + 1, s] < C.data[curid, s] / monoIncTol: C.data[curid + 1, s] = C.data[curid, s] # Force monotonic decrease # ---------------------------------------------- if monoDecConc is not None: for s in monoDecConc: for curid in np.arange(ny - 1): if C.data[curid + 1, s] > C.data[curid, s] * monoDecTol: C.data[curid + 1, s] = C.data[curid, s] # Closure # ------------------------------------------ if closureConc is not None: if closureMethod == 'scaling': Q = np.linalg.lstsq(C.data[:, closureConc], closureTarget.T, rcond=None)[0] C.data[:, closureConc] = np.dot(C.data[:, closureConc], np.diag(Q)) elif closureMethod == 'constantSum': totalConc = np.sum(C.data[:, closureConc], axis=1) C.data[:, closureConc] = C.data[:, closureConc] * closureTarget[:, None] / totalConc[:, None] # external concentration profiles # ------------------------------------------ if externalConc is not None: extOutput = getExternalConc(*((C, externalConc, external_to_C_idx,) + args)) if isinstance(extOutput, dict): extC = extOutput['concentrations'] args = extOutput['new_args'] else: extC = extOutput if type(extC) is NDDataset: extC = extC.data C.data[:, externalConc] = extC[:, external_to_C_idx] # stores C in C_hard and recompute C for consistency (soft modeling) # Chard = C.copy() # TODO: not used? C.data = np.linalg.lstsq(St.data.T, X.data.T, rcond=None)[0].T St.data = np.linalg.lstsq(C.data, X.data, rcond=None)[0] # stores St in Stsoft # Stsoft = St.copy() # TODO: not used? # Force non-negative spectra # -------------------------- if nonnegSpec is not None: St.data[nonnegSpec, :] = St.data[nonnegSpec, :].clip(min=0) # rescale spectra & concentrations if normSpec == 'max': alpha = np.max(St.data, axis=1).reshape(nspecies, 1) St.data = St.data / alpha C.data = C.data * alpha.T elif normSpec == 'euclid': alpha = np.linalg.norm(St.data, axis=1).reshape(nspecies, 1) St.data = St.data / alpha C.data = C.data * alpha.T # compute residuals # ----------------- X_hat = dot(C, St) stdev2 = (X_hat - X.data).std() change = 100 * (stdev2 - stdev) / stdev stdev_PCA = (X_hat - Xpca.data).std() # TODO: Check PCA : values are different from the Arnaud version ? logentry = '{:3d} {:10f} {:10f} {:10f}'.format(niter, stdev_PCA, stdev2, change) logs += logentry + '\n' info_(logentry) stdev = stdev2 if change > 0: ndiv += 1 else: ndiv = 0 change = -change if change < tol: logentry = 'converged !' logs += logentry + '\n' info_(logentry) if ndiv == maxdiv: logline = f"Optimization not improved since {maxdiv} iterations... unconverged " \ f"or 'tol' set too small ?\n" logline += 'Stop ALS optimization' logs += logline + '\n' info_(logline) if niter == maxit: logline = 'Convergence criterion (\'tol\') not reached after {:d} iterations.'.format(maxit) logline += 'Stop ALS optimization' logs += logline + '\n' info_(logline) self._X = X self._params = kwargs self._C = C if externalConc is not None: self._extC = extC self._extOutput = extOutput else: self._extC = None self._extOutput = None self._St = St self._logs = logs # self._Stsoft = Stsoft # self._Chard = Chard @property def X(self): """ The original dataset. """ return self._X @property def extC(self): """ The last concentration profiles including external profiles. """ return self._extC @property def extOutput(self): """ The last output of the external function used to get. """ return self._extOutput @property def C(self): """ The final concentration profiles. """ return self._C @property def St(self): """ The final spectra profiles. """ return self._St @property def params(self): """ the parameters used to perform the MCR als. """ return self._params @property def logs(self): """ Logs output. """ return self._logs def reconstruct(self): """ Transform data back to the original space. The following matrice operation is performed : :math:`X'_{hat} = C'.S'^t` Returns ------- X_hat : |NDDataset| The reconstructed dataset based on the MCS-ALS optimization. """ # reconstruct from concentration and spectra profiles C = self.C St = self.St X_hat = dot(C, St) X_hat.history = 'Dataset reconstructed by MCS ALS optimization' X_hat.title = 'X_hat: ' + self.X.title return X_hat def plotmerit(self, **kwargs): """ Plots the input dataset, reconstructed dataset and residuals Returns ------- ax subplot """ colX, colXhat, colRes = kwargs.get('colors', ['blue', 'green', 'red']) X_hat = self.reconstruct() res = self.X - X_hat ax = self.X.plot() if self.X.x is not None: ax.plot(self.X.x.data, X_hat.T.data, color=colXhat) ax.plot(self.X.x.data, res.T.data, color=colRes) else: ax.plot(X_hat.T.data, color=colXhat) ax.plot(res.T.data, color=colRes) ax.autoscale(enable=True) ax.set_title('MCR ALS merit plot') return ax <file_sep>/spectrochempy/core/dataset/coord.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, # Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in # the root directory = # ====================================================================================================================== """ This module implements the class |Coord|. """ __all__ = ['Coord', 'LinearCoord'] import textwrap from traitlets import Bool, observe, All, Unicode, Integer from spectrochempy.core.dataset.ndarray import NDArray from spectrochempy.core.dataset.ndmath import NDMath, _set_operators from spectrochempy.utils import colored_output, NOMASK from spectrochempy.units import Quantity, ur # ====================================================================================================================== # Coord # ====================================================================================================================== class Coord(NDMath, NDArray): _copy = Bool() _html_output = False _parent_dim = Unicode(allow_none=True) # ------------------------------------------------------------------------------------------------------------------ # initialization # ------------------------------------------------------------------------------------------------------------------ def __init__(self, data=None, **kwargs): """ Explicit coordinates for a dataset along a given axis. The coordinates of a |NDDataset| can be created using the |Coord| object. This is a single dimension array with either numerical (float) values or labels (str, `Datetime` objects, or any other kind of objects) to represent the coordinates. Only a one numerical axis can be defined, but labels can be multiple. Parameters ----------- data : ndarray, tuple or list The actual data array contained in the |Coord| object. The given array (with a single dimension) can be a list, a tuple, a |ndarray|, or a |ndarray|-like object. If an object is passed that contains labels, or units, these elements will be used to accordingly set those of the created object. If possible, the provided data will not be copied for `data` input, but will be passed by reference, so you should make a copy the `data` before passing it in the object constructor if that's the desired behavior or set the `copy` argument to True. **kwargs See other parameters Other Parameters ---------------- dtype : str or dtype, optional, default=np.float64 If specified, the data will be casted to this dtype, else the type of the data will be used dims : list of chars, optional. if specified the list must have a length equal to the number od data dimensions (ndim) and the chars must be taken among among x,y,z,u,v,w or t. If not specified, the dimension names are automatically attributed in this order. name : str, optional A user friendly name for this object. If not given, the automatic `id` given at the object creation will be used as a name. labels : array of objects, optional Labels for the `data`. labels can be used only for 1D-datasets. The labels array may have an additional dimension, meaning several series of labels for the same data. The given array can be a list, a tuple, a |ndarray|, a ndarray-like, a |NDArray| or any subclass of |NDArray|. units : |Unit| instance or str, optional Units of the data. If data is a |Quantity| then `units` is set to the unit of the `data`; if a unit is also explicitly provided an error is raised. Handling of units use the `pint <https://pint.readthedocs.org/>`_ package. title : str, optional The title of the dimension. It will later be used for instance for labelling plots of the data. It is optional but recommended to give a title to each ndarray. dlabel : str, optional. Alias of `title`. meta : dict-like object, optional. Additional metadata for this object. Must be dict-like but no further restriction is placed on meta. copy : bool, optional Perform a copy of the passed object. Default is False. linear : bool, optional If set to True, the coordinate is considered as a ``LinearCoord`` object. See Also -------- NDDataset : Main SpectroChemPy object: an array with masks, units and coordinates. LinearCoord : Implicit linear coordinates. Examples -------- We first import the object from the api : >>> from spectrochempy import Coord We then create a numpy |ndarray| and use it as the numerical `data` axis of our new |Coord| object. >>> c0 = Coord.arange(1., 12., 2., title='frequency', units='Hz') >>> c0 Coord: [float64] Hz (size: 6) We can take a series of str to create a non numerical but labelled axis : >>> tarr = list('abcdef') >>> tarr ['a', 'b', 'c', 'd', 'e', 'f'] >>> c1 = Coord(labels=tarr, title='mylabels') >>> c1 Coord: [labels] [ a b c d e f] (size: 6) """ super().__init__(data=data, **kwargs) if len(self.shape) > 1: raise ValueError('Only one 1D arrays can be used to define coordinates') # .................................................................................................................. def implements(self, name=None): """ Utility to check if the current object implement `Coord`. Rather than isinstance(obj, Coord) use object.implements('Coord'). This is useful to check type without importing the module """ if name is None: return 'Coord' else: return name == 'Coord' # ------------------------------------------------------------------------------------------------------------------ # readonly property # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @property def reversed(self): """bool - Whether the axis is reversed (readonly property). """ if self.units in ['1 / centimeter', 'ppm']: return True return False # Return a correct result only if the data are sorted # return # bool(self.data[0] > self.data[-1]) @property def default(self): # this is in case default is called on a coord, while it is a coordset property return self # ------------------------------------------------------------------------------------------------------------------ # hidden properties (for the documentation, only - we remove the docstring) # some of the property of NDArray has to be hidden because they # are not useful for this Coord class # ------------------------------------------------------------------------------------------------------------------ # NDarray methods # .................................................................................................................. @property def is_complex(self): return False # always real # .................................................................................................................. @property def ndim(self): ndim = super().ndim if ndim > 1: raise ValueError("Coordinate's array should be 1-dimensional!") return ndim # .................................................................................................................. @property def T(self): # no transpose return self # .................................................................................................................. # @property # def values(self): # return super().values # .................................................................................................................. @property def masked_data(self): return super().masked_data # .................................................................................................................. @property def is_masked(self): return False # .................................................................................................................. @property def mask(self): return super().mask # .................................................................................................................. @mask.setter def mask(self, val): # Coordinates cannot be masked. Set mask always to NOMASK self._mask = NOMASK # NDmath methods # .................................................................................................................. def cumsum(self, **kwargs): raise NotImplementedError # .................................................................................................................. def mean(self, **kwargs): raise NotImplementedError # .................................................................................................................. def pipe(self, func=None, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def remove_masks(self, **kwargs): raise NotImplementedError # .................................................................................................................. def std(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def sum(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def swapdims(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def swapaxes(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def squeeze(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def random(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def empty(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def empty_like(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def var(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def ones(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def ones_like(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def full(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def diag(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def diagonal(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def full_like(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def identity(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def eye(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def zeros(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def zeros_like(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def coordmin(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def coordmax(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def conjugate(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def conj(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def abs(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def absolute(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def all(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def any(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def argmax(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def argmin(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def asfortranarray(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def average(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def clip(self, *args, **kwargs): raise NotImplementedError # .................................................................................................................. def get_axis(self, *args, **kwargs): return super().get_axis(*args, **kwargs) # .................................................................................................................. @property def origin(self, *args, **kwargs): return None # .................................................................................................................. @property def author(self): return None # .................................................................................................................. @property def dims(self): return ['x'] # .................................................................................................................. @property def is_1d(self): return True # .................................................................................................................. def transpose(self): return self # ------------------------------------------------------------------------------------------------------------------ # public methods # ------------------------------------------------------------------------------------------------------------------ def loc2index(self, loc): return self._loc2index(loc) # ------------------------------------------------------------------------------------------------------------------ # special methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def __copy__(self): res = self.copy(deep=False) # we keep name of the coordinate by default res.name = self.name return res # .................................................................................................................. def __deepcopy__(self, memo=None): res = self.copy(deep=True, memo=memo) res.name = self.name return res # .................................................................................................................. def __dir__(self): # remove some methods with respect to the full NDArray # as they are not usefull for Coord. return ['data', 'labels', 'units', 'meta', 'title', 'name', 'offset', 'increment', 'linear', 'roi'] # .................................................................................................................. def __getitem__(self, items, return_index=False): # we need to keep the names when copying coordinates to avoid later # problems res = super().__getitem__(items, return_index=return_index) res.name = self.name return res # .................................................................................................................. def __str__(self): return repr(self) # .................................................................................................................. def _cstr(self, header=' coordinates: ... \n', print_size=True, **kwargs): indent = kwargs.get('indent', 0) out = '' if not self.is_empty and print_size: out += f'{self._str_shape().rstrip()}\n' out += f' title: {self.title}\n' if self.title else '' if self.has_data: out += '{}\n'.format(self._str_value(header=header)) elif self.is_empty and not self.is_labeled: out += header.replace('...', '\0Undefined\0') if self.is_labeled: header = ' labels: ... \n' text = str(self.labels.T).strip() if '\n' not in text: # single line! out += header.replace('...', '\0\0{}\0\0'.format(text)) else: out += header out += '\0\0{}\0\0'.format(textwrap.indent(text.strip(), ' ' * 9)) if out[-1] == '\n': out = out[:-1] if indent: out = "{}".format(textwrap.indent(out, ' ' * indent)) first_indent = kwargs.get("first_indent", 0) if first_indent < indent: out = out[indent - first_indent:] if not self._html_output: return colored_output(out) else: return out # .................................................................................................................. def __repr__(self): out = self._repr_value().rstrip() return out # ------------------------------------------------------------------------------------------------------------------ # Events # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @observe(All) def _anytrait_changed(self, change): # ex: change { # 'owner': object, # The HasTraits instance # 'new': 6, # The new value # 'old': 5, # The old value # 'name': "foo", # The name of the changed trait # 'type': 'change', # The event type of the notification, usually # 'change' # } # debug_(f'changes in Coord: {change.name}') if change.name in ['_linear', '_increment', '_offset', '_size']: super()._anytrait_changed(change) class LinearCoord(Coord): _use_time = Bool(False) _show_datapoints = Bool(True) _zpd = Integer def __init__(self, *args, offset=0.0, increment=1.0, **kwargs): """ Linear coordinates. Such coordinates correspond to a ascending or descending linear sequence of values, fully determined by two parameters, i.e., an offset (off) and an increment (inc) : .. math:: \\mathrm{data} = i*\\mathrm{inc} + \\mathrm{off} Parameters ---------- data : a 1D array-like object, optional wWen provided, the `size` parameters is adjusted to the size of the array, and a linearization of the array is performed (only if it is possible: regular spacing in the 1.e5 relative accuracy) offset : float, optional If omitted a value of 0.0 is taken for tje coordinate offset. increment : float, optional If omitted a value of 1.0 is taken for the coordinate increment. Other Parameters ---------------- dtype : str or dtype, optional, default=np.float64 If specified, the data will be casted to this dtype, else the type of the data will be used dims : list of chars, optional. if specified the list must have a length equal to the number od data dimensions (ndim) and the chars must be taken among among x,y,z,u,v,w or t. If not specified, the dimension names are automatically attributed in this order. name : str, optional A user friendly name for this object. If not given, the automatic `id` given at the object creation will be used as a name. labels : array of objects, optional Labels for the `data`. labels can be used only for 1D-datasets. The labels array may have an additional dimension, meaning several series of labels for the same data. The given array can be a list, a tuple, a |ndarray|, a ndarray-like, a |NDArray| or any subclass of |NDArray|. units : |Unit| instance or str, optional Units of the data. If data is a |Quantity| then `units` is set to the unit of the `data`; if a unit is also explicitly provided an error is raised. Handling of units use the `pint <https://pint.readthedocs.org/>`_ package. title : str, optional The title of the dimension. It will later be used for instance for labelling plots of the data. It is optional but recommended to give a title to each ndarray. dlabel : str, optional. Alias of `title`. meta : dict-like object, optional. Additional metadata for this object. Must be dict-like but no further restriction is placed on meta. copy : bool, optional Perform a copy of the passed object. Default is False. fill_missing : bool Create a linear coordinate array where missing data are masked. See Also -------- NDDataset : Main SpectroChemPy object: an array with masks, units and coordinates. Coord : Explicit coordinates. Examples -------- >>> from spectrochempy import LinearCoord, Coord To create a linear coordinate, we need to specify an offset, an increment and the size of the data >>> c1 = LinearCoord(offset=2.0, increment=2.0, size=10) Alternatively, linear coordinates can be created using the ``linear`` keyword >>> c2 = Coord(linear=True, offset=2.0, increment=2.0, size=10) """ super().__init__(*args, **kwargs) # when data is present, we don't need offset and increment, nor size, # we just do linear=True and these parameters are ignored if self._data is not None: self._linear = True elif not self.linear: # in case it was not already a linear array self.offset = offset self.increment = increment self._linear = True # .................................................................................................................. def implements(self, name=None): """ Utility to check if the current object implement `LinearCoord`. Rather than isinstance(obj, Coord) use object.implements( 'LinearCoord'). This is useful to check type without importing the module """ if name is None: return 'LinearCoord' else: return name == 'LinearCoord' # .................................................................................................................. @property # read only def linear(self): return self._linear # .................................................................................................................. def geomspace(self): raise NotImplementedError # .................................................................................................................. def logspace(self): raise NotImplementedError # .................................................................................................................. def __dir__(self): # remove some methods with respect to the full NDArray # as they are not usefull for Coord. return ['data', 'labels', 'units', 'meta', 'title', 'name', 'offset', 'increment', 'linear', 'size', 'roi', 'show_datapoints'] def set_laser_frequency(self, frequency=15798.26 * ur('cm^-1')): if not isinstance(frequency, Quantity): frequency = frequency * ur('cm^-1') frequency.ito('Hz') self.meta.laser_frequency = frequency if self._use_time: spacing = 1. / frequency spacing.ito('picoseconds') self.increment = spacing.m self.offset = 0 self._units = ur.picoseconds self.title = 'time' else: frequency.ito('cm^-1') spacing = 1. / frequency spacing.ito('mm') self.increment = spacing.m self.offset = -self.increment * self._zpd self._units = ur.mm self.title = 'optical path difference' @property def _use_time_axis(self): # private property # True if time scale must be used for interferogram axis. Else it # will be set to optical path difference. return self._use_time @_use_time_axis.setter def _use_time_axis(self, val): self._use_time = val if 'laser_frequency' in self.meta: self.set_laser_frequency(self.meta.laser_frequency) @property def show_datapoints(self): """ Bool : True if axis must discard values and show only datapoints. """ if 'laser_frequency' not in self.meta or self.units.dimensionality not in ['[time]', '[length]']: return False return self._show_datapoints @show_datapoints.setter def show_datapoints(self, val): self._show_datapoints = val @property def laser_frequency(self): """ Quantity: Laser frequency (if needed) """ return self.meta.laser_frequency @laser_frequency.setter def laser_frequency(self, val): self.meta.aser_frequency = val # ====================================================================================================================== # Set the operators # ====================================================================================================================== _set_operators(Coord, priority=50) # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/tests/test_scripts/test_scripts.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy import Script, info_ def test_script(): Script('name', 'print(2)') try: Script('0name', 'print(3)') except Exception: info_('name not valid') <file_sep>/docs/credits/seealso.rst .. _see_also: See also ======== If you are looking for intuitive GUI for spectroscopic data, `Orange <https://orange.biolab.si/>`_, together with the `Orange-Spectroscopy Add-on <https://orange-spectroscopy.readthedocs.io/en/latest/>`_ could be a good choice. If you are looking for librairies allowing the manipulation of dataset with coordinates, we advise to look at `pandas <https://pandas.pydata.org>`_ and `xarray <http://xarray.pydata.org/en/stable/>`_. If you are interested by plotting data using matplotlib based graphic framework, `seaborn <https://seaborn.pydata.org>`_ or `bokeh <https://bokeh .pydata.org/en/latest/>`_ may be what you are looking for. <file_sep>/tests/test_readers_writers/test_read_write_jdx.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.utils.testing import assert_dataset_almost_equal def test_read_write_jdx(IR_dataset_2D): X = IR_dataset_2D[:10, :100] # write f = X.write_jdx('nh4y-activation.jdx') # read Y = NDDataset.read_jdx(f) assert_dataset_almost_equal(X, Y, decimal=2) # delete f.unlink() # write f = X.write_jdx() assert f.stem == X.name Y = NDDataset.read_jcamp(f, name='xxx') assert Y.name == 'xxx' f.unlink() <file_sep>/docs/userguide/introduction/interface.py # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Starting Jupyter lab # # Currently **SpectroChemPy** can be used as a library for python scripts. # # For ease of use, we recommend using the # __[JupyterLab](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html)__ # application or for those who are more comfortable with programming, # writing python scripts in a development environment such as # __[PyCharm](https://www.jetbrains.com/fr-fr/pycharm/)__, __[VS # Code](https://code.visualstudio.com)__ or __[Spyder](https://www.spyder-ide.org)__. # # To launch `Jupyter Lab`, open a terminal and follow the steps below: # # * Go to your favorite user document folder (*e.g.,* `$HOME/workspace` or # any other folder you want to use to store your work). # ```bash # $ cd $HOME/workspace # ``` # * Then type the following command: # ```bash # $ jupyter lab # ``` # # Your default browser should now be open, and the window should look like # this: # # <img src='images/launch_lab.png' /> # # From there, it is quite easy to create notebooks or to navigate to # already existing ones. # # ## Create a new Jupyter notebook # # * Click on the Notebook python 3 icon # * A new notebook is created # * Enter your first command, in the displayed cell, and type `SHIFT+ENTER` to run the code # ```ipython3 # from spectrochempy import * # ``` # * You can rename the notebook using context menu in the sidebar # # <img src='images/enter_code.png' /> # # * Then you can click on the `+` sign to create a new cell. This cell is by default a Code cell which can contain # Python code, but you can also enter some text, in Markdown format. Choose the content type of the cell in the # dropdown menu, or by typing `ESC+M`. # <img src='images/enter_md.png' /> # # ## Markdown cheat sheet # To get more information on Markdown format, you can look [here](mdcheatsheet.ipynb). # # # Using the application in a web browser # # <div class='alert alert-warning'> # <b>In Progress</b> # # For the moment we don’t yet have a graphical interface to offer other # than Jupyter notebooks or python scripts. It is in any case our # preferred way of working with SpectroChemPy because it offers all the # necessary flexibility for a fast and above all reproducible realization # of the different tasks to be performed on spectroscopic data. # # However we have started to create a simple interface using Dash which # will allow in a future version to work perhaps more simply for those who # do not have the time or the will to learn to master the rudiments of # python or who do not wish to program. # </div> # %% <file_sep>/spectrochempy/core/processors/autosub.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Plugin module to perform automatic subtraction of ref on a dataset. """ __all__ = ['autosub'] __dataset_methods__ = __all__ import numpy as np from scipy.optimize import minimize_scalar from spectrochempy.core.dataset.coordrange import trim_ranges def autosub(dataset, ref, *ranges, dim='x', method='vardiff', return_coefs=False, inplace=False): """ Automatic subtraction of a reference to the dataset. The subtraction coefficient are adjusted to either minimise the variance of the subtraction (method = 'vardiff') which will minimize peaks due to ref or minimize the sum of squares of the subtraction (method = 'ssdiff'). Parameters ---------- dataset : |NDDataset| Dataset to which we want to subtract the reference data. ref : |NDDataset| 1D reference data, with a size maching the axis to subtract. (axis parameter). # TODO : optionally use title of axis. *ranges : pair(s) of values Any number of pairs is allowed. Coord range(s) in which the variance is minimized. dim : `str` or `int`, optional, default='x' Tells on which dimension to perform the subtraction. If dim is an integer it refers to the axis index. method : str, optional, default='vardiff' 'vardiff': minimize the difference of the variance. 'ssdiff': minimize the sum of sqares difference of sum of squares. return_coefs : `bool`, optional, default=`False` Returns the table of coefficients. inplace : `bool`, optional, default=`False` True if the subtraction is done in place. In this case we do not need to catch the function output. Returns -------- out : |NDDataset| The subtracted dataset. coefs : `ndarray`. The table of subtraction coeffcients (only if `return_coefs` is set to `True`). See Also -------- BaselineCorrection : Manual baseline corrections. abc : Automatic baseline corrections. Examples --------- >>> import spectrochempy as scp >>> path_A = 'irdata/nh4y-activation.spg' >>> A = scp.read(path_A, protocol='omnic') >>> ref = A[0, :] # let's subtrack the first row >>> B = A.autosub(ref, [3900., 3700.], [1600., 1500.], inplace=False) >>> B NDDataset: [float64] a.u. (shape: (y:55, x:5549)) """ # output dataset if not inplace: new = dataset.copy() else: new = dataset # we assume that the last dimension ('x' for transposed array) is always the dimension to which we want # to subtract. # Swap the axes to be sure to be in this situation axis, dim = new.get_axis(dim) if axis == new.ndim - 1: axis = -1 try: ref.to(dataset.units) except Exception: raise ValueError('Units of the dataset and reference are not compatible') swaped = False if axis != -1: new = new.swapdims(axis, -1) swaped = True # TODO: detect the case where the ref is not exactly with same coords: interpolate? # selection of the multiple ranges # shape = list(new.shape) ranges = tuple(np.array(ranges, dtype=float)) # must be float to be considered as frequency for instance coords = new.coordset[dim] xrange = trim_ranges(*ranges, reversed=coords.reversed) s = [] r = [] # TODO: this do not work obviously for axis != -1 - correct this for xpair in xrange: # determine the slices sl = slice(*xpair) s.append(dataset[..., sl].data) r.append(ref[..., sl].data) X_r = np.concatenate((*s,), axis=-1) ref_r = np.concatenate((*r,), axis=-1).squeeze() indices, _ = list(zip(*np.ndenumerate(X_r[..., 0]))) # .squeeze()))) # two methods # @jit def _f(alpha, p): if method == 'ssdiff': return np.sum((p - alpha * ref_r) ** 2) elif method == 'vardiff': return np.var(np.diff(p - alpha * ref_r)) else: raise ValueError('Not implemented for method={}'.format(method)) # @jit(cache=True) def _minim(): # table of subtraction coefficients x = [] for tup in indices: # slices = [i for i in tup] # slices.append(slice(None)) # args = (X_r[slices],) args = X_r[tup] res = minimize_scalar(_f, args=(args,), method='brent') x.append(res.x) x = np.asarray(x) return x x = _minim() new._data -= np.dot(x.reshape(-1, 1), ref.data.reshape(1, -1)) if swaped: new = new.swapdims(axis, -1) new.history = str( new.modified) + ': ' + 'Automatic subtraction of:' + ref.name + '\n' if return_coefs: return new, x else: return new <file_sep>/spectrochempy/scripts/get_testdata.py # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ===================================================================================================================== # """ Download data from Google Drive to the local directory """ from pathlib import Path import urllib.request testdata_url = Path('https://drive.google.com/drive/folders/1rfc9O7jK6v_SbygzJHoFEXXxYY3wIqmh?usp=sharing') wodger = testdata_url / 'wodger.spg' try: with urllib.request.urlopen(str(testdata_url)) as f: file = f.read().decode('utf-8') except Exception: pass # TODO: WIP <file_sep>/docs/readme.md # TIPS and NOTES A goog way to have an immediate preview of the tst file is e.g., the following online editor: https://livesphinx.herokuapp.com<file_sep>/docs/gettingstarted/examples/processing/plot_proc_sp.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2020 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Sine bell and squared Sine bell window multiplication ===================================================== In this example, we use sine bell or squared sine bell window multiplication to apodize a NMR signal in the time domain. """ import spectrochempy as scp import os path = os.path.join(scp.preferences.datadir, 'nmrdata', 'bruker', 'tests', 'nmr', 'topspin_1d') dataset1D = scp.read_topspin(path, expno=1, remove_digital_filter=True) ######################################################################################################################## # Normalize the dataset values and reduce the time domain dataset1D /= dataset1D.real.data.max() # normalize dataset1D = dataset1D[0.:15000.] ######################################################################################################################## # Apply Sine bell window apodization with parameter ssb=2, which correspond to a cosine function new1, curve1 = scp.sinm(dataset1D, ssb=2, retapod=True, inplace=False) # this is equivalent to _ = dataset1D.sinm(ssb=2, retapod=True, inplace=False) # or also _ = scp.sp(dataset1D, ssb=2, pow=1, retapod=True, inplace=False) ######################################################################################################################## # Apply Sine bell window apodization with parameter ssb=2, which correspond to a sine function new2, curve2 = dataset1D.sinm(ssb=1, retapod=True, inplace=False) ######################################################################################################################## # Apply Squared Sine bell window apodization with parameter ssb=1 and ssb=2 new3, curve3 = scp.qsin(dataset1D, ssb=2, retapod=True, inplace=False) new4, curve4 = dataset1D.qsin(ssb=1, retapod=True, inplace=False) ######################################################################################################################## # Apply shifted Sine bell window apodization with parameter ssb=8 (mixed sine/cosine window) new5, curve5 = dataset1D.sinm(ssb=8, retapod=True, inplace=False) ######################################################################################################################## # Plotting p = dataset1D.plot(zlim=(-2, 2), color='k') curve1.plot(color='r', clear=False) new1.plot(data_only=True, color='r', clear=False, label=' sinm with ssb= 2 (cosine window)') curve2.plot(color='b', clear=False) new2.plot(data_only=True, color='b', clear=False, label=' sinm with ssb= 1 (sine window)') curve3.plot(color='m', clear=False) new3.plot(data_only=True, color='m', clear=False, label=' qsin with ssb= 2') curve4.plot(color='g', clear=False) new4.plot(data_only=True, color='g', clear=False, label=' qsin with ssb= 1') curve5.plot(color='c', ls='--', clear=False) new5.plot(data_only=True, color='c', ls='--', clear=False, label=' sinm with ssb= 8', legend='best') # scp.show() # uncomment to show plot if needed (not necessary in jupyter notebook) <file_sep>/spectrochempy/core/processors/interpolate.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module defines functions related to interpolations """ __all__ = ['interpolate'] __dataset_methods__ = __all__ # import scipy.interpolate # import numpy as np # from ...utils import NOMASK, MASKED, UnitsCompatibilityError # from spectrochempy.extern.orderedset import OrderedSet # from spectrochempy.core import warning_, error_ # ............................................................................ def interpolate(dataset, axis=0, size=None): # TODO: a simple interpolator of the data (either to reduce # or increase number of points in every dimension) raise NotImplementedError('Not yet implemented') <file_sep>/tests/test_dataset/test_ndcomplex.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from copy import copy, deepcopy from quaternion import as_quat_array, as_float_array, quaternion import numpy as np import pytest from spectrochempy.core.dataset.ndcomplex import NDComplexArray from spectrochempy.units import ur, Quantity from spectrochempy.utils.testing import (assert_equal, assert_array_equal, assert_approx_equal, ) # TODO: a lot of repetition - must be simplified with some logics typequaternion = np.dtype(np.quaternion) def test_ndarray_comparison(ndarray, ndarrayunit, ndarraycplx, ndarrayquaternion): # test comparison nd1 = ndarray.copy() assert nd1 == ndarray assert nd1 is not ndarray nd2 = ndarrayunit.copy() assert nd2 == ndarrayunit assert nd1 != nd2 assert not nd1 == nd2 nd3 = ndarraycplx.copy() assert nd3 == ndarraycplx nd4 = ndarrayquaternion.copy() assert nd4 == ndarrayquaternion assert nd1 != 'xxxx' nd2n = nd2.to(None, force=True) assert nd2n != nd2 def test_ndcomplex_init_quaternion_witharray(): d = np.arange(24).reshape(3, 2, 4) d = as_quat_array(d) d0 = NDComplexArray(d) assert d0.shape == (3, 2) assert_array_equal(d0.real.data, [[0, 4], [8, 12], [16, 20]]) d1 = NDComplexArray(d) d1 = d1.set_quaternion() assert_array_equal(d1.real.data, [[0, 4], [8, 12], [16, 20]]) d1 = d0.swapdims(1, 0) assert d1.shape == (2, 3) assert_array_equal(d1.real.data, [[0, 8, 16], [4, 12, 20]]) assert d1[0, 0].values == quaternion(0, 2, 1, 3) def test_ndcomplex_init_quaternion(): # test with complex data in all dimension np.random.seed(12345) d = np.random.random((4, 3)) * np.exp(.1j) d0 = NDComplexArray(d, units=ur.Hz, mask=[[False, True, False], [True, False, False]], dtype=typequaternion) # with units & mask assert d0.shape == (2, 3) assert 'NDComplexArray: [quaternion] Hz' in repr(d0) def test_ndcomplex_init_quaternion_error1(): # test with complex data in all dimension but odd number of comlumn (should raise an error d = np.random.random((3, 3)) * np.exp(.1j) with pytest.raises(ValueError): NDComplexArray(d, dtype=typequaternion) # with units & mask def test_ndcomplex_init_quaternion_error2(): # test with complex data in all dimension but odd number of rows(should raise an error d = np.random.random((3, 4)) with pytest.raises(ValueError): NDComplexArray(d, dtype=typequaternion) # with units & mask def test_ndcomplex_init_complex_with_copy_of_ndarray(): # test with complex from copy of another ndArray d = np.ones((2, 2)) * np.exp(.1j) d1 = NDComplexArray(d) d2 = NDComplexArray(d1) assert d1._data is d2._data assert np.all(d1.data == d2.data) assert d2.has_complex_dims assert not d2.is_quaternion assert d2.shape == (2, 2) def test_ndcomplex_init_complex_with_mask(): # test with complex with mask and units np.random.seed(12345) d = np.random.random((2, 2)) * np.exp(.1j) d3 = NDComplexArray(d, units=ur.Hz, mask=[[False, True], [False, False]]) # with units & mask # internal representation (interleaved) assert d3.shape == (2, 2) assert d3._data.shape == (2, 2) assert d3.data.shape == (2, 2) assert d3.size == 4 assert (d3.real.data == d.real).all() assert np.all(d3.data.real == d.real) assert d3.dtype == np.complex128 assert d3.has_complex_dims assert d3.mask.shape[-1] == d3.shape[-1] d3RR = d3.component('RR') assert not d3RR.has_complex_dims assert d3RR._data.shape == (2, 2) assert d3RR._mask.shape == (2, 2) assert isinstance(d3[1, 1].values, Quantity) assert d3[1, 1].values.magnitude == d[1, 1] def test_ndcomplex_swapdims(): np.random.seed(12345) d = np.random.random((4, 3)) * np.exp(.1j) d3 = NDComplexArray(d, units=ur.Hz, mask=[[False, True, False], [False, True, False], [False, True, False], [True, False, False]]) # with units & mask assert d3.shape == (4, 3) assert d3._data.shape == (4, 3) assert d3.has_complex_dims assert not d3.is_quaternion assert d3.dims == ['y', 'x'] d4 = d3.swapdims(0, 1) assert d4.dims == ['x', 'y'] assert d4.shape == (3, 4) assert d4._data.shape == (3, 4) assert d4.has_complex_dims assert not d4.is_quaternion def test_ndcomplex_ndarraycplx_fixture2(ndarraycplx): nd = ndarraycplx.copy() # some checking assert nd.size == 40 assert nd.data.size == 40 assert nd.shape == (10, 4) assert nd.has_complex_dims assert nd.data.dtype == np.complex128 assert nd.ndim == 2 def test_ndcomplex_init_complex_with_a_ndarray(): # test with complex data in the last dimension d = np.array([[1, 2], [3, 4]]) * np.exp(.1j) d0 = NDComplexArray(d) assert d0.dtype == np.complex assert d0.has_complex_dims assert d0.shape == (2, 2) assert d0.size == 4 assert 'NDComplexArray: [complex128]' in repr(d0) def test_ndcomplex_quaternion_fixture(ndarrayquaternion): nd = ndarrayquaternion.copy() # some checking assert nd.size == 20 assert nd.data.size == 20 assert nd.shape == (5, 4) assert nd.has_complex_dims assert nd.is_quaternion assert nd.data.dtype == typequaternion assert nd.dtype == typequaternion assert nd.ndim == 2 def test_ndcomplex_real_imag(): np.random.seed(12345) d = np.random.random((2, 2)) * np.exp(.1j) d3 = NDComplexArray(d) new = d3.copy() new.data = d3.real.data + 1j * d3.imag.data assert_equal(d3.data, new.data) def test_ndcomplex_set_with_complex(ndarraycplx): nd = ndarraycplx.copy() nd.units = 'meter/hour' assert nd.units == ur.meter / ur.hour def test_ndcomplex_copy_of_ndarray(ndarraycplx): nd1 = ndarraycplx nd2 = copy(ndarraycplx) assert nd2 is not nd1 assert nd2.shape == nd1.shape assert nd2.is_complex == nd1.is_complex assert nd2.ndim == nd1.ndim def test_ndcomplex_deepcopy_of_ndarray(ndarraycplx): # for this example there is no diif with copy (write another test for this) nd1 = ndarraycplx.copy() nd2 = deepcopy(nd1) assert nd2 is not nd1 assert nd2.data.size == 40 def test_ndcomplex_len_and_sizes_cplx(ndarraycplx): ndc = ndarraycplx.copy() assert ndc.has_complex_dims assert ndc.is_complex assert len(ndc) == 10 # len is the number of rows assert ndc.shape == (10, 4) assert ndc.size == 40 assert ndc.ndim == 2 # def test_ndcomplex_slicing_byindex_cplx(ndarraycplx): # ndc = ndarraycplx.copy() # ndc1 = ndc[1, 1] # assert_equal(ndc1.values, ndc.RR[1, 1].values + ndc.RI[1, 1].values * 1.j) def test_ndcomplex_slicing_byindex_quaternion(ndarrayquaternion): ndc = ndarrayquaternion.copy() ndc1 = ndc[1, 1].real assert_approx_equal(ndc1.values.magnitude, 4.646475973719301, 3) def test_ndcomplex_complex(ndarraycplx): nd = ndarraycplx.copy() ndr = nd.real assert_array_equal(ndr.data, nd.data.real) assert ndr.size == nd.size assert not ndr.is_complex def test_ndcomplex_str_representation_for_complex(): nd1 = NDComplexArray([1. + 2.j, 2. + 3.j]) assert "NDComplexArray: [complex128] unitless" in repr(nd1) def test_ndcomplex_quaternion_str_representation(): np.random.seed(12345) d = np.random.random((4, 2)) * np.exp(.1j) NDComplexArray(d, dtype=typequaternion) def test_ndcomplex_real_imag_quaternion(): np.random.seed(12345) d = np.random.random((2, 2)) * np.exp(.1j) d3 = NDComplexArray(d, dtype=typequaternion) d3r = d3.real assert d3r.dtype == np.float64 assert d3r.shape == (1, 2) d3i = d3.imag assert d3i.dtype == typequaternion def test_ndcomplex_swapdims_quaternion(): np.random.seed(12345) d = np.random.random((4, 3)) * np.exp(.1j) d3 = NDComplexArray(d, units=ur.Hz, mask=[[False, True, False], [True, False, False]], dtype=typequaternion) # quaternion with units & mask assert d3.shape == (2, 3) assert d3._data.shape == (2, 3) assert d3.has_complex_dims assert d3.is_quaternion w, x, y, z = as_float_array(d3.data).T d4 = d3.swapdims(0, 1) assert d4.shape == (3, 2) assert d4._data.shape == (3, 2) assert d4.has_complex_dims assert d4.is_quaternion wt, yt, xt, zt = as_float_array(d4.data).T assert_array_equal(xt, x.T) assert_array_equal(yt, y.T) assert_array_equal(zt, z.T) assert_array_equal(wt, w.T) def test_ndcomplex_squeeze(ndarrayunit): nd = NDComplexArray(ndarrayunit) assert nd.shape == (10, 8) d = nd[..., 0] d = d.squeeze() assert d.shape == (10,) d = nd[0] d = d.squeeze() assert d.shape == (8,) nd1 = nd.set_complex() assert nd1.shape == (10, 4) nd1._repr_html_() d = nd[..., 0] d = d.squeeze() assert d.shape == (10,) d = nd[0] assert d.shape == (1, 8) d1 = d.squeeze() assert d1.shape == (8,) assert d1 is not d # TODO: test a revoir # d = nd[..., 0].real # assert np.all(d == nd[..., 0].RR) # assert d.shape == (10, 1) # d1 = d.squeeze("x") # assert d1.shape == (10,) # assert d1 is not d # # # inplace # d = nd[..., 0:1] # assert d.shape == (10, 1) # d1 = d.squeeze(dims=1, inplace=True) # assert d1.shape == (10,) # assert d1 is d # # d = nd[0:1] # assert d.shape == (1, 8) # d1 = d.squeeze(dims=0, inplace=True) # assert d1.shape == (8,) # assert d1 is d <file_sep>/docs/userguide/reference/index.rst .. _api_reference: .. currentmodule:: spectrochempy ############## API reference ############## .. contents:: Table of Contents **************** Loading the API **************** The |scpy| API exposes many objects and functions. To use the API, you must import it using one of the following syntax: .. ipython:: python import spectrochempy as scp nd = scp.NDDataset() .. ipython:: python from spectrochempy import * nd = NDDataset() With the second syntax, as often in python, the access to objects/functions can be greatly simplified. For example, we can use `NDDataset` without a prefix instead of `scp.NDDataset` which is the first syntax) but there is always a risk of overwriting some variables or functions already present in the namespace. Therefore, the first syntax is generally highly recommended. ********************* The NDDataset object ********************* The NDDataset is the main object use by |scpy|. Like numpy ndarrays, NDDataset have the capability to be sliced, sorted and subject to mathematical operations. But, in addition, NDDataset may have units, can be masked and each dimensions can have coordinates also with units. This make NDDataset aware of unit compatibility, *e.g.*, for binary operation such as additions or subtraction or during the application of mathematical operations. In addition or in replacement of numerical data for coordinates, NDDataset can also have labeled coordinates where labels can be different kind of objects (strings, datetime, numpy nd.ndarray or othe NDDatasets, etc...). This offers a lot of flexibility in using NDDatasets that, we hope, will be useful for applications. See the **Tutorials** for more information about such possible applications. .. autosummary:: :nosignatures: :toctree: generated/ NDDataset *************************** Coordinates related objects *************************** |NDDataset| in |scpy| in contrast to numpy nd-arrays can have coordinates for each dimension. The individual coordinates are represented by a specific object: |Coord|. All coordinates of an |NDDataset| are grouped in a particular object: |CoordSet|. .. autosummary:: :nosignatures: :toctree: generated/ Coord LinearCoord CoordSet ******************* Creating NDDataset ******************* A |NDDataset| can be created using the |NDDataset| class constructor, for instance here we create a dataset from a random two dimensional array: .. ipython:: python import numpy as np X = np.random.random((4,4)) nd = NDDataset(X) The above code in |scpy| can be simplified using the ``random`` creation method: .. ipython:: python X = NDDataset.random((4,4)) (see the :ref:`userguide` for a large set of examples on how to use this constructor.) Many SpectroChemPy methods mimics numpy equivalent, but output a NDDataset object. Basic creation methods ======================= .. autosummary:: :nosignatures: :toctree: generated/ empty zeros ones full empty_like zeros_like ones_like full_like eye identity random diag Creation from existing data ============================ .. autosummary:: :nosignatures: :toctree: generated/ copy fromfunction fromiter Creation from numerical ranges ============================== .. autosummary:: :nosignatures: :toctree: generated/ arange linspace logspace geomspace Creation from from external sources ==================================== .. autosummary:: :nosignatures: :toctree: generated/ read read_omnic read_spg read_spa read_srs read_opus read_labspec read_topspin read_zip read_csv read_jcamp read_matlab read_quadera read_dir read_carroucell ****************** Export a NDDataset ****************** .. autosummary:: :nosignatures: :toctree: generated/ NDDataset.save NDDataset.save_as load write write_jcamp to_array to_xarray ************************** Select data in a NDDataset ************************** .. autosummary:: :nosignatures: :toctree: generated/ take ******************** Plotting functions ******************** .. autosummary:: :nosignatures: :toctree: generated/ plot plot_1D plot_pen plot_scatter plot_bar plot_2D plot_map plot_stack plot_image plot_surface plot_waterfall ************ Processing ************ Transpose-like oprations ======================== .. autosummary:: :nosignatures: :toctree: generated/ transpose NDDataset.T swapdims Changing number of dimensions ============================= .. autosummary:: :nosignatures: :toctree: generated/ squeeze expand_dims Changing type ============== .. autosummary:: :nosignatures: :toctree: generated/ set_complex set_hypercomplex set_quaternion asfortranarray Joining or splitting datasets ============================= .. autosummary:: :nosignatures: :toctree: generated/ concatenate stack split Indexing ======== .. autosummary:: :nosignatures: :toctree: generated/ diag diagonal take Sorting ======= .. autosummary:: :nosignatures: :toctree: generated/ sort Minimum and maximum =================== .. autosummary:: :nosignatures: :toctree: generated/ argmin argmax coordmin coordmax min max ptp Clipping and rounding ===================== .. autosummary:: :nosignatures: :toctree: generated/ clip rint floor ceil fix trunc around round_ Algebra ======== .. autosummary:: :nosignatures: :toctree: generated/ dot SVD LSTSQ NNLS Logic functions ================ .. autosummary:: :nosignatures: :toctree: generated/ all any sign Sums, integal, difference ========================== .. autosummary:: :nosignatures: :toctree: generated/ sum cumsum trapz simps diff Complex ======= .. autosummary:: :nosignatures: :toctree: generated/ NDDataset.real NDDataset.imag NDDataset.RR NDDataset.RI NDDataset.IR NDDataset.II part conj conjugate abs absolute Masks ===== .. autosummary:: :nosignatures: :toctree: generated/ remove_masks Units manipulation =================== .. autosummary:: :nosignatures: :toctree: generated/ to to_base_units to_reduced_units ito ito_base_units ito_reduced_units is_units_compatible deg2rad rad2deg Unary mathematical operations ============================== .. autosummary:: :nosignatures: :toctree: generated/ fabs negative exp exp2 log log2 log10 expm1 log1p sqrt square cbrt reciprocal sin cos tan arcsin arccos arctan sinh cosh tanh arcsinh arccosh arctanh Statistical operations ======================= .. autosummary:: :nosignatures: :toctree: generated/ mean average std sum var Baseline correction ==================== .. autosummary:: :nosignatures: :toctree: generated/ BaselineCorrection autosub ab abc detrend Fourier transform ================== .. autosummary:: :nosignatures: :toctree: generated/ fft ifft Smoothing, apodization ======================= .. autosummary:: :nosignatures: :toctree: generated/ savgol_filter smooth bartlett blackmanharris hamming mertz triang em gm sp sine qsin sinm Alignment, interpolation ======================== .. autosummary:: :nosignatures: :toctree: generated/ align interpolate Miscellaneous ============= .. autosummary:: :nosignatures: :toctree: generated/ pipe ******************** Fitting ******************** .. autosummary:: :nosignatures: :toctree: generated/ Fit CurveFit LSTSQ NNLS ******************* Analysis ******************* .. autosummary:: :nosignatures: :toctree: generated/ find_peaks EFA PCA NNMF SIMPLISMA MCRALS IRIS ******************** Project management ******************** .. autosummary:: :nosignatures: :toctree: generated/ Project ********** Scripting ********** This is rather experimental .. autosummary:: :nosignatures: :toctree: generated/ Script ********** Utilities ********** .. autosummary:: :nosignatures: :toctree: generated/ download_IRIS <file_sep>/spectrochempy/core/analysis/integrate.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== __all__ = ['simps', 'trapz'] __dataset_methods__ = ['simps', 'trapz'] import scipy.integrate def trapz(dataset, *args, **kwargs): """ Wrapper of scpy.integrate.trapz() : Integrate along the given dimension using the composite trapezoidal rule. Integrate NDDataset along given dimension. Parameters ---------- dataset : |NDDataset| dataset to be integrated. dim : str, optional Dimension along which to integrate. Default is the dimension corresponding to the last axis, generally 'x'. axis : int, optional When dim is not used, this is the axis along which to integrate. Default is the last axis. Returns ------- trapz Definite integral as approximated by trapezoidal rule. Example -------- >>> import spectrochempy as scp >>> dataset = scp.read('irdata/nh4y-activation.spg') >>> dataset[:,1250.:1800.].trapz() NDDataset: [float64] a.u..cm^-1 (size: 55) """ # handle the various syntax to pass the axis if args: kwargs['dim'] = args[0] args = [] dim = dataset._get_dims_from_args(*args, **kwargs) if dim is None: dim = -1 axis = dataset._get_dims_index(dim) axis = axis[0] if axis and not dataset.is_1d else None data = scipy.integrate.trapz(dataset.data, x=dataset.coord(dim).data, axis=axis) if dataset.coord(dim).reversed: data *= -1 new = dataset.copy() new._data = data del new._dims[axis] if new.implements('NDDataset') and new._coordset and (dim in new._coordset.names): idx = new._coordset.names.index(dim) del new._coordset.coords[idx] new.title = 'Area' new._units = dataset.units * dataset.coord(dim).units new._history = ['Dataset resulting from application of `trapz` method'] return new def simps(dataset, *args, **kwargs): """ Wrapper of scpy.integrate.simps() : Integrate y(x) using samples along the given axis and the composite Simpson's rule. If x is None, spacing of dx is assumed. If there are an even number of samples, N, then there are an odd number of intervals (N-1), but Simpson's rule requires an even number of intervals. The parameter 'even' controls how this is handled. Parameters ---------- dataset : |NDDataset| dataset to be integrated. dim : str, optional Dimension along which to integrate. Default is the dimension corresponding to the last axis, generally 'x'. axis : int, optional When dim is not used, this is the axis along which to integrate. Default is the last axis. even : str {'avg', 'first', 'last'}, optional. Default is 'avg'. 'avg' : Average two results: 1) use the first N-2 intervals with a trapezoidal rule on the last interval and 2) use the last N-2 intervals with a trapezoidal rule on the first interval. 'first' : Use Simpson's rule for the first N-2 intervals with a trapezoidal rule on the last interval. 'last' : Use Simpson's rule for the last N-2 intervals with a trapezoidal rule on the first interval. Returns ------- simps Definite integral as approximated using the composite Simpson's rule. Example -------- >>> import spectrochempy as scp >>> dataset = scp.read('irdata/nh4y-activation.spg') >>> dataset[:,1250.:1800.].simps() NDDataset: [float64] a.u..cm^-1 (size: 55) """ # handle the various syntax to pass the axis if args: kwargs['dim'] = args[0] args = [] dim = dataset._get_dims_from_args(*args, **kwargs) if dim is None: dim = -1 axis = dataset._get_dims_index(dim) axis = axis[0] if axis and not dataset.is_1d else None data = scipy.integrate.simps(dataset.data, x=dataset.coord(dim).data, axis=axis, even=kwargs.get('even', 'avg')) if dataset.coord(dim).reversed: data *= -1 new = dataset.copy() new._data = data del new._dims[axis] if new.implements('NDDataset') and new._coordset and (dim in new._coordset.names): idx = new._coordset.names.index(dim) del new._coordset.coords[idx] new.title = 'Area' new._units = dataset.units * dataset.coord(dim).units new._history = ['Dataset resulting from application of `simps` method'] return new <file_sep>/tests/test_utils/test_system.py # -*- coding: utf-8 -*- # # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # ===================================================================================================================== # import pytest from spectrochempy.utils import get_user, get_user_and_node, get_node, is_kernel, sh def test_get_user(): res = get_user() assert res is not None def test_get_node(): res = get_node() assert res is not None def test_get_user_and_node(): res = get_user_and_node() assert res is not None def test_is_kernel(): res = is_kernel() assert not res @pytest.mark.skip('problem with one of the commit - look at this later') def test_sh(): res = sh.git('show', 'HEAD') assert res is not None <file_sep>/tests/test_projects/test_projects.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy.core.project.project import Project from spectrochempy.core.scripts.script import Script, run_script from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core import preferences, INPLACE prefs = preferences # Basic # -------------------------------------------------------------------------------------------------------- def test_project(ds1, ds2, dsm): myp = Project(name='AGIR processing', method='stack') ds1.name = 'toto' ds2.name = 'tata' dsm.name = 'titi' ds = ds1[:, 10, INPLACE] assert ds1.shape == ds.shape assert ds is ds1 myp.add_datasets(ds1, ds2, dsm) print(myp.datasets_names) assert myp.datasets_names[-1] == 'toto' assert ds1.parent == myp # iteration d = [] for item in myp: d.append(item) assert d[1][0] == 'titi' ## # add sub project msp1 = Project(name='AGIR ATG') msp1.add_dataset(ds1) assert ds1.parent == msp1 # ds1 has changed of project assert ds1.name not in myp.datasets_names msp2 = Project(name='AGIR IR') myp.add_projects(msp1, msp2) print(myp) # an object can be accessed by it's name whatever it's type assert 'tata' in myp.allnames myp['titi'] assert myp['titi'] == dsm # import multiple objects in Project myp2 = Project(msp1, msp2, ds1, ds2) # multi dataset and project and no # names print(myp2) def test_empty_project(): proj = Project(name="XXX") assert proj.name == "XXX" assert str(proj).strip() == "Project XXX:\n (empty project)" def test_project_with_script(): # Example from tutorial agir notebook proj = Project( Project(name='P350', label=r'$\mathrm{M_P}\,(623\,K)$'), Project(name='A350', label=r'$\mathrm{M_A}\,(623\,K)$'), Project(name='B350', label=r'$\mathrm{M_B}\,(623\,K)$'), name='HIZECOKE_TEST') assert proj.projects_names == ['A350', 'B350', 'P350'] # add a dataset to a subproject ir = NDDataset([1, 2, 3]) tg = NDDataset([1, 3, 4]) proj.A350['IR'] = ir proj['TG'] = tg print(proj.A350) print(proj) print(proj.A350.label) f = proj.save() newproj = Project.load('HIZECOKE_TEST') # print(newproj) assert str(newproj) == str(proj) assert newproj.A350.label == proj.A350.label # proj = Project.load('HIZECOKE') # assert proj.projects_names == ['A350', 'B350', 'P350'] script_source = 'set_loglevel(INFO)\n' \ 'info_("samples contained in the project are : ' \ '%s"%proj.projects_names)' proj['print_info'] = Script('print_info', script_source) # print(proj) # save but do not chnge the original data proj.save_as('HIZECOKE_TEST', overwrite_data=False) newproj = Project.load('HIZECOKE_TEST') # execute run_script(newproj.print_info, locals()) newproj.print_info.execute(locals()) newproj.print_info(locals()) # attemps to resolve locals newproj.print_info() proj.save_as('HIZECOKE_TEST') newproj = Project.load('HIZECOKE_TEST') def test_save_and_load_project(ds1, ds2): myp = Project(name='process') ds1.name = 'toto' ds2.name = 'tata' myp.add_datasets(ds1, ds2) myp.save() <file_sep>/tests/test_dataset/test_ndio.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Tests for the ndplugin module """ import pathlib import pytest from spectrochempy.utils.testing import assert_dataset_equal from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core import preferences as prefs from spectrochempy.utils.testing import assert_array_equal from spectrochempy.utils import pathclean irdatadir = pathclean(prefs.datadir) / "irdata" nmrdatadir = pathclean(prefs.datadir) / "nmrdata" / "bruker" / "tests" / "nmr" cwd = pathlib.Path.cwd() # Basic # ---------------------------------------------------------------------------------------------------------------------- def test_ndio_generic(NMR_dataset_1D): nmr = NMR_dataset_1D assert nmr.directory == nmrdatadir # save with the default filename or open a dialog if it doesn't exists # ------------------------------------------------------------------------------------------------------------------ # save with the default name (equivalent to save_as in this case) # as this file (IR_1D.scp) doesn't yet exist a confirmation dialog is opened f = nmr.save() assert nmr.filename == f.name assert nmr.directory == nmrdatadir # load back this file : the full path f is given so no dialog is opened nd = NDDataset.load(f) assert_dataset_equal(nd, nmr) # as it has been already saved, we should not get dialogs f = nd.save() assert nd.filename == 'NMR_1D.scp' # return # now it opens a dialog and the name can be changed f1 = nmr.save_as() assert nmr.filename == f1.name # remove these files f.unlink() f1.unlink() # save in a specified directory nmr.save_as(irdatadir / 'essai') # save essai.scp assert nmr.directory == irdatadir assert nmr.filename == "essai.scp" (irdatadir / nmr.filename).unlink() # save in the current directory f = nmr.save_as(cwd / 'essai') # try to load without extension specification (will first assume it is scp) dl = NDDataset.load('essai') # assert dl.directory == cwd assert_array_equal(dl.data, nmr.data) f.unlink() def test_ndio_2D(IR_dataset_2D): # test with a 2D ir2 = IR_dataset_2D.copy() f = ir2.save_as('essai2D') assert ir2.directory == irdatadir with pytest.raises(FileNotFoundError): nd = NDDataset.load("essai2D") nd = NDDataset.load("irdata/essai2D") assert nd.directory == irdatadir f.unlink() # EOF <file_sep>/spectrochempy/core/readers/readomnic.py # -*- coding: utf-8 -*- # # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, # Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in # the root directory # ===================================================================================================================== # """ This module extend NDDataset with the import method for OMNIC generated data files. """ __all__ = ['read_omnic', 'read_spg', 'read_spa', 'read_srs'] __dataset_methods__ = __all__ from datetime import datetime, timezone, timedelta import io import struct import numpy as np from spectrochempy.core.dataset.coord import Coord, LinearCoord from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.readers.importer import importermethod, Importer from spectrochempy.units import Quantity # ====================================================================================================================== # Public functions # ====================================================================================================================== def read_omnic(*paths, **kwargs): """ Open a Thermo Nicolet OMNIC file. Open Omnic file or a list of files with extension ``.spg`` , ``.spa`` or ``.srs`` and set data/metadata in the current dataset. The collected metatdata are: - names of spectra - acquisition dates (UTC) - units of spectra (absorbance, transmittance, reflectance, Log(1/R), Kubelka-Munk, Raman intensity, photoacoustics, volts) - units of xaxis (wavenumbers in cm^-1, wavelengths in nm or micrometer, Raman shift in cm^-1) - spectra history (but only incorporated in the NDDataset if a single spa is read) An error is generated if attempt is made to inconsistent datasets: units of spectra and xaxis, limits and number of points of the xaxis. Parameters ----------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- out The dataset or a list of dataset corresponding to a (set of) .spg, .spa or .srs file(s). Other Parameters ----------------- directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description : str, optional A Custom description. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True). recursive : bool, optional Read also in subfolders. (default=False). See Also -------- read : Generic read method. read_dir : Read a set of data from a directory. read_spg : Read Omnic files *.spg. read_spa : Read Omnic files *.spa. read_srs : Read Omnic files *.srs. read_opus : Read Bruker OPUS files. read_topspin : Read TopSpin NMR files. read_csv : Read *.csv. read_matlab : Read MATLAB files *.mat. read_zip : Read zipped group of files. Examples --------- Reading a single OMNIC file (providing a windows type filename relative to the default ``datadir``) >>> import spectrochempy as scp >>> scp.read_omnic('irdata\\\\nh4y-activation.spg') NDDataset: [float64] a.u. (shape: (y:55, x:5549)) Reading a single OMNIC file (providing a unix/python type filename relative to the default ``datadir``) Note that here read_omnic is called as a classmethod of the NDDataset class >>> scp.NDDataset.read_omnic('irdata/nh4y-activation.spg') NDDataset: [float64] a.u. (shape: (y:55, x:5549)) Single file specified with pathlib.Path object >>> from pathlib import Path >>> folder = Path('irdata') >>> p = folder / 'nh4y-activation.spg' >>> scp.read_omnic(p) NDDataset: [float64] a.u. (shape: (y:55, x:5549)) The diretory can also be specified independantly, either as a string or a pathlib object >>> scp.read_omnic('nh4y-activation.spg', directory=folder) NDDataset: [float64] a.u. (shape: (y:55, x:5549)) Multiple files not merged (return a list of datasets) >>> le = scp.read_omnic('irdata/nh4y-activation.spg', 'wodger.spg') >>> len(le) 2 >>> le[1] NDDataset: [float64] a.u. (shape: (y:2, x:5549)) Multiple files merged as the `merge` keyword is set to true >>> scp.read_omnic('irdata/nh4y-activation.spg', 'wodger.spg', merge=True) NDDataset: [float64] a.u. (shape: (y:57, x:5549)) Multiple files to merge : they are passed as a list (note the brakets) instead of using the keyword `merge` >>> scp.read_omnic(['irdata/nh4y-activation.spg', 'wodger.spg']) NDDataset: [float64] a.u. (shape: (y:57, x:5549)) Multiple files not merged : they are passed as a list but `merge` is set to false >>> l2 = scp.read_omnic(['irdata/nh4y-activation.spg', 'wodger.spg'], merge=False) >>> len(l2) 2 Read without a filename. This has the effect of opening a dialog for file(s) selection >>> nd = scp.read_omnic() Read in a directory (assume that only OPUS files are present in the directory (else we must use the generic `read` function instead) >>> l3 = scp.read_omnic(directory='irdata/subdir/1-20') >>> len(l3) 3 Again we can use merge to stack all 4 spectra if thet have compatible dimensions. >>> scp.read_omnic(directory='irdata/subdir', merge=True) NDDataset: [float64] a.u. (shape: (y:4, x:5549)) An example, where bytes contents are passed directly to the read_omnic method. >>> datadir = scp.preferences.datadir >>> filename1 = datadir / 'irdata' / 'subdir' / '7_CZ0-100 Pd_101.SPA' >>> content1 = filename1.read_bytes() >>> filename2 = datadir / 'wodger.spg' >>> content2 = filename2.read_bytes() >>> listnd = scp.read_omnic({filename1.name: content1, filename2.name: content2}) >>> len(listnd) 2 >>> scp.read_omnic({filename1.name: content1, filename2.name: content2}, merge=True) NDDataset: [float64] a.u. (shape: (y:3, x:5549)) """ kwargs['filetypes'] = ['OMNIC files (*.spa *.spg)', 'OMNIC series (*.srs)'] kwargs['protocol'] = ['omnic', 'spa', 'spg', 'srs'] importer = Importer() return importer(*paths, **kwargs) # ...................................................................................................................... def read_spg(*paths, **kwargs): """ Open a Thermo Nicolet file or a list of files with extension ``.spg``. Parameters ----------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read_spg The dataset or a list of dataset corresponding to a (set of) .spg file(s). Other Parameters ----------------- directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description : str, optional A Custom description. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True). recursive : bool, optional Read also in subfolders. (default=False). See Also -------- read : Generic read method. read_dir : Read a set of data from a directory. read_omnnic : Read Omnic files. read_spa : Read Omnic files *.spa. read_srs : Read Omnic files *.srs. read_opus : Read Bruker OPUS files. read_topspin : Read TopSpin NMR files. read_csv : Read *.csv. read_matlab : Read MATLAB files *.mat. read_zip : Read zipped group of files. Notes ----- This method is an alias of ``read_omnic``, except that the type of file is contrain to *.spg. Examples --------- >>> import spectrochempy as scp >>> scp.read_spg('irdata/nh4y-activation.spg') NDDataset: [float64] a.u. (shape: (y:55, x:5549)) See ``read_omnic`` for more examples of use """ kwargs['filetypes'] = ['OMNIC files (*.spg)'] kwargs['protocol'] = ['spg'] importer = Importer() return importer(*paths, **kwargs) # ...................................................................................................................... def read_spa(*paths, **kwargs): """ Open a Thermo Nicolet file or a list of files with extension ``.spa``. Parameters ----------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read_spa The dataset or a list of dataset corresponding to a (set of) .spg file(s). Other Parameters ----------------- protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description: str, optional A Custom description. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True). recursive : bool, optional Read also in subfolders. (default=False). See Also -------- read : Generic read method. read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_labspec : Read Raman LABSPEC spectra. read_spg : Read Omnic *.spg grouped spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. Notes ----- This method is an alias of ``read_omnic``, except that the type of file is contrain to *.spa. Examples --------- >>> import spectrochempy as scp >>> scp.read_spa('irdata/subdir/20-50/7_CZ0-100 Pd_21.SPA') NDDataset: [float64] a.u. (shape: (y:1, x:5549)) >>> scp.read_spa(directory='irdata/subdir', merge=True) NDDataset: [float64] a.u. (shape: (y:4, x:5549)) See ``read_omnic`` for more examples of use """ kwargs['filetypes'] = ['OMNIC files (*.spa)'] kwargs['protocol'] = ['spa'] importer = Importer() return importer(*paths, **kwargs) # ...................................................................................................................... def read_srs(*paths, **kwargs): """ Open a Thermo Nicolet file or a list of files with extension ``.srs``. Parameters ----------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read_srs The dataset or a list of dataset corresponding to a (set of) .spg file(s). Other Parameters ----------------- protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description: str, optional A Custom description. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True) recursive : bool, optional Read also in subfolders. (default=False). See Also -------- read : Generic read method. read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_labspec : Read Raman LABSPEC spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. Notes ----- This method is an alias of ``read_omnic``, except that the type of file is contrain to *.srs. Examples --------- >>> import spectrochempy as scp >>> scp.read_srs('irdata/omnic series/rapid_scan_reprocessed.srs') NDDataset: [float64] a.u. (shape: (y:643, x:3734)) See ``read_omnic`` for more examples of use See Also -------- read : Generic read method read_omnic, read_spg, read_spa, read_opus """ kwargs['filetypes'] = ['OMNIC series (*.srs)'] kwargs['protocol'] = ['srs'] importer = Importer() return importer(*paths, **kwargs) # ====================================================================================================================== # Private functions # ====================================================================================================================== # ...................................................................................................................... @importermethod def _read_spg(*args, **kwargs): # read spg file dataset, filename = args sortbydate = kwargs.pop("sortbydate", True) content = kwargs.get('content', False) if content: fid = io.BytesIO(content) else: fid = open(filename, 'rb') # Read title: # The file title starts at position hex 1e = decimal 30. Its max length # is 256 bytes. # It is the original filename under which the group has been saved: it # won't match with # the actual filename if a subsequent renaming has been done in the OS. spg_title = _readbtext(fid, 30) # Check if it is really a spg file (in this case title his the filename # with extension spg) if spg_title[-4:].lower() != '.spg': # probably not a spg content # try .spa fid.close() return _read_spa(*args, **kwargs) # Count the number of spectra # From hex 120 = decimal 304, individual spectra are described # by blocks of lines starting with "key values", # for instance hex[02 6a 6b 69 1b 03 82] -> dec[02 106 107 105 27 03 130] # Each of theses lines provides positions of data and metadata in the file: # # key: hex 02, dec 02: position of spectral header (=> nx, firstx, # lastx, nscans, nbkgscans) # key: hex 03, dec 03: intensity position # key: hex 04, dec 04: user text position # key: hex 1B, dec 27: position of History text # key: hex 69, dec 105: ? # key: hex 6a, dec 106: ? # key: hex 6b, dec 107: position of spectrum title, the acquisition # date follows at +256(dec) # key: hex 80, dec 128: ? # key: hex 82, dec 130: ? # # the number of line per block may change from one omnic version to # another, # but the total number of lines is given at hex 294, hence allowing # counting # number of spectra: # read total number of lines fid.seek(294) nlines = _fromfile(fid, 'uint16', count=1) # read "key values" pos = 304 keys = np.zeros(nlines) for i in range(nlines): fid.seek(pos) keys[i] = _fromfile(fid, dtype='uint8', count=1) pos = pos + 16 # the number of occurences of the key '02' is number of spectra nspec = np.count_nonzero((keys == 2)) if nspec == 0: raise IOError('Error : File format not recognized' ' - information markers not found') # container to hold values nx, firstx, lastx = np.zeros(nspec, 'int'), np.zeros(nspec, 'float'), np.zeros(nspec, 'float') xunits = [] xtitles = [] units = [] titles = [] # Extracts positions of '02' keys key_is_02 = (keys == 2) # ex: [T F F F F T F (...) F T ....]' indices02 = np.nonzero(key_is_02) # ex: [1 9 ...] position02 = 304 * np.ones(len(indices02[0]), dtype='int') + 16 * indices02[0] # ex: [304 432 ...] for i in range(nspec): info02 = _readheader02(fid, position02[i]) nx[i] = info02['nx'] firstx[i] = info02['firstx'] lastx[i] = info02['lastx'] xunits.append(info02['xunits']) xtitles.append(info02['xtitle']) units.append(info02['units']) titles.append(info02['title']) # check the consistency of xaxis and data units if np.ptp(nx) != 0: raise ValueError('Error : Inconsistent data set -' ' number of wavenumber per spectrum should be ' 'identical') elif np.ptp(firstx) != 0: raise ValueError('Error : Inconsistent data set - ' 'the x axis should start at same value') elif np.ptp(lastx) != 0: raise ValueError('Error : Inconsistent data set -' ' the x axis should end at same value') elif len(set(xunits)) != 1: raise ValueError('Error : Inconsistent data set - ' 'data units should be identical') elif len(set(units)) != 1: raise ValueError('Error : Inconsistent data set - ' 'x axis units should be identical') data = np.ndarray((nspec, nx[0]), dtype='float32') # Now the intensity data # Extracts positions of '03' keys key_is_03 = (keys == 3) indices03 = np.nonzero(key_is_03) position03 = 304 * np.ones(len(indices03[0]), dtype='int') + 16 * indices03[0] # Read number of spectral intensities for i in range(nspec): data[i, :] = _getintensities(fid, position03[i]) # Get spectra titles & acquisition dates: # container to hold values spectitles, acquisitiondates, timestamps = [], [], [] # Extract positions of '6B' keys (spectra titles & acquisition dates) key_is_6B = (keys == 107) indices6B = np.nonzero(key_is_6B) position6B = 304 * np.ones(len(indices6B[0]), dtype='int') + 16 * indices6B[0] # Read spectra titles and acquisition date for i in range(nspec): # determines the position of informatioon fid.seek(position6B[i] + 2) # go to line and skip 2 bytes spa_title_pos = _fromfile(fid, 'uint32', 1) # read filename spa_title = _readbtext(fid, spa_title_pos) # [0]) spectitles.append(spa_title) # and the acquisition date fid.seek(spa_title_pos + 256) timestamp = _fromfile(fid, dtype='uint32', count=1) # # since 31/12/1899, 00:00 acqdate = datetime(1899, 12, 31, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=int(timestamp)) acquisitiondates.append(acqdate) timestamp = acqdate.timestamp() # Transform back to timestamp for storage in the Coord object # use datetime.fromtimestamp(d, timezone.utc)) # to transform back to datetime obkct timestamps.append(timestamp) # Not used at present # ------------------- # extract positions of # '1B' codes (history text # -- # # # # sometimes absent, # e.g. peakresolve) # key_is_1B = (keys == 27) # indices1B = # np.nonzero( # key_is_1B) # # # position1B = 304 * np.ones(len( # indices1B[0]), dtype='int') + 16 * indices6B[0] # # if len( # position1B) != 0: # # read history texts # for j in range( # nspec): # # # determine the position of information # # # f.seek(position1B[j] + 2) # history_pos = # _fromfile(f, # 'uint32', 1) # # read history # # history = # _readbtext(f, history_pos[0]) # allhistories.append(history) fid.close() # Create Dataset Object of spectral content dataset.data = data dataset.units = units[0] dataset.title = titles[0] dataset.name = filename.stem dataset.filename = filename # now add coordinates # _x = Coord(np.around(np.linspace(firstx[0], lastx[0], nx[0]), 3), # title=xtitles[0], units=xunits[0]) spacing = (lastx[0] - firstx[0]) / int(nx[0] - 1) _x = LinearCoord(offset=firstx[0], increment=spacing, size=int(nx[0]), title=xtitles[0], units=xunits[0]) _y = Coord(timestamps, title='Acquisition timestamp (GMT)', units='s', labels=(acquisitiondates, spectitles)) dataset.set_coordset(y=_y, x=_x) # Set origin and description dataset.origin = "omnic" dataset.description = kwargs.get('description', f'Omnic title: {spg_title}\nOmnic ' f'filename: {filename}') # Set the NDDataset date dataset._date = datetime.now(timezone.utc) # Set origin, description and history dataset.history = str(dataset.date) + ':imported from spg file {} ; '.format(filename) if sortbydate: dataset.sort(dim='y', inplace=True) dataset.history = str(dataset.date) + ':sorted by date' # debug_("end of reading") return dataset # ...................................................................................................................... @importermethod def _read_omnic(*args, **kwargs): return Importer._read_spg(*args, **kwargs) # ...................................................................................................................... @importermethod def _read_spa(*args, **kwargs): dataset, filename = args content = kwargs.get('content', False) if content: fid = io.BytesIO(content) else: fid = open(filename, 'rb') # Read title: # The file title starts at position hex 1e = decimal 30. Its max length # is 256 bytes. It is the original # filename under which the group has been saved: it won't match with # the actual filename if a subsequent # renaming has been done in the OS. spa_title = _readbtext(fid, 30) # The acquisition date (GMT) is at hex 128 = decimal 296. # The format is HFS+ 32 bit hex value, little endian fid.seek(296) # days since 31/12/1899, 00:00 timestamp = _fromfile(fid, dtype="uint32", count=1) acqdate = datetime(1899, 12, 31, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=int(timestamp)) acquisitiondate = acqdate # Transform back to timestamp for storage in the Coord object # use datetime.fromtimestamp(d, timezone.utc)) # to transform back to datetime object timestamp = acqdate.timestamp() # From hex 120 = decimal 304, the spectrum is described # by blocks of lines starting with "key values", # for instance hex[02 6a 6b 69 1b 03 82] -> dec[02 106 107 105 27 03 130] # Each of theses lines provides positions of data and metadata in the file: # # key: hex 02, dec 02: position of spectral header (=> nx, # firstx, lastx, nscans, nbkgscans) # key: hex 03, dec 03: intensity position # key: hex 04, dec 04: user text position # key: hex 1B, dec 27: position of History text # key: hex 69, dec 105: ? # key: hex 6a, dec 106: ? # key: hex 80, dec 128: ? # key: hex 82, dec 130: ? gotinfos = [False, False, False] # spectral header, intensity, history # scan "key values" pos = 304 while not (all(gotinfos)): fid.seek(pos) key = _fromfile(fid, dtype='uint8', count=1) if key == 2: info02 = _readheader02(fid, pos) nx = info02['nx'] firstx = info02['firstx'] lastx = info02['lastx'] xunit = info02['xunits'] xtitle = info02['xtitle'] units = info02['units'] title = info02['title'] gotinfos[0] = True elif key == 3: intensities = _getintensities(fid, pos) gotinfos[1] = True elif key == 27: fid.seek(pos + 2) history_pos = _fromfile(fid, 'uint32', 1) # read history history = _readbtext(fid, history_pos) gotinfos[2] = True elif not key: break pos += 16 fid.close() # load spectral content into the NDDataset dataset.data = np.array(intensities[np.newaxis], dtype='float32') dataset.units = units dataset.title = title dataset.name = filename.stem dataset.filename = str(filename) # now add coordinates # _x = Coord(np.around(np.linspace(firstx, lastx, nx, 3)), title=xtitle, # units=xunit) spacing = (lastx - firstx) / (nx - 1) _x = LinearCoord(offset=firstx, increment=spacing, size=nx, title=xtitle, units=xunit) _y = Coord([timestamp], title='Acquisition timestamp (GMT)', units='s', labels=([acquisitiondate], [filename])) dataset.set_coordset(y=_y, x=_x) # Set origin, description, history, date dataset.origin = "omnic" dataset.description = kwargs.get('description', f'Omnic title: {spa_title}\nOmnic ' f'filename: {filename.name}') dataset.history = str(datetime.now(timezone.utc)) + ':imported from spa files' dataset.history = history dataset._date = datetime.now(timezone.utc) if dataset.x.units is None and dataset.x.title == 'data points': # interferogram dataset.meta.interferogram = True dataset.meta.td = list(dataset.shape) dataset.x._zpd = int(np.argmax(dataset)[-1]) # zero path difference dataset.meta.laser_frequency = Quantity('15798.26 cm^-1') dataset.x.set_laser_frequency() dataset.x._use_time_axis = False # True to have time, else it will # be optical path difference return dataset # ...................................................................................................................... @importermethod def _read_srs(*args, **kwargs): dataset, filename = args frombytes = kwargs.get('frombytes', False) if frombytes: # in this case, filename is actualy a byte content fid = io.BytesIO(filename) else: fid = open(filename, 'rb') # at pos=306 (hex:132) is the position of the xheader fid.seek(306) pos_xheader = _fromfile(fid, dtype='int32', count=1) info, pos = _read_xheader(fid, pos_xheader) # reset current position at the start of next line pos = _nextline(pos) if info['mode'] != 'rapidscan': raise NotImplementedError("Only implemented for rapidscan") # read the data part of series files found = False background = None names = [] data = np.zeros((info['ny'], info['nx'])) # find the position of the background and of the first interferogram # based on # empirical "fingerprints". while not found: pos += 16 fid.seek(pos) line = _fromfile(fid, dtype='uint8', count=16) if np.all(line == [15, 0, 0, 0, 2, 0, 0, 0, 24, 0, 0, 0, 0, 0, 72, 67]): # hex 0F 00 00 00 02 00 00 00 18 00 00 00 00 00 48 43 # this is a fingerprint of header of data fields for # non-processed series # the first one is the background if background is None: pos += 52 fid.seek(pos) key = _fromfile(fid, dtype='uint16', count=1) if key > 0: # a background file was selected; it is present as a # single sided interferogram # key could be the zpd of the double sided interferogram background_size = key - 2 pos += 8 background_name = _readbtext(fid, pos) pos += 256 # max length of text pos += 8 # unknown info ? fid.seek(pos) background = _fromfile(fid, dtype='float32', count=background_size) pos += background_size * 4 pos = _nextline(pos) elif key == 0: # no background file was selected; the background is the # one that was recorded with the series background_size = info['nx'] pos += 8 fid.seek(pos) background = _fromfile(fid, dtype='float32', count=background_size) pos += background_size * 4 background_name = _readbtext(fid, pos) # uncomment below to read unused data (noise measurement ?) # pos += 268 # f.seek(pos) # noisy_data = _fromfile(f, dtype='float32', count=499) pos = _nextline(pos) # Create a NDDataset for the background background = NDDataset(background) _x = Coord(np.around(np.linspace(0, background_size - 1, background_size), 0), title='data points', units='dimensionless') background.set_coordset(x=_x) background.name = background_name background.units = 'V' background.title = 'volts' background.origin = 'omnic' background.description = 'background from omnic srs file.' background.history = str(datetime.now(timezone.utc)) + ':imported from srs file' else: # this is likely the first interferogram of the series found = True names.append(_readbtext(fid, pos + 64)) pos += 148 elif np.all(line == [2, 0, 0, 0, 24, 0, 0, 0, 0, 0, 72, 67, 0, 80, 67, 71]) or np.all( line == [30, 0, 0, 0, 2, 0, 0, 0, 24, 0, 0, 0, 0, 0, 72, 67]): # hex 02 00 00 00 18 00 00 00 00 00 48 43 00 50 43 47 # this is likely header of data field of reprocessed series # the first one is skipped TODO: check the nature of these data if background is None: # skip background = NDDataset() else: # this is likely the first spectrum of the series found = True names.append(_readbtext(fid, pos + 64)) pos += 148 # read first data fid.seek(pos) data[0, :] = _fromfile(fid, dtype='float32', count=info['nx'])[:] pos += info['nx'] * 4 # and the remaining part: for i in np.arange(info['ny'])[1:]: pos += 16 names.append(_readbtext(fid, pos)) pos += 84 fid.seek(pos) data[i, :] = _fromfile(fid, dtype='float32', count=info['nx'])[:] pos += info['nx'] * 4 # Create NDDataset Object for the series dataset = NDDataset(data) dataset.name = info['name'] dataset.units = info['units'] dataset.title = info['title'] dataset.origin = 'omnic' # now add coordinates spacing = (info['lastx'] - info['firstx']) / (info['nx'] - 1) _x = LinearCoord(offset=info['firstx'], increment=spacing, size=info['nx'], title=info['xtitle'], units=info['xunits']) _y = Coord(np.around(np.linspace(info['firsty'], info['lasty'], info['ny']), 3), title='Time', units='minute', labels=names) dataset.set_coordset(y=_y, x=_x) # Set origin, description and history dataset.origin = "omnic" dataset.description = kwargs.get('description', 'Dataset from omnic srs file.') dataset.history = str(datetime.now(timezone.utc)) + ':imported from srs file {} ; '.format(filename) if dataset.x.units is None and dataset.x.title == 'data points': # interferogram dataset.meta.interferogram = True dataset.meta.td = list(dataset.shape) dataset.x._zpd = int(np.argmax(dataset)[-1]) # zero path difference dataset.meta.laser_frequency = Quantity('15798.26 cm^-1') dataset.x.set_laser_frequency() dataset.x._use_time_axis = False # True to have time, else it will # be optical path difference # uncomment below to load the last datafield # has the same dimension as the time axis # its function is not known. related to Grams-schmidt ? # pos = _nextline(pos) # found = False # while not found: # pos += 16 # f.seek(pos) # key = _fromfile(f, dtype='uint8', count=1) # if key == 1: # pos += 4 # f.seek(pos) # X = _fromfile(f, dtype='float32', count=info['ny']) # found = True # # X = NDDataset(X) # _x = Coord(np.around(np.linspace(0, info['ny']-1, info['ny']), 0), # title='time', # units='minutes') # X.set_coordset(x=_x) # X.name = '?' # X.title = '?' # X.origin = 'omnic' # X.description = 'unknown' # X.history = str(datetime.now(timezone.utc)) + ':imported from srs fid.close() return dataset # ...................................................................................................................... def _fromfile(fid, dtype, count): # to replace np.fromfile in case of io.BytesIO object instead of byte # object t = {'uint8': 'B', 'int8': 'b', 'uint16': 'H', 'int16': 'h', 'uint32': 'I', 'int32': 'i', 'float32': 'f', } typ = t[dtype] * count if dtype.endswith('16'): count = count * 2 elif dtype.endswith('32'): count = count * 4 out = struct.unpack(typ, fid.read(count)) if len(out) == 1: return out[0] return np.array(out) # ...................................................................................................................... def _readbtext(fid, pos): # Read some text in binary file, until b\0\ is encountered. # Returns utf-8 string fid.seek(pos) # read first byte, ensure entering the while loop btext = fid.read(1) while not (btext[len(btext) - 1] == 0): # while the last byte of btext differs from # zero btext = btext + fid.read(1) # append 1 byte btext = btext[0:len(btext) - 1] # cuts the last byte try: text = btext.decode(encoding='utf-8') # decode btext to string except UnicodeDecodeError: try: text = btext.decode(encoding='latin_1') except UnicodeDecodeError: text = btext.decode(encoding='utf-8', errors='ignore') return text # ...................................................................................................................... def _nextline(pos): # reset current position to the begining of next line (16 bytes length) return 16 * (1 + pos // 16) # ...................................................................................................................... def _readheader02(fid, pos): # read spectrum header, pos is the position of the 02 key # returns a dict fid.seek(pos + 2) # go to line and skip 2 bytes info_pos = _fromfile(fid, dtype='uint32', count=1) # other positions: # nx_pos = info_pos + 4 # xaxis unit code = info_pos + 8 # data unit code = info_pos + 12 # fistx_pos = info_pos + 16 # lastx_pos = info_pos + 20 # nscan_pos = info_pos + 36; # nbkgscan_pos = info_pos + 52; fid.seek(info_pos + 4) out = {'nx': _fromfile(fid, 'uint32', 1)} # read xaxis unit fid.seek(info_pos + 8) key = _fromfile(fid, dtype='uint8', count=1) if key == 1: out['xunits'] = 'cm ^ -1' out['xtitle'] = 'wavenumbers' elif key == 2: out['xunits'] = None out['xtitle'] = 'data points' elif key == 3: out['xunits'] = 'nm' out['xtitle'] = 'wavelengths' elif key == 4: out['xunits'] = 'um' out['xtitle'] = 'wavelengths' elif key == 32: out['xunits'] = 'cm^-1' out['xtitle'] = 'raman shift' else: out['xunits'] = None out['xtitle'] = 'xaxis' # warning: 'The nature of data is not # recognized, xtitle set to \'xaxis\') # read data unit fid.seek(info_pos + 12) key = _fromfile(fid, dtype='uint8', count=1) if key == 17: out['units'] = 'absorbance' out['title'] = 'absorbance' elif key == 16: out['units'] = 'percent' out['title'] = 'transmittance' elif key == 11: out['units'] = 'percent' out['title'] = 'reflectance' elif key == 12: out['units'] = None out['title'] = 'Log(1/R)' elif key == 20: out['units'] = 'Kubelka_Munk' out['title'] = 'Kubelka-Munk' elif key == 22: out['units'] = 'V' out['title'] = 'detector signal' elif key == 26: out['units'] = None out['title'] = 'photoacoustic' elif key == 31: out['units'] = None out['title'] = 'raman intensity' else: out['units'] = None out['title'] = 'intensity' # warning: 'The nature of data is not # recognized, title set to \'Intensity\') fid.seek(info_pos + 16) out['firstx'] = _fromfile(fid, 'float32', 1) fid.seek(info_pos + 20) out['lastx'] = _fromfile(fid, 'float32', 1) fid.seek(info_pos + 36) out['nscan'] = _fromfile(fid, 'uint32', 1) fid.seek(info_pos + 52) out['nbkgscan'] = _fromfile(fid, 'uint32', 1) return out # ...................................................................................................................... def _read_xheader(fid, pos): # read spectrum header, pos is the position of the 03 or 01 key # for series files # return a dict and updated position in the file # Todo: merge with _readheader02 fid.seek(pos) key = _fromfile(fid, dtype='uint8', count=1) if key not in (1, 3): raise ValueError( "xheader key={} not recognized yet.".format(key) + " Please report this error (and the corresponding srs " "file) to the developers" "They will do their best to fix the issue") else: out = {'xheader': key} # positions # nx_pos = info_pos + 4 # xaxis unit code = info_pos + 8 # data unit code = info_pos + 12 # fistx_pos = info_pos + 16 # lastx_pos = info_pos + 20 # scan_pts_pos = info_pos + 29, # nscan_pos = info_pos + 36; # nbkgscan_pos = info_pos + 52; fid.seek(pos + 4) out['nx'] = _fromfile(fid, 'uint32', count=1) # read xaxis unit fid.seek(pos + 8) key = _fromfile(fid, dtype='uint8', count=1) if key == 1: out['xunits'] = 'cm ^ -1' out['xtitle'] = 'wavenumbers' elif key == 2: out['xunits'] = None out['xtitle'] = 'data points' elif key == 3: out['xunits'] = 'nm' out['xtitle'] = 'wavelengths' elif key == 4: out['xunits'] = 'um' out['xtitle'] = 'wavelengths' elif key == 32: out['xunits'] = 'cm^-1' out['xtitle'] = 'raman shift' else: out['xunits'] = None out['xtitle'] = 'xaxis' # warning: 'The nature of data is not # recognized, xtitle set to \'xaxis\') # read data unit fid.seek(pos + 12) key = _fromfile(fid, dtype='uint8', count=1) if key == 17: out['units'] = 'absorbance' out['title'] = 'absorbance' elif key == 16: out['units'] = 'percent' out['title'] = 'transmittance' elif key == 11: out['units'] = 'percent' out['title'] = 'reflectance' elif key == 12: out['units'] = None out['title'] = 'log(1/R)' elif key == 20: out['units'] = 'Kubelka_Munk' out['title'] = 'Kubelka-Munk' elif key == 22: out['units'] = 'V' out['title'] = 'detector signal' elif key == 26: out['units'] = None out['title'] = 'photoacoustic' elif key == 31: out['units'] = None out['title'] = 'raman intensity' else: out['title'] = None out['title'] = 'intensity' # warning: 'The nature of data is not # recognized, title set to \'Intensity\') fid.seek(pos + 16) out['firstx'] = _fromfile(fid, 'float32', 1) fid.seek(pos + 20) out['lastx'] = _fromfile(fid, 'float32', 1) fid.seek(pos + 28) out['scan_pts'] = _fromfile(fid, 'uint32', 1) fid.seek(pos + 32) out['zpd'] = _fromfile(fid, 'uint32', 1) fid.seek(pos + 36) out['nscan'] = _fromfile(fid, 'uint32', 1) fid.seek(pos + 52) out['nbkgscan'] = _fromfile(fid, 'uint32', 1) if out['nbkgscan'] == 0: # then probably interferogram in rapid scan mode # out['units'] = 'V' # out['title'] = 'Volts' # out['xunits'] = 'dimensionless' # out['xtitle'] = 'Data points' if out['firstx'] > out['lastx']: out['firstx'], out['lastx'] = out['lastx'], out['firstx'] out['mode'] = 'rapidscan' else: out['mode'] = 'GC-IR or TGA-IR' out['name'] = _readbtext(fid, pos + 938) fid.seek(pos + 1002) out['coll_length'] = _fromfile(fid, 'float32', 1) * 60 fid.seek(pos + 1006) out['lasty'] = _fromfile(fid, 'float32', 1) fid.seek(pos + 1010) out['firsty'] = _fromfile(fid, 'float32', 1) fid.seek(pos + 1026) out['ny'] = _fromfile(fid, 'uint32', 1) # y unit could be at pos+1030 with 01 = minutes ? return out, pos + 1026 # ...................................................................................................................... def _getintensities(fid, pos): # get intensities from the 03 key # returns a ndarray fid.seek(pos + 2) # skip 2 bytes intensity_pos = _fromfile(fid, 'uint32', 1) fid.seek(pos + 6) intensity_size = _fromfile(fid, 'uint32', 1) nintensities = int(intensity_size / 4) # Read and return spectral intensities fid.seek(intensity_pos) return _fromfile(fid, 'float32', int(nintensities)) # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/spectrochempy/core/readers/importer.py # -*- coding: utf-8 -*- # # ===================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ===================================================================================================================== # """This module define a generic class to import files and contents. """ __all__ = ['read'] __dataset_methods__ = __all__ from warnings import warn from datetime import datetime, timezone from traitlets import HasTraits, List, Dict, Type, Unicode from spectrochempy.utils import pathclean, check_filename_to_open from spectrochempy.utils.exceptions import DimensionsCompatibilityError, ProtocolError from spectrochempy.core import warning_ FILETYPES = [('scp', 'SpectroChemPy files (*.scp)'), ('omnic', 'Nicolet OMNIC files and series (*.spa *.spg *.srs)'), ('labspec', 'LABSPEC exported files (*.txt)'), ('opus', 'Bruker OPUS files (*.[0-9]*)'), ('topspin', 'Bruker TOPSPIN fid or series or processed data files (fid ser 1[r|i] 2[r|i]* 3[r|i]*)'), ('matlab', 'MATLAB files (*.mat)'), ('dso', 'Data Set Object files (*.dso)'), ('jcamp', 'JCAMP-DX files (*.jdx *.dx)'), ('csv', 'CSV files (*.csv)'), ('excel', 'Microsoft Excel files (*.xls)'), ('zip', 'Compressed folder of data files (*.zip)'), ('quadera', 'Quadera ascii files (*.asc)') # ('all', 'All files (*.*)') ] ALIAS = [('spg', 'omnic'), ('spa', 'omnic'), ('srs', 'omnic'), ('mat', 'matlab'), ('txt', 'labspec'), ('jdx', 'jcamp'), ('dx', 'jcamp'), ('xls', 'excel'), ('asc', 'quadera')] # ---------------------------------------------------------------------------------------------------------------------- class Importer(HasTraits): # Private _Importer class objtype = Type datasets = List files = Dict default_key = Unicode protocol = Unicode protocols = Dict filetypes = Dict def __init__(self): self.filetypes = dict(FILETYPES) temp = list(zip(*FILETYPES)) temp.reverse() self.protocols = dict(zip(*temp)) # add alias self.alias = dict(ALIAS) # .................................................................................................................. def __call__(self, *args, **kwargs): self.datasets = [] self.default_key = kwargs.pop('default_key', '.scp') if 'merge' not in kwargs.keys(): # if merge is not specified, but the args are provided as a single list, then will are supposed to merge # the datasets. If merge is specified then it has priority. # This is not usefull for the 1D datasets, as if they are compatible they are merged automatically if args and len(args) == 1 and isinstance(args[0], (list, tuple)): kwargs['merge'] = True args, kwargs = self._setup_objtype(*args, **kwargs) res = check_filename_to_open(*args, **kwargs) if res: self.files = res else: return None for key in self.files.keys(): if key == 'frombytes': # here we need to read contents for filename, content in self.files[key].items(): files_ = check_filename_to_open(filename) kwargs['content'] = content key_ = list(files_.keys())[0] self._switch_protocol(key_, files_, **kwargs) if len(self.datasets) > 1: self.datasets = self._do_merge(self.datasets, **kwargs) elif key and key[1:] not in list(zip(*FILETYPES))[0] + list(zip(*ALIAS))[0]: continue else: # here files are read from the disk using filenames self._switch_protocol(key, self.files, **kwargs) # now we will reset preference for this newly loaded datasets if len(self.datasets) > 0: prefs = self.datasets[0].preferences prefs.reset() if len(self.datasets) == 1: nd = self.datasets[0] # a single dataset is returned name = kwargs.pop('name', None) if name: nd.name = name return nd else: nds = self.datasets names = kwargs.pop('names', None) if names and len(names) == len(nds): for nd, name in zip(nds, names): nd.name = name elif names and len(names) != len(nds): warn('length of the `names` list and of the list of datsets mismatch - names not applied') return nds # .................................................................................................................. def _setup_objtype(self, *args, **kwargs): # check if the first argument is an instance of NDDataset or Project args = list(args) if args and hasattr(args[0], 'implements') and args[0].implements() in ['NDDataset']: # the first arg is an instance of NDDataset object = args.pop(0) self.objtype = type(object) else: # by default returned objtype is NDDataset (import here to avoid circular import) from spectrochempy.core.dataset.nddataset import NDDataset self.objtype = kwargs.pop('objtype', NDDataset) return args, kwargs # .................................................................................................................. def _switch_protocol(self, key, files, **kwargs): protocol = kwargs.get('protocol', None) if protocol is not None and protocol != 'ALL': if not isinstance(protocol, list): protocol = [protocol] if key and key[1:] not in protocol and self.alias[key[1:]] not in protocol: return datasets = [] for filename in files[key]: try: read_ = getattr(self, f"_read_{key[1:]}") except AttributeError: warning_(f'a file with extension {key} was found in this directory but will be ignored') try: res = read_(self.objtype(), filename, **kwargs) if not isinstance(res, list): datasets.append(res) else: datasets.extend(res) except FileNotFoundError: warning_(f'No file with name `{filename}` could be found. Sorry! ') except IOError as e: warning_(str(e)) except Exception: warning_(f'The file `{filename}` has a known extension but it could not be read. It is ignored!') if len(datasets) > 1: datasets = self._do_merge(datasets, **kwargs) if kwargs.get('merge', False): datasets[0].name = pathclean(filename).stem datasets[0].filename = pathclean(filename) self.datasets.extend(datasets) def _do_merge(self, datasets, **kwargs): # several datasets returned (only if several files have been passed) and the `merge` keyword argument is False merged = kwargs.get('merge', False) shapes = {nd.shape for nd in datasets} if len(shapes) == 1: # homogeneous set of files dim0 = shapes.pop()[0] if dim0 == 1: merged = kwargs.get('merge', True) # priority to the keyword setting else: merged = kwargs.get('merge', False) if merged: # Try to stack the dataset into a single one try: dataset = self.objtype.stack(datasets) if kwargs.pop("sortbydate", True): dataset.sort(dim='y', inplace=True) dataset.history = str(datetime.now(timezone.utc)) + ':sorted by date' datasets = [dataset] except DimensionsCompatibilityError as e: warn(str(e)) # return only the list return datasets # ...................................................................................................................... def importermethod(func): # Decorateur setattr(Importer, func.__name__, staticmethod(func)) return func # ---------------------------------------------------------------------------------------------------------------------- # Generic Read function # ---------------------------------------------------------------------------------------------------------------------- def read(*paths, **kwargs): """ Generic read method. This method is generally abble to load experimental files based on extensions. Parameters ---------- *paths : str, pathlib.Path object, list of str, or list of pathlib.Path objects, optional The data source(s) can be specified by the name or a list of name for the file(s) to be loaded: *e.g.,( file1, file2, ..., **kwargs )* If the list of filenames are enclosed into brackets: *e.g.,* ( **[** *file1, file2, ...* **]**, **kwargs *)* The returned datasets are merged to form a single dataset, except if `merge` is set to False. If a source is not provided (i.e. no `filename`, nor `content`), a dialog box will be opened to select files. **kwargs : dict See other parameters. Returns -------- read |NDDataset| or list of |NDDataset|. Other Parameters ---------------- protocol : {'scp', 'omnic', 'opus', 'topspin', 'matlab', 'jcamp', 'csv', 'excel'}, optional Protocol used for reading. If not provided, the correct protocol is inferred (whnever it is possible) from the file name extension. directory : str, optional From where to read the specified `filename`. If not specified, read in the default ``datadir`` specified in SpectroChemPy Preferences. merge : bool, optional Default value is False. If True, and several filenames have been provided as arguments, then a single dataset with merged (stacked along the first dimension) is returned (default=False). sortbydate : bool, optional Sort multiple spectra by acquisition date (default=True). description : str, optional A Custom description. origin : {'omnic', 'tga'}, optional In order to properly interpret CSV file it can be necessary to set the origin of the spectra. Up to now only 'omnic' and 'tga' have been implemented. csv_delimiter : str, optional Set the column delimiter in CSV file. By default it is the one set in SpectroChemPy ``Preferences``. content : bytes object, optional Instead of passing a filename for further reading, a bytes content can be directly provided as bytes objects. The most convenient way is to use a dictionary. This feature is particularly useful for a GUI Dash application to handle drag and drop of files into a Browser. For exemples on how to use this feature, one can look in the ``tests/tests_readers`` directory. listdir : bool, optional If True and filename is None, all files present in the provided `directory` are returned (and merged if `merge` is True. It is assumed that all the files correspond to current reading protocol (default=True) recursive : bool, optional Read also in subfolders. (default=False) See Also -------- read_topspin : Read TopSpin Bruker NMR spectra. read_omnic : Read Omnic spectra. read_opus : Read OPUS spectra. read_labspec : Read Raman LABSPEC spectra. read_spg : Read Omnic *.spg grouped spectra. read_spa : Read Omnic *.Spa single spectra. read_srs : Read Omnic series. read_csv : Read CSV files. read_zip : Read Zip files. read_matlab : Read Matlab files. Examples --------- Reading a single OPUS file (providing a windows type filename relative to the default ``Datadir``) >>> import spectrochempy as scp >>> scp.read('irdata\\\\OPUS\\\\test.0000') NDDataset: [float64] a.u. (shape: (y:1, x:2567)) Reading a single OPUS file (providing a unix/python type filename relative to the default ``Datadir``) Note that here read_opus is called as a classmethod of the NDDataset class >>> scp.NDDataset.read('irdata/OPUS/test.0000') NDDataset: [float64] a.u. (shape: (y:1, x:2567)) Single file specified with pathlib.Path object >>> from pathlib import Path >>> folder = Path('irdata/OPUS') >>> p = folder / 'test.0000' >>> scp.read(p) NDDataset: [float64] a.u. (shape: (y:1, x:2567)) Multiple files not merged (return a list of datasets). Note that a directory is specified >>> le = scp.read('test.0000', 'test.0001', 'test.0002', directory='irdata/OPUS') >>> len(le) 3 >>> le[0] NDDataset: [float64] a.u. (shape: (y:1, x:2567)) Multiple files merged as the `merge` keyword is set to true >>> scp.read('test.0000', 'test.0001', 'test.0002', directory='irdata/OPUS', merge=True) NDDataset: [float64] a.u. (shape: (y:3, x:2567)) Multiple files to merge : they are passed as a list instead of using the keyword `merge` >>> scp.read(['test.0000', 'test.0001', 'test.0002'], directory='irdata/OPUS') NDDataset: [float64] a.u. (shape: (y:3, x:2567)) Multiple files not merged : they are passed as a list but `merge` is set to false >>> le = scp.read(['test.0000', 'test.0001', 'test.0002'], directory='irdata/OPUS', merge=False) >>> len(le) 3 Read without a filename. This has the effect of opening a dialog for file(s) selection >>> nd = scp.read() Read in a directory (assume that only OPUS files are present in the directory (else we must use the generic `read` function instead) >>> le = scp.read(directory='irdata/OPUS') >>> len(le) 2 Again we can use merge to stack all 4 spectra if thet have compatible dimensions. >>> scp.read(directory='irdata/OPUS', merge=True) [NDDataset: [float64] a.u. (shape: (y:4, x:2567)), NDDataset: [float64] a.u. (shape: (y:1, x:5549))] """ importer = Importer() protocol = kwargs.get('protocol', None) available_protocols = list(importer.protocols.values()) available_protocols.extend(list(importer.alias.keys())) # to handle variants of protocols if protocol is None: kwargs['filetypes'] = list(importer.filetypes.values()) kwargs['protocol'] = 'ALL' else: try: kwargs['filetypes'] = [importer.filetypes[protocol]] except KeyError: raise ProtocolError(protocol, list(importer.protocols.values())) return importer(*paths, **kwargs) # ...................................................................................................................... @importermethod def _read_scp(*args, **kwargs): dataset, filename = args return dataset.load(filename, **kwargs) # ...................................................................................................................... @importermethod def _read_(*args, **kwargs): dataset, filename = args if not filename or filename.is_dir(): return Importer._read_dir(*args, **kwargs) protocol = kwargs.get('protocol', None) if protocol and '.scp' in protocol: return dataset.load(filename, **kwargs) elif filename and filename.name in ('fid', 'ser', '1r', '2rr', '3rrr'): # probably an Topspin NMR file return dataset.read_topspin(filename, **kwargs) elif filename: # try scp format try: return dataset.load(filename, **kwargs) except Exception: # lets try some common format for key in ['omnic', 'opus', 'topspin', 'labspec', 'matlab', 'jdx']: try: _read = getattr(dataset, f"read_{key}") f = f'{filename}.{key}' return _read(f, **kwargs) except Exception: pass raise NotImplementedError # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': pass <file_sep>/spectrochempy/core/analysis/cantera_utilities.py # -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Description # Utility functions to deal with Cantera input/output # # --------------------------------------------------------------------------------- import importlib import datetime import numpy as np from scipy.optimize import minimize __all__ = ['coverages_vs_time', 'concentrations_vs_time', 'modify_rate', 'modify_reactive_phase', 'fit_to_concentrations'] HAS_CANTERA = importlib.util.find_spec("cantera") if HAS_CANTERA: import cantera as ct from spectrochempy.core.dataset.nddataset import NDDataset, Coord from spectrochempy.utils.exceptions import SpectroChemPyException def coverages_vs_time(surface, t, returnNDDataset=False): ''' Returns the surface coverages at time(s) t params: ------ surface: instance of cantera.composite.Interface t: iterable or spectrochempy.Coord, times at which the coverages must be computed return_NDDataset: boolean, if True returns the concentration matrix as a NDDataset, else as a np.ndarray default: False ''' init_coverages = surface.coverages coverages = np.zeros((len(t), surface.coverages.shape[0])) if type(t) is Coord: t = t.data for i, ti in enumerate(t): surface.coverages = init_coverages surface.advance_coverages(ti) coverages[i, :] = surface.coverages surface.coverages = init_coverages if returnNDDataset: coverages = NDDataset(coverages) coverages.y = Coord(t, title='time') coverages.x.title = 'coverage / -' coverages.x.labels = surface.species_names return coverages def concentrations_vs_time(reactive_phase, t, reactorNet=None, returnNDDataset=False): ''' Returns the concentrations at time(s) t params: ------ surface: instance of cantera.composite.Interface or t: iterable or spectrochempy.Coord, times at which the concentrations must be computed return_NDDataset: boolean, if True returns the concentration matrix as a NDDataset, else as a np.ndarray default: False ''' if not HAS_CANTERA: raise SpectroChemPyException('Cantera is not available : please install it before continuing: \n' 'conda install -c cantera cantera') if type(reactive_phase) is ct.composite.Interface: concentrations = coverages_vs_time(reactive_phase, t, returnNDDataset) * reactive_phase.site_density if returnNDDataset: concentrations.x.title = 'concentration' return concentrations else: raise NotImplementedError('not implmented for reactive_phase={}'.format(str(type(reactive_phase)))) # # code for reactorNet # if type(t) is Coord: # t = t.data # # for i, ti in enumerate(t): # reactorNet.advance(ti) # concentrations[i, :] = reactive_phase.concentrations # reactive_phase.concentrations = init_concentrations # # # if returnNDDataset: # concentrations = NDDataset(concentrations) # concentrations.y = Coord(t, title='time') # concentrations.x.title = 'concentrations' # concentrations.x.labels = reactive_phase.species_names def modify_rate(reactive_phase, i_reaction, rate): """ Changes one of the rates of a cantera reactive phase. Parameters ---------- reactive_phase : i_reaction : rate : Returns ------- reactive_phase """ rxn = reactive_phase.reaction(i_reaction) rxn.rate = rate reactive_phase.modify_reaction(i_reaction, rxn) return reactive_phase def modify_reactive_phase(reactive_phase, param_to_change, param_value): """changes a set of numerical parameters of a cantera reactive phase. only implemented for cantera.composite.Interface and the following parameters: site_density, coverages, concentrations, pre-exponential factor, temperature_exponent, activation_energy """ if not HAS_CANTERA: raise SpectroChemPyException('Cantera is not available : please install it before continuing: \n' 'conda install -c cantera cantera') # check some parameters if type(reactive_phase) is not ct.composite.Interface: raise ValueError('only implemented of ct.composite.Interface') if len(param_to_change) != len(param_value): raise ValueError('number of parameters to change and values should be equal') for i, param in enumerate(param_to_change): # check that param_to_change exists try: eval('reactive_phase.' + param) except ValueError: print('class {} has no \'{}\' attribute'.format(type(reactive_phase), param)) raise # if exists => sets its new value # if the attribute is writable: if param in ('site_density', 'coverages', 'concentrations'): exec('reactive_phase.' + param + '=' + str(param_value[i])) # else use Cantera methods (or derived from cantera) elif param.split('.')[-1] == 'pre_exponential_factor': str_rate = 'reactive_phase.' + '.'.join(param.split('.')[-3:-1]) b, E = eval(str_rate + '.temperature_exponent,' + str_rate + '.activation_energy ') rxn = int(param.split('.')[0].split('[')[-1].split(']')[0]) modify_rate(reactive_phase, rxn, ct.Arrhenius(param_value[i], b, E)) elif param.split('.')[-1] == 'temperature_exponent': str_rate = 'reactive_phase.' + '.'.join(param.split('.')[-3:-1]) A, E = eval(str_rate + 'pre_exponential_factor,' + str_rate + '.activation_energy ') rxn = int(param.split('.')[0].split('[')[-1].split(']')[0]) modify_rate(reactive_phase, rxn, ct.Arrhenius(A, param_value[i], E)) elif param.split('.')[-1] == 'activation_energy': str_rate = 'reactive_phase.' + '.'.join(param.split('.')[-3:-1]) A, b = eval(str_rate + 'pre_exponential_factor,' + str_rate + '.temperature_exponent') rxn = int(param.split('.')[0].split('[')[-1].split(']')[0]) modify_rate(reactive_phase, rxn, ct.Arrhenius(A, b, param_value[i])) return def fit_to_concentrations(C, externalConc, external_to_C_idx, reactive_phase, param_to_optimize, guess_param, **kwargs): """ Function fitting rate parameters and concentrations to a given concentration profile. Parameters ------------ C: NDDataset experimental concentration profiles on which to fit the model. C can contain more concentration profiles than those to fit. externalConc: indexes of experimental concentration profiles on which the model will be fitted external_to_C_idx: correspondence between optimized (external) concentration profile and experimental concentration profile reactivePhase: cantera active phase. Currently implemented for surface only param_to_optimize: list list of reactive phase parameters to optomize guess_param: initial guess for the parameters to fit **kwargs: parameters for the optimization (see scipy.optimize.minimize) Returns ---------- a dictionary """ def objective(param_value, param_to_optimize, C, externalConc, external_to_C_idx, surface): modify_reactive_phase(surface, param_to_optimize, param_value) Chat = concentrations_vs_time(surface, C.y) return np.sum(np.square(C.data[:, externalConc] - Chat[:, external_to_C_idx])) method = kwargs.get("method", "Nelder-Mead") bounds = kwargs.get("bounds", None) tol = kwargs.get("tol", None) options = kwargs.get("options", { 'disp': True }) if options['disp']: print('Optimization of the parameters.') print(' Initial parameters: {}'.format(guess_param)) print(' Initial function value: {}'.format(objective(guess_param, param_to_optimize, C, externalConc, external_to_C_idx, reactive_phase))) tic = datetime.datetime.now(datetime.timezone.utc) res = minimize(objective, guess_param, args=(param_to_optimize, C, externalConc, external_to_C_idx, reactive_phase), method=method, bounds=bounds, tol=tol, options=options) toc = datetime.datetime.now(datetime.timezone.utc) guess_param = res.x if options['disp']: print(' Optimization time: {}'.format((toc - tic))) print(' Final parameters: {}'.format(guess_param)) Ckin = concentrations_vs_time(reactive_phase, C.y, returnNDDataset=True) newargs = (reactive_phase, param_to_optimize, guess_param) return { 'concentrations': Ckin, 'results': res, 'new_args': newargs } <file_sep>/CHANGELOG.md # What\'s new ## Version 0.2.15 **NEW FEATURES** * Added a baseline correction method: `basc`. ## Version 0.2.14 **NEW FEATURES** * A default coordinate can now be selected for multiple coordinates dimensions. **BUGS FIXED** * Alignment along several dimensions (issue #248) * to() and ito() methods have been fixed to work correctly (issue #255) * Baseline correction works on all dimensions ## Version 0.2.13 **BUGS FIXED** * Solved the problem that reading of experimental datasets was too slow in v.0.2.12. ## Version 0.2.12 **BUGS FIXED** * LinearCoord operations now working. * Baseline default now "sequential" as expected. **WARNING**: It was wrongly set to "mutivariate" in previous releases, so you should expect some difference with processings you may have done before. * Comparison of coordinates now correct for mathematical operations. * Alignment methods now working (except for multidimensional alignement). ## Version 0.2.11 **BUGS FIXED** * Plot2D now works when more than one coord in 'y' axis (#238). * Spectrochempy_data location have been corrected (#239). ## Version 0.2.10 **NEW FEATURES** * All data for tests and examples are now external. They are now located in a separate conda package: `spectrochempy_data`. * Installation in Colab with Examples is now supported. **BUGS FIXED** * Read_quadera() and example now based on a correct asc file ## Version 0.2.9 **BUGS FIXED** * Hotfix regarding dispay of NMR x scale ## Version 0.2.8 **NEW FEATURES** * Added write_csv() dir 1D datasets * Added read_quadera() for Pfeiffer Vacuum's QUADERA® MS files * Added test for trapz(), simps(), readquadera() * Improved displaying of Interferograms **BUGS FIXED** * Problem with trapz(), simps() * FIX: interferogram x scaling ## Version 0.2.7 **NEW FEATURES** * Test and data for read_carroucell(), read_srs(), read_dso() * Added NMR processing of 2D spectra. * Added FTIR interferogram processing. **BUGS FIXED** * Problem with read_carroucell(), read_srs(), read_dso() * Colaboratory compatibility * Improved check updates ## Version 0.2.6 **NEW FEATURES** * Check for new version on anaconda cloud spectrocat channel. * 1D NMR processing with the addition of several new methods. * Improved handling of Linear coordinates. **BUGS FIXED** * Adding quantity to datasets with different scaling (#199). * Math operates now on linear coordinates. * Compatibility with python 3.6 ## Version 0.2.5 **TASKS** * Docker image building. * instructions to use it added in the documentation. **NEW FEATURES** * cantera installation optional. * use of pyqt for matplotlib optional. **BUGS FIXED** * added fonts in order to solve missing fonts problems on linux and windows. ## Version 0.2.4 **TASKS** * Documentation largely revisited and hopefully improved. *Still some work to be done*. * NDMath (mathematical and dataset creation routines) module revisited. *Still some work to be done*. **NEW FEATURES** * Changed CoordRange behavior. **BUGS FIXED** * Fix a problem with importing the API. * Fix dim handling in processing functions. ## Version 0.2.0 **NEW FEATURES** * Copyright update. * Requirements and env yml files updated. * Use of the coordinates in math operation improved. * Added ROI and Offset properties to NDArrays. * Readers / Writers revisited. * Bruker TOPSPIN reader. * Added LabSpec reader for .txt exported files. * Simplified the format of scp file - now zipped JSON files. * Rewriting json serialiser. * Add function pathclean to the API. * Add some array creation function to NDMath. * Refactoring plotting preferences system. * Baseline correction now accept single value for ranges. * Add a waterfall plot. * Refactoring plot2D and 1D methods. * Added Simpson'rule integration. * Addition of multiple coordinates to a dimension works better. * Added Linear coordinates (EXPERIMENTAL). * Test for NDDataset dtype change at initialisation. * Added subdir of txt files in ramandata. * Comparison of datasets improved in testing.py. * Comparison of datasets and projects. **BUGS FIXED** * Dtype parameter was not taken into account during initialisation of NDArrays. * Math function behavior for coords. * Color normalisation on the full range for colorscale. * Configuration settings in the main application. * Compatibility read_zip with py3.7. * NDpanel temporary removed from the master. * 2D IRIS fixed. * Trapz integration to return NDDataset. * Suppressed a forgotten sleep statement that was slowing down the SpectroChemPy initialisation. * Error in SIMPLISMA (changed affectations such as C.data[...] = something by C[...] = something. * Cleaning mplstyle about non-style parameters and fix makestyle. * Argument of set_xscale. * Use read_topspin instead of the deprecated function read_bruker_nmr. * Some issues with interactive baseline. * Baseline and fitting tutorials. * Removed dependency of isotopes.py to pandas. ## Version 0.1.x * Initial development versions. <file_sep>/setup.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # ====================================================================================================================== # import atexit import warnings import shutil from pathlib import Path from setuptools import setup, find_packages from setuptools.command.develop import develop as _develop from setuptools.command.install import install as _install def _install_mpl(): """ Install matplotlib styles and fonts """ try: import matplotlib as mpl from matplotlib import get_cachedir except ImportError: warnings.warn('Sorry, but we cannot install mpl plotting styles and fonts ' 'if MatPlotLib is not installed.\n' 'Please install MatPlotLib using:\n' ' pip install matplotlib\n' 'or\n' ' conda install matplotlib\n' 'and then install again.') return # install all plotting styles in the matplotlib stylelib library stylesheets = Path("scp_data") / "stylesheets" if not stylesheets.exists(): raise IOError(f"Can't find the stylesheets from SpectroChemPy {str(stylesheets)}.\n" f"Installation incomplete!") cfgdir = Path(mpl.get_configdir()) stylelib = cfgdir / 'stylelib' if not stylelib.exists(): stylelib.mkdir() styles = stylesheets.glob('*.mplstyle') for src in styles: dest = stylelib / src.name shutil.copy(src, dest) print(f'Stylesheets installed in {dest}') # install fonts in mpl-data # https://stackoverflow.com/a/47743010 # Copy files over # _dir_data = Path(matplotlib_fname()).parent _dir_data = Path(mpl.rcParams['datapath']) dir_source = Path("scp_data") / 'fonts' if not dir_source.exists(): raise IOError(f'directory {dir_source} not found!') dir_dest = _dir_data / 'fonts' / 'ttf' if not dir_dest.exists(): dir_dest.mkdir(parents=True, exist_ok=True) for file in dir_source.glob('*.[ot]tf'): if not (dir_dest / file.name).exists(): print(f'Adding font "{file.name}".') shutil.copy(file, dir_dest) if (dir_dest / file.name).exists(): print('success') # Delete cache dir_cache = Path(get_cachedir()) for file in list(dir_cache.glob('*.cache')) + list(dir_cache.glob('font*')): if not file.is_dir(): # don't dump the tex.cache folder... because dunno why file.unlink() print(f'Deleted font cache {file}.') class PostInstallCommand(_install): """Post-installation for installation mode.""" def run(self): _install_mpl() _install.run(self) class PostDevelopCommand(_develop): """Post-installation for development mode.""" def run(self): _install_mpl() _develop.run(self) # Data for setuptools packages = [] setup_args = dict( # packages informations name="spectrochempy", use_scm_version=True, license="CeCILL-B Free Software", author="<NAME> & <NAME>", author_email="contact (at) spectrochempy.fr", maintainer="<NAME>", maintainer_email="christian.fernandez (at) ensicaen.fr", url='http:/www.spectrochempy.fr', description='Processing, analysis and modelling Spectroscopic data for ' 'Chemistry with Python', long_description=Path('README.md').read_text(), long_description_content_type="text/markdown", classifiers=["Development Status :: 3 - Alpha", "Topic :: Utilities", "Topic :: Scientific/Engineering", "Topic :: Software Development :: Libraries", "Intended Audience :: Science/Research", "License :: CeCILL-B Free Software License Agreement (CECILL-B)", "Operating System :: OS Independent", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", ], platforms=['Windows', 'Mac OS X', 'Linux'], # packages discovery zip_safe=False, packages=find_packages() + packages, include_package_data=True, # requirements python_requires=">=3.6.9", setup_requires=['setuptools_scm', 'matplotlib'], install_requires=['matplotlib'], # install_requires(dev=__DEV__), # tests_require=extras_require['tests'], # post-commands cmdclass={'develop': PostDevelopCommand, 'install': PostInstallCommand, }, # scripts # # scripts = {'scripts/launch_api.py'}, # entry_points={'console_scripts': ['scpy_update=spectrochempy.scripts.scpy_update:main'], }, ) # ====================================================================================================================== if __name__ == '__main__': # execute setup setup(**setup_args) <file_sep>/spectrochempy/core/project/baseproject.py # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== # import uuid from traitlets import HasTraits __all__ = [] class AbstractProject(HasTraits): """ Project class will subclass it. This is mainly for type comparison purpose """ <file_sep>/spectrochempy/core/dataset/ndmath.py # -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ This module implements the |NDMath| class. """ __all__ = ['NDMath', ] __dataset_methods__ = [] import copy as cpy import functools import inspect import sys import operator from warnings import catch_warnings import numpy as np from orderedset import OrderedSet from quaternion import as_float_array from spectrochempy.units.units import ur, Quantity, DimensionalityError from spectrochempy.core.dataset.ndarray import NDArray from spectrochempy.utils import NOMASK, TYPE_COMPLEX, quat_as_complex_array, as_quaternion from spectrochempy.core import warning_, error_ from spectrochempy.utils.testing import assert_dataset_almost_equal from spectrochempy.utils.exceptions import CoordinateMismatchError # ====================================================================================================================== # utilities # ====================================================================================================================== def _reduce_method(method): # Decorator # --------- # set the flag reduce to true for the _from numpy decorator. Must be placed above this decorator. # e.g., # @_reduce_method # @_from_numpy_method # def somefunction(....): # method.reduce = True return method class _from_numpy_method(object): # Decorator # --------- # This decorator assumes that the signature starts always by : (cls, ...) # the second positional only argument can be `dataset` - in this case this mean that the function apply on a # dataset reduce = False def __init__(self, method): self.method = method def __get__(self, instance, cls): @functools.wraps(self.method) def func(*args, **kwargs): from spectrochempy.core.dataset.nddataset import NDDataset from spectrochempy.core.dataset.coord import Coord method = self.method.__name__ pars = inspect.signature(self.method).parameters args = list(args) klass = NDDataset # by default new = klass() if 'dataset' not in pars: if instance is not None: klass = type(instance) elif issubclass(cls, (NDDataset, Coord)): klass = cls else: # Probably a call from the API ! # We return a NDDataset class constructor klass = NDDataset else: # determine the input object if instance is not None: # the call is made as an attributes of the instance # instance.method(...) new = instance.copy() args.insert(0, new) else: dataset = cpy.copy(args[0]) try: # call as a classmethod # class.method(dataset, ...) new = cls(dataset) except TypeError: if issubclass(cls, NDMath): # Probably a call from the API ! # spc.method(dataset, ...) new = dataset if not isinstance(new, NDArray): # we have only an array-like dataset # make a NDDataset object from it new = NDDataset(dataset) argpos = [] for par in pars.values(): if par.name in ['self', 'cls', 'kwargs']: # or (par.name == 'dataset' and instance is not None): continue argpos.append(args.pop(0) if args else kwargs.pop(par.name, par.default)) # in principle args should be void at this point assert not args # ----------------------------- # Creation from scratch methods # ----------------------------- if 'dataset' not in pars: # separate object keyword from other specific to the function kw = {} keys = dir(klass()) for k in list(kwargs.keys())[:]: if k not in keys: kw[k] = kwargs[k] del kwargs[k] kwargs['kw'] = kw # now call the np function and make the object new = self.method(klass, *argpos, **kwargs) if new.implements('NDDataset'): new.history = f'Created using method : {method}' # (args:{argpos}, kwargs:{kwargs})' return new # ----------------------------- # Create from an existing array # ------------------------------ # Replace some of the attribute according to the kwargs for k, v in list(kwargs.items())[:]: if k != 'units': setattr(new, k, v) del kwargs[k] else: new.ito(v, force=True) del kwargs[k] # Be sure that the dataset passed to the numpy function are a numpy (masked) array if isinstance(argpos[0], (NDDataset, Coord)): # argpos[0] = argpos[0].real.masked_data argpos[0] = argpos[0].masked_data # case of creation like method # ............................ if not self.reduce: # _like' in method: new = self.method(new, *argpos) if new.implements('NDDataset'): new.history = f'Created using method : {method}' # (args:{argpos}, kwargs:{kw})' return new else: # reduce methods # ............... # apply the numpy operator on the masked data new = self.method(new, *argpos) if not isinstance(new, (NDDataset, Coord)): # if a numpy array or a scalar is returned after reduction return new # # particular case of functions that returns Dataset with no coordinates # if dim is None and method in ['sum', 'trapz', 'prod', 'mean', 'var', 'std']: # # delete all coordinates # new._coordset = None new.history = f'Dataset resulting from application of `{method}` method' return new return func def _get_name(x): return str(x.name if hasattr(x, 'name') else x) DIMENSIONLESS = ur('dimensionless').units UNITLESS = None TYPEPRIORITY = {'Coord': 2, 'NDDataset': 3} unary_str = """ negative(x [, out, where, casting, order, …]) Numerical negative, element-wise. abs(x [, out, where, casting, order, …]) Calculate the absolute value element-wise (alias of absolute). absolute(x [, out, where, casting, order, …]) Calculate the absolute value element-wise. fabs(x [, out, where, casting, order, …]) Compute the absolute values element-wise. rint(x [, out, where, casting, order, …]) Round elements of the array to the nearest integer. floor(x [, out, where, casting, order, …]) Return the floor of the input, element-wise. ceil(x [, out, where, casting, order, …]) Return the ceiling of the input, element-wise. trunc(x [, out, where, casting, order, …]) Return the truncated value of the input, element-wise. around(x [, decimals, out]) Evenly round to the given number of decimals. round_(x [, decimals, out]) Round an array to the given number of decimals. rint(x [, out, where, casting, order, …]) Round elements of the array to the nearest integer. fix(x[, out]) Round to nearest integer towards zero exp(x [, out, where, casting, order, …]) Calculate the exponential of all elements in the input array. exp2(x [, out, where, casting, order, …]) Calculate 2**p for all p in the input array. log(x [, out, where, casting, order, …]) Natural logarithm, element-wise. log2(x [, out, where, casting, order, …]) Base-2 logarithm of x. log10(x [, out, where, casting, order, …]) Return the base 10 logarithm of the input array, element-wise. expm1(x [, out, where, casting, order, …]) Calculate exp(x) - 1 for all elements in the array. log1p(x [, out, where, casting, order, …]) Return the natural logarithm of one plus the input array, element-wise. sqrt(x [, out, where, casting, order, …]) Return the non-negative square-root of an array, element-wise. square(x [, out, where, casting, order, …]) Return the element-wise square of the input. cbrt(x [, out, where, casting, order, …]) Return the cube-root of an array, element-wise. reciprocal(x [, out, where, casting, …]) Return the reciprocal of the argument, element-wise. sin(x [, out, where, casting, order, …]) Trigonometric sine, element-wise. cos(x [, out, where, casting, order, …]) Cosine element-wise. tan(x [, out, where, casting, order, …]) Compute tangent element-wise. arcsin(x [, out, where, casting, order, …]) Inverse sine, element-wise. arccos(x [, out, where, casting, order, …]) Trigonometric inverse cosine, element-wise. arctan(x [, out, where, casting, order, …]) Trigonometric inverse tangent, element-wise. sinh(x [, out, where, casting, order, …]) Hyperbolic sine, element-wise. cosh(x [, out, where, casting, order, …]) Hyperbolic cosine, element-wise. tanh(x [, out, where, casting, order, …]) Compute hyperbolic tangent element-wise. arcsinh(x [, out, where, casting, order, …]) Inverse hyperbolic sine element-wise. arccosh(x [, out, where, casting, order, …]) Inverse hyperbolic cosine, element-wise. arctanh(x [, out, where, casting, order, …]) Inverse hyperbolic tangent element-wise. degrees(x [, out, where, casting, order, …]) Convert angles from radians to degrees. radians(x [, out, where, casting, order, …]) Convert angles from degrees to radians. deg2rad(x [, out, where, casting, order, …]) Convert angles from degrees to radians. rad2deg(x [, out, where, casting, order, …]) Convert angles from radians to degrees. sign(x [, out, where, casting, order, …]) Returns an element-wise indication of the sign of a number. isfinite(x [, out, where, casting, order, …]) Test element-wise for finiteness (not infinity or not Not a Number). isinf(x [, out, where, casting, order, …]) Test element-wise for positive or negative infinity. isnan(x [, out, where, casting, order, …]) Test element-wise for NaN and return result as a boolean array. logical_not(x [, out, where, casting, …]) Compute the truth value of NOT x element-wise. signbit(x, [, out, where, casting, order, …]) Returns element-wise True where signbit is set (less than zero). """ def _unary_ufuncs(): liste = unary_str.split("\n") ufuncs = {} for item in liste: item = item.strip() if item and not item.startswith('#'): item = item.split('(') string = item[1].split(')') ufuncs[item[0]] = f'({string[0]}) -> {string[1].strip()}' return ufuncs binary_str = """ multiply(x1, x2 [, out, where, casting, …]) Multiply arguments element-wise. divide(x1, x2 [, out, where, casting, …]) Returns a true division of the inputs, element-wise. maximum(x1, x2 [, out, where, casting, …]) Element-wise maximum of array elements. minimum(x1, x2 [, out, where, casting, …]) Element-wise minimum of array elements. fmax(x1, x2 [, out, where, casting, …]) Element-wise maximum of array elements. fmin(x1, x2 [, out, where, casting, …]) Element-wise minimum of array elements. add(x1, x2 [, out, where, casting, order, …]) Add arguments element-wise. subtract(x1, x2 [, out, where, casting, …]) Subtract arguments, element-wise. copysign(x1, x2 [, out, where, casting, …]) Change the sign of x1 to that of x2, element-wise. """ def _binary_ufuncs(): liste = binary_str.split("\n") ufuncs = {} for item in liste: item = item.strip() if not item: continue if item.startswith('#'): continue item = item.split('(') ufuncs[item[0]] = item[1] return ufuncs comp_str = """ # Comparison functions greater(x1, x2 [, out, where, casting, …]) Return the truth value of (x1 > x2) element-wise. greater_equal(x1, x2 [, out, where, …]) Return the truth value of (x1 >= x2) element-wise. less(x1, x2 [, out, where, casting, …]) Return the truth value of (x1 < x2) element-wise. less_equal(x1, x2 [, out, where, casting, …]) Return the truth value of (x1 =< x2) element-wise. not_equal(x1, x2 [, out, where, casting, …]) Return (x1 != x2) element-wise. equal(x1, x2 [, out, where, casting, …]) Return (x1 == x2) element-wise. """ def _comp_ufuncs(): liste = comp_str.split("\n") ufuncs = {} for item in liste: item = item.strip() if not item: continue if item.startswith('#'): continue item = item.split('(') ufuncs[item[0]] = item[1] return ufuncs logical_binary_str = """ logical_and(x1, x2 [, out, where, …]) Compute the truth value of x1 AND x2 element-wise. logical_or(x1, x2 [, out, where, casting, …]) Compute the truth value of x1 OR x2 element-wise. logical_xor(x1, x2 [, out, where, …]) Compute the truth value of x1 XOR x2, element-wise. """ def _logical_binary_ufuncs(): liste = logical_binary_str.split("\n") ufuncs = {} for item in liste: item = item.strip() if not item: continue if item.startswith('#'): continue item = item.split('(') ufuncs[item[0]] = item[1] return ufuncs class NDMath(object): """ This class provides the math and some other array manipulation functionalities to |NDArray| or |Coord|. Below is a list of mathematical functions (numpy) implemented (or planned for implementation) **Ufuncs** These functions should work like for numpy-ndarray, except that they may be units-aware. For instance, `ds` being a |NDDataset|, just call the np functions like this. Most of the time it returns a new NDDataset, while in some cases noted below, one get a |ndarray|. >>> import spectrochempy as scp >>> ds = scp.NDDataset([1.,2.,3.]) >>> np.sin(ds) NDDataset: [float64] unitless (size: 3) In this particular case (*i.e.*, `np.sin` ufuncs) , the `ds` units must be `unitless`, `dimensionless` or angle-units : `radians` or `degrees`, or an exception will be raised. Examples -------- >>> nd1 = scp.read('wodger.spg') >>> nd1 NDDataset: [float64] a.u. (shape: (y:2, x:5549)) >>> nd1.data array([[ 2.005, 2.003, ..., 1.826, 1.831], [ 1.983, 1.984, ..., 1.698, 1.704]]) >>> nd2 = np.negative(nd1) >>> nd2 NDDataset: [float64] a.u. (shape: (y:2, x:5549)) >>> nd2.data array([[ -2.005, -2.003, ..., -1.826, -1.831], [ -1.983, -1.984, ..., -1.698, -1.704]]) """ __radian = 'radian' __degree = 'degree' __require_units = { 'cumprod': DIMENSIONLESS, 'arccos': DIMENSIONLESS, 'arcsin': DIMENSIONLESS, 'arctan': DIMENSIONLESS, 'arccosh': DIMENSIONLESS, 'arcsinh': DIMENSIONLESS, 'arctanh': DIMENSIONLESS, 'exp': DIMENSIONLESS, 'expm1': DIMENSIONLESS, 'exp2': DIMENSIONLESS, 'log': DIMENSIONLESS, 'log10': DIMENSIONLESS, 'log1p': DIMENSIONLESS, 'log2': DIMENSIONLESS, 'sin': __radian, 'cos': __radian, 'tan': __radian, 'sinh': __radian, 'cosh': __radian, 'tanh': __radian, 'radians': __degree, 'degrees': __radian, 'deg2rad': __degree, 'rad2deg': __radian, 'logaddexp': DIMENSIONLESS, 'logaddexp2': DIMENSIONLESS } __compatible_units = ['add', 'sub', 'iadd', 'isub', 'maximum', 'minimum', 'fmin', 'fmax', 'lt', 'le', 'ge', 'gt'] __complex_funcs = ['real', 'imag', 'absolute', 'abs'] __keep_title = ['negative', 'absolute', 'abs', 'fabs', 'rint', 'floor', 'ceil', 'trunc', 'add', 'subtract'] __remove_title = ['multiply', 'divide', 'true_divide', 'floor_divide', 'mod', 'fmod', 'remainder', 'logaddexp', 'logaddexp2'] __remove_units = ['logical_not', 'isfinite', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'iscomplex', 'signbit', 'sign'] __quaternion_aware = ['add', 'iadd', 'sub', 'isub', 'mul', 'imul', 'div', 'idiv', 'log', 'exp', 'power', 'negative', 'conjugate', 'copysign', 'equal', 'not_equal', 'less', 'less_equal', 'isnan', 'isinf', 'isfinite', 'absolute', 'abs'] # the following methods are to give NDArray based class # a behavior similar to np.ndarray regarding the ufuncs # .................................................................................................................. @property def __array_struct__(self): if hasattr(self.umasked_data, 'mask'): self._mask = self.umasked_data.mask return self.data.__array_struct__ # .................................................................................................................. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): fname = ufunc.__name__ # # case of complex or hypercomplex data # if self.implements(NDComplexArray) and self.has_complex_dims: # # if fname in self.__complex_funcs: # return getattr(inputs[0], fname)() # # if fname in ["fabs", ]: # # fonction not available for complex data # raise ValueError(f"Operation `{ufunc}` does not accept complex data!") # # # If this reached, data are not complex or hypercomplex # if fname in ['absolute', 'abs']: # f = np.fabs # set history string history = f'Ufunc {fname} applied.' if fname in ['sign', 'logical_not', 'isnan', 'isfinite', 'isinf', 'signbit']: return (getattr(np, fname))(inputs[0].masked_data) # case of a dataset data, units, mask, returntype = self._op(ufunc, inputs, isufunc=True) new = self._op_result(data, units, mask, history, returntype) # make a new title depending on the operation if fname in self.__remove_title: new.title = f"<{fname}>" elif fname not in self.__keep_title and isinstance(new, NDArray): if hasattr(new, 'title') and new.title is not None: new.title = f"{fname}({new.title})" else: new.title = f"{fname}(data)" return new # ------------------------------------------------------------------------------------------------------------------ # public methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. @_from_numpy_method def absolute(cls, dataset, dtype=None): """ Calculate the absolute value element-wise. `abs` is a shorthand for this function. For complex input, a + ib, the absolute value is :math:`\\sqrt{ a^2 + b^2}`. Parameters ---------- dataset : array_like Input array or object that can be converted to an array. dtype : dtype The type of the output array. If dtype is not given, infer the data type from the other input arguments. Returns ------- absolute An ndarray containing the absolute value of each element in dataset. """ if not cls.has_complex_dims: data = np.ma.fabs(dataset, dtype=dtype) # not a complex, return fabs should be faster elif not cls.is_quaternion: data = np.ma.sqrt(dataset.real ** 2 + dataset.imag ** 2) else: data = np.ma.sqrt( dataset.real ** 2 + dataset.part('IR') ** 2 + dataset.part('RI') ** 2 + dataset.part('II') ** 2, dtype=dtype) cls._is_quaternion = False cls._data = data.data cls._mask = data.mask return cls abs = absolute # .................................................................................................................. @_from_numpy_method def conjugate(cls, dataset, dim='x'): """ Conjugate of the NDDataset in the specified dimension. Parameters ---------- dataset : array_like Input array or object that can be converted to an array. dim : int, str, optional, default=(0,) Dimension names or indexes along which the method should be applied. Returns ------- conjugated Same object or a copy depending on the ``inplace`` flag. See Also -------- conj, real, imag, RR, RI, IR, II, part, set_complex, is_complex """ axis, dim = cls.get_axis(dim, allows_none=True) if cls.is_quaternion: # TODO: dataset = dataset.swapdims(axis, -1) dataset[..., 1::2] = - dataset[..., 1::2] dataset = dataset(axis, -1) else: dataset = np.ma.conjugate(dataset) cls._data = dataset.data cls._mask = dataset.mask return cls conj = conjugate # .................................................................................................................. @_reduce_method @_from_numpy_method def all(cls, dataset, dim=None, keepdims=False): """ Test whether all array elements along a given axis evaluate to True. Parameters ---------- dataset : array_like Input array or object that can be converted to an array. dim : None or int or str, optional Axis or axes along which a logical AND reduction is performed. The default (``axis=None``) is to perform a logical AND over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then `keepdims` will not be passed through to the `all` method of sub-classes of `ndarray`, however any non-default value will be. If the sub-class' method does not implement `keepdims` any exceptions will be raised. Returns ------- all A new boolean or array is returned unless `out` is specified, in which case a reference to `out` is returned. See Also -------- any : Test whether any element along a given axis evaluates to True. Notes ----- Not a Number (NaN), positive infinity and negative infinity evaluate to `True` because these are not equal to zero. """ axis, dim = cls.get_axis(dim, allows_none=True) data = np.all(dataset, axis, keepdims=keepdims) return data # .................................................................................................................. @_reduce_method @_from_numpy_method def amax(cls, dataset, dim=None, keepdims=False, **kwargs): """ Return the maximum of the dataset or maxima along given dimensions. Parameters ---------- dataset : array_like Input array or object that can be converted to an array. dim : None or int or dimension name or tuple of int or dimensions, optional dimension or dimensions along which to operate. By default, flattened input is used. If this is a tuple, the maximum is selected over multiple dimensions, instead of a single dimension or all the dimensions as before. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- amax Maximum of the data. If `dim` is None, the result is a scalar value. If `dim` is given, the result is an array of dimension ``ndim - 1``. Note ---- For dataset with complex or hypercomplex type type, the default is the value with the maximum real part. See Also -------- amin : The minimum value of a dataset along a given dimension, propagating any NaNs. minimum : Element-wise minimum of two datasets, propagating any NaNs. maximum : Element-wise maximum of two datasets, propagating any NaNs. fmax : Element-wise maximum of two datasets, ignoring any NaNs. fmin : Element-wise minimum of two datasets, ignoring any NaNs. argmax : Return the indices or coordinates of the maximum values. argmin : Return the indices or coordinates of the minimum values. """ axis, dim = cls.get_axis(dim, allows_none=True) quaternion = False if dataset.dtype in [np.quaternion]: from quaternion import as_float_array quaternion = True data = dataset dataset = as_float_array(dataset)[..., 0] # real part m = np.ma.max(dataset, axis=axis, keepdims=keepdims) if quaternion: if dim is None: # we return the corresponding quaternion value idx = np.ma.argmax(dataset) c = list(np.unravel_index(idx, dataset.shape)) m = data[..., c[-2], c[-1]][()] else: m = np.ma.diag(data[np.ma.argmax(dataset, axis=axis)]) if np.isscalar(m) or (m.size == 1 and not keepdims): if not np.isscalar(m): # case of quaternion m = m[()] if cls.units is not None: return Quantity(m, cls.units) else: return m dims = cls.dims if hasattr(m, 'mask'): cls._data = m.data cls._mask = m.mask else: cls._data = m # Here we must eventually reduce the corresponding coordinates if hasattr(cls, 'coordset'): coordset = cls.coordset if coordset is not None: if dim is not None: idx = coordset.names.index(dim) if not keepdims: del coordset.coords[idx] dims.remove(dim) else: coordset.coords[idx].data = [0, ] else: # find the coordinates idx = np.ma.argmax(dataset) c = list(np.unravel_index(idx, dataset.shape)) coord = {} for i, item in enumerate(c[::-1]): dim = dims[-(i + 1)] id = coordset.names.index(dim) coord[dim] = coordset.coords[id][item] cls.set_coordset(coord) cls.dims = dims return cls max = amax # .................................................................................................................. @_reduce_method @_from_numpy_method def amin(cls, dataset, dim=None, keepdims=False, **kwargs): """ Return the maximum of the dataset or maxima along given dimensions. Parameters ---------- dataset : array_like Input array or object that can be converted to an array. dim : None or int or dimension name or tuple of int or dimensions, optional dimension or dimensions along which to operate. By default, flattened input is used. If this is a tuple, the minimum is selected over multiple dimensions, instead of a single dimension or all the dimensions as before. keepdims : bool, optional If this is set to True, the dimensions which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- amin Minimum of the data. If `dim` is None, the result is a scalar value. If `dim` is given, the result is an array of dimension ``ndim - 1``. See Also -------- amax : The maximum value of a dataset along a given dimension, propagating any NaNs. minimum : Element-wise minimum of two datasets, propagating any NaNs. maximum : Element-wise maximum of two datasets, propagating any NaNs. fmax : Element-wise maximum of two datasets, ignoring any NaNs. fmin : Element-wise minimum of two datasets, ignoring any NaNs. argmax : Return the indices or coordinates of the maximum values. argmin : Return the indices or coordinates of the minimum values. """ axis, dim = cls.get_axis(dim, allows_none=True) m = np.ma.min(dataset, axis=axis, keepdims=keepdims) if np.isscalar(m): if cls.units is not None: return Quantity(m, cls.units) else: return m dims = cls.dims cls._data = m.data cls._mask = m.mask # Here we must eventually reduce the corresponding coordinates if hasattr(cls, 'coordset'): coordset = cls.coordset if coordset is not None: if dim is not None: idx = coordset.names.index(dim) if not keepdims: del coordset.coords[idx] dims.remove(dim) else: coordset.coords[idx].data = [0, ] else: # find the coordinates idx = np.ma.argmin(dataset) c = list(np.unravel_index(idx, dataset.shape)) coord = {} for i, item in enumerate(c[::-1]): dim = dims[-(i + 1)] id = coordset.names.index(dim) coord[dim] = coordset.coords[id][item] cls.set_coordset(coord) cls.dims = dims return cls min = amin # .................................................................................................................. @_reduce_method @_from_numpy_method def any(cls, dataset, dim=None, keepdims=False): """ Test whether any array element along a given axis evaluates to True. Returns single boolean unless `dim` is not ``None`` Parameters ---------- dataset : array_like Input array or object that can be converted to an array. dim : None or int or tuple of ints, optional Axis or axes along which a logical OR reduction is performed. The default (``axis=None``) is to perform a logical OR over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then `keepdims` will not be passed through to the `any` method of sub-classes of `ndarray`, however any non-default value will be. If the sub-class' method does not implement `keepdims` any exceptions will be raised. See Also -------- all : Test whether all array elements along a given axis evaluate to True. Returns ------- any A new boolean or `ndarray` is returned. """ axis, dim = cls.get_axis(dim, allows_none=True) data = np.any(dataset, axis, keepdims=keepdims) return data # .................................................................................................................. @_from_numpy_method def arange(cls, start=0, stop=None, step=None, dtype=None, **kwargs): """ Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop). Parameters ---------- start : number, optional Start of interval. The interval includes this value. The default start value is 0. stop : number End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. It might be prefereble to use inspace in such case. step : number, optional Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given. dtype : dtype The type of the output array. If dtype is not given, infer the data type from the other input arguments. **kwargs : dict Keywords argument used when creating the returned object, such as units, name, title, ... Returns ------- arange Array of evenly spaced values. See also -------- linspace : Evenly spaced numbers with careful handling of endpoints. Examples -------- >>> import spectrochempy as scp >>> scp.arange(1, 20.0001, 1, units='s', name='mycoord') NDDataset: [float64] s (size: 20) """ return cls(np.arange(start, stop, step, dtype), **kwargs) # .................................................................................................................. @_reduce_method @_from_numpy_method def argmax(cls, dataset, dim=None): """indexes of maximum of data along axis""" axis, dim = cls.get_axis(dim, allows_none=True) idx = np.ma.argmax(dataset, axis) if cls.ndim > 1 and axis is None: idx = np.unravel_index(idx, cls.shape) return idx # .................................................................................................................. @_reduce_method @_from_numpy_method def argmin(cls, dataset, dim=None): """indexes of minimum of data along axis""" axis, dim = cls.get_axis(dim, allows_none=True) idx = np.ma.argmin(dataset, axis) if cls.ndim > 1 and axis is None: idx = np.unravel_index(idx, cls.shape) return idx @_reduce_method @_from_numpy_method def average(cls, dataset, dim=None, weights=None, returned=False): """ Compute the weighted average along the specified axis. Parameters ---------- dataset : array_like Array containing data to be averaged. dim : None or int or dimension name or tuple of int or dimensions, optional Dimension or dimensions along which to operate. By default, flattened input is used. If this is a tuple, the minimum is selected over multiple dimensions, instead of a single dimension or all the dimensions as before. weights : array_like, optional An array of weights associated with the values in `dataset`. Each value in `a` contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of `dataset` along the given axis) or of the same shape as `dataset`. If `weights=None`, then all data in `dataset` are assumed to have a weight equal to one. The 1-D calculation is:: avg = sum(a * weights) / sum(weights) The only constraint on `weights` is that `sum(weights)` must not be 0. returned : bool, optional Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`) is returned, otherwise only the average is returned. If `weights=None`, `sum_of_weights` is equivalent to the number of elements over which the average is taken. Returns ------- average, [sum_of_weights] Return the average along the specified axis. When `returned` is `True`, return a tuple with the average as the first element and the sum of the weights as the second element. `sum_of_weights` is of the same type as `retval`. The result dtype follows a genereal pattern. If `weights` is None, the result dtype will be that of `a` , or ``float64`` if `a` is integral. Otherwise, if `weights` is not None and `a` is non- integral, the result type will be the type of lowest precision capable of representing values of both `a` and `weights`. If `a` happens to be integral, the previous rules still applies but the result dtype will at least be ``float64``. Raises ------ ZeroDivisionError When all weights along axis are zero. See `numpy.ma.average` for a version robust to this type of error. TypeError When the length of 1D `weights` is not the same as the shape of `a` along axis. See Also -------- mean : Compute the arithmetic mean along the specified axis. Examples -------- >>> import spectrochempy as scp >>> nd = scp.read('irdata/nh4y-activation.spg') >>> nd NDDataset: [float64] a.u. (shape: (y:55, x:5549)) >>> scp.average(nd) <Quantity(1.25085858, 'absorbance')> >>> m = scp.average(nd, dim='y') >>> m NDDataset: [float64] a.u. (size: 5549) >>> m.x LinearCoord: [float64] cm^-1 (size: 5549) >>> m = scp.average(nd, dim='y', weights=np.arange(55)) >>> m.data array([ 1.789, 1.789, ..., 1.222, 1.22]) """ axis, dim = cls.get_axis(dim, allows_none=True) m, retval = np.ma.average(dataset, axis=axis, weights=weights, returned=True) if np.isscalar(m): if cls.units is not None: return Quantity(m, cls.units) else: return m dims = cls.dims cls._data = m.data cls._mask = m.mask # Here we must eventually reduce the corresponding coordinates if hasattr(cls, 'coordset'): coordset = cls.coordset if coordset is not None: if dim is not None: idx = coordset.names.index(dim) del coordset.coords[idx] dims.remove(dim) else: # dim being None we remove the coordset cls.set_coordset(None) cls.dims = dims if returned: return cls, retval else: return cls # .................................................................................................................. @_from_numpy_method def clip(cls, dataset, a_min=None, a_max=None, **kwargs): """ Clip (limit) the values in a dataset. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of ``[0, 1]`` is specified, values smaller than 0 become 0, and values larger than 1 become 1. No check is performed to ensure ``a_min < a_max``. Parameters ---------- dataset : array_like Input array or object that can be converted to an array. a_min : scalar or array_like or None Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of `a_min` and `a_max` may be None. a_max : scalar or array_like or None Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of `a_min` and `a_max` may be None. If `a_min` or `a_max` are array_like, then the three arrays will be broadcasted to match their shapes. Returns ------- clip An array with the elements of `a`, but where values < `a_min` are replaced with `a_min`, and those > `a_max` with `a_max`. """ # if len(args) > 2 or len(args) == 0: # raise ValueError('Clip requires at least one argument or at most two arguments') # amax = kwargs.pop('a_max', args[0] if len(args) == 1 else args[1]) # amin = kwargs.pop('a_min', self.min() if len(args) == 1 else args[0]) # amin, amax = np.minimum(amin, amax), max(amin, amax) # if self.has_units: # if not isinstance(amin, Quantity): # amin = amin * self.units # if not isinstance(amax, Quantity): # amax = amax * self.units # res = self._method('clip', a_min=amin, a_max=amax, **kwargs) # res.history = f'Clipped with limits between {amin} and {amax}' # return res data = np.ma.clip(dataset, a_min, a_max) cls._data = data return cls # .................................................................................................................. @_reduce_method @_from_numpy_method def coordmax(cls, dataset, dim=None): """Coordinates of maximum of data along axis""" if not cls.implements('NDDataset') or cls.coordset is None: raise Exception('Method `coordmax` apply only on NDDataset and if it has defined coordinates') axis, dim = cls.get_axis(dim, allows_none=True) idx = np.ma.argmax(dataset, fill_value=-1e30) cmax = list(np.unravel_index(idx, dataset.shape)) dims = cls.dims coordset = cls.coordset.copy() coord = {} for i, item in enumerate(cmax[::-1]): _dim = dims[-(i + 1)] coord[_dim] = coordset[_dim][item].values if cls._squeeze_ndim == 1: dim = dims[-1] if dim is not None: return coord[dim] return coord # .................................................................................................................. @_reduce_method @_from_numpy_method def coordmin(cls, dataset, dim=None): """Coordinates of mainimum of data along axis""" if not cls.implements('NDDataset') or cls.coordset is None: raise Exception('Method `coordmin` apply only on NDDataset and if it has defined coordinates') axis, dim = cls.get_axis(dim, allows_none=True) idx = np.ma.argmin(dataset, fill_value=-1e30) cmax = list(np.unravel_index(idx, cls.shape)) dims = cls.dims coordset = cls.coordset coord = {} for i, item in enumerate(cmax[::-1]): _dim = dims[-(i + 1)] coord[_dim] = coordset[_dim][item].values if cls._squeeze_ndim == 1: dim = dims[-1] if dim is not None: return coord[dim] return coord # .................................................................................................................. @_from_numpy_method def cumsum(cls, dataset, dim=None, dtype=None): """ Return the cumulative sum of the elements along a given axis. Parameters ---------- dataset : array_like Calculate the cumulative sum of these values. dim : None or int or dimension name , optional Dimension or dimensions along which to operate. By default, flattened input is used. dtype : dtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. Returns ------- sum A new array containing the cumulative sum. See Also -------- sum : Sum array elements. trapz : Integration of array values using the composite trapezoidal rule. diff : Calculate the n-th discrete difference along given axis. Examples -------- >>> import spectrochempy as scp >>> nd = scp.read('irdata/nh4y-activation.spg') >>> nd NDDataset: [float64] a.u. (shape: (y:55, x:5549)) >>> scp.sum(nd) <Quantity(381755.783, 'absorbance')> >>> scp.sum(nd, keepdims=True) NDDataset: [float64] a.u. (shape: (y:1, x:1)) >>> m = scp.sum(nd, dim='y') >>> m NDDataset: [float64] a.u. (size: 5549) >>> m.data array([ 100.7, 100.7, ..., 74, 73.98]) """ axis, dim = cls.get_axis(dim, allows_none=True) data = np.ma.cumsum(dataset, axis=axis, dtype=dtype) cls._data = data return cls # .................................................................................................................. @_from_numpy_method def diag(cls, dataset, offset=0, **kwargs): """ Extract a diagonal or construct a diagonal array. See the more detailed documentation for ``numpy.diagonal`` if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using. Parameters ---------- dataset : array_like If `dataset` is a 2-D array, return a copy of its `k`-th diagonal. If `dataset` is a 1-D array, return a 2-D array with `v` on the `k`-th. diagonal. offset : int, optional Diagonal in question. The default is 0. Use offset>0 for diagonals above the main diagonal, and offset<0 for diagonals below the main diagonal. Returns ------- diag The extracted diagonal or constructed diagonal array. """ new = cls if new.ndim == 1: # construct a diagonal array # -------------------------- data = np.diag(new.data) mask = NOMASK if new.is_masked: size = new.size m = np.repeat(new.mask, size).reshape(size, size) mask = m | m.T coordset = None if new.coordset is not None: coordset = (new.coordset[0], new.coordset[0]) dims = ['y'] + new.dims new.data = data new.mask = mask new._dims = dims if coordset is not None: new.set_coordset(coordset) return new elif new.ndim == 2: # extract a diagonal # ------------------ return new.diagonal(offset=offset, **kwargs) else: raise ValueError("Input must be 1- or 2-d.") # .................................................................................................................. @_reduce_method @_from_numpy_method def diagonal(cls, dataset, offset=0, dim='x', dtype=None, **kwargs): """ Return the diagonal of a 2D array. As we reduce a 2D to a 1D we must specified which is the dimension for the coordinates to keep!. Parameters ---------- dataset : |NDDataset| or array-like Object from which to extract the diagonal. offset : int, optional Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal (0). dim : str, optional Dimension to keep for coordinates. By default it is the last (-1, `x` or another name if the default dimension name has been modified). dtype : dtype, optional The type of the returned array. **kwargs : dict Additional keyword parameters to be passed to the NDDataset constructor. Returns ------- diagonal The diagonal of the input array. See Also -------- diag : Extract a diagonal or construct a diagonal array. Examples -------- >>> import spectrochempy as scp >>> nd = scp.full((2, 2), 0.5, units='s', title='initial') >>> nd NDDataset: [float64] s (shape: (y:2, x:2)) >>> nd.diagonal(title='diag') NDDataset: [float64] s (size: 2) """ axis, dim = cls.get_axis(dim) if hasattr(dataset, 'mask'): data = np.ma.diagonal(dataset, offset=offset) cls._data = data cls._mask = data.mask else: cls._data = np.diagonal(dataset, offset=offset) if dtype is not None: cls.data = cls.data.astype(dtype) cls._history = [] # set the new coordinates if hasattr(cls, 'coordset') and cls.coordset is not None: idx = cls._coordset.names.index(dim) cls.set_coordset({dim: cls._coordset.coords[idx][:cls.size]}) cls.dims = [dim] return cls @_from_numpy_method def empty(cls, shape, dtype=None, **kwargs): """ Return a new |NDDataset| of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int Shape of the empty array. dtype : data-type, optional Desired output data-type. **kwargs : dict See other parameters. Returns ------- empty Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. Other Parameters ---------------- units : str or ur instance Units of the returned object. If not provided, try to copy from the input object. coordset : list or Coordset object Coordinates for the returned objet. If not provided, try to copy from the input object. See Also -------- zeros_like : Return an array of zeros with shape and type of input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. full_like : Fill an array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to 1. full : Fill a new array. Notes ----- `empty`, unlike `zeros`, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution. Examples -------- >>> import spectrochempy as scp >>> scp.empty([2, 2], dtype=int, units='s') NDDataset: [int64] s (shape: (y:2, x:2)) """ return cls(np.empty(shape, dtype), dtype=dtype, **kwargs) @_from_numpy_method def empty_like(cls, dataset, dtype=None, **kwargs): """ Return a new uninitialized |NDDataset|. The returned |NDDataset| have the same shape and type as a given array. Units, coordset, ... can be added in kwargs. Parameters ---------- dataset : |NDDataset| or array-like Object from which to copy the array structure. dtype : data-type, optional Overrides the data type of the result. **kwargs : dict See other parameters. Returns ------- emptylike Array of `fill_value` with the same shape and type as `dataset`. Other Parameters ---------------- units : str or ur instance Units of the returned object. If not provided, try to copy from the input object. coordset : list or Coordset object Coordinates for the returned objet. If not provided, try to copy from the input object. See Also -------- full_like : Return an array with a given fill value with shape and type of the input. ones_like : Return an array of ones with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. empty : Return a new uninitialized array. ones : Return a new array setting values to one. zeros : Return a new array setting values to zero. full : Fill a new array. Notes ----- This function does *not* initialize the returned array; to do that use for instance `zeros_like`, `ones_like` or `full_like` instead. It may be marginally faster than the functions that do set the array values. """ cls._data = np.empty_like(dataset, dtype) cls._dtype = np.dtype(dtype) return cls @_from_numpy_method def eye(cls, N, M=None, k=0, dtype=float, **kwargs): """ Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the output. M : int, optional Number of columns in the output. If None, defaults to `N`. k : int, optional Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype : data-type, optional Data-type of the returned array. **kwargs Other parameters to be passed to the object constructor (units, coordset, mask ...). Returns ------- eye NDDataset of shape (N,M) An array where all elements are equal to zero, except for the `k`-th diagonal, whose values are equal to one. See Also -------- identity : Equivalent function with k=0. diag : Diagonal 2-D NDDataset from a 1-D array specified by the user. Examples -------- >>> import spectrochempy as scp >>> scp.eye(2, dtype=int) NDDataset: [float64] unitless (shape: (y:2, x:2)) >>> scp.eye(3, k=1, units='km').values <Quantity([[ 0 1 0] [ 0 0 1] [ 0 0 0]], 'kilometer')> """ return cls(np.eye(N, M, k, dtype), **kwargs) # .................................................................................................................. @_from_numpy_method def fromfunction(cls, function, shape=None, dtype=float, units=None, coordset=None, **kwargs): """ Construct a nddataset by executing a function over each coordinate. The resulting array therefore has a value ``fn(x, y, z)`` at coordinate ``(x, y, z)``. Parameters ---------- function : callable The function is called with N parameters, where N is the rank of `shape` or from the provided ``coordset`. shape : (N,) tuple of ints, optional Shape of the output array, which also determines the shape of the coordinate arrays passed to `function`. It is optional only if `coordset` is None. dtype : data-type, optional Data-type of the coordinate arrays passed to `function`. By default, `dtype` is float. units : str, optional Dataset units. When None, units will be determined from the function results. coordset : |Coordset| instance, optional If provided, this determine the shape and coordinates of each dimension of the returned |NDDataset|. If shape is also passed it will be ignored. **kwargs : dict Other kwargs are passed to the final object constructor. Returns ------- fromfunction The result of the call to `function` is passed back directly. Therefore the shape of `fromfunction` is completely determined by `function`. See Also -------- fromiter : Make a dataset from an iterable. Examples -------- Create a 1D NDDataset from a function >>> import spectrochempy as scp >>> def func1(t, v): ... d = v * t ... return d ... >>> time = scp.LinearCoord.arange(0, 60, 10, units='min') >>> d = scp.fromfunction(func1, v=scp.Quantity(134, 'km/hour'), coordset=scp.CoordSet(t=time)) >>> d.dims ['t'] >>> d NDDataset: [float64] km (size: 6) """ from spectrochempy.core.dataset.coordset import CoordSet if coordset is not None: if not isinstance(coordset, CoordSet): coordset = CoordSet(*coordset) shape = coordset.sizes idx = np.indices(shape) args = [0] * len(shape) if coordset is not None: for i, co in enumerate(coordset): args[i] = co.data[idx[i]] if units is None and co.has_units: args[i] = Quantity(args[i], co.units) kw = kwargs.pop('kw', {}) data = function(*args, **kw) data = data.T dims = coordset.names[::-1] new = cls(data, coordset=coordset, dims=dims, units=units, **kwargs) new.ito_reduced_units() return new @_from_numpy_method def fromiter(cls, iterable, dtype=np.float64, count=-1, **kwargs): """ Create a new 1-dimensional array from an iterable object. Parameters ---------- iterable : iterable object An iterable object providing data for the array. dtype : data-type The data-type of the returned array. count : int, optional The number of items to read from iterable. The default is -1, which means all data is read. **kwargs : dict Other kwargs are passed to the final object constructor. Returns ------- fromiter The output nddataset. See Also -------- fromfunction : Construct a nddataset by executing a function over each coordinate. Notes ----- Specify count to improve performance. It allows fromiter to pre-allocate the output array, instead of resizing it on demand. Examples -------- >>> import spectrochempy as scp >>> iterable = (x * x for x in range(5)) >>> d = scp.fromiter(iterable, float, units='km') >>> d NDDataset: [float64] km (size: 5) >>> d.data array([ 0, 1, 4, 9, 16]) """ return cls(np.fromiter(iterable, dtype=dtype, count=count), **kwargs) @_from_numpy_method def full(cls, shape, fill_value=0.0, dtype=None, **kwargs): """ Return a new |NDDataset| of given shape and type, filled with `fill_value`. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. fill_value : scalar Fill value. dtype : data-type, optional The desired data-type for the array, e.g., `np.int8`. Default is fill_value.dtype. **kwargs : dict See other parameters. Returns ------- full Array of `fill_value`. Other Parameters ---------------- units : str or ur instance Units of the returned object. If not provided, try to copy from the input object. coordset : list or Coordset object Coordinates for the returned objet. If not provided, try to copy from the input object. See Also -------- zeros_like : Return an array of zeros with shape and type of input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. full_like : Fill an array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. Examples -------- >>> import spectrochempy as scp >>> scp.full((2, ), np.inf) NDDataset: [float64] unitless (size: 2) >>> scp.NDDataset.full((2, 2), 10, dtype=np.int) NDDataset: [int64] unitless (shape: (y:2, x:2)) """ return cls(np.full(shape, fill_value, dtype), dtype=dtype, **kwargs) @_from_numpy_method def full_like(cls, dataset, fill_value=0.0, dtype=None, **kwargs): """ Return a |NDDataset| of fill_value. The returned |NDDataset| have the same shape and type as a given array. Units, coordset, ... can be added in kwargs Parameters ---------- dataset : |NDDataset| or array-like Object from which to copy the array structure. fill_value : scalar Fill value. dtype : data-type, optional Overrides the data type of the result. **kwargs : dict See other parameters. Returns ------- fulllike Array of `fill_value` with the same shape and type as `dataset`. Other Parameters ---------------- units : str or ur instance Units of the returned object. If not provided, try to copy from the input object. coordset : list or Coordset object Coordinates for the returned objet. If not provided, try to copy from the input object. See Also -------- zeros_like : Return an array of zeros with shape and type of input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. full : Fill a new array. Examples -------- 3 possible ways to call this method 1) from the API >>> import spectrochempy as scp >>> x = np.arange(6, dtype=int) >>> scp.full_like(x, 1) NDDataset: [float64] unitless (size: 6) 2) as a classmethod >>> x = np.arange(6, dtype=int) >>> scp.NDDataset.full_like(x, 1) NDDataset: [float64] unitless (size: 6) 3) as an instance method >>> scp.NDDataset(x).full_like(1, units='km') NDDataset: [float64] km (size: 6) """ cls._data = np.full_like(dataset, fill_value, dtype) cls._dtype = np.dtype(dtype) return cls @_from_numpy_method def geomspace(cls, start, stop, num=50, endpoint=True, dtype=None, **kwargs): """ Return numbers spaced evenly on a log scale (a geometric progression). This is similar to `logspace`, but with endpoints specified directly. Each output sample is a constant multiple of the previous. Parameters ---------- start : number The starting value of the sequence. stop : number The final value of the sequence, unless `endpoint` is False. In that case, ``num + 1`` values are spaced over the interval in log-space, of which all but the last (a sequence of length `num`) are returned. num : integer, optional Number of samples to generate. Default is 50. endpoint : boolean, optional If true, `stop` is the last sample. Otherwise, it is not included. Default is True. dtype : dtype The type of the output array. If `dtype` is not given, infer the data type from the other input arguments. **kwargs : dict Keywords argument used when creating the returned object, such as units, name, title, ... Returns ------- geomspace `num` samples, equally spaced on a log scale. See Also -------- logspace : Similar to geomspace, but with endpoints specified using log and base. linspace : Similar to geomspace, but with arithmetic instead of geometric progression. arange : Similar to linspace, with the step size specified instead of the number of samples. """ return cls(np.geomspace(start, stop, num, endpoint, dtype), **kwargs) @_from_numpy_method def identity(cls, n, dtype=None, **kwargs): """ Return the identity |NDDataset| of a given shape. The identity array is a square array with ones on the main diagonal. Parameters ---------- n : int Number of rows (and columns) in `n` x `n` output. dtype : data-type, optional Data-type of the output. Defaults to ``float``. **kwargs Other parameters to be passed to the object constructor (units, coordset, mask ...). Returns ------- identity `n` x `n` array with its main diagonal set to one, and all other elements 0. See Also -------- eye : Almost equivalent function. diag : Diagonal 2-D array from a 1-D array specified by the user. Examples -------- >>> import spectrochempy as scp >>> scp.identity(3).data array([[ 1, 0, 0], [ 0, 1, 0], [ 0, 0, 1]]) """ return cls(np.identity(n, dtype), **kwargs) @_from_numpy_method def linspace(cls, start, stop, num=50, endpoint=True, retstep=False, dtype=None, **kwargs): """ Return evenly spaced numbers over a specified interval. Returns num evenly spaced samples, calculated over the interval [start, stop]. The endpoint of the interval can optionally be excluded. Parameters ---------- start : array_like The starting value of the sequence. stop : array_like The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False. num : int, optional Number of samples to generate. Default is 50. Must be non-negative. endpoint : bool, optional If True, stop is the last sample. Otherwise, it is not included. Default is True. retstep : bool, optional If True, return (samples, step), where step is the spacing between samples. dtype : dtype, optional The type of the array. If dtype is not given, infer the data type from the other input arguments. **kwargs : dict Keywords argument used when creating the returned object, such as units, name, title, ... Returns ------- linspace : ndarray There are num equally spaced samples in the closed interval [start, stop] or the half-open interval [start, stop) (depending on whether endpoint is True or False). step : float, optional Only returned if retstep is True Size of spacing between samples. """ return cls(np.linspace(start, stop, num, endpoint, retstep, dtype), **kwargs) @_from_numpy_method def logspace(cls, start, stop, num=50, endpoint=True, base=10.0, dtype=None, **kwargs): """ Return numbers spaced evenly on a log scale. In linear space, the sequence starts at ``base ** start`` (`base` to the power of `start`) and ends with ``base ** stop`` (see `endpoint` below). Parameters ---------- start : array_like ``base ** start`` is the starting value of the sequence. stop : array_like ``base ** stop`` is the final value of the sequence, unless `endpoint` is False. In that case, ``num + 1`` values are spaced over the interval in log-space, of which all but the last (a sequence of length `num`) are returned. num : integer, optional Number of samples to generate. Default is 50. endpoint : boolean, optional If true, `stop` is the last sample. Otherwise, it is not included. Default is True. base : float, optional The base of the log space. The step size between the elements in ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform. Default is 10.0. dtype : dtype The type of the output array. If `dtype` is not given, infer the data type from the other input arguments. **kwargs : dict Keywords argument used when creating the returned object, such as units, name, title, ... Returns ------- logspace `num` samples, equally spaced on a log scale. See Also -------- arange : Similar to linspace, with the step size specified instead of the number of samples. Note that, when used with a float endpoint, the endpoint may or may not be included. linspace : Similar to logspace, but with the samples uniformly distributed in linear space, instead of log space. geomspace : Similar to logspace, but with endpoints specified directly. """ return cls(np.logspace(start, stop, num, endpoint, base, dtype), **kwargs) # .................................................................................................................. @_reduce_method @_from_numpy_method def mean(cls, dataset, dim=None, dtype=None, keepdims=False): """ Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. Parameters ---------- dataset : array_like Array containing numbers whose mean is desired. dim : None or int or dimension name, optional Dimension or dimensions along which to operate. dtype : data-type, optional Type to use in computing the mean. For integer inputs, the default is `float64`; for floating point inputs, it is the same as the input dtype. keepdims : bool, optional If this is set to True, the dimensions which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- mean A new array containing the mean values. See Also -------- average : Weighted average. std : Standard deviation values along axis. var : Variance values along axis. Notes ----- The arithmetic mean is the sum of the elements along the axis divided by the number of elements. Examples -------- >>> import spectrochempy as scp >>> nd = scp.read('irdata/nh4y-activation.spg') >>> nd NDDataset: [float64] a.u. (shape: (y:55, x:5549)) >>> scp.mean(nd) <Quantity(1.25085858, 'absorbance')> >>> scp.mean(nd, keepdims=True) NDDataset: [float64] a.u. (shape: (y:1, x:1)) >>> m = scp.mean(nd, dim='y') >>> m NDDataset: [float64] a.u. (size: 5549) >>> m.x LinearCoord: [float64] cm^-1 (size: 5549) """ axis, dim = cls.get_axis(dim, allows_none=True) m = np.ma.mean(dataset, axis=axis, dtype=dtype, keepdims=keepdims) if np.isscalar(m): if cls.units is not None: return Quantity(m, cls.units) else: return m dims = cls.dims cls._data = m.data cls._mask = m.mask # Here we must eventually reduce the corresponding coordinates if hasattr(cls, 'coordset'): coordset = cls.coordset if coordset is not None: if dim is not None: idx = coordset.names.index(dim) if not keepdims: del coordset.coords[idx] dims.remove(dim) else: coordset.coords[idx].data = [0, ] else: # dim being None we remove the coordset cls.set_coordset(None) cls.dims = dims return cls @_from_numpy_method def ones(cls, shape, dtype=None, **kwargs): """ Return a new |NDDataset| of given shape and type, filled with ones. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. **kwargs : dict See other parameters. Returns ------- ones Array of `ones`. Other Parameters ---------------- units : str or ur instance Units of the returned object. If not provided, try to copy from the input object. coordset : list or Coordset object Coordinates for the returned objet. If not provided, try to copy from the input object. See Also -------- zeros_like : Return an array of zeros with shape and type of input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. full_like : Fill an array with shape and type of input. zeros : Return a new array setting values to zero. empty : Return a new uninitialized array. full : Fill a new array. Examples -------- >>> import spectrochempy as scp >>> nd = scp.ones(5, units='km') >>> nd NDDataset: [float64] km (size: 5) >>> nd.values <Quantity([ 1 1 1 1 1], 'kilometer')> >>> nd = scp.ones((5,), dtype=np.int, mask=[True, False, False, False, True]) >>> nd NDDataset: [int64] unitless (size: 5) >>> nd.values masked_array(data=[ --, 1, 1, 1, --], mask=[ True, False, False, False, True], fill_value=999999) >>> nd = scp.ones((5,), dtype=np.int, mask=[True, False, False, False, True], units='joule') >>> nd NDDataset: [int64] J (size: 5) >>> nd.values <Quantity([ -- 1 1 1 --], 'joule')> >>> scp.ones((2, 2)).values array([[ 1, 1], [ 1, 1]]) """ return cls(np.ones(shape), dtype=dtype, **kwargs) @_from_numpy_method def ones_like(cls, dataset, dtype=None, **kwargs): """ Return |NDDataset| of ones. The returned |NDDataset| have the same shape and type as a given array. Units, coordset, ... can be added in kwargs. Parameters ---------- dataset : |NDDataset| or array-like Object from which to copy the array structure. dtype : data-type, optional Overrides the data type of the result. **kwargs : dict See other parameters. Returns ------- oneslike Array of `1` with the same shape and type as `dataset`. Other Parameters ---------------- units : str or ur instance Units of the returned object. If not provided, try to copy from the input object. coordset : list or Coordset object Coordinates for the returned objet. If not provided, try to copy from the input object. See Also -------- full_like : Return an array with a given fill value with shape and type of the input. zeros_like : Return an array of zeros with shape and type of input. empty_like : Return an empty array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. full : Fill a new array. Examples -------- >>> import spectrochempy as scp >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x = scp.NDDataset(x, units='s') >>> x NDDataset: [float64] s (shape: (y:2, x:3)) >>> scp.ones_like(x, dtype=float, units='J') NDDataset: [float64] J (shape: (y:2, x:3)) """ cls._data = np.ones_like(dataset, dtype) cls._dtype = np.dtype(dtype) return cls def pipe(self, func, *args, **kwargs): """Apply func(self, *args, **kwargs) Parameters ---------- func : function function to apply to the |NDDataset|. `*args`, and `**kwargs` are passed into `func`. Alternatively a `(callable, data_keyword)` tuple where `data_keyword` is a string indicating the keyword of `callable` that expects the array object. *args : positional arguments passed into `func`. **kwargs : keyword arguments passed into `func`. Returns ------- pipe the return type of `func`. Notes ----- Use ``.pipe`` when chaining together functions that expect a |NDDataset|. """ if isinstance(func, tuple): func, target = func if target in kwargs: error_(f'{target} is both the pipe target and a keyword argument. Operation not applied!') return self kwargs[target] = self return func(*args, **kwargs) return func(self, *args, **kwargs) # .................................................................................................................. @_reduce_method @_from_numpy_method def ptp(cls, dataset, dim=None, keepdims=False): """ Range of values (maximum - minimum) along a dimension. The name of the function comes from the acronym for 'peak to peak'. Parameters ---------- dim : None or int or dimension name, optional Dimension along which to find the peaks. If None, the operation is made on the first dimension. keepdims : bool, optional If this is set to True, the dimensions which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input dataset. Returns ------- ptp A new dataset holding the result. """ axis, dim = cls.get_axis(dim, allows_none=True) m = np.ma.ptp(dataset, axis=axis, keepdims=keepdims) if np.isscalar(m): if cls.units is not None: return Quantity(m, cls.units) else: return m dims = cls.dims cls._data = m.data cls._mask = m.mask # Here we must eventually reduce the corresponding coordinates if hasattr(cls, 'coordset'): coordset = cls.coordset if coordset is not None: if dim is not None: idx = coordset.names.index(dim) if not keepdims: del coordset.coords[idx] dims.remove(dim) else: coordset.coords[idx].data = [0, ] else: # dim being None we remove the coordset cls.set_coordset(None) cls.dims = dims return cls @_from_numpy_method def random(cls, size=None, dtype=None, **kwargs): """ Return random floats in the half-open interval [0.0, 1.0). Results are from the “continuous uniform” distribution over the stated interval. To sample :math:`\\mathrm{Uniform}[a, b), b > a` multiply the output of random by (b-a) and add a: (b - a) * random() + a Parameters ---------- size : int or tuple of ints, optional Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned. dtype : dtype, optional Desired dtype of the result, only float64 and float32 are supported. The default value is np.float64. **kwargs : dict Keywords argument used when creating the returned object, such as units, name, title, ... Returns ------- random Array of random floats of shape size (unless size=None, in which case a single float is returned). """ from numpy.random import default_rng rng = default_rng() return cls(rng.random(size, dtype), **kwargs) # .................................................................................................................. @_reduce_method @_from_numpy_method def std(cls, dataset, dim=None, dtype=None, ddof=0, keepdims=False): """ Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. Parameters ---------- dataset : array_like Calculate the standard deviation of these values. dim : None or int or dimension name , optional Dimension or dimensions along which to operate. By default, flattened input is used. dtype : dtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. ddof : int, optional Means Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``, where ``N`` represents the number of elements. By default `ddof` is zero. keepdims : bool, optional If this is set to True, the dimensions which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- std A new array containing the standard deviation. See Also -------- var : Variance values along axis. mean : Compute the arithmetic mean along the specified axis. Notes ----- The standard deviation is the square root of the average of the squared deviations from the mean, i.e., ``std = sqrt(mean(abs(x - x.mean())**2))``. The average squared deviation is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of the infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ``ddof=1``, it will not be an unbiased estimate of the standard deviation per se. Note that, for complex numbers, `std` takes the absolute value before squaring, so that the result is always real and nonnegative. For floating-point input, the *std* is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the `dtype` keyword can alleviate this issue. Examples -------- >>> import spectrochempy as scp >>> nd = scp.read('irdata/nh4y-activation.spg') >>> nd NDDataset: [float64] a.u. (shape: (y:55, x:5549)) >>> scp.std(nd) <Quantity(0.807972021, 'absorbance')> >>> scp.std(nd, keepdims=True) NDDataset: [float64] a.u. (shape: (y:1, x:1)) >>> m = scp.std(nd, dim='y') >>> m NDDataset: [float64] a.u. (size: 5549) >>> m.data array([ 0.08521, 0.08543, ..., 0.251, 0.2537]) """ axis, dim = cls.get_axis(dim, allows_none=True) m = np.ma.std(dataset, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims) if np.isscalar(m): if cls.units is not None: return Quantity(m, cls.units) else: return m dims = cls.dims cls._data = m.data cls._mask = m.mask # Here we must eventually reduce the corresponding coordinates if hasattr(cls, 'coordset'): coordset = cls.coordset if coordset is not None: if dim is not None: idx = coordset.names.index(dim) if not keepdims: del coordset.coords[idx] dims.remove(dim) else: coordset.coords[idx].data = [0, ] else: # dim being None we remove the coordset cls.set_coordset(None) cls.dims = dims return cls # .................................................................................................................. @_reduce_method @_from_numpy_method def sum(cls, dataset, dim=None, dtype=None, keepdims=False): """ Sum of array elements over a given axis. Parameters ---------- dataset : array_like Calculate the sum of these values. dim : None or int or dimension name , optional Dimension or dimensions along which to operate. By default, flattened input is used. dtype : dtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. keepdims : bool, optional If this is set to True, the dimensions which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- sum A new array containing the sum. See Also -------- mean : Compute the arithmetic mean along the specified axis. trapz : Integration of array values using the composite trapezoidal rule. Examples -------- >>> import spectrochempy as scp >>> nd = scp.read('irdata/nh4y-activation.spg') >>> nd NDDataset: [float64] a.u. (shape: (y:55, x:5549)) >>> scp.sum(nd) <Quantity(381755.783, 'absorbance')> >>> scp.sum(nd, keepdims=True) NDDataset: [float64] a.u. (shape: (y:1, x:1)) >>> m = scp.sum(nd, dim='y') >>> m NDDataset: [float64] a.u. (size: 5549) >>> m.data array([ 100.7, 100.7, ..., 74, 73.98]) """ axis, dim = cls.get_axis(dim, allows_none=True) m = np.ma.sum(dataset, axis=axis, dtype=dtype, keepdims=keepdims) if np.isscalar(m): if cls.units is not None: return Quantity(m, cls.units) else: return m dims = cls.dims cls._data = m.data cls._mask = m.mask # Here we must eventually reduce the corresponding coordinates if hasattr(cls, 'coordset'): coordset = cls.coordset if coordset is not None: if dim is not None: idx = coordset.names.index(dim) if not keepdims: del coordset.coords[idx] dims.remove(dim) else: coordset.coords[idx].data = [0, ] else: # dim being None we remove the coordset cls.set_coordset(None) cls.dims = dims return cls # .................................................................................................................. @_reduce_method @_from_numpy_method def var(cls, dataset, dim=None, dtype=None, ddof=0, keepdims=False): """ Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. Parameters ---------- dataset : array_like Array containing numbers whose variance is desired. dim : None or int or dimension name , optional Dimension or dimensions along which to operate. By default, flattened input is used. dtype : dtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. ddof : int, optional Means Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``, where ``N`` represents the number of elements. By default `ddof` is zero. keepdims : bool, optional If this is set to True, the dimensions which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- var A new array containing the standard deviation. See Also -------- std : Standard deviation values along axis. mean : Compute the arithmetic mean along the specified axis. Notes ----- The variance is the average of the squared deviations from the mean, i.e., ``var = mean(abs(x - x.mean())**2)``. The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of a hypothetical infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative. For floating-point input, the variance is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for `float32` (see example below). Specifying a higher-accuracy accumulator using the ``dtype`` keyword can alleviate this issue. Examples -------- >>> import spectrochempy as scp >>> nd = scp.read('irdata/nh4y-activation.spg') >>> nd NDDataset: [float64] a.u. (shape: (y:55, x:5549)) >>> scp.var(nd) <Quantity(0.652818786, 'absorbance')> >>> scp.var(nd, keepdims=True) NDDataset: [float64] a.u. (shape: (y:1, x:1)) >>> m = scp.var(nd, dim='y') >>> m NDDataset: [float64] a.u. (size: 5549) >>> m.data array([0.007262, 0.007299, ..., 0.06298, 0.06438]) """ axis, dim = cls.get_axis(dim, allows_none=True) m = np.ma.var(dataset, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims) if np.isscalar(m): if cls.units is not None: return Quantity(m, cls.units) else: return m dims = cls.dims cls._data = m.data cls._mask = m.mask # Here we must eventually reduce the corresponding coordinates if hasattr(cls, 'coordset'): coordset = cls.coordset if coordset is not None: if dim is not None: idx = coordset.names.index(dim) if not keepdims: del coordset.coords[idx] dims.remove(dim) else: coordset.coords[idx].data = [0, ] else: # dim being None we remove the coordset cls.set_coordset(None) cls.dims = dims return cls @_from_numpy_method def zeros(cls, shape, dtype=None, **kwargs): """ Return a new |NDDataset| of given shape and type, filled with zeros. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. **kwargs : dict See other parameters. Returns ------- zeros Array of zeros. Other Parameters ---------------- units : str or ur instance Units of the returned object. If not provided, try to copy from the input object. coordset : list or Coordset object Coordinates for the returned objet. If not provided, try to copy from the input object. See Also -------- zeros_like : Return an array of zeros with shape and type of input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. full_like : Fill an array with shape and type of input. ones : Return a new array setting values to 1. empty : Return a new uninitialized array. full : Fill a new array. Examples -------- >>> import spectrochempy as scp >>> nd = scp.NDDataset.zeros(6) >>> nd NDDataset: [float64] unitless (size: 6) >>> nd = scp.zeros((5, )) >>> nd NDDataset: [float64] unitless (size: 5) >>> nd.values array([ 0, 0, 0, 0, 0]) >>> nd = scp.zeros((5, 10), dtype=np.int, units='absorbance') >>> nd NDDataset: [int64] a.u. (shape: (y:5, x:10)) """ return cls(np.zeros(shape), dtype=dtype, **kwargs) @_from_numpy_method def zeros_like(cls, dataset, dtype=None, **kwargs): """ Return a |NDDataset| of zeros. The returned |NDDataset| have the same shape and type as a given array. Units, coordset, ... can be added in kwargs. Parameters ---------- dataset : |NDDataset| or array-like Object from which to copy the array structure. dtype : data-type, optional Overrides the data type of the result. **kwargs : dict See other parameters. Returns ------- zeorslike Array of `fill_value` with the same shape and type as `dataset`. Other Parameters ---------------- units : str or ur instance Units of the returned object. If not provided, try to copy from the input object. coordset : list or Coordset object Coordinates for the returned objet. If not provided, try to copy from the input object. See Also -------- full_like : Return an array with a given fill value with shape and type of the input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. full : Fill a new array. Examples -------- >>> import spectrochempy as scp >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> nd = scp.NDDataset(x, units='s') >>> nd NDDataset: [float64] s (shape: (y:2, x:3)) >>> nd.values <Quantity([[ 0 1 2] [ 3 4 5]], 'second')> >>> nd = scp.zeros_like(nd) >>> nd NDDataset: [float64] s (shape: (y:2, x:3)) >>> nd.values <Quantity([[ 0 0 0] [ 0 0 0]], 'second')> """ cls._data = np.zeros_like(dataset, dtype) cls._dtype = np.dtype(dtype) return cls # ------------------------------------------------------------------------------------------------------------------ # private methods # ------------------------------------------------------------------------------------------------------------------ # .................................................................................................................. def _op(self, f, inputs, isufunc=False): # Achieve an operation f on the objs fname = f.__name__ inputs = list(inputs) # work with a list of objs not tuples # print(fname) # By default the type of the result is set regarding the first obj in inputs # (except for some ufuncs that can return numpy arrays or masked numpy arrays # but sometimes we have something such as 2 * nd where nd is a NDDataset: In this case we expect a dataset. # For binary function, we also determine if the function needs object with compatible units. # If the object are not compatible then we raise an error # Take the objects out of the input list and get their types and units. Additionally determine if we need to # use operation on masked arrays and/or on quaternion objtypes = [] objunits = OrderedSet() returntype = None isquaternion = False ismasked = False compatible_units = (fname in self.__compatible_units) remove_units = (fname in self.__remove_units) quaternion_aware = (fname in self.__quaternion_aware) for i, obj in enumerate(inputs): # type objtype = type(obj).__name__ objtypes.append(objtype) # units if hasattr(obj, 'units'): objunits.add(ur.get_dimensionality(obj.units)) if len(objunits) > 1 and compatible_units: objunits = list(objunits) raise DimensionalityError(*objunits[::-1], extra_msg=f", Units must be compatible for the `{fname}` operator") # returntype if objtype == 'NDDataset': returntype = 'NDDataset' elif objtype == 'Coord' and returntype != 'NDDataset': returntype = 'Coord' elif objtype == 'LinearCoord' and returntype != 'NDDataset': returntype = 'LinearCoord' else: # only the three above type have math capabilities in spectrochempy. pass # If one of the input is hypercomplex, this will demand a special treatment isquaternion = isquaternion or False if not hasattr(obj, 'is_quaternion') else obj.is_quaternion # Do we have to deal with mask? if hasattr(obj, 'mask') and np.any(obj.mask): ismasked = True # it may be necessary to change the object order regarding the types if returntype in ['NDDataset', 'Coord', 'LinearCoord'] and objtypes[0] != returntype: inputs.reverse() objtypes.reverse() if fname in ['mul', 'multiply', 'add', 'iadd']: pass elif fname in ['truediv', 'divide', 'true_divide']: fname = 'multiply' inputs[0] = np.reciprocal(inputs[0]) elif fname in ['isub', 'sub', 'subtract']: fname = 'add' inputs[0] = np.negative(inputs[0]) else: raise NotImplementedError() # Now we can proceed obj = cpy.copy(inputs.pop(0)) objtype = objtypes.pop(0) other = None if inputs: other = cpy.copy(inputs.pop(0)) othertype = objtypes.pop(0) # Our first object is a NDdataset ------------------------------------------------------------------------------ isdataset = (objtype == 'NDDataset') # Get the underlying data: If one of the input is masked, we will work with masked array if ismasked and isdataset: d = obj._umasked(obj.data, obj.mask) else: d = obj.data # Do we have units? # We create a quantity q that will be used for unit calculations (without dealing with the whole object) def reduce_(magnitude): if hasattr(magnitude, 'dtype'): if magnitude.dtype in TYPE_COMPLEX: magnitude = magnitude.real elif magnitude.dtype == np.quaternion: magnitude = as_float_array(magnitude)[..., 0] magnitude = magnitude.max() return magnitude q = reduce_(d) if hasattr(obj, 'units') and obj.units is not None: q = Quantity(q, obj.units) q = q.values if hasattr(q, 'values') else q # case of nddataset, coord, # Now we analyse the other operands --------------------------------------------------------------------------- args = [] otherqs = [] # If other is None, then it is a unary operation we can pass the following if other is not None: # First the units may require to be compatible, and if thet are sometimes they may need to be rescales if othertype in ['NDDataset', 'Coord', 'LinearCoord', 'Quantity']: # rescale according to units if not other.unitless: if hasattr(obj, 'units'): # obj is a Quantity if compatible_units: # adapt the other units to that of object other.ito(obj.units) # If all inputs are datasets BUT coordset mismatch. if isdataset and (othertype == 'NDDataset') and (other._coordset != obj._coordset): obc = obj.coordset otc = other.coordset # here we can have several situations: # ----------------------------------- # One acceptable situation could be that we have a single value if other._squeeze_ndim == 0 or ((obc is None or obc.is_empty) and (otc is None or otc.is_empty)): pass # Another acceptable situation is that the other NDDataset is 1D, with compatible # coordinates in the x dimension elif other._squeeze_ndim >= 1: try: assert_dataset_almost_equal(obc[obj.dims[-1]], otc[other.dims[-1]], decimal=3, data_only=True) # we compare only data for this operation except AssertionError as e: raise CoordinateMismatchError(str(e)) # if other is multidimensional and as we are talking about element wise operation, we assume # that all coordinates must match elif other._squeeze_ndim > 1: for idx in range(obj.ndim): try: assert_dataset_almost_equal(obc[obj.dims[idx]], otc[other.dims[idx]], decimal=3, data_only=True) # we compare only data for this operation except AssertionError as e: raise CoordinateMismatchError(str(e)) if othertype in ['NDDataset', 'Coord', 'LinearCoord']: # mask? if ismasked: arg = other._umasked(other.data, other.mask) else: arg = other.data else: # Not a NDArray. # if it is a quantity than separate units and magnitude if isinstance(other, Quantity): arg = other.m else: # no units arg = other args.append(arg) otherq = reduce_(arg) if hasattr(other, 'units') and other.units is not None: otherq = Quantity(otherq, other.units) otherq = otherq.values if hasattr(otherq, 'values') else otherq # case of nddataset, coord, otherqs.append(otherq) # Calculate the resulting units (and their compatibility for such operation) # -------------------------------------------------------------------------------------------------------------- # Do the calculation with the units to find the final one def check_require_units(fname, _units): if fname in self.__require_units: requnits = self.__require_units[fname] if (requnits == DIMENSIONLESS or requnits == 'radian' or requnits == 'degree') and _units.dimensionless: # this is compatible: _units = DIMENSIONLESS else: if requnits == DIMENSIONLESS: s = 'DIMENSIONLESS input' else: s = f'`{requnits}` units' raise DimensionalityError(_units, requnits, extra_msg=f'\nFunction `{fname}` requires {s}') return _units # define an arbitrary quantity `q` on which to perform the units calculation units = UNITLESS if not remove_units: if hasattr(q, 'units'): # q = q.m * check_require_units(fname, q.units) q = q.to(check_require_units(fname, q.units)) for i, otherq in enumerate(otherqs[:]): if hasattr(otherq, 'units'): if np.ma.isMaskedArray(otherq): otherqm = otherq.m.data else: otherqm = otherq.m otherqs[i] = otherqm * check_require_units(fname, otherq.units) else: # here we want to change the behavior a pint regarding the addition of scalar to quantity # # in principle it is only possible with dimensionless quantity, else a dimensionerror is # raised. if fname in ['add', 'sub', 'iadd', 'isub', 'and', 'xor', 'or'] and hasattr(q, 'units'): otherqs[i] = otherq * q.units # take the unit of the first obj # some functions are not handled by pint regardings units, try to solve this here f_u = f if compatible_units: f_u = np.add # take a similar function handled by pint try: res = f_u(q, *otherqs) except Exception as e: if not otherqs: # in this case easy we take the units of the single argument except for some function where units # can be dropped res = q else: raise e if hasattr(res, 'units'): units = res.units # perform operation on magnitudes # -------------------------------------------------------------------------------------------------------------- if isufunc: with catch_warnings(record=True) as ws: # try to apply the ufunc if fname == 'log1p': fname = 'log' d = d + 1. if fname in ['arccos', 'arcsin', 'arctanh']: if np.any(np.abs(d) > 1): d = d.astype(np.complex128) elif fname in ['sqrt']: if np.any(d < 0): d = d.astype(np.complex128) if fname == "sqrt": # do not work with masked array data = d ** (1. / 2.) elif fname == 'cbrt': data = np.sign(d) * np.abs(d) ** (1. / 3.) else: data = getattr(np, fname)(d, *args) # if a warning occurs, let handle it with complex numbers or return an exception: if ws and 'invalid value encountered in ' in ws[-1].message.args[0]: ws = [] # clear # this can happen with some function that do not work on some real values such as log(-1) # then try to use complex data = getattr(np, fname)(d.astype(np.complex128), *args) # data = getattr(np.emath, fname)(d, *args) if ws: raise ValueError(ws[-1].message.args[0]) elif ws and 'overflow encountered' in ws[-1].message.args[0]: warning_(ws[-1].message.args[0]) elif ws: raise ValueError(ws[-1].message.args[0]) # TODO: check the complex nature of the result to return it else: # make a simple operation try: if not isquaternion: data = f(d, *args) elif quaternion_aware and all([arg.dtype not in TYPE_COMPLEX for arg in args]): data = f(d, *args) else: # in this case we will work on both complex separately dr, di = quat_as_complex_array(d) datar = f(dr, *args) datai = f(di, *args) data = as_quaternion(datar, datai) except Exception as e: raise ArithmeticError(e.args[0]) # get possible mask if isinstance(data, np.ma.MaskedArray): mask = data._mask data = data._data else: mask = NOMASK # np.zeros_like(data, dtype=bool) # return calculated data, units and mask return data, units, mask, returntype # .................................................................................................................. @staticmethod def _unary_op(f): @functools.wraps(f) def func(self): fname = f.__name__ if hasattr(self, 'history'): history = f'Unary operation {fname} applied' else: history = None data, units, mask, returntype = self._op(f, [self]) return self._op_result(data, units, mask, history, returntype) return func # .................................................................................................................. def _check_order(self, fname, inputs): objtypes = [] returntype = None for i, obj in enumerate(inputs): # type objtype = type(obj).__name__ objtypes.append(objtype) if objtype == 'NDDataset': returntype = 'NDDataset' elif objtype == 'Coord' and returntype != 'NDDataset': returntype = 'Coord' elif objtype == 'LinearCoord' and returntype != 'NDDataset': returntype = 'LinearCoord' else: # only the three above type have math capabilities in spectrochempy. pass # it may be necessary to change the object order regarding the types if returntype in ['NDDataset', 'Coord', 'LinearCoord'] and objtypes[0] != returntype: inputs.reverse() objtypes.reverse() if fname in ['mul', 'add', 'iadd']: pass elif fname in ['truediv', 'divide', 'true_divide']: fname = 'mul' inputs[0] = np.reciprocal(inputs[0]) elif fname in ['isub', 'sub', 'subtract']: fname = 'add' inputs[0] = np.negative(inputs[0]) elif fname in ['pow']: fname = 'exp' inputs[0] *= np.log(inputs[1]) inputs = inputs[:1] else: raise NotImplementedError() if fname in ['exp']: f = getattr(np, fname) else: f = getattr(operator, fname) return f, inputs # .................................................................................................................. @staticmethod def _binary_op(f, reflexive=False): @functools.wraps(f) def func(self, other): fname = f.__name__ if not reflexive: objs = [self, other] else: objs = [other, self] fm, objs = self._check_order(fname, objs) if hasattr(self, 'history'): history = f'Binary operation {fm.__name__} with `{_get_name(objs[-1])}` has been performed' else: history = None data, units, mask, returntype = self._op(fm, objs) new = self._op_result(data, units, mask, history, returntype) return new return func # .................................................................................................................. @staticmethod def _inplace_binary_op(f): @functools.wraps(f) def func(self, other): fname = f.__name__ if hasattr(self, 'history'): self.history = f'Inplace binary op: {fname} with `{_get_name(other)}` ' # else: # history = None objs = [self, other] fm, objs = self._check_order(fname, objs) data, units, mask, returntype = self._op(fm, objs) if returntype != 'LinearCoord': self._data = data else: from spectrochempy.core.dataset.coord import LinearCoord self = LinearCoord(data) self._units = units self._mask = mask return self return func # .................................................................................................................. def _op_result(self, data, units=None, mask=None, history=None, returntype=None): # make a new NDArray resulting of some operation new = self.copy() if returntype == 'NDDataset' and not new.implements('NDDataset'): from spectrochempy.core.dataset.nddataset import NDDataset new = NDDataset(new) if returntype != 'LinearCoord': new._data = cpy.deepcopy(data) else: from spectrochempy.core.dataset.coord import LinearCoord new = LinearCoord(cpy.deepcopy(data)) # update the attributes new._units = cpy.copy(units) if mask is not None and np.any(mask != NOMASK): new._mask = cpy.copy(mask) if history is not None and hasattr(new, 'history'): new._history.append(history.strip()) # case when we want to return a simple masked ndarray if returntype == 'masked_array': return new.masked_data return new # ---------------------------------------------------------------------------------------------------------------------- # ARITHMETIC ON NDArray # ---------------------------------------------------------------------------------------------------------------------- # unary operators UNARY_OPS = ['neg', 'pos', 'abs'] # binary operators CMP_BINARY_OPS = ['lt', 'le', 'ge', 'gt'] NUM_BINARY_OPS = ['add', 'sub', 'and', 'xor', 'or', 'mul', 'truediv', 'floordiv', 'pow'] # .................................................................................................................. def _op_str(name): return f'__{name}__' # .................................................................................................................. def _get_op(name): return getattr(operator, _op_str(name)) class _ufunc: def __init__(self, name): self.name = name self.ufunc = getattr(np, name) def __call__(self, *args, **kwargs): return self.ufunc(*args, **kwargs) @property def __doc__(self): doc = f""" {_unary_ufuncs()[self.name].split('->')[-1].strip()} Wrapper of the numpy.ufunc function ``np.{self.name}(dataset)``. Parameters ---------- dataset : array-like object to pass to the numpy function. Returns ------- out |NDDataset| Notes ----- Numpy Ufuncs referenced in our documentation can be directly applied to |NDDataset| or |Coord| type of SpectrochemPy objects. Most of these Ufuncs, however, instead of returning a numpy array, will return the same type of object. See Also -------- `numpy <https://numpy.org/doc/stable/reference/generated/numpy.{self.name}.html>`_ : Corresponding numpy Ufunc. Examples -------- >>> import spectrochempy as scp >>> ds = scp.read('wodger.spg') >>> ds_transformed = scp.{self.name}(ds) Numpy Ufuncs can also be transparently applied directly to SpectroChemPy object >>> ds_transformed = np.{self.name}(ds) """ return doc thismodule = sys.modules[__name__] def _set_ufuncs(cls): for func in _unary_ufuncs(): # setattr(cls, func, _ufunc(func)) setattr(thismodule, func, _ufunc(func)) thismodule.__all__ += [func] # .................................................................................................................. def _set_operators(cls, priority=50): cls.__array_priority__ = priority # unary ops for name in UNARY_OPS: setattr(cls, _op_str(name), cls._unary_op(_get_op(name))) for name in CMP_BINARY_OPS + NUM_BINARY_OPS: setattr(cls, _op_str(name), cls._binary_op(_get_op(name))) for name in NUM_BINARY_OPS: # only numeric operations have in-place and reflexive variants setattr(cls, _op_str('r' + name), cls._binary_op(_get_op(name), reflexive=True)) setattr(cls, _op_str('i' + name), cls._inplace_binary_op(_get_op('i' + name))) # ---------------------------------------------------------------------------------------------------------------------- # module functions # ---------------------------------------------------------------------------------------------------------------------- # make some NDMath operation accessible from the spectrochempy API # make some API functions api_funcs = [ # creation functions 'empty_like', 'zeros_like', 'ones_like', 'full_like', 'empty', 'zeros', 'ones', 'full', 'eye', 'identity', 'random', 'linspace', 'arange', 'logspace', 'geomspace', 'fromfunction', 'fromiter', # 'diagonal', 'diag', 'sum', 'average', 'mean', 'std', 'var', 'amax', 'amin', 'min', 'max', 'argmin', 'argmax', 'cumsum', 'coordmin', 'coordmax', 'clip', 'ptp', 'pipe', 'abs', 'conjugate', 'absolute', 'conj', 'all', 'any', ] for funcname in api_funcs: setattr(thismodule, funcname, getattr(NDMath, funcname)) thismodule.__all__.append(funcname) # ====================================================================================================================== if __name__ == '__main__': pass <file_sep>/spectrochempy/utils/__init__.py # -*- coding: utf-8 -*- # flake8: noqa # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== """ Package containing various utilities classes and functions. """ # some useful constants # ---------------------------------------------------------------------------------------------------------------------- # import numpy as np # masked arrays # ---------------------------------------------------------------------------------------------------------------------- from numpy.ma.core import masked as MASKED, nomask as NOMASK, MaskedArray, MaskedConstant # noqa: F401 # import util files content # ---------------------------------------------------------------------------------------------------------------------- from .exceptions import * from .fake import * from .file import * from .jsonutils import * from .misc import * from .packages import * from .plots import * from .system import * from .traitlets import * from .zip import * from .print import * <file_sep>/docs/userguide/processing/td_baseline.py # --- # jupyter: # jupytext: # formats: ipynb,py:percent # notebook_metadata_filter: all # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython # version: 3 # file_extension: .py # mimetype: text/x-python # name: python # nbconvert_exporter: python # pygments_lexer: ipython3 # version: 3.9.1 # widgets: # application/vnd.jupyter.widget-state+json: # state: {} # version_major: 2 # version_minor: 0 # --- # %% [markdown] # # Time domain baseline correction (NMR) # # Here we chow how to baseline correct dataset in the time domain before applying FFT. # # The example spectra were downloaded from [this page]( # http://anorganik.uni-tuebingen.de/klaus/nmr/processing/index.php?p=dcoffset/dcoffset) where you can find some # explanations on this kind of process. # %% import spectrochempy as scp # %% path = scp.preferences.datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'h3po4' fid = scp.read_topspin(path, expno=4) prefs = fid.preferences prefs.figure.figsize = (7, 3) _ = fid.plot(show_complex=True) # %% spec = scp.fft(fid) _ = spec.plot(xlim=(5, -5)) # %% [markdown] # We can see that in the middle of the spectrum there are an artifact (a transmitter spike) # due to different DC offset between imaginary. # # In SpectroChemPy, for now, we provide a simple kind of dc correction using the `dc`command. # %% dc_corrected_fid = fid.dc() spec = scp.fft(dc_corrected_fid) _ = spec.plot(xlim=(5, -5)) # %% path = scp.preferences.datadir / 'nmrdata' / 'bruker' / 'tests' / 'nmr' / 'cadmium' fid2 = scp.read_topspin(path, expno=100) _ = fid2.plot(show_complex=True) # %% spec2 = scp.fft(fid2) _ = spec2.plot() # %% dc_corrected_fid2 = fid2.dc() spec2 = scp.fft(dc_corrected_fid2) _ = spec2.plot()
815cce702c1fd5e9018426fa946415ec815d13bc
[ "reStructuredText", "JavaScript", "Markdown", "INI", "Python", "Text", "Dockerfile", "Shell" ]
255
Python
mw00847/spectrochempy
599b356c229cd5e2690a7b2df06ada1cbd1f63b3
2ed14d8c992acb06f165499ea177d419e7f2b6fb
refs/heads/master
<file_sep>with open("sheetla.txt","wt") as f: print(f.write("hello world"))<file_sep>def build_dict(**kwargs): return kwargs v=build_dict(name="sheetla.txt",language="python") print(v)<file_sep>with open("sheetla.txt","at") as f: print(f.write(" hello india"))<file_sep>num1=int(input("enter the first number:")) num2=int(input("enter the second number:")) if (num1%num2==0): print("number is divisible") else: print("number is not divisible") <file_sep>with open("sheetla.txt","rt") as f: print (f.read())
91b2f7bc5f77657be7482b7c3eb87f51485d38b2
[ "Python" ]
5
Python
sheetla971/pycharm-3rd-project
06118edd88d792771a91f4cb5f0e453d7cce92f8
6d6403ca68ac727bded82beee426059782685af7
refs/heads/master
<file_sep># basic core <file_sep>package com.pandey.encryption.logic; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class TripleDES { public final static String KEY="!@@!YEDNAPRAMUKJAR^&%)"; /** * @param data is the plain text sent to get encrypted. * @return Base64 Encoded String * @throws Exception: It can throw: NoSuchAlgorithmException, UnsupportedEncodingException, * NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException */ public String encrypt(String data) throws Exception { //Creating a key for the digest from external key. final MessageDigest md = MessageDigest.getInstance("SHA1"); final byte[] digestOfPassword = md.digest(KEY.getBytes("utf-8")); //Copying 24 bytes to an Array final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); // Picking the Last 16 bytes for (int j = 0, k = 8; j < 16;) { keyBytes[k++] = keyBytes[j++]; } // Fetching Triple DES SecretKey final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); // Create 8 byte iv final IvParameterSpec iv = new IvParameterSpec(new byte[8]); // Set Mode to CBC and padding final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); //Encrypt the data final byte[] cipherText = cipher.doFinal(data.getBytes("utf-8")); // return after base64 encoding return Base64.getEncoder().encodeToString(cipherText); } /** * @param data is the base64 encoded text sent to get decrypted. * @return Plain String * @throws Exception: It can throw: NoSuchAlgorithmException, UnsupportedEncodingException, * NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException */ public String decrypt(String data) throws Exception { //converts into Base64 encoded string to Byte array byte[] message = Base64.getDecoder().decode(data); final MessageDigest md = MessageDigest.getInstance("SHA1"); final byte[] digestOfPassword = md.digest(KEY.getBytes("utf-8")); //Copying 24 bytes to an Array final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 8; j < 16;) { keyBytes[k++] = keyBytes[j++]; } // Fetching Triple DES SecretKey final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); // Create 8 byte iv final IvParameterSpec iv = new IvParameterSpec(new byte[8]); // Set Mode to CBC and padding final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); // Decrypt the data final byte[] plainText = decipher.doFinal(message); // return after converting to plain Text return new String(plainText, "UTF-8"); } public static void main(String[] args) throws Exception { String text = "||Rajkumar|Pandey||"; System.out.println("Plain Text:"+text); String codedtext = new TripleDES().encrypt(text); System.out.println("base64encoded:"+codedtext); String decodedtext = new TripleDES().decrypt(codedtext); System.out.println("Decrypted:"+decodedtext); } }<file_sep>package com.pandey.git.caller; /** * * @author <NAME> * */ public class HelloGit { public static void main(String[] args) { System.out.println("Pandey Says, Hello GIT HUB"); } }
5f0cfa5c3fb5d27b2c1cc30c5ab4551a5abebe62
[ "Markdown", "Java" ]
3
Markdown
rajkumarpandey786/basic
c1fad7ed15445a641a3bcb2a8f170b1c326beb0e
43be696f5d0c31bf08dc2f75dc203420bdd52108
refs/heads/master
<repo_name>LucasMacedoS/Jsystem<file_sep>/app/Http/Controllers/ProdutoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Produto; use App\Models\Categoria; use App\Models\Grupo; class ProdutoController extends Controller { // ============================ // INICIO CRUD // ============================ // Retorna todos os produtos cadastrados public function index() { $produtos = Produto::all(); $categorias = Categoria::all(); $grupos = Grupo::all(); return view('produtos.index') ->with('categorias', $categorias) ->with('grupos', $grupos) ->with('produtos', $produtos); } // Retorna o fomulário de cadastro de produtos public function novo() { $grupos = Grupo::all(); $categorias = Categoria::all(); return view('produtos.novo') ->with('categorias', $categorias) ->with('grupos', $grupos); } // Salva no banco de dados um produto cadastrado public function salvar(Request $request) { // dd($request); $produto = new Produto; $produto->fill($request->all()); $produto->save(); return redirect()->back()->with('success', 'Produto salvo com sucesso!'); } public function show($id) { // } // Retorna o formulário de edição de produto public function editar($id) { $produto = Produto::find($id); $categorias = Categoria::all(); $grupos = Grupo::all(); return view('produtos.editar') ->with('produto', $produto) ->with('categorias', $categorias) ->with('grupos', $grupos); } // Atualiza o cadastro de um produto no banco de dados public function atualizar(Request $request, $id) { $produto = Produto::find($id); $produto->fill($request->all()); $produto->save(); return redirect()->back()->with('success', 'Produto atualizado com sucesso!'); } //Deleta um produto do bando de dados public function excluir($id) { $produto = Produto::find($id); $produto->delete(); return redirect()->back()->with('success', 'Produto excluido com sucesso!'); } // ============================ // FIM CRUD // ============================ } <file_sep>/app/Models/Pedido.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Pedido extends Model { protected $fillable = [ 'id_comanda', 'id_mesa', 'id_produto', 'valor_total', 'id_forma_pagamento' ]; public function produto(){ return $this->hasOne('App\Models\Produto', 'id', 'produto_id'); } } <file_sep>/app/Models/Comanda.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Comanda extends Model { protected $fillable = [ 'id_comanda', 'id_cliente', 'status', ]; } <file_sep>/database/seeds/FuncionariosSeeder.php <?php use Illuminate\Database\Seeder; class FuncionariosSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('users')->insert([ 'nome' => '<NAME>', 'email' => '<EMAIL>', 'password' => '<PASSWORD>' ]); DB::table('users')->insert([ 'nome' => '<NAME>', 'email' => '<EMAIL>', 'password' => '<PASSWORD>' ]); DB::table('users')->insert([ 'nome' => '<NAME>', 'email' => '<EMAIL>', 'password' => '<PASSWORD>' ]); DB::table('users')->insert([ 'nome' => '<NAME>', 'email' => '<EMAIL>', 'password' => '<PASSWORD>' ]); DB::table('users')->insert([ 'nome' => '<NAME>', 'email' => '<EMAIL>', 'password' => '<PASSWORD>' ]); DB::table('users')->insert([ 'nome' => '<NAME>', 'email' => '<EMAIL>', 'password' => '<PASSWORD>' ]); DB::table('users')->insert([ 'nome' => '<NAME>', 'email' => '<EMAIL>', 'password' => '<PASSWORD>' ]); DB::table('users')->insert([ 'nome' => '<NAME>', 'email' => '<EMAIL>', 'password' => '<PASSWORD>' ]); } } <file_sep>/app/Models/Cliente.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Cliente extends Model { protected $fillable = [ 'nome','cpf','data_nascimento' ]; } <file_sep>/app/User.php <?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'nome', 'email', 'password', 'perfil' , 'status' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function status() { $status = [ 'Inativo', 'Ativo' ]; return $status[$this->status]; } } <file_sep>/app/Models/Produto.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Produto extends Model { protected $fillable = [ 'nome', 'categoria_id', 'grupo_id', 'manipulado', 'estoque', 'valor_unitario' ]; public function manipulado() { $manipulado = [ 'Não', 'Sim' ]; return $manipulado[$this->manipulado]; } public function grupo(){ return $this->hasOne('App\Models\Grupo', 'id', 'grupo_id'); } public function categoria(){ return $this->hasOne('App\Models\Categoria', 'id', 'categoria_id'); } } <file_sep>/database/seeds/balancoCaixaSeeder.php <?php use Illuminate\Database\Seeder; class balancoCaixaSeeder extends Seeder { public function run() { DB::table('balanco_caixas')->insert([ 'venda_id' => '1', 'tipo' => 'Entrada', 'valor' => '10.50' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '2', 'tipo' => 'Entrada', 'valor' => '5.99' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '3', 'tipo' => 'Entrada', 'valor' => '4.60' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '4', 'tipo' => 'Entrada', 'valor' => '3' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '5', 'tipo' => 'Entrada', 'valor' => '10.99' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '6', 'tipo' => 'Entrada', 'valor' => '7.10' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '7', 'tipo' => 'Entrada', 'valor' => '8' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '8', 'tipo' => 'Entrada', 'valor' => '10' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '9', 'tipo' => 'Entrada', 'valor' => '5' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '10', 'tipo' => 'Entrada', 'valor' => '3' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '11', 'tipo' => 'Entrada', 'valor' => '7.80' ]); DB::table('balanco_caixas')->insert([ 'venda_id' => '12', 'tipo' => 'Entrada', 'valor' => '6' ]); } } <file_sep>/app/Http/Controllers/CategoriaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Categoria; use App\Models\Grupo; class CategoriaController extends Controller { // ============================ // INICIO CRUD // ============================ // Retorna todos as categorias cadastradas public function index() { $categorias = Categoria::all(); $grupos = Grupo::all(); return view('categorias.index') ->with('grupos', $grupos) ->with('categorias', $categorias); } // Retorna o formulário de cadastro de categoria public function novo() { $grupos = Grupo::all(); return view('categorias.novo') ->with('grupos', $grupos); } // Salva no banco dedos uma categoria cadastrada public function salvar(Request $request) { $categoria = new Categoria; $categoria->fill($request->all()); $categoria->save(); return redirect()->back()->with('success', 'Categoria salva com sucesso!'); } public function show($id) { // } // Retorna o fomulário para edição de categoria public function editar($id) { $categoria = Categoria::find($id); $grupos = Grupo::all(); return view('categorias.editar') ->with('categoria', $categoria) ->with('grupos', $grupos); } // Atualiza um cadastro de categoria no banco de dados public function atualizar(Request $request, $id) { $categoria = Categoria::find($id); $categoria->fill($request->all()); $categoria->save(); return redirect()->back()->with('success', 'Categoria atualizada com sucesso!'); } // Deleta uma categoria do banco de dados public function excluir($id) { $categoria = Categoria::find($id); $categoria->delete(); return redirect()->back()->with('seccess', 'Categoria deletada com sucesso!'); } // ============================ // FIM CRUD // ============================ } <file_sep>/app/Http/Controllers/RelatorioController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; class RelatorioController extends Controller { public function index () { // } public function funcionarios () { $funcionarios = User::all(); return view('relatorios.funcionarios.index') ->with('funcionarios', $funcionarios); } } <file_sep>/database/migrations/2019_04_03_211646_create_pedidos_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePedidosTable extends Migration { public function up() { Schema::create('pedidos', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('comanda_id'); $table->foreign('comanda_id')->references('id')->on('comandas'); $table->unsignedInteger('produto_id'); $table->foreign('produto_id')->references('id')->on('produtos'); $table->tinyInteger('quantidade'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('pedidos'); } } <file_sep>/routes/breadcrumbs.php <?php // Home Breadcrumbs::for('home', function ($trail) { $trail->push('Home', route('home')); }); // Login Breadcrumbs::for('login', function ($trail) { $trail->push('Login', route('login')); }); // Registro Breadcrumbs::for('regsitro.novo', function ($trail) { $trail->push('Registro', route('regsitro.novo')); }); // Comanda Breadcrumbs::for('comandas.index', function ($trail) { $trail->parent('home'); $trail->push('Comandas', route('comandas.index')); }); // Grupo Breadcrumbs::for('grupos.index', function ($trail) { $trail->parent('home'); $trail->push('Grupos', route('grupos.index')); }); Breadcrumbs::for('grupos.novo', function ($trail) { $trail->parent('grupos.index'); $trail->push('Novo', route('grupos.novo')); }); // Categoria Breadcrumbs::for('categorias.index', function ($trail) { $trail->parent('home'); $trail->push('Categorias', route('categorias.index')); }); Breadcrumbs::for('categorias.novo', function ($trail) { $trail->parent('categorias.index'); $trail->push('Novo', route('categorias.novo')); }); // Produto Breadcrumbs::for('produtos.index', function ($trail) { $trail->parent('home'); $trail->push('Produtos', route('produtos.index')); }); Breadcrumbs::for('produtos.novo', function ($trail) { $trail->parent('produtos.index'); $trail->push('Novo', route('produtos.novo')); }); Breadcrumbs::for('produtos.editar', function ($trail, $id) { $trail->parent('produtos.index'); $trail->push('Editar', route('produtos.editar', $id)); }); // Relatórios Breadcrumbs::for('relatorios.index', function ($trail) { $trail->parent('home'); $trail->push('Relatórios', route('relatorios.index')); }); Breadcrumbs::for('relatorios.funcionarios', function ($trail) { $trail->parent('relatorios.index'); $trail->push('Funcionários', route('relatorios.funcionarios')); }); // Caixa Breadcrumbs::for('caixa.balcao', function ($trail) { $trail->parent('home'); $trail->push('Balcão', route('caixa.balcao')); }); Breadcrumbs::for('caixa.comanda', function ($trail) { $trail->parent('home'); $trail->push('Comanda', route('caixa.comanda')); }); Breadcrumbs::for('caixa.index', function ($trail) { $trail->parent('home'); $trail->push('Balanço de Caixa', route('caixa.index')); }); // Erros Breadcrumbs::for('errors.404', function ($trail) { $trail->parent('home'); $trail->push('404', route('errors.404')); }); <file_sep>/app/Models/Venda.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Venda extends Model { protected $fillable = [ 'comanda_id', 'tipo_pagamento', 'total_venda', ]; } <file_sep>/database/seeds/UsersSeeder.php <?php use Illuminate\Database\Seeder; class UsersSeeder extends Seeder { public function run() { DB::table('users')->insert([ 'nome' => 'Admin', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'admin', 'status' => '1' ]); DB::table('users')->insert([ 'nome' => 'Joao', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'usuario', 'status' => '0' ]); DB::table('users')->insert([ 'nome' => 'Maria', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'usuario', 'status' => '1' ]); DB::table('users')->insert([ 'nome' => 'Joaquim', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'usuario', 'status' => '0' ]); DB::table('users')->insert([ 'nome' => 'Adamastor', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'usuario', 'status' => '1' ]); DB::table('users')->insert([ 'nome' => 'Clara', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'usuario', 'status' => '1' ]); DB::table('users')->insert([ 'nome' => 'Pedro', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'usuario', 'status' => '1' ]); DB::table('users')->insert([ 'nome' => 'Guilherme', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'usuario', 'status' => '1' ]); DB::table('users')->insert([ 'nome' => 'Andre', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'usuario', 'status' => '1' ]); DB::table('users')->insert([ 'nome' => 'Carlos', 'email' => '<EMAIL>', 'password' => '<PASSWORD>', 'perfil' => 'usuario', 'status' => '1' ]); } } <file_sep>/app/Models/Categoria.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Categoria extends Model { public $fillable = [ 'nome', 'grupo_id', ]; public function grupo(){ return $this->hasOne('App\Models\Grupo', 'id', 'grupo_id'); } } <file_sep>/database/seeds/GruposSeeder.php <?php use Illuminate\Database\Seeder; class GruposSeeder extends Seeder { public function run() { DB::table('grupos')->insert([ 'nome' => 'Bebidas' ]); DB::table('grupos')->insert([ 'nome' => 'Refeições' ]); DB::table('grupos')->insert([ 'nome' => 'Salgados' ]); } } <file_sep>/database/seeds/ProdutosSeeder.php <?php use Illuminate\Database\Seeder; class ProdutosSeeder extends Seeder { public function run() { DB::table('produtos')->insert([ 'nome' => 'Skol 1L', 'categoria_id' => '2', 'grupo_id' => '1', 'manipulado' => 0, 'estoque' => '100', 'valor_unitario' => '11.50' ]); DB::table('produtos')->insert([ 'nome' => 'Pizza - Mussarela', 'categoria_id' => '1', 'grupo_id' => '3', 'manipulado' => 1, 'estoque' => '7', 'valor_unitario' => '22.99' ]); DB::table('produtos')->insert([ 'nome' => 'Feijoada', 'categoria_id' => '4', 'grupo_id' => '2', 'manipulado' => 1, 'estoque' => '15', 'valor_unitario' => '17.00' ]); DB::table('produtos')->insert([ 'nome' => 'Coca-Cola 600ml', 'categoria_id' => '3', 'grupo_id' => '1', 'manipulado' => 0, 'estoque' => '252', 'valor_unitario' => '6.50' ]); } } <file_sep>/database/seeds/Pedido_ProdutosSeeder.php <?php use Illuminate\Database\Seeder; class Pedido_ProdutosSeeder extends Seeder { public function run() { DB::table('produto_pedido')->insert([ 'pedido_id' => '1', 'produto_id' => '3' ]); DB::table('produto_pedido')->insert([ 'pedido_id' => '1', 'produto_id' => '4' ]); DB::table('produto_pedido')->insert([ 'pedido_id' => '2', 'produto_id' => '1' ]); DB::table('produto_pedido')->insert([ 'pedido_id' => '2', 'produto_id' => '2' ]); } } <file_sep>/database/seeds/VendasSeeder.php <?php use Illuminate\Database\Seeder; class VendasSeeder extends Seeder { public function run() { DB::table('vendas')->insert([ 'comanda_id' => '1', 'tipo_pagamento' => 'Dinheiro', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '2', 'tipo_pagamento' => 'Debito', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '3', 'tipo_pagamento' => 'Debito', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '4', 'tipo_pagamento' => 'Debito', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '5', 'tipo_pagamento' => 'Dinheiro', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '5', 'tipo_pagamento' => 'Debito', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '6', 'tipo_pagamento' => 'Dinheiro', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '7', 'tipo_pagamento' => 'Dinheiro', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '8', 'tipo_pagamento' => 'Credito', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '9', 'tipo_pagamento' => 'Dinheiro', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '10', 'tipo_pagamento' => 'Credito', 'total_venda' => '0' ]); DB::table('vendas')->insert([ 'comanda_id' => '11', 'tipo_pagamento' => 'Dinheiro', 'total_venda' => '0' ]); } } <file_sep>/database/seeds/Tipo_pagamentoSeeder.php <?php use Illuminate\Database\Seeder; class Tipo_pagamentoSeeder extends Seeder { public function run() { DB::table('tipo_pagamento')->insert([ 'tipo_pagamento' => 'Debito' ]); DB::table('tipo_pagamento')->insert([ 'tipo_pagamento' => 'Credito' ]); DB::table('tipo_pagamento')->insert([ 'tipo_pagamento' => 'Dinheiro' ]); } } <file_sep>/database/seeds/ComandasSeeder.php <?php use Illuminate\Database\Seeder; class ComandasSeeder extends Seeder { public function run() { //1- ativo / 0 - inativo DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '2' ]); DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '0', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '1' ]); DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '0', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '0', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '0', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '0' ]); DB::table('comandas')->insert([ 'status' => '1', 'desconto' => '0' ]); } } <file_sep>/app/Models/Mesa.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Mesa extends Model { protected $fillable = [ 'id_mesa', 'id_cliente', 'status' ]; } <file_sep>/database/seeds/DatabaseSeeder.php <?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run() { $this->call(UsersSeeder::class); $this->call(GruposSeeder::class); $this->call(CategoriasSeeder::class); $this->call(ProdutosSeeder::class); $this->call(ComandasSeeder::class); $this->call(PedidosSeeder::class); // $this->call(Pedido_ProdutosSeeder::class); // $this->call(FuncionariosSeeder::class); $this->call(Tipo_pagamentoSeeder::class); $this->call(VendasSeeder::class); $this->call(balancoCaixaSeeder::class); } } <file_sep>/app/Models/BalancoCaixa.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class BalancoCaixa extends Model { protected $table = 'balanco_caixas'; protected $fillable = [ 'venda_id', 'tipo', 'valor', ]; } <file_sep>/database/seeds/PedidosSeeder.php <?php use Illuminate\Database\Seeder; class PedidosSeeder extends Seeder { public function run() { DB::table('pedidos')->insert([ 'comanda_id' => '1', 'produto_id' => '2', 'quantidade' => '1' ]); DB::table('pedidos')->insert([ 'comanda_id' => '2', 'produto_id' => '1', 'quantidade' => '2' ]); DB::table('pedidos')->insert([ 'comanda_id' => '4', 'produto_id' => '4', 'quantidade' => '1' ]); DB::table('pedidos')->insert([ 'comanda_id' => '4', 'produto_id' => '3', 'quantidade' => '2' ]); DB::table('pedidos')->insert([ 'comanda_id' => '4', 'produto_id' => '1', 'quantidade' => '3' ]); DB::table('pedidos')->insert([ 'comanda_id' => '6', 'produto_id' => '4', 'quantidade' => '1' ]); DB::table('pedidos')->insert([ 'comanda_id' => '7', 'produto_id' => '2', 'quantidade' => '5' ]); DB::table('pedidos')->insert([ 'comanda_id' => '8', 'produto_id' => '1', 'quantidade' => '2' ]); } } <file_sep>/database/seeds/CategoriasSeeder.php <?php use Illuminate\Database\Seeder; class CategoriasSeeder extends Seeder { public function run() { DB::table('categorias')->insert([ 'nome' => 'Pizza', 'grupo_id' => '3' ]); DB::table('categorias')->insert([ 'nome' => 'Alcoolicos', 'grupo_id' => '1' ]); DB::table('categorias')->insert([ 'nome' => 'Refrigerantes', 'grupo_id' => '1' ]); DB::table('categorias')->insert([ 'nome' => 'Refeições', 'grupo_id' => '2' ]); } } <file_sep>/app/Http/Controllers/ComandaController.php <?php namespace App\Http\Controllers; use App\Models\Pedido; use Illuminate\Http\Request; use App\Models\Comanda; class ComandaController extends Controller { // ============================ // INICIO CRUD // ============================ // Retorna todas as comandas cadastradas public function index() { $comandas = Comanda::where('status', 1)->get(); foreach ($comandas as $comanda){ $pedidos = Pedido::where('comanda_id', $comanda->id)->count(); $comanda['pedidos'] = $pedidos; } // dd($comandas); return view ('comanda.index')->with('comandas', $comandas); } // Retorna o formulário de cadastro de usuário public function novo() { // } // Salva no banco de dados um usuário cadastrado public function salvar(Request $request) { // } public function show($id) { // } // Retorna o formulário de edição de comada public function editar($id) { // } // Atualiza o cadastro de uma comada no banco de dados public function update(Request $request, $id) { // } // Deleta uma comada do banco de dados public function destroy($id) { // } // ============================ // FIM CRUD // ============================ } <file_sep>/app/Http/Controllers/UsuarioController.php <?php namespace App\Http\Controllers; use App\Models\BalancoCaixa; use Illuminate\Http\Request; use App\User; use App\Models\Comanda; use Hash; use Auth; class UsuarioController extends Controller { // ============================ // INICIO CRUD // ============================ // Retorna todos os usuários cadastrados public function index() { // } // Retorna todos os usuários cadastrados public function login() { // return view('auth.login'); } // Retorna todos os usuários cadastrados public function entrar(Request $request) { $usuario = User::where('email', $request->email)->first(); // dd($usuario); if(($usuario != null) && (Hash::check($request->password, $usuario->password))){ Auth::loginUsingId($usuario->id); return redirect()->route('home')->with('success_toast', 'Usuário logado!'); } return redirect()->back()->with('error', 'Usuário ou senha incorreta!'); } // Retorna o formulário de cadastro de usuário public function novo() { return view('auth.registro'); } // Salva no banco de dados um usuário cadastrado public function salvar(Request $request) { //Colocar validações $usuario = new User; $usuario->fill($request->all()); $usuario->password = <PASSWORD>::make($request->password); $usuario->save(); Auth::loginUsingId($usuario->id); return redirect()->route('home')->with('success_toast', 'Usuário Cadastrado e Logado!'); } public function show($id) { // } // Retorna o formulário de edição de usuário public function editar($id) { // } // Atualiza o cadastro de um usuário no banco de dados public function update(Request $request, $id) { // } // Deleta um usuário do banco de dados public function destroy($id) { // } // ============================ // FIM CRUD // ============================ public function home () { $funcionarios = User::where('perfil', 'usuario')->where('status', 1)->count(); $comandas = Comanda::where('status', 'ATIVO')->count(); $caixa_suplemento = BalancoCaixa::select('valor')->where('tipo' , 'Suplemento')->sum('valor'); $caixa_sangria = BalancoCaixa::select('valor')->where('tipo' , 'sangria')->sum('valor'); $caixa_entrada = BalancoCaixa::select('valor')->where('tipo' , 'Entrada')->sum('valor'); // dd($caixa_entrada); $caixa = (($caixa_suplemento + $caixa_entrada) - $caixa_sangria); return view('home') ->with('funcionarios', $funcionarios) ->with('caixa', $caixa) ->with('comandas', $comandas); } } <file_sep>/app/Http/Controllers/GrupoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Grupo; use App\Models\Categoria; class GrupoController extends Controller { // ============================ // INICIO CRUD // ============================ // Retorna todos os grupos cadastrados public function index() { $grupos = Grupo::all(); return view('grupos.index') ->with('grupos', $grupos); } // Retorna o furmulário de cadastro de grupo public function novo() { return view('grupos.novo'); } // Salva no banco de dados um grupo cadastrado public function salvar(Request $request) { $grupo = new Grupo; $grupo->fill($request->all()); $grupo->save(); return redirect()->back()->with('success', 'Grupo salvo com sucesso!'); } public function show($id) { // } // Retorna o formulário de edição de grupo public function editar($id) { $grupo = Grupo::find($id); $categoria = Categoria::where('grupo_id', $grupo->id)->first(); return view('grupos.editar') ->with('grupo', $grupo); } // Atualiza o cadastro de um grupo no banco de dados public function atualizar(Request $request, $id) { // dd($request); $grupo = Grupo::find($id); // dd($grupo); $grupo->fill($request->all()); $grupo->save(); return redirect()->back()->with('success', 'Grupo atualizado com sucesso!'); } //Deleta um grupo do banco de dados public function excluir($id) { $grupo = Grupo::find($id); $grupo->delete(); // dd($grupo); return redirect()->back()->with('success', 'Grupo excluido com sucesso!'); } // ============================ // FIM CRUD // ============================ } <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //Rotas de autenticação Auth::routes(); //Home Route::get('/', 'UsuarioController@home')->name('home'); // Route::get('/', function () { // return view('home'); // })->name('home'); //Rota Coringa // Route::get('/login', function () { // return view('auth.login'); // }); //Rotas de Login Registro Route::get('/login', 'UsuarioController@login')->name('login'); Route::post('/login/validar', 'UsuarioController@entrar')->name('login.entrar'); Route::get('/registro', 'UsuarioController@novo')->name('registro.novo'); Route::post('/registro/salvar', 'UsuarioController@salvar')->name('registro.salvar'); //Grupos Route::prefix('grupos')->group(function (){ Route::get('/', 'GrupoController@index')->name('grupos.index')->middleware('auth'); Route::get('/novo', 'GrupoController@novo')->name('grupos.novo')->middleware('auth'); Route::post('/salvar', 'GrupoController@salvar')->name('grupos.salvar')->middleware('auth'); Route::get('/editar/{id}', 'GrupoController@editar')->name('grupos.editar')->middleware('auth'); Route::post('/{id}', 'GrupoController@atualizar')->name('grupos.atualizar')->middleware('auth'); Route::post('/excluir/{id}', 'GrupoController@excluir')->name('grupos.excluir')->middleware('auth'); }); //Categorias Route::prefix('categorias')->group(function (){ Route::get('/', 'CategoriaController@index')->name('categorias.index')->middleware('auth'); Route::get('/novo', 'CategoriaController@novo')->name('categorias.novo')->middleware('auth'); Route::post('/salvar', 'CategoriaController@salvar')->name('categorias.salvar')->middleware('auth'); Route::get('/editar/{id}', 'CategoriaController@editar')->name('categorias.editar')->middleware('auth'); Route::post('/{id}', 'CategoriaController@atualizar')->name('categorias.atualizar')->middleware('auth'); Route::post('/excluir/{id}', 'CategoriaController@excluir')->name('categorias.excluir')->middleware('auth'); }); //Produtos Route::prefix('produtos')->group(function (){ Route::get('/', 'ProdutoController@index')->name('produtos.index')->middleware('auth'); Route::get('/novo', 'ProdutoController@novo')->name('produtos.novo')->middleware('auth'); Route::post('/salvar', 'ProdutoController@salvar')->name('produtos.salvar')->middleware('auth'); Route::get('/editar/{id}', 'ProdutoController@editar')->name('produtos.editar')->middleware('auth'); Route::post('/{id}', 'ProdutoController@atualizar')->name('produtos.atualizar')->middleware('auth'); Route::post('/excluir/{id}', 'ProdutoController@excluir')->name('produtos.excluir')->middleware('auth'); }); //Relatórios Route::prefix('relatorios')->group(function (){ Route::get('/', 'RelatorioController@index')->name('relatorios.index')->middleware('auth'); Route::get('/funcionarios', 'RelatorioController@funcionarios')->name('relatorios.funcionarios')->middleware('auth'); }); //Caixa Route::prefix('Caixa')->group(function (){ Route::get('index', 'CaixaController@index')->name('caixa.index')->middleware('auth'); Route::get('pagamento/balcao', 'CaixaController@balcao')->name('caixa.balcao')->middleware('auth'); Route::post('pagamento/balcao/finalizar', 'CaixaController@balcao_pagamento')->name('caixa.balcao.pagamento')->middleware('auth'); Route::post('pagamento/comanda/', 'CaixaController@comanda')->name('caixa.comanda')->middleware('auth'); Route::post('pagamento/comanda/finalizar', 'CaixaController@comanda_pagamento')->name('caixa.comanda.pagamento')->middleware('auth'); Route::post('pagamento/comanda/parcial', 'CaixaController@comanda_pagamento_parcial')->name('caixa.comanda.pagamento.parcial')->middleware('auth'); Route::post('sangria', 'CaixaController@sangria')->name('caixa.sangria')->middleware('auth'); Route::post('suplemento', 'CaixaController@suplemento')->name('caixa.suplemento')->middleware('auth'); }); Route::prefix('erros')->group(function (){ Route::get('/404', function (){ return 'error.404'; })->name('errors.404'); }); //Comandas Route::get('/comandas', 'ComandaController@index')->name('comandas.index')->middleware('auth'); //Usuario Relatório Route::get('/usuario', 'UsuarioController@index')->name('usuarios.index')->middleware('auth'); //Rotas em JSON (API Mobile) Route::get('products', function() { return Produto::all(); }); Route::get('products/{id}', function($id) { return Produto::find($id); }); Route::post('products', function(Request $request) { return Produto::create($request->all()); }); Route::put('products/{id}', function(Request $request, $id) { $article = Produto::findOrFail($id); $article->update($request->all()); return $article; }); Route::delete('products/{id}', function($id) { Produto::find($id)->delete(); return 204; }); <file_sep>/app/Http/Controllers/CaixaController.php <?php namespace App\Http\Controllers; use App\Models\BalancoCaixa; use App\Models\Comanda; use App\Models\Pedido; use App\Models\Produto; use App\Models\Venda; use Illuminate\Http\Request; class CaixaController extends Controller { public function index(){ $caixas = BalancoCaixa::all(); return view('caixa.caixa') ->with('caixas', $caixas); } public function balcao(){ $produtos = Produto::all(); return view('caixa.balcao') ->with('produtos', $produtos); } public function balcao_pagamento(Request $request){ dd($request); return view('caixa.balcao'); } public function comanda(Request $request){ // dd($request); $pedidos = Pedido::where('comanda_id', $request->comanda_id)->get(); $comanda = Comanda::find($request->comanda_id); // dd($comanda); if($comanda == null){ return redirect()->back()->with('error', 'Comanda não encontrada'); } if($comanda->status == 1){ return view('caixa.comanda') ->with('pedidos', $pedidos) ->with('comanda', $comanda); }else{ return redirect()->back()->with('error', 'Comanda inativa'); } } public function comanda_pagamento(Request $request){ $venda = new Venda; $venda->fill([ 'comanda_id' => $request->comanda_id, 'tipo_pagamento' => $request->tipo_pagamento, 'total_venda' => $request->total_venda, ]); $venda->save(); $balanco = new BalancoCaixa; $balanco->fill([ 'venda_id' => $venda->id, 'tipo' => 'Entrada', 'valor' => $venda->total_venda, ]); $balanco->save(); $comanda = Comanda::find($request->comanda_id); $comanda->status = 0; $comanda->save(); return redirect()->route('home')->with('success', 'Pagamento realizado com sucesso!'); } public function comanda_pagamento_parcial(Request $request){ // dd($request); $venda = new Venda; $venda->fill([ 'comanda_id' => $request->comanda_id, 'tipo_pagamento' => $request->tipo_pagamento, 'total_venda' => $request->pagamento_parcial, ]); $venda->save(); $balanco = new BalancoCaixa; $balanco->fill([ 'venda_id' => $venda->id, 'tipo' => 'Entrada', 'valor' => $venda->total_venda, ]); $balanco->save(); $comanda = Comanda::find($request->comanda_id); $desconto = $comanda->desconto; $desconto += $request->pagamento_parcial; $comanda->desconto = $desconto; $comanda->save(); return redirect()->route('home')->with('success', 'Pagamento realizado com sucesso!'); } public function sangria(Request $request){ $sangria = new BalancoCaixa; $sangria->fill([ 'tipo' => 'Sangria', 'valor' => $request->sangria ]); $sangria->save(); return redirect()->back()->with('success', 'Valor retirado do caixa!'); } public function suplemento(Request $request){ $suplemento = new BalancoCaixa; $suplemento->fill([ 'tipo' => 'Suplemento', 'valor' => $request->suplemento ]); $suplemento->save(); return redirect()->back()->with('success', 'Valor adicionado ao caixa!'); } } <file_sep>/database/migrations/2019_04_03_211406_create_comandas_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateComandasTable extends Migration { public function up() { Schema::create('comandas', function (Blueprint $table) { $table->increments('id'); $table->boolean('status'); $table->float('desconto',255,2)->nullable(); $table->timestamps(); }); } public function down() { Schema::dropIfExists('comandas'); } }
25465e02c16106c7310586ad16cf797457c0204d
[ "PHP" ]
32
PHP
LucasMacedoS/Jsystem
2178f5d2112fd40c569bd907db64ddc942154b18
b495034c998762ecb4f28280d71b0190dd4599a0
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tpv.dominio.ticket; /** * * @author daniel */ /*import hfl.argentina.HasarImpresoraFiscalRG3561; import hfl.argentina.HasarImpresoraFiscalRG3561.RespuestaConsultarEstado; import hfl.argentina.Hasar_Funcs.AtributosDeTexto; import hfl.argentina.HasarImpresoraFiscalRG3561.RespuestaConsultarVersion; */ public class HasarLibreria { public static void main(String args[]){ /*HasarImpresoraFiscalRG3561 hasar = new HasarImpresoraFiscalRG3561() ; RespuestaConsultarVersion resp; hasar.conectar("127.0.0.1",1600); try{ AtributosDeTexto estilo = new AtributosDeTexto(); estilo.setCentrado(true); //hasar.ImprimirTextoGenerico(estilo, "TITULO DOC. GENERICO", hfl.argentina.HasarImpresoraFiscalRG3561.ModosDeDisplay.DISPLAY_NO); resp = hasar.ConsultarVersion(); System.out.println("Producto: "+resp.getNombreProducto()); System.out.println("Marca: "+resp.getMarca()); System.out.println("Modelo y versión: "+resp.getVersion()); }catch(Exception e){ System.out.println("SE PRODUJO UN ERROR: "); e.printStackTrace(); } System.out.println("SE TERMINO"); */ } }
13279a3e1a2dffa9013be99d45886e8cc3a8a3d5
[ "Java" ]
1
Java
dom061077/tpvprint
a87ff66f045868e86dd9f9c3c5ae2271e1fc44a0
afe0da0850aabdb0f93dd898e97ed50aca866834
refs/heads/master
<file_sep>const ayuda = "Ya sabes que poco puedo hacer. Unicamente saludar y decir adios."; const mensajes = ["<say-as interpret-as=\"interjection\">comorr</say-as>.", "No he entendido nada de lo dicho."]; const getMensaje = () => mensajes[Math.random()*mensajes.length]; const ErrorHandler = { canHandle() { console.log("Inside ErrorHandler"); return true; }, handle(handlerInput, error) { console.log("Inside ErrorHandler - handle"); console.log(`Error handled: ${JSON.stringify(error)}`); console.log(`Handler Input: ${JSON.stringify(handlerInput)}`); return handlerInput.responseBuilder .speak(getMensaje()) .reprompt(ayuda) .getResponse(); }, }; module.exports = ErrorHandler;<file_sep> const helpMessage = "Poco puedo hacer. Tan sólo saludar y decir adios."; const HelpHandler = { canHandle(handlerInput) { console.log("Inside HelpHandler"); const request = handlerInput.requestEnvelope.request; return request.type === 'IntentRequest' && request.intent.name === 'AMAZON.HelpHandler'; }, handle(handlerInput) { console.log("Inside HelpHandler - handle"); return handlerInput.responseBuilder .speak(helpMessage) .reprompt(helpMessage) .getResponse(); }, }; module.exports = HelpHandler;<file_sep># Eventos de lambdas para probar intents Ejecuta los eventos con `serverless` en local usando el siguiente comando sls invoke -f hello --path events/archivo_evento.json Puedes invocar la lambda en local si añades `local` y no esperar que desplegar la lambda sls invoke local -f hello --path events/archivo_eventos.json<file_sep>const despedida = ` Ha sido un placer estar con todos vosotros. Espero que podamos charlar más a menudo, o vernos por la consola de Alexa. Nos vemos.`; const DespedirHandler = { canHandle(handlerInput) { console.log("Inside DespedidaHandler"); const request = handlerInput.requestEnvelope.request; return request.type === `IntentRequest` && request.intent.name === 'DespedirIntent'; }, handle(handlerInput) { console.log("Inside DespedidaHandler - handler"); return handlerInput.responseBuilder .speak(despedida) .getResponse(); }, }; module.exports = DespedirHandler;<file_sep>const months = { 0: "Enero", 1: "Febrero", 2: "Marzo", 3: "Abril", 4: "Mayo", 5: "Junio", 6: "Julio", 7: "Agosto", 8: "Septiembre", 9: "Octubre", 10: "Noviembre", 11: "Diciembre" }; const calculateNextEvent = () => { const today = new Date(); const currentMonth = today.getMonth(); let year = today.getFullYear(); const possibleDay = calculateFirstFriday(year, currentMonth); if (today <= possibleDay) { return possibleDay; } else { let nextMonth = currentMonth + 1; if (nextMonth > 12) { nextMonth = 1; year += 1; } return calculateFirstFriday(year, nextMonth); } }; const calculateFirstFriday = (year, month) => { for (let i = 1; i < 8; i++) { const possibleDay = new Date(year, month, i); if (possibleDay.getDay() === 5) return possibleDay; } }; const ProximoEventoHandler = { canHandle(handlerInput) { console.log("Inside ProximoEventoHandler"); const request = handlerInput.requestEnvelope.request; return ( request.type === `IntentRequest` && request.intent.name === "ProximoEventoIntent" ); }, handle(handlerInput) { console.log("Inside ProximoEventoHandler - handler"); const nextEvent = calculateNextEvent(); return handlerInput.responseBuilder .speak( `La próxima charla será el ${nextEvent.getDate()} de ${ months[nextEvent.getMonth()] } de ${ nextEvent.getFullYear() }, de 6 y media a 8 y media. <say-as interpret-as="interjection">vamos</say-as>` ) .getResponse(); } }; module.exports = ProximoEventoHandler; <file_sep>const SaludarAlguienHandler = { canHandle(handlerInput) { console.log("Inside SaludarAlguienHandler"); const request = handlerInput.requestEnvelope.request; return request.type === `IntentRequest` && request.intent.name === 'SaludarAlguienIntent'; }, handle(handlerInput) { console.log("Inside SaludarAlguienHandler - handler"); const {alguien} = handlerInput.requestEnvelope.request.intent.slots; return handlerInput.responseBuilder .speak(`Hola ${alguien.value}. <say-as interpret-as=\"interjection\">¡qué tal!</say-as>`) .getResponse(); }, }; module.exports = SaludarAlguienHandler;<file_sep>const welcomeMessage ="Hola, soy la skill de Alexa para Coders Cantabria."; const helpMessage = "Poco puedo hacer. Tan sólo saludar y decir adios."; const LaunchRequestHandler = { canHandle(handlerInput) { console.log("Inside LaunchRequest"); return handlerInput.requestEnvelope.request.type === `LaunchRequest`; }, handle(handlerInput) { console.log("Inside LaunchRequest - handle"); return handlerInput.responseBuilder .speak(welcomeMessage) .reprompt(helpMessage) .getResponse(); }, }; module.exports = LaunchRequestHandler;
0c941be16791a3967f5b9573e586322180b404ea
[ "JavaScript", "Markdown" ]
7
JavaScript
lomedil/alexa-coders-cantabria
c93b28c8cfccf175eadb4ee7156f4fb40ed7daed
c335f99be9b41baa01cd9181799b1a14b1968d44
refs/heads/master
<file_sep>import math, collections class CustomModel: def __init__(self, corpus): """Initial custom language model and structures needed by this mode""" self.train(corpus) def train(self, corpus): """ Takes a corpus and trains your language model. """ # TODO your code here pass def score(self, sentence): """ With list of strings, return the log-probability of the sentence with language model. Use information generated from train. """ # TODO your code here return 0.0 <file_sep>import math, collections class SmoothBigramModel: def __init__(self, corpus): """Initialize your data structures in the constructor.""" self.total = 0 # self.bigramCounts = collections.defaultdict(lambda: 1) self.bigramCounts = {} self.corpus = corpus self.train(self.corpus) def train(self, corpus): """ Takes a corpus and trains your language model. Compute any counts or other corpus statistics in this function. """ # TODO your code here # Tip: To get words from the corpus, try # for sentence in corpus.corpus: # for datum in sentence.data: # word = datum.word for sentence in corpus.corpus: for i in range(0, len(sentence.data) -1): # if word already in dictionary if sentence.data[i].word in self.bigramCounts: if sentence.data[i+1].word in self.bigramCounts[sentence.data[i].word]: self.bigramCounts[sentence.data[i].word][sentence.data[i+1].word] += 1 else: self.bigramCounts[sentence.data[i].word][sentence.data[i+1].word] = 1 self.total += 1 # if word not in dictionary yet else: # create new nested dictionary, and initiate it to 1 cuz of smoothing self.bigramCounts[sentence.data[i].word] = {} self.bigramCounts[sentence.data[i].word][sentence.data[i+1].word] = 1 self.total += 1 def score(self, sentence): """ Takes a list of strings as argument and returns the log-probability of the sentence using your language model. Use whatever data you computed in train() here. """ # TODO your code here score = 0.0 for i in range(1, len(sentence) - 1): print "sentence word: " + sentence[i] # if sentence[i] in self.bigramCounts: count = (self.bigramCounts[sentence[i-1]][sentence[i]] * self.bigramCounts[sentence[i]]) / (self.bigramCounts[sentence[i-1]] + len(self.corpus)) if count > 0: score += math.log(count) score -= math.log(self.total) #Ignore unseen words return score
e8a785d2cc7dbeab322d3b5e39a735d39e4abf67
[ "Python" ]
2
Python
asoong-94/NLP
3515717f5301834b9bd101c19884075f9eff98cd
91955819f49ee7709fb9c06a56b3f8e7193c41e2
refs/heads/master
<file_sep>/** * Created by SHINING on 2017/3/28. */ var mongoose = require('mongoose'); var training_contentsSchema = require('../schemas/training_contents'); module.exports = mongoose.model('Training_content',training_contentsSchema);<file_sep>/** * Created by SHINING on 2017/3/28. */ //用户数据库 var mongoose = require('mongoose'); //分类的表结构 module.exports = new mongoose.Schema({ //分类名 Nav_name:String, //导航顺序 Nav_order:{ type: Number, default: 0 }, Nav_url: String, Nav_count:{ type:Number, default:0 } });<file_sep>/** * Created by SHINING on 2017/3/28. */ var mongoose = require('mongoose'); var abroadsSchema = require('../schemas/abroads'); module.exports = mongoose.model('Abroad',abroadsSchema);<file_sep>/** * Created by SHINING on 2017/3/28. */ var mongoose = require('mongoose'); var abroad_t_titlesSchema = require('../schemas/abroad_t_titles'); module.exports = mongoose.model('Abroad_t_title',abroad_t_titlesSchema);<file_sep>/** * Created by Administrator on 2017/4/28. */ $(function () { var btnSub = $('#btnSub'), errorTip = $('#errorTip'), file_info = document.getElementById('file-info'), file_list = document.getElementById('file_list'), file_num = $('#file_num'); var files = []; btnSub.on('click',function(){ var length = file_info.files.length; var fd = new FormData(); var re = /\/admin.*/; //获取当前URL,用于判定post请求的位置 var url = document.URL; url = url.match(re); errorTip.css('display','none'); if(!length) { errorTip.css('display','block'); return false; } //利用FormData对象,存放files for (var i = 0, j = files.length; i<j;i++){ //第一个参数是提交后的数据名,第二个参数是要接入的数据 fd.append('files', files[i]); } var xhrOnProgress = function(fun) { xhrOnProgress.onprogress = fun; //绑定监听 //使用闭包实现监听绑 return function() { //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象 var xhr = $.ajaxSettings.xhr(); //判断监听函数是否为函数 if (typeof xhrOnProgress.onprogress !== 'function') return xhr; //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去 if (xhrOnProgress.onprogress && xhr.upload) { xhr.upload.onprogress = xhrOnProgress.onprogress; } return xhr; } }; var progress = $('.file_load'); var percentage = $('.percent'); var cancel = $('.file_cancel'); $.ajax({ type: 'post', url: url, data: fd, processData: false, contentType: false, xhr: xhrOnProgress(function (e) { var percent = (e.loaded / e.total * 100 | 0);//计算百分比 progress.val(percent); progress.html(percent); percentage.html(percent + '%'); if(progress.val() === 100){ cancel.html('成功'); //成功后解绑取消函数,同时清空表单的文件 cancel.off(); files = []; file_info.value = ''; } }), success: function (data) { file_num.html(data.message); } }); //阻止默认表单提交 return false; }); $('#file-info').change(function () { //隐藏错误提示 errorTip.css('display','none'); file_list.innerHTML = ''; var html = ''; //默认的文件files不能操作(没有权限),只能赋值给新数组,对新数组进行操作 Array.prototype.push.apply(files, file_info.files); //数组筛选,除掉重复的文件 var tmp; tmp = files; for(var i = 0, a = files.length; i < a; i++){ for(var j = i+1; j < files.length; j++){ if(tmp[i].name === files[j].name){ tmp[i] = ''; } } } files = []; for(var i = 0, j = 0; i < tmp.length; i++){ if(tmp[i]){ files[j] = tmp[i]; j++; } } //打印文件列表 for(var file in files){ html += '<li><p>' + files[file].name + '</p><span class="file_cancel">取消</span><br><progress class="file_load" value="0" max="100">0</progress><span class="percent">0</span></li>'; } file_list.innerHTML = html; $('#file-info').css('color',"#fff"); file_num.html('你已经选择了' + files.length + '个文件'); //添加取消按钮事件 $('.file_cancel').on('click',function () { var $this_li = $(this).closest('li'); var name = $this_li.find('p').text(); $this_li.hide(); files = files.filter(function (file) { return file.name !== name; }); file_num.html('你已经选择了' + files.length + '个文件'); }); }); });<file_sep>/** * Created by SHINING on 2017/3/19. */ /* * 后台路由 * */ var express = require('express'), router = express.Router(), formidable = require('formidable'), fs = require('fs'), User = require('../models/User'), Navigation = require('../models/Navigation'), Nav_title = require('../models/Nav_title'), Nav_content = require('../models/Nav_content'), Area = require('../models/Area'), School = require('../models/School'), Abroad = require('../models/Abroad'), Test = require('../models/Test'), Abroad_nav = require('../models/Abroad_nav'), Abroad_content = require('../models/Abroad_content'), Abroad_enroll = require('../models/Abroad_enroll'), Training = require('../models/Training'), Training_content = require('../models/Training_content'), Teacher = require('../models/Teacher'), Abroad_transparent = require('../models/Abroad_transparent'), Abroad_t_title = require('../models/Abroad_t_title'), markdown = require('markdown').markdown, Leave_message = require('../models/Leave_message'), data; /* * 处理分页的函数 * */ function setArrFont(sum) { var arr = []; for(var i = 0;i<sum;i++){ arr[i] = i+1; } return arr; } function setArrEnd(sum) { if(sum >= 5){ var arr = [], a = sum; for(var i = 0;i<5;i++){ arr[i] = a; a--; } return arr.reverse(); }else{ var arr = [], a = sum; for(var i = 0;i<5;i++){ arr[i] = a; a--; } } } function calculatePages(count) { data.count = count; //计算总页数 data.pages = Math.ceil(count / data.limit); data.pagesFont = setArrFont(data.pages); data.pagesEnd = setArrEnd(data.pages); //取值不能超过pages data.page = Math.min(data.page, data.pages); //取值不能小于1 data.page = Math.max(data.page, 1); //跳过的条数 data.skip = (data.page - 1) * data.limit; } /* * 通用数据 * */ router.use(function (req, res, next) { data = { userInfo: req.userInfo, limit: 20, count: 0, warning: '如果图片已存在,将会覆盖!(图片大小不超过2m,只允许jpg和png)' }; next(); }); router.use(function (req, res, next) { if(!req.userInfo.isAdmin){ //如果当前用户是非管理员 res.send('对不起,只有管理员才可以进入后台管理'); return ; //return不能省,因为要阻止后面的next进行,next应该就是退出路由执行下面的路由的意思 } //这里的next不能省 next(); }); /* * 首页 * */ router.get('/',function (req, res) { res.render('admin/index', data); }); /* * 用户管理 * */ router.get('/user',function (req, res) { data.page = Number(req.query.page) || 1; //获取数据库中的条数 User.count().then(function (count) { calculatePages(count); User.find().sort({_id:-1}).limit(data.limit).skip(data.skip).then(function (users) { data.forPage = 'user'; data.users = users; res.render('admin/user/user_index', data); }); }); }); /* * 用户添加 * */ router.get('/user/add',function (req, res) { res.render('admin/user/user_add', data); }); /* * 用户添加保存 * */ router.post('/user/add',function (req, res) { var username = req.body.username || '', password = req.body.password || '', isAdmin = req.body.isAdmin || false; if(username === '' || password === ''){ data.message = '用户名称或者密码不能为空!'; res.render('admin/error', data); return ; } //判断是否有相同名字的用户 User.findOne({ username: username }).then(function (rs) { if(rs){ data.message = '用户已经存在!'; res.render('admin/error', data); return Promise.reject(); }else{ //数据库不存在该用户,可以保存 return new User({ username: username, password: <PASSWORD>, isAdmin: isAdmin }).save(); } }).then(function () { data.message = '用户保存成功!'; data.url = '/admin/user'; res.render('admin/success', data); }); }); /* * 用户修改 * */ router.get('/user/edit',function (req, res) { //获取要修改的用户的信息,并且用表单的形式展现出来 var id = req.query.id || ''; //获取要修改的用户id User.findOne({ _id: id }).then(function (rs) { if(!rs){ data.message = '用户信息不存在!'; res.render('admin/error', data); return Promise.reject(); }else{ data.user = rs; res.render('admin/user/user_edit', data); } }) }); /* * 用户修改保存 * */ router.post('/user/edit',function (req, res) { var id = req.query.id || '', //获取post提交过来的名称 username = req.body.username || '', password = req.body.password || '', isAdmin = req.body.isAdmin || false; if(username === '' || password === ''){ data.message = '用户名称或者密码不能为空!'; res.render('admin/error', data); return ; } User.findOne({ _id: id }).then(function (rs) { if(!rs){ data.message = '用户信息不存在!'; res.render('admin/error', data); return Promise.reject(); }else{ //当用户没有修改名称和密码提交的时候 if(username === rs.username && password === <PASSWORD>){ User.update({ _id: id },{ username: username, password: <PASSWORD>, isAdmin: isAdmin }).then(function () { data.message = '用户信息修改成功!'; data.url = '/admin/user'; res.render('admin/success', data); }); return Promise.reject(); }else { //要修改的导航名称是否存在 return User.findOne({ _id: {$ne: id}, username: username }); } } }).then(function (sameNavigation) { if(sameNavigation){ data.message = '数据库中已经存在同名用户!'; res.render('admin/error', data); return Promise.reject(); }else{ return User.update({ _id: id },{ username: username, password: <PASSWORD>, isAdmin: isAdmin }); } }).then(function () { data.message = '用户信息修改成功!'; data.url = '/admin/user'; res.render('admin/success', data); }); }); /* * 用户删除 * */ router.get('/user/delete',function (req, res) { //获取要删除的分类的id var id = req.query.id || ''; User.remove({ _id: id }).then(function () { data.message = '删除成功!'; data.url = '/admin/user'; res.render('admin/success', data); }); }); /* * 导航管理首页 * */ router.get('/navigation',function (req, res) { Navigation.find().sort({Nav_order:1}).then(function (navigations) { data.navigations = navigations; res.render('admin/navigation/navigation_index', data); }); }); /* * 导航添加 * */ router.get('/navigation/add',function (req, res) { res.render('admin/navigation/navigation_add', data); }); /* * 导航添加的保存 * */ router.post('/navigation/add',function (req, res) { var Nav_name = req.body.Nav_name || '', Nav_order = Number(req.body.Nav_order), Nav_url = req.body.Nav_url || '/'; if(Nav_name === ''){ res.render('admin/error',{ userInfo:req.userInfo, message: '导航名称不能为空!' }); } //判断是否有相同名字的导航 Navigation.findOne({ Nav_name:Nav_name }).then(function (rs) { if(rs){ res.render('admin/error',{ userInfo: req.userInfo, message: '导航已经存在!' }); return Promise.reject(); }else{ //数据库不存在该导航,可以保存 return new Navigation({ Nav_name:Nav_name, Nav_order:Nav_order, Nav_url:Nav_url }).save(); } }).then(function () { res.render('admin/success',{ userInfo: req.userInfo, message: '导航保存成功!', url: '/admin/navigation' }); }); }); /* * 导航修改 * */ router.get('/navigation/edit',function (req, res) { //获取要修改的导航的信息,并且用表单的形式展现出来 var id = req.query.id || ''; //获取要修改的导航id Navigation.findOne({ _id: id }).then(function (rs) { if(!rs){ res.render('admin/error',{ userInfo: req.userInfo, message: '导航信息不存在!' }); return Promise.reject(); }else{ res.render('admin/navigation/navigation_edit',{ userInfo: req.userInfo, navigation: rs }); } }) }); /* * 导航修改保存 * */ router.post('/navigation/edit',function (req, res) { var id = req.query.id || '', //获取post提交过来的名称 Nav_name = req.body.Nav_name || '', Nav_order = Number(req.body.Nav_order), Nav_url = req.body.Nav_url || '/'; if(Nav_name === ''){ res.render('admin/error',{ userInfo: req.userInfo, message: '导航名称不能为空!' }); return ; } Navigation.findOne({ _id: id }).then(function (rs) { if(!rs){ res.render('admin/error',{ userInfo: req.userInfo, message: '导航信息不存在!' }); return Promise.reject(); }else{ //当用户没有修改名称提交的时候 if(Nav_name === rs.Nav_name){ Navigation.update({ _id: id },{ Nav_name: Nav_name, Nav_order: Nav_order, Nav_url: Nav_url }).then(function () { res.render('admin/success',{ userInfo: req.userInfo, message: '导航信息修改成功!', url: '/admin/navigation' }); }); return Promise.reject(); }else { //要修改的导航名称是否存在 return Navigation.findOne({ _id: {$ne: id}, Nav_name: Nav_name }); } } }).then(function (sameNavigation) { if(sameNavigation){ res.render('admin/error',{ userInfo: req.userInfo, message: '数据库中已经存在同名导航!' }); return Promise.reject(); }else{ return Navigation.update({ _id: id },{ Nav_name: Nav_name, Nav_order: Nav_order, Nav_url: Nav_url }); } }).then(function () { res.render('admin/success',{ userInfo: req.userInfo, message: '导航信息修改成功!', url: '/admin/navigation' }); }); }); /* * 导航删除 * */ router.get('/navigation/delete',function (req, res) { //获取要删除的分类的id var id = req.query.id || ''; Navigation.remove({ _id: id }).then(function () { res.render('admin/success',{ userInfo: req.userInfo, message: '删除成功!', url: '/admin/navigation' }); }); }); /* * 导航内容标题列表 * */ router.get('/navigation/title',function (req, res) { data.page = Number(req.query.page) || 1; //获取数据库中的条数 Nav_title.count().then(function (count) { calculatePages(count); Nav_title.find().sort({navigation:1,Nav_title_order:1}).limit(data.limit).skip(data.skip).populate('navigation').then(function (Nav_titles) { data.forPage = 'navigation/title'; data.Nav_titles = Nav_titles; res.render('admin/navigation/navigation_title', data); }); }); }); /* * 导航内容标题添加页面 * */ router.get('/navigation/title/add',function (req, res) { Navigation.find().sort({Nav_order:1}).then(function (navigations) { res.render('admin/navigation/navigation_title_add',{ userInfo: req.userInfo, navigations:navigations }); }); }); /* * 导航内容标题保存页面 * */ router.post('/navigation/title/add',function (req, res) { var navigation = req.body.navigation || '', title = req.body.Nav_title || '', order = Number(req.body.Nav_title_order); if(navigation === ''){ data.message = '导航分类不能为空!'; res.render('admin/error', data); return ; } if(title === ''){ data.message = '导航内容标题不能为空!'; res.render('admin/error', data); return ; } Nav_title.findOne({ navigation: navigation, Nav_title: title }).then(function (sameTitle) { if(sameTitle){ data.message = '导航内容标题不能重复!'; res.render('admin/error', data); return Promise.reject(); }else{ new Nav_title({ navigation: navigation, Nav_title: title, Nav_title_order: order }).save().then(function () { Nav_title.find({ navigation: navigation }).count().then(function (rs) { Navigation.update({ _id: navigation },{ Nav_count: rs }).then(function () { data.message = '导航内容标题保存成功!'; data.url = '/admin/navigation/title'; res.render('admin/success', data); }); }); }) } }); }); /* * 修改导航内容标题 * */ router.get('/navigation/title/edit',function (req, res) { var id = req.query.id || '', navigations = []; Navigation.find().sort({Nav_order:1}).then(function (rs) { navigations = rs; return Nav_title.findOne({ _id:id }).populate('navigation'); }).then(function (nav_title) { if(!nav_title){ data.message = '导航内容标题不存在!'; res.render('admin/error', data); return Promise.reject(); }else { data.navigations = navigations; data.nav_title = nav_title; res.render('admin/navigation/navigation_title_edit', data); } }); }); /* * 修改导航内容标题保存 * */ router.post('/navigation/title/edit',function (req, res) { var id = req.query.id || '', title = req.body.Nav_title || '', order = Number(req.body.Nav_title_order); Nav_title.findOne({ _id: id }).populate('navigation').then(function () { if (req.body.navigation === '') { data.message = '导航名称不能为空!'; res.render('admin/error', data); return Promise.reject(); } else if (title === '') { data.message = '内容标题不能为空!'; res.render('admin/error', data); return Promise.reject(); } else { return Nav_title.findOne({ navigation: req.body.navigation, _id: {$ne:id}, Nav_title: title }); } }).then(function (sameTitle) { if(sameTitle){ data.message = '导航内容标题不能重复!'; res.render('admin/error', data); return Promise.reject(); }else{ return Nav_title.update({ _id: id },{ navigation: req.body.navigation, Nav_title: title, Nav_title_order: order }); } }).then(function () { data.message = '内容修改保存成功'; data.url = '/admin/navigation/title'; res.render('admin/success', data); }); }); /* * 删除导航内容标题 * */ router.get('/navigation/title/delete',function (req, res) { //获取要删除的分类的id var id = req.query.id || '', navigation_id; Nav_title.findById({ _id: id }).then(function (rs) { navigation_id = rs.navigation; Nav_title.remove({ _id: id }).then(function () { Nav_title.find({ navigation: navigation_id }).count().then(function (rs) { Navigation.update({ _id: navigation_id }, { Nav_count: rs }).then(function () { data.message = '删除成功!'; data.url = '/admin/navigation/title'; res.render('admin/success', data); }); }); }); }); }); /* * 标题内容列表 * */ router.get('/navigation/title/content',function (req, res) { data.page = Number(req.query.page) || 1; //获取数据库中的条数 Nav_content.count().then(function (count) { calculatePages(count); Nav_content.find().populate(['navigation','nav_title']).sort({navigation:1,nav_title:1,Nav_content_order:1}).limit(data.limit).skip(data.skip).then(function (Nav_contents) { data.Nav_contents = Nav_contents; data.forPage = 'navigation/title/content'; res.render('admin/navigation/navigation_title_content', data); }); }); }); /* * 标题内容添加 * */ router.get('/navigation/title/content/add',function (req, res) { Navigation.find().sort({Nav_order:1}).then(function (navigations) { data.navigations = navigations; res.render('admin/navigation/navigation_title_content_add',data); }); }); /* * 标题内容添加保存 * */ router.post('/navigation/title/content/add',function (req, res) { var navigation = req.body.navigation || '', nav_title = req.body.nav_title || '', Nav_content_name = req.body.Nav_content_name || '', Nav_content_url = req.body.Nav_content_url || '/', Nav_content_order = Number(req.body.Nav_content_order); if(navigation === '' || nav_title === ''){ data.message = '导航名称或者导航标题不能为空!'; res.render('admin/error',data); return ; } if(Nav_content_name === ''){ data.message = '标题内容不能为空!'; res.render('admin/error',data); return ; } Nav_content.findOne({ navigation: navigation, nav_title: nav_title, Nav_content_name: Nav_content_name }).then(function (sameName) { if(sameName){ data.message = '标题内容不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ new Nav_content({ navigation: navigation, nav_title: nav_title, Nav_content_name: Nav_content_name, Nav_content_order: Nav_content_order, Nav_content_url: Nav_content_url }).save().then(function () { Nav_content.find({ navigation: navigation, nav_title: nav_title }).count().then(function (count) { Nav_title.update({ _id: nav_title },{ Nav_title_count: count }).then(function () { data.message = '标题内容保存成功!'; data.url = '/admin/navigation/title/content'; res.render('admin/success',data); }); }); }); } }); }); /* * 标题内容修改 * */ router.get('/navigation/title/content/edit',function (req, res) { var id = req.query.id || ''; Navigation.find().sort({Nav_order:1}).then(function (rs) { data.navigations = rs; return Nav_content.findOne({ _id:id }).populate(['navigation','nav_title']); }).then(function (nav_content) { if(!nav_content){ data.message = '导航内容标题不存在!'; res.render('admin/error',data); return Promise.reject(); }else { data.nav_content = nav_content; Nav_content.findById(id).populate(['navigation','nav_title']).then(function (rs) { Nav_title.find({ navigation: rs.navigation._id }).populate(['navigation','nav_title']).sort({Nav_title_order: 1}).then(function (rs) { data.nav_titles = rs; res.render('admin/navigation/navigation_title_content_edit',data); }); }); } }); }); /* * 标题内容修改保存 * */ router.post('/navigation/title/content/edit',function (req, res) { var id = req.query.id || '', navigation = req.body.navigation || '', nav_title = req.body.nav_title || '', Nav_content_name = req.body.Nav_content_name, Nav_content_url = req.body.Nav_content_url, Nav_content_order = Number(req.body.Nav_content_order); if(navigation === '' || nav_title === ''){ data.message = '导航或者导航标题不能为空!'; res.render('admin/error',data); return ; } if(Nav_content_name === ''){ data.message = '标题内容不能为空!'; res.render('admin/error',data); return ; } Nav_content.findOne({ _id: {$ne:id}, navigation: navigation, nav_title: nav_title, Nav_content_name: Nav_content_name }).populate(['navigation','nav_title']).then(function (rs) { if(rs){ data.message = '标题内容不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return Nav_content.update({ _id: id },{ navigation: navigation, nav_title: nav_title, Nav_content_name: Nav_content_name, Nav_content_order: Nav_content_order, Nav_content_url: Nav_content_url }); } }).then(function () { data.message = '修改成功!'; data.url = '/admin/navigation/title/content'; res.render('admin/success',data); }); }); /* * 标题内容删除 * */ router.get('/navigation/title/content/delete',function (req, res) { var id = req.query.id, nav_title_id; Nav_content.findById({ _id: id }).then(function (rs) { nav_title_id = rs.nav_title; Nav_content.remove({ _id: id }).then(function () { Nav_content.find({ nav_title: nav_title_id }).count().then(function (rs) { Nav_title.update({ _id: nav_title_id }, { Nav_title_count: rs }).then(function () { data.message = '删除成功!'; data.url = '/admin/navigation/title/content'; res.render('admin/success',data); }); }); }); }); }); /* * 地区列表 * */ router.get('/area',function (req, res) { Area.find().sort({Area_order:1}).then(function (rs) { data.areas = rs; res.render('admin/school/school_area',data); }); }); /* * 地区添加列表 * */ router.get('/area/add',function (req, res) { res.render('admin/school/school_area_add',data); }); /* * 地区添加列表保存 * */ router.post('/area/add',function (req, res) { var area_name = req.body.area_name, area_order = req.body.area_order; if(area_name === ''){ data.message = '地区名称不能为空!'; res.render('admin/error',data); return ; } Area.findOne({Area_name:area_name}).then(function (rs) { if(rs){ data.message = '地区名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else { new Area({ Area_name: area_name, Area_order: area_order }).save().then(function () { data.message = '地区保存成功!'; data.url = '/admin/area'; res.render('admin/success',data); }); } }); }); /* * 地区修改 * */ router.get('/area/edit',function (req, res) { var id = req.query.id || ''; Area.findById(id).then(function (rs) { if(!rs){ data.message = '所要删除的地区不存在!'; res.render('admin/error',data); return Promise.reject(); } data.area = rs; res.render('admin/school/school_area_edit',data); }); }); /* * 地区修改保存 * */ router.post('/area/edit',function (req, res) { var area_name = req.body.area_name || '', area_order = Number(req.body.area_order), id = req.query.id || ''; if(!area_name){ data.message = '地区名称不能为空!'; res.render('admin/error',data); return ; } Area.findOne({Area_name: area_name,_id: {$ne:id}}).then(function (rs) { if(rs){ data.message = '地区名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return Area.update({ _id: id },{ Area_name: area_name, Area_order: area_order }); } }).then(function () { data.message = '地区修改成功!'; data.url = '/admin/area'; res.render('admin/success',data); }); }); /* * 地区删除 * */ router.get('/area/delete',function (req, res) { var id = req.query.id || ''; if(!id){ data.message = '所要删除的地区不存在!'; res.render('admin/error',data); return ; } Area.remove({ _id:id }).then(function () { data.message = '地区删除成功!'; data.url = '/admin/area'; res.render('admin/success',data); }); }); /* * 学校信息列表 * */ router.get('/school',function (req, res) { data.page = Number(req.query.page) || 1; //获取数据库中的条数 School.count().then(function (count) { calculatePages(count); School.find().populate('area').sort({School_rank:1}).limit(data.limit).skip(data.skip).then(function (schools) { data.schools = schools; data.forPage = 'school'; res.render('admin/school/school_index', data); }); }); }); /* * 学校添加 * */ router.get('/school/add',function (req, res) { Area.find().sort({Area_order:1}).then(function (rs) { data.areas = rs; res.render('admin/school/school_add',data); }); }); /* * 学校添加保存 * */ router.post('/school/add',function (req, res) { var area_name = req.body.area_name || '', school_zn = req.body.school_zn || '', school_en = req.body.school_en || '', school_rank = Number(req.body.school_rank), school_url = req.body.school_url || '/', school_img = req.body.school_img; if(area_name === ''){ data.message = '学校地区不能为空!'; res.render('admin/error',data); return ; } if(school_zn === '' || school_en === ''){ data.message = '学校名称不能为空!'; res.render('admin/error',data); return ; } School.findOne({ School_zn: school_zn }).then(function (rs) { if(rs){ data.message = '学校中文名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return School.findOne({ School_en: school_en }); } }).then(function (rs) { if(rs){ data.message = '学校英文名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return new School({ area: area_name, School_zn: school_zn, School_en: school_en, School_rank: school_rank, School_url: school_url, School_img: school_img }).save(); } }).then(function () { return School.find({area:area_name}).count(); }).then(function (count) { return Area.update({ _id:area_name },{ Area_count: count }); }).then(function () { data.message = '学校保存成功!'; data.url = '/admin/school'; res.render('admin/success',data); }); }); /* * 学校修改 * */ router.get('/school/edit',function (req, res) { var id = req.query.id || ''; Area.find().sort({Area_order:1}).then(function (rs) { data.areas = rs; }).then(function () { return School.findById(id).populate('area'); }).then(function (rs) { data.school = rs; res.render('admin/school/school_edit',data); }); }); /* * 学校修改保存 * */ router.post('/school/edit',function (req, res) { var id = req.query.id || '', area_name = req.body.area_name || '', school_zn = req.body.school_zn || '', school_en = req.body.school_en || '', school_rank = Number(req.body.school_rank), school_url = req.body.school_url, school_img = req.body.school_img; if(area_name === ''){ data.message = '学校地区不能为空!'; res.render('admin/error',data); return ; } if(school_zn === '' || school_en === ''){ data.message = '学校名称不能为空!'; res.render('admin/error',data); return ; } School.findOne({_id: {$ne:id},School_zn: school_zn}).then(function (rs) { if(rs){ data.message = '学校中文名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return School.findOne({_id: {$ne:id},School_en: school_en}); } }).then(function (rs) { if(rs){ data.message = '学校英文名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else { return School.update({ _id: id },{ area: area_name, School_zn: school_zn, School_en: school_en, School_rank: school_rank, School_url: school_url, School_img: school_img }); } }).then(function () { data.message = '学校修改成功!'; data.url = '/admin/school'; res.render('admin/success',data); }); }); /* * 学校删除 * */ router.get('/school/delete',function (req, res) { var id = req.query.id || '', area; School.findById(id).then(function (rs) { if(!rs){ data.message = '要删除的学校不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ area = rs.area; return School.remove({ _id: id }); } }).then(function () { return School.find({ area: area }).count(); }).then(function (count) { return Area.update({ _id: area },{ Area_count: count }); }).then(function () { data.message = '学校删除成功!'; data.url = '/admin/school'; res.render('admin/success',data); }) }); /* *考试列表 * */ router.get('/study_abroad/test',function (req, res) { Test.find().sort({Test_order: 1}).then(function (rs) { data.tests = rs; res.render('admin/abroad/abroad_test_index',data); }); }); /* * 考试添加 * */ router.get('/study_abroad/test/add',function (req, res) { res.render('admin/abroad/abroad_test_add',data); }); /* * 考试添加保存 * */ router.post('/study_abroad/test/add',function (req, res) { var test_name = req.body.test_name, test_url = req.body.test_url || '/', test_order = Number(req.body.test_order); if(!test_name){ data.message = '考试名称不能为空!'; res.render('admin/error',data); return ; } Test.findOne({Test_name: test_name}).then(function (rs) { if(rs){ data.message = '考试名称不能重复!'; res.render('admin/error',data); return ; } new Test({ Test_name: test_name, Test_url: test_url, test_order: test_order }).save().then(function () { data.message = '考试保存成功!'; data.url = '/admin/study_abroad/test'; res.render('admin/success',data); }); }); }); /* * 考试修改 * */ router.get('/study_abroad/test/edit',function (req, res) { var id = req.query.id; Test.findById({_id:id}).then(function (rs) { if(!rs){ data.message = '所要修改的项目不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ data.test = rs; res.render('admin/abroad/abroad_test_edit',data); } }); }); /* * 考试修改保存 * */ router.post('/study_abroad/test/edit',function (req, res) { var id = req.query.id, test_name = req.body.test_name, test_url = req.body.test_url || '/', test_order = Number(req.body.test_order); if(!test_name){ data.message = '考试名称不能为空!'; res.render('admin/error',data); return ; } Test.findOne({Test_name:test_name,_id: {$ne: id}}).then(function (rs) { if(rs){ data.message = '考试名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return Test.update({ _id: id },{ Test_name: test_name, Test_url: test_url, Test_order: test_order }); } }).then(function () { data.message = '考试名称修改成功!'; data.url = '/admin/study_abroad/test'; res.render('admin/success',data); }); }); /* * 考试删除 * */ router.get('/study_abroad/test/delete',function (req, res) { var id = req.query.id; Test.findById({_id:id}).then(function (rs) { if(!rs){ data.message = '所要删除的项目不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ return Test.remove({_id: id}); } }).then(function () { data.message = '考试删除成功!'; data.url = '/admin/study_abroad/test'; res.render('admin/success',data); }); }); /* * 留学列表 * */ router.get('/study_abroad',function (req, res) { Abroad.find().sort({_id:-1}).then(function (abroads) { data.abroads = abroads; res.render('admin/abroad/abroad_index',data); }); }); /* * 留学添加 * */ router.get('/study_abroad/add',function (req, res) { res.render('admin/abroad/abroad_add',data); }); /* * 留学添加保存 * */ router.post('/study_abroad/add',function (req, res) { var abroad_name = req.body.abroad_name || ''; if(!abroad_name){ data.message = '留学名称不能为空!'; res.render('admin/error',data); return ; } Abroad.findOne({Abroad_name:abroad_name}).then(function (rs) { if(rs){ data.message = '留学名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ new Abroad({ Abroad_name:abroad_name }).save().then(function () { data.message = '留学保存成功!'; data.url = '/admin/study_abroad'; res.render('admin/success',data); }); } }); }); /* * 留学修改 * */ router.get('/study_abroad/edit',function (req, res) { var id = req.query.id || ''; Abroad.findById(id).then(function (rs) { if(!rs){ data.message = '留学项目不存在!'; res.render('admin/error',data); return ; } data.abroad = rs; res.render('admin/abroad/abroad_edit',data); }); }); /* * 留学修改保存 * */ router.post('/study_abroad/edit',function (req,res) { var abroad_name = req.body.abroad_name || '', id = req.query.id || ''; if(!abroad_name){ data.message = '留学名称不能为空!'; res.render('admin/error',data); return ; } Abroad.findOne({Abroad_name:abroad_name,_id:{$ne:id}}).then(function (rs) { if(rs){ data.message = '留学名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return Abroad.update({ _id: id },{ Abroad_name: abroad_name }); } }).then(function () { data.message = '留学修改成功!'; data.url = '/admin/study_abroad'; res.render('admin/success',data); }); }); /* * 留学删除 * */ router.get('/study_abroad/delete',function (req,res) { var id = req.query.id; Abroad.findById(id).then(function (rs) { if(!rs){ data.message = '所要删除的留学不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ return Abroad.remove({_id:id}); } }).then(function () { data.message = '留学删除成功!'; data.url = '/admin/study_abroad'; res.render('admin/success',data); }); }); /* * 留学导航列表 * */ router.get('/study_abroad/nav',function (req, res) { data.page = Number(req.query.page) || 1; //获取数据库中的条数 Abroad_nav.count().then(function (count) { calculatePages(count); Abroad_nav.find().populate('abroad').sort({abroad:1,Abroad_nav_order:1}).limit(data.limit).skip(data.skip).then(function (rs) { data.abroad_navs = rs; data.forPage = 'study_abroad/nav'; res.render('admin/abroad/abroad_nav_index',data); }); }); }); /* * 留学导航添加 * */ router.get('/study_abroad/nav/add',function (req, res) { Abroad.find().sort({_id:-1}).then(function (rs) { data.abroads = rs; res.render('admin/abroad/abroad_nav_add',data); }); }); /* * 留学导航添加保存 * */ router.post('/study_abroad/nav/add',function (req, res) { var abroad = req.body.abroad, abroad_nav_name = req.body.abroad_nav_name || '', abroad_nav_url = req.body.abroad_nav_url, abroad_nav_order = Number(req.body.abroad_nav_order); if(!abroad_nav_name){ data.message = '留学导航名称不能为空!'; res.render('admin/error',data); return ; } if(!abroad){ data.message = '请选择留学项目!'; res.render('admin/error',data); return ; } Abroad_nav.findOne({abroad: abroad,Abroad_nav_name:abroad_nav_name}).then(function (rs) { if(rs){ data.message = '留学导航不能重复!'; res.render('admin/error',data); return Promise.reject(); } new Abroad_nav({ abroad: abroad, Abroad_nav_name: abroad_nav_name, Abroad_nav_url: abroad_nav_url, Abroad_nav_order: abroad_nav_order }).save().then(function () { Abroad_nav.find({abroad:abroad}).count().then(function (count) { Abroad.update({ _id:abroad },{ Abroad_count: count }).then(function () { data.message = '留学导航添加成功!'; data.url = '/admin/study_abroad/nav'; res.render('admin/success',data); }); }); }); }); }); /* * 留学导航修改 * */ router.get('/study_abroad/nav/edit',function (req, res) { var id = req.query.id; Abroad_nav.findById(id).populate('abroad').then(function (rs) { data.abroad_nav = rs; }).then(function () { Abroad.find().sort({_id:-1}).then(function (rs) { data.abroads = rs; res.render('admin/abroad/abroad_nav_edit',data); }) }); }); /* * 留学导航修改保存 * */ router.post('/study_abroad/nav/edit',function (req, res) { var id = req.query.id, abroad = req.body.abroad || '', abroad_nav_name = req.body.abroad_nav_name || '', abroad_nav_url = req.body.abroad_nav_url, abroad_nav_order = Number(req.body.abroad_nav_order); if(!abroad){ data.message = '请选择留学项目!'; res.render('admin/error',data); return ; } if(!abroad_nav_name){ data.message = '留学导航名称不能为空!'; res.render('admin/error',data); return ; } Abroad_nav.findOne({abroad:abroad,Abroad_nav_name:abroad_nav_name,_id:{$ne:id}}).then(function (rs) { if(rs){ data.message = '留学导航不能重复!'; res.render('admin/error',data); return Promise.reject(); } Abroad_nav.update({ _id: id },{ abroad: abroad, Abroad_nav_name: abroad_nav_name, Abroad_nav_url: abroad_nav_url, Abroad_nav_order: abroad_nav_order }).then(function () { data.message = '修改保存成功!'; data.url = '/admin/study_abroad/nav'; res.render('admin/success',data); }); }); }); /* * 留学导航删除 * */ router.get('/study_abroad/nav/delete',function (req, res) { var id = req.query.id; Abroad_nav.findById(id).then(function (rs) { if(!rs){ data.message = '要删除的留学导航不存在!'; res.render('admin/error',data); return Promise.reject(); } data.abroadC = rs.abroad; Abroad_nav.remove({_id:id}).then(function () { Abroad_nav.find({abroad:data.abroadC}).count().then(function (count) { Abroad.update({ _id: data.abroadC },{ Abroad_count: count }).then(function () { data.message = '留学导航删除成功!'; data.url = '/admin/study_abroad/nav'; res.render('admin/success',data); }); }); }); }); }); /* * 留学导航文章列表 * */ router.get('/study_abroad/nav/content',function (req, res) { data.page = Number(req.query.page) || 1; //获取数据库中的条数 Abroad_content.count().then(function (count) { calculatePages(count); Abroad_content.find().populate(['abroad','abroad_nav']).sort({abroad:1,abroad_nav:1,Abroad_content_order:1}).limit(data.limit).skip(data.skip).then(function (rs) { data.abroad_contents = rs; data.forPage = 'study_abroad/nav/content'; res.render('admin/abroad/abroad_nav_content_index',data); }); }); }); /* * 留学导航文章添加 * */ router.get('/study_abroad/nav/content/add',function (req, res) { Abroad.find().sort({_id:-1}).then(function (rs) { data.abroads = rs; res.render('admin/abroad/abroad_nav_content_add',data); }); }); /* * 留学导航文章添加保存 * */ router.post('/study_abroad/nav/content/add',function (req, res) { var abroad = req.body.abroad, abroad_nav = req.body.abroad_nav, abroad_content_name = req.body.abroad_content_name, abroad_content_url = req.body.abroad_content_url, abroad_content_order = Number(req.body.abroad_content_order), abroad_content_markdown = req.body.abroad_content_markdown; if(!abroad || !abroad_nav){ data.message = '留学项目或者导航名称不能为空!'; res.render('admin/error',data); return ; } if(!abroad_content_name){ data.message = '文章标题不能为空!'; res.render('admin/error',data); return ; } if(!abroad_content_url){ data.message = '文章url不能为空!'; res.render('admin/error',data); return ; } Abroad_content.findOne({abroad:abroad,abroad_nav:abroad_nav,Abroad_content_name:abroad_content_name}).then(function (rs) { if(rs){ data.message = '文章标题不能重复!'; res.render('admin/error',data); return Promise.reject(); } new Abroad_content({ abroad: abroad, abroad_nav: abroad_nav, Abroad_content_name: abroad_content_name, Abroad_content_url: abroad_content_url, Abroad_content_order: abroad_content_order, Abroad_content_markdown: abroad_content_markdown }).save().then(function () { Abroad_content.find({abroad_nav: abroad_nav}).count().then(function (count) { Abroad_nav.update({ _id: abroad_nav },{ Abroad_nav_count: count }).then(function () { data.message = '文章标题保存成功!'; data.url = '/admin/study_abroad/nav/content'; res.render('admin/success',data); }); }); }); }); }); /* * 留学导航文章修改 * */ router.get('/study_abroad/nav/content/edit',function (req, res) { var id = req.query.id; if(!id){ data.message = '所要修改的文章不存在!'; res.render('admin/error',data); return ; } Abroad.find().sort({_id:-1}).then(function (rs) { data.abroads = rs; Abroad_nav.find().sort({abroad: 1}).then(function (rs) { data.abroad_navs = rs; Abroad_content.findById(id).populate(['abroad','abroad_nav']).then(function (rs) { data.abroad_content = rs; res.render('admin/abroad/abroad_nav_content_edit',data); }); }); }); }); /* * 留学导航文章修改保存 * */ router.post('/study_abroad/nav/content/edit',function (req, res) { var id = req.query.id, abroad = req.body.abroad, abroad_nav = req.body.abroad_nav, abroad_content_name = req.body.abroad_content_name, abroad_content_url = req.body.abroad_content_url, abroad_content_order = Number(req.body.abroad_content_order), abroad_content_markdown = req.body.abroad_content_markdown; if(!abroad || !abroad_nav){ data.message = '留学项目或者留学导航不能为空!'; res.render('admin/error',data); return ; } if(!abroad_content_name){ data.message = '文章标题不能为空!'; res.render('admin/error',data); return ; } if(!abroad_content_url){ data.message = '文章url不能为空!'; res.render('admin/error',data); return ; } Abroad_content.findOne({abroad:abroad,abroad_nav:abroad_nav,Abroad_content_name:abroad_content_name,_id:{$ne: id}}).then(function (rs) { if(rs){ data.message = '文章标题不能重复!'; res.render('admin/error',data); return Promise.reject(); } Abroad_content.update({ _id:id },{ abroad: abroad, abroad_nav: abroad_nav, Abroad_content_name: abroad_content_name, Abroad_content_url: abroad_content_url, Abroad_content_order: abroad_content_order, Abroad_content_markdown: abroad_content_markdown }).then(function () { data.message = '文章修改成功!'; data.url = '/admin/study_abroad/nav/content'; res.render('admin/success',data); }); }); }); /* * 留学导航文章删除 * */ router.get('/study_abroad/nav/content/delete',function (req, res) { var id = req.query.id; Abroad_content.findById(id).then(function (rs) { if(!rs){ data.message = '要删除的文章标题不存在!'; res.render('admin/error',data); return Promise.reject(); } data.abroadC = rs.abroad_nav; Abroad_content.remove({_id:id}).then(function () { Abroad_content.find({abroad_nav:data.abroadC}).count().then(function (count) { Abroad_nav.update({ _id: data.abroadC },{ Abroad_nav_count: count }).then(function () { data.message = '文章标题删除成功!'; data.url = '/admin/study_abroad/nav/content'; res.render('admin/success',data); }); }); }); }); }); /* * 录取案例列表 * */ router.get('/study_abroad/nav/enroll',function (req, res) { data.page = Number(req.query.page) || 1; //获取数据库中的条数 Abroad_enroll.count().then(function (count) { calculatePages(count); Abroad_enroll.find().populate(['abroad','school','test1','test2']).sort({abroad:1,Abroad_enroll_order:1}).limit(data.limit).skip(data.skip).then(function (rs) { data.abroad_enrolls = rs; data.forPage = 'study_abroad/nav/enroll'; res.render('admin/abroad/abroad_nav_enroll_index',data); }); }); }); /* * 录取案例添加 * */ router.get('/study_abroad/nav/enroll/add',function (req, res) { Abroad.find().sort({_id:-1}).then(function (rs) { data.abroads = rs; Test.find().sort({Test_order: 1}).then(function (rs) { data.tests = rs; res.render('admin/abroad/abroad_nav_enroll_add',data); }); }); }); /* * 录取案例添加保存 * */ router.post('/study_abroad/nav/enroll/add',function (req, res) { var abroad =req.body.abroad, abroad_enroll_name = req.body.abroad_enroll_name, school_zn = req.body.school, abroad_enroll_subject = req.body.abroad_enroll_subject, abroad_enroll_student = req.body.abroad_enroll_student, abroad_enroll_code = req.body.abroad_enroll_code, test1 = req.body.test1, test2 = req.body.test2, abroad_enroll_score1 = parseFloat(req.body.abroad_enroll_score1).toFixed(2), abroad_enroll_score2 = parseFloat(req.body.abroad_enroll_score2).toFixed(2), abroad_enroll_url = req.body.abroad_enroll_url, abroad_enroll_order = req.body.abroad_enroll_order, school_id; if(!abroad){ data.message = '留学项目不能为空!'; res.render('admin/error',data); return ; } if(!school_zn){ data.message = '录取学校不能为空!'; res.render('admin/error',data); return ; } if(!abroad_enroll_student){ data.message = '录取学生姓名不能为空!'; res.render('admin/error',data); return ; } if(!test1 || !test2){ data.message = '考试科目不能为空!'; res.render('admin/error',data); return ; } if(test1 === test2){ data.message = '两个考试科目重复!'; res.render('admin/error',data); return ; } School.findOne({School_zn: school_zn}).then(function (rs) { if(!rs){ data.message = '录取的学校不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ school_id = rs._id; Abroad_enroll.findOne({Abroad_enroll_student: abroad_enroll_student}).then(function (rs) { if(rs){ data.message = '该学生信息已存在!'; res.render('admin/error',data); return ; } new Abroad_enroll({ abroad: abroad, school: school_id, test1: test1, test2: test2, Abroad_enroll_score1: abroad_enroll_score1, Abroad_enroll_score2: abroad_enroll_score2, Abroad_enroll_name: abroad_enroll_name, Abroad_enroll_subject: abroad_enroll_subject, Abroad_enroll_student: abroad_enroll_student, Abroad_enroll_code: abroad_enroll_code, Abroad_enroll_url: abroad_enroll_url, Abroad_enroll_order: abroad_enroll_order }).save().then(function () { Abroad_enroll.find({school: school_id}).count().then(function (count) { School.update({ _id: school_id },{ School_enroll: count }).then(function () { data.message = '录取案例保存成功!'; data.url = '/admin/study_abroad/nav/enroll'; res.render('admin/success',data); }); }); }); }); } }); }); /* * 录取案例修改 * */ router.get('/study_abroad/nav/enroll/edit',function (req, res) { var id = req.query.id; Abroad_enroll.findById(id).populate(['abroad','school','test1','test2']).then(function (rs) { if(!rs){ data.message = '要修改的录取案例不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ data.abroad_enroll = rs; Abroad.find().then(function (rs) { data.abroads = rs; }).then(function () { Test.find().sort({Test_order: 1}).then(function (rs) { data.tests = rs; res.render('admin/abroad/abroad_nav_enroll_edit',data); }); }); } }); }); /* * 录取案例修改保存 * */ router.post('/study_abroad/nav/enroll/edit',function (req, res) { var id = req.query.id, abroad =req.body.abroad, abroad_enroll_name = req.body.abroad_enroll_name, school_zn = req.body.school, abroad_enroll_subject = req.body.abroad_enroll_subject, abroad_enroll_student = req.body.abroad_enroll_student, abroad_enroll_code = req.body.abroad_enroll_code, test1 = req.body.test1, test2 = req.body.test2, abroad_enroll_score1 = parseFloat(req.body.abroad_enroll_score1).toFixed(2), abroad_enroll_score2 = parseFloat(req.body.abroad_enroll_score2).toFixed(2), abroad_enroll_url = req.body.abroad_enroll_url, abroad_enroll_order = req.body.abroad_enroll_order, school_id; if(!abroad){ data.message = '留学项目不能为空!'; res.render('admin/error',data); return ; } if(!school_zn){ data.message = '录取学校不能为空!'; res.render('admin/error',data); return ; } if(!abroad_enroll_student){ data.message = '录取学生姓名不能为空!'; res.render('admin/error',data); return ; } if(!test1 || !test2){ data.message = '考试科目不能为空!'; res.render('admin/error',data); return ; } if(test1 === test2){ data.message = '两个考试科目重复!'; res.render('admin/error',data); return ; } School.findOne({School_zn: school_zn}).then(function (rs) { if(!rs){ data.message = '录取的学校不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ school_id = rs._id; Abroad_enroll.findOne({Abroad_enroll_student: abroad_enroll_student,_id:{$ne:id}}).then(function (rs) { if(rs){ data.message = '该学生信息已存在!'; res.render('admin/error',data); return ; } Abroad_enroll.update({ _id: id },{ abroad: abroad, school: school_id, test1: test1, test2: test2, Abroad_enroll_score1: abroad_enroll_score1, Abroad_enroll_score2: abroad_enroll_score2, Abroad_enroll_name: abroad_enroll_name, Abroad_enroll_subject: abroad_enroll_subject, Abroad_enroll_student: abroad_enroll_student, Abroad_enroll_code: abroad_enroll_code, Abroad_enroll_url: abroad_enroll_url, Abroad_enroll_order: abroad_enroll_order }).then(function () { data.message = '录取案例保存成功!'; data.url = '/admin/study_abroad/nav/enroll'; res.render('admin/success',data); }); }); } }); }); /* * 录取案例删除 * */ router.get('/study_abroad/nav/enroll/delete',function (req, res) { var id = req.query.id, enroll_school; Abroad_enroll.findById(id).populate('school').then(function (rs) { if(!rs){ data.message = '要删除的案例不存在!'; res.render('admin/error',data); }else{ enroll_school = rs.school._id; return Abroad_enroll.remove({_id:id}); } }).then(function () { Abroad_enroll.find({school: enroll_school}).count().then(function (count) { School.update({ _id: enroll_school },{ School_enroll: count }).then(function () { data.message = '案例删除成功!'; data.url = '/admin/study_abroad/nav/enroll'; res.render('admin/success',data); }); }); }); }); /* * 培训分类列表 * */ router.get('/training',function (req, res) { data.page = Number(req.query.page) || 1; Training.find().count().then(function (count) { calculatePages(count); data.forPage = 'training'; Training.find().populate('test').sort({test:1,Training_order: 1}).limit(data.limit).skip(data.skip).then(function (rs) { data.trainings = rs; res.render('admin/training/training_category_index',data); }); }); }); /* * 培训分类添加 * */ router.get('/training/add',function (req, res) { Test.find().sort({Test_order: 1}).then(function (rs) { data.tests = rs; res.render('admin/training/training_category_add',data); }); }); /* * 培训分类添加保存 * */ router.post('/training/add',function (req, res) { var test = req.body.test, training_name = req.body.training_name, training_url = req.body.training_url || '/', training_order = Number(req.body.training_order); if(!test){ data.message = '考试项目不能为空!'; res.render('admin/error',data); return ; } if(!training_name){ data.message = '培训分类名称不能为空!'; res.render('admin/error',data); return ; } Training.findOne({test: test,Training_name: training_name}).then(function (rs) { if(rs){ data.message = '培训分类名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return new Training({ test: test, Training_name: training_name, Training_url: training_url, Training_order: training_order }).save(); } }).then(function () { Training.find({test: test}).count().then(function (count) { return Test.update({_id: test},{Test_count: count}); }).then(function () { data.message = '培训分类添加成功!'; data.url = '/admin/training'; res.render('admin/success',data); }); }); }); /* * 培训分类修改 * */ router.get('/training/edit',function (req, res) { var id = req.query.id; Test.find().sort({Test_order: 1}).then(function (rs) { data.tests =rs; Training.findById(id).populate('test').then(function (rs) { if(!rs){ data.message = '所要修改的培训分类不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ data.training = rs; res.render('admin/training/training_category_edit',data); } }); }); }); /* * 培训分类修改保存 * */ router.post('/training/edit',function (req, res) { var id = req.query.id, test = req.body.test, training_name = req.body.training_name, training_url = req.body.training_url || '/', training_order = Number(req.body.training_order); if(!test){ data.message = '考试项目不能为空!'; res.render('admin/error',data); return ; } if(!training_name){ data.message = '培训分类名称不能为空!'; res.render('admin/error',data); return ; } Training.findOne({test: test,_id:{$ne:id},Training_name: training_name}).then(function (rs) { if(rs){ data.message = '培训分类名称不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return Training.update({ _id:id },{ test: test, Training_name: training_name, Training_url: training_url, Training_order: training_order }); } }).then(function () { data.message = '培训分类修改成功!'; data.url = '/admin/training'; res.render('admin/success',data); }); }); /* * 培训分类删除 * */ router.get('/training/delete',function (req, res) { var id = req.query.id, test; Training.findById(id).populate('test').then(function (rs) { if(!rs){ data.message = '要删除的培训分类不存在!'; res.render('admin/error',data); }else{ test = rs.test._id; return Training.remove({_id:id}); } }).then(function () { Training.find({test: test}).count().then(function (count) { return Test.update({_id: test},{Test_count: count}); }).then(function () { data.message = '培训分类删除成功!'; data.url = '/admin/training'; res.render('admin/success',data); }); }); }); /* * 培训文章列表 * */ router.get('/training/content',function (req, res) { data.page = Number(req.query.page) || 1; Training_content.find().count().then(function (count) { calculatePages(count); data.forPage = 'training/content'; Training_content.find().populate(['test','training']).sort({test:1,training:1,Training_content_order:1}).limit(data.limit).skip(data.skip).then(function (rs) { data.training_contents = rs; res.render('admin/training/training_content_index',data); }); }); }); /* * 培训文章添加 * */ router.get('/training/content/add',function (req, res) { Test.find().sort({Test_order:1}).then(function (rs) { data.tests = rs; res.render('admin/training/training_content_add',data); }); }); /* * 培训文章添加保存 * */ router.post('/training/content/add',function (req, res) { var test = req.body.test, training = req.body.training, training_content_name = req.body.training_content_name, training_content_url = req.body.training_content_url || '/', training_content_order = Number(req.body.training_content_order || 10), training_content_markdown = req.body.training_content_markdown; if(!test || !training){ data.message = '考试项目或者培训分类不能为空!'; res.render('admin/error',data); return ; } if(!training_content_name){ data.message = '培训分类文章标题不能为空!'; res.render('admin/error',data); return ; } Training_content.findOne({test: test,training: training,Training_content_name:training_content_name}).then(function (rs) { if(rs){ data.message = '培训分类文章标题不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return new Training_content({ test: test, training: training, Training_content_name: training_content_name, Training_content_url: training_content_url, Training_content_order: training_content_order, Training_content_markdown: training_content_markdown }).save(); } }).then(function () { Training_content.find({test: test,training: training}).count().then(function (count) { Training.update({ _id: training },{ Training_count: count }).then(function () { data.message = '培训文章添加成功!'; data.url = '/admin/training/content'; res.render('admin/success',data); }); }); }); }); /* * 培训文章修改 * */ router.get('/training/content/edit',function (req, res) { var id = req.query.id; Test.find().sort({Test_order:1}).then(function (rs) { data.tests = rs; Training_content.findById(id).populate('test').then(function (re) { if(!re){ data.message = '要修改的培训文章不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ data.training_content = re; Training.find({test: data.training_content.test._id}).sort({Training_order:1}).then(function (rs) { data.trainings = rs; res.render('admin/training/training_content_edit',data); }); } }); }); }); /* * 培训文章修改保存 * */ router.post('/training/content/edit',function (req, res) { var id = req.query.id, test = req.body.test, training = req.body.training, training_content_name = req.body.training_content_name, training_content_url = req.body.training_content_url || '/', training_content_order = Number(req.body.training_content_order || 10), training_content_markdown = req.body.training_content_markdown; if(!test || !training){ data.message = '考试项目或者培训分类不能为空!'; res.render('admin/error',data); return ; } if(!training_content_name){ data.message = '培训文章标题不能为空!'; res.render('admin/error',data); return ; } Training_content.findOne({Training_content_name: training_content_name,_id: {$ne:id}}).then(function (rs) { if(rs){ data.message = '培训文章标题不能重复!'; res.render('admin/error',data); return Promise.reject(); }else{ return Training_content.update({ _id: id },{ test: test, training: training, Training_content_name: training_content_name, Training_content_url: training_content_url, Training_content_order: training_content_order, Training_content_markdown: training_content_markdown }); } }).then(function () { data.message = '培训文章修改成功!'; data.url = '/admin/training/content'; res.render('admin/success',data); }); }); /* * 培训文章删除 * */ router.get('/training/content/delete',function (req, res) { var id = req.query.id, training; Training_content.findById(id).populate('training').then(function (rs) { if(!rs){ data.message = '要删除的文章不存在!'; res.render('admin/error',data); return Promise.reject(); }else{ training = rs.training._id; return Training_content.remove({_id: id}); } }).then(function () { Training_content.find({training: training}).count().then(function (count) { console.log(training); Training.update({_id: training},{Training_count:count}).then(function () { data.message = '培训文章删除成功!'; data.url = '/admin/training/content'; res.render('admin/success',data); }); }); }); }); /* * 教师列表 * */ router.get('/teacher',function (req, res) { data.page = Number(req.query.page) || 1; Teacher.find().count().then(function (count) { calculatePages(count); data.forPage = 'teacher'; Teacher.find().sort({Teacher_order: 1}).limit(data.limit).skip(data.skip).then(function (rs) { data.teachers = rs; res.render('admin/teacher/teacher_index',data); }); }); }); /* * 教师添加 * */ router.get('/teacher/add',function (req, res) { res.render('admin/teacher/teacher_add',data); }); /* * 教师添加保存 * */ router.post('/teacher/add',function (req, res) { var teacher_name = req.body.teacher_name, teacher_intro = req.body.teacher_intro, teacher_img = req.body.teacher_img, teacher_url = req.body.teacher_url || '/', teacher_order = Number(req.body.teacher_order || 0), teacher_background = req.body.teacher_background; if(!teacher_name){ data.message = '教师名称不能为空'; res.render('admin/error',data); return ; } new Teacher({ Teacher_name: teacher_name, Teacher_intro: teacher_intro, Teacher_img: teacher_img, Teacher_url: teacher_url, Teacher_order: teacher_order, Teacher_background: teacher_background }).save().then(function () { data.message = '教师信息保存成功!'; data.url = '/admin/teacher'; res.render('admin/success',data); }); }); /* * 教师修改 * */ router.get('/teacher/edit',function (req, res) { var id = req.query.id; Teacher.findById(id).then(function (rs) { if(!rs){ data.message = '所要修改的教师信息不存在!'; res.render('admin/error',data); return Promise.reject(); } data.teacher = rs; res.render('admin/teacher/teacher_edit',data); }) }); /* * 教师修改保存 * */ router.post('/teacher/edit',function (req, res) { var id = req.query.id, teacher_name = req.body.teacher_name, teacher_intro = req.body.teacher_intro, teacher_img = req.body.teacher_img, teacher_url = req.body.teacher_url || '/', teacher_order = Number(req.body.teacher_order || 0), teacher_background = req.body.teacher_background; if(!teacher_name){ data.message = '教师名称不能为空!'; res.render('admin/error',data); return ; } Teacher.update({_id: id},{ Teacher_name: teacher_name, Teacher_intro: teacher_intro, Teacher_img: teacher_img, Teacher_url: teacher_url, Teacher_order: teacher_order, Teacher_background: teacher_background }).then(function () { data.message = '教师信息修改成功!'; data.url = '/admin/teacher'; res.render('admin/success',data); }); }); /* * 教师删除 * */ router.get('/teacher/delete',function (req, res) { var id = req.query.id; Teacher.findById(id).then(function (rs) { if(!rs){ data.message = '所要删除的教师信息不存在!'; res.render('admin/error',data); return Promise.reject(); } Teacher.remove({_id: id}).then(function () { data.message = '教师信息删除成功!'; data.url = '/admin/teacher'; res.render('admin/success',data); }) }) }); /* * 文件上传--学校 * */ router.get('/file_upload/school',function (req, res) { data.message = '学校图片上传'; res.render('admin/fileupload/fileupload_index',data); }); /* * 学校图片上传保存 * */ router.post('/file_upload/school',function (req, res) { var form = new formidable.IncomingForm(); //创建上传表单 form.encoding = 'utf-8'; //设置编码 form.uploadDir = 'public/images/school/'; //设置上传目录 form.keepExtensions = true; //保留后缀 form.maxFieldsSize = 2 * 1024 * 1024; //限制文件大小,2m form.multiples = true; //允许多文件上传 form.parse(req, function (err, fields, files) { //错误, 字段域, 文件信息 if(err){ data.message = err; res.render('admin/error',data); return ; } /* * 保留文件原来名字 * */ if(files.files.length){ //如果同时上传多个文件,返回的是数组,对所有数组中的文件重命名 for(var i = 0; i < files.files.length;i++){ fs.renameSync(files.files[i].path, form.uploadDir + files.files[i].name); //重命名 } }else{ //对单一文件进行重命名 fs.renameSync(files.files.path, form.uploadDir + files.files.name); //重命名 } data.school_img_num = files.files.length || 1; }); form.on('end', function() { data.message = '上传成功,共上传了' + data.school_img_num + '张图片'; res.json(data); }); }); /* * 学校图片列表 * */ router.get('/file_upload/school/list',function (req, res) { var path = 'public/images/school'; var fileArray = fs.readdirSync(path); data.fileArray = []; data.page = Number(req.query.page) || 1; for(var i = (data.page - 1) * data.limit; i < (data.page) * data.limit; i++ ){ if(fileArray[i]){ data.fileArray.push(fileArray[i]); } } data.count = fileArray.length; data.forPage = 'file_upload/school/list'; calculatePages(data.count); res.render('admin/fileupload/fileupload_school_list',data); }); /* * 学校图片删除 * */ router.get('/file_upload/school/list/delete',function (req, res) { var name = req.query.filename, path = 'public/images/school'; fs.unlink(path + '/' + name, function (err) { if(err){ data.message = err; res.render('admin/error',data); }else{ data.message = '删除文件' + name + '成功!'; data.url = '/admin/file_upload/school/list'; res.render('admin/success',data); } }); }); /* * 文件上传--教师 * */ router.get('/file_upload/teacher',function (req, res) { data.message = '教师图片上传'; res.render('admin/fileupload/fileupload_index',data); }); /* * 教师图片上传保存 * */ router.post('/file_upload/teacher',function (req, res) { var form = new formidable.IncomingForm(); //创建上传表单 form.encoding = 'utf-8'; //设置编码 form.uploadDir = 'public/images/teacher/'; //设置上传目录 form.keepExtensions = true; //保留后缀 form.maxFieldsSize = 2 * 1024 * 1024; //限制文件大小,2m form.multiples = true; //允许多文件上传 form.parse(req, function (err, fields, files) { //错误, 字段域, 文件信息 if(err){ data.message = err; res.render('admin/error',data); return ; } /* * 保留文件原来名字 * */ if(files.files.length){ //如果同时上传多个文件,返回的是数组,对所有数组中的文件重命名 for(var i = 0; i < files.files.length;i++){ fs.renameSync(files.files[i].path, form.uploadDir + files.files[i].name); //重命名 } }else{ //对单一文件进行重命名 fs.renameSync(files.files.path, form.uploadDir + files.files.name); //重命名 } data.school_img_num = files.files.length || 1; }); form.on('end', function() { data.message = '上传成功,共上传了' + data.school_img_num + '张图片'; res.json(data); }); }); /* * 教师图片列表 * */ router.get('/file_upload/teacher/list',function (req, res) { var path = 'public/images/teacher'; var fileArray = fs.readdirSync(path); data.fileArray = []; data.page = Number(req.query.page) || 1; for(var i = (data.page - 1) * data.limit; i < (data.page) * data.limit; i++ ){ if(fileArray[i]){ data.fileArray.push(fileArray[i]); } } data.count = fileArray.length; data.forPage = 'file_upload/teacher/list'; calculatePages(data.count); res.render('admin/fileupload/fileupload_teacher_list',data); }); /* * 教师图片删除 * */ router.get('/file_upload/teacher/list/delete',function (req, res) { var name = req.query.filename, path = 'public/images/teacher'; fs.unlink(path + '/' + name, function (err) { if(err){ data.message = err; res.render('admin/error',data); }else{ data.message = '删除文件' + name + '成功!'; data.url = '/admin/file_upload/teacher/list'; res.render('admin/success',data); } }); }); /* * 透明导航列表 * */ router.get('/abroad_transparent',function (req, res) { data.page = Number(req.query.page) || 1; Abroad_transparent.find().count().then(function (count) { calculatePages(count); data.forPage = 'abroad_transparent'; Abroad_transparent.find().sort({Abroad_t_order: 1}).limit(data.limit).skip(data.skip).then(function (rs) { data.abroad_transparents = rs; res.render('admin/abroad/abroad_transparent',data); }); }); }); /* * 透明导航添加 * */ router.get('/abroad_transparent/add',function (req, res) { res.render('admin/abroad/abroad_transparent_add',data); }); /* * 透明导航添加保存 * */ router.post('/abroad_transparent/add',function (req, res) { var abroad_t_name = req.body.abroad_t_name, abroad_t_order = Number(req.body.abroad_t_order || 0), abroad_t_content = req.body.abroad_t_content; if(!abroad_t_name){ data.message = '透明导航标题名称不能为空!'; res.render('admin/error',data); return ; } new Abroad_transparent({ Abroad_t_name: abroad_t_name, Abroad_t_order: abroad_t_order, Abroad_t_content: abroad_t_content }).save().then(function () { data.message = '透明导航保存成功!'; data.url = '/admin/abroad_transparent'; res.render('admin/success',data); }) }); /* * 透明导航修改 * */ router.get('/abroad_transparent/edit',function (req, res) { var id = req.query.id; Abroad_transparent.findById(id).then(function (rs) { if(!rs){ data.message = '所有修改的标题不存在!'; req.render('admin/error',data); return ; } data.abroad_transparent = rs; res.render('admin/abroad/abroad_transparent_edit',data); }); }); /* * 透明导航修改保存 * */ router.post('/abroad_transparent/edit',function (req, res) { var id = req.query.id, abroad_t_name = req.body.abroad_t_name, abroad_t_order = Number(req.body.abroad_t_order || 0), abroad_t_content = req.body.abroad_t_content; if(!abroad_t_name){ data.message = '透明导航标题名称不能为空!'; res.render('admin/error',data); return ; } Abroad_transparent.findOne({_id:{$ne:id},Abroad_t_name:abroad_t_name}).then(function (rs) { if(rs){ data.message = '透明导航标题名称不能为重复!'; res.render('admin/error',data); return Promise.reject(); } Abroad_transparent.update({_id: id},{ Abroad_t_name: abroad_t_name, Abroad_t_order: abroad_t_order, Abroad_t_content: abroad_t_content }).then(function () { data.message = '透明导航修改成功!'; data.url = '/admin/abroad_transparent'; res.render('admin/success',data); }); }); }); /* * 透明导航删除 * */ router.get('/abroad_transparent/delete',function (req, res) { var id = req.query.id; Abroad_transparent.findById(id).then(function (rs) { if(!rs){ data.message = '要删除的标题不存在!'; res.render('admin/error',data); return ; } Abroad_transparent.remove({_id:id}).then(function () { data.message = '透明导航删除成功!'; data.url = '/admin/abroad_transparent'; res.render('admin/success',data); }); }); }); /* * 透明标题内容列表 * */ router.get('/abroad_transparent/content',function (req, res) { data.page = Number(req.query.page) || 1; Abroad_t_title.find().count().then(function (count) { calculatePages(count); data.forPage = 'abroad_transparent/content'; Abroad_t_title.find().sort({abroad_transparent: 1,Abroad_t_title_order: 1}).limit(data.limit).skip(data.skip).populate('abroad_transparent').then(function (rs) { data.abroad_t_titles = rs; res.render('admin/abroad/abroad_transparent_title',data); }); }); }); /* * 透明标题内容添加 * */ router.get('/abroad_transparent/content/add',function (req, res) { Abroad_transparent.find().sort({Abroad_t_order: 1}).then(function (rs) { data.abroad_transparents = rs; res.render('admin/abroad/abroad_transparent_title_add',data); }); }); /* * 透明标题内容添加保存 * */ router.post('/abroad_transparent/content/add',function (req, res) { var abroad_transparent = req.body.abroad_transparent, abroad_t_title = req.body.abroad_t_title, abroad_t_title_order = Number(req.body.abroad_t_title_order || 0), abroad_t_title_content = req.body.abroad_t_title_content; if(!abroad_transparent){ data.message = '导航标题不能为空!'; res.render('admin/error',data); return ; } if(!abroad_t_title){ data.message = '内容标题名称不能为空!'; res.render('admin/error',data); return ; } new Abroad_t_title({ abroad_transparent: abroad_transparent, Abroad_t_title: abroad_t_title, Abroad_t_title_order: abroad_t_title_order, Abroad_t_title_content: abroad_t_title_content }).save().then(function () { data.message = '标题内容添加成功!'; data.url = '/admin/abroad_transparent/content'; res.render('admin/success',data); }) }); /* * 透明标题内容修改 * */ router.get('/abroad_transparent/content/edit',function (req, res) { var id = req.query.id; Abroad_t_title.findById(id).populate('abroad_transparent').then(function (rs) { if(!rs){ data.message = '要修改的内容标题名称不存在!'; res.render('admin/error',data); return ; } data.abroad_t_title = rs; Abroad_transparent.find().sort({Abroad_t_order: 1}).then(function (rs) { data.abroad_transparents = rs; res.render('admin/abroad/abroad_transparent_title_edit',data); }); }); }); /* * 透明标题内容修改保存 * */ router.post('/abroad_transparent/content/edit',function (req, res) { var id = req.query.id, abroad_transparent = req.body.abroad_transparent, abroad_t_title = req.body.abroad_t_title, abroad_t_title_order = Number(req.body.abroad_t_title_order || 0), abroad_t_title_content = req.body.abroad_t_title_content; if(!abroad_transparent || !abroad_t_title){ data.message = '标题或者内容标题名称不能为空!'; res.render('admin/error',data); return ; } Abroad_t_title.findOne({ abroad_transparent: abroad_transparent, Abroad_t_title: abroad_t_title, _id: {$ne: id} }).then(function (rs) { if(rs){ data.message = '内容标题名称不能重复!'; res.render('admin/error',data); return Promise.reject(); } Abroad_t_title.update({ _id: id },{ Abroad_transparent: abroad_transparent, Abroad_t_title: abroad_t_title, Abroad_t_title_order: abroad_t_title_order, Abroad_t_title_content: abroad_t_title_content }).then(function () { data.message = '标题内容修改成功!'; data.url = '/admin/abroad_transparent/content'; res.render('admin/success',data); }); }); }); /* * 透明标题删除 * */ router.get('/abroad_transparent/content/delete',function (req, res) { var id = req.query.id; Abroad_t_title.findById(id).then(function (rs) { if(!rs){ data.message = '要删除的内容标题不存在!'; res.render('admin/error',data); return ; } Abroad_t_title.remove({_id:id}).then(function () { data.message = '内容标题删除成功!'; data.url = '/admin/abroad_transparent/content'; res.render('admin/success',data); }); }); }); /* * 获取留言列表 * */ router.get('/leave_message',function (req, res) { data.page = Number(req.query.page) || 1; //获取数据库中的条数 Leave_message.count().then(function (count) { calculatePages(count); Leave_message.find().sort({_id:-1}).limit(data.limit).skip(data.skip).then(function (rs) { data.forPage = 'leave_message'; data.leave_messages = rs; res.render('admin/leave_message/leave_message_index', data); }); }); }); /* * 查看留言 * */ router.get('/leave_message/check',function (req, res) { var id = req.query.id; Leave_message.findById(id).then(function (rs) { if(!rs){ data.message = '留言不存在!'; res.render('admin/error',data); return ; } data.leave_message = rs; res.render('admin/leave_message/leave_message_check',data); }) }); /* * 删除留言 * */ router.get('/leave_message/delete',function (req, res) { var id = req.query.id; Leave_message.findById(id).then(function (rs) { if(!rs){ data.message = '所要删除的留言不存在!'; res.render('admin/error',data); return ; } Leave_message.remove({ _id: id }).then(function () { data.message = '留言删除成功!'; data.url = '/admin/leave_message'; res.render('admin/success',data); }) }); }); //返回出去给app.js module.exports = router;<file_sep>/** * Created by SHINING on 2017/3/28. */ var mongoose = require('mongoose'); var abroad_transparentsSchema = require('../schemas/abroad_transparents'); module.exports = mongoose.model('Abroad_transparent',abroad_transparentsSchema);<file_sep>/** * Created by SHINING on 2017/3/28. */ $(function () { /* * 侧栏免费通话 * */ var $tel_logo = $('.tel_logo'), $tel_call = $('.tel_call'); $tel_logo.on('click',function () { $tel_call.show(); $tel_logo.hide(); }); $tel_call.find('em').on('click',function () { $tel_logo.show(); $tel_call.hide(); }); /* * 导航展示宽度修改 * */ var $nav_head = $('.nav_head'), width = $('.navigation').css('width'); $nav_head.find('.nav_content').css('width',width); /* * 文章统计 * */ var $article_content_a = $('#article_content a'), $article_detail = $('.article_detail'), $recommend_articles_a = $('.recommend_articles a'); function articleCount(rs) { $.ajax({ type: 'post', url: '/api/Abroad_article', data: { article: rs.data('id') }, dataType: 'json', success: function () { } }); } $article_content_a.on('click',function () { var $this = $(this); articleCount($this); }); $article_detail.on('click',function () { var $this = $(this); articleCount($this); }); $recommend_articles_a.on('click',function () { var $this = $(this); articleCount($this); }); });<file_sep>/** * Created by SHINING on 2017/4/16. */ $(function () { //九宫格显示 var $night_part_li = $('.night_part ul li'), time1; $night_part_li.mouseenter(function () { var $this = $(this); time1 = setTimeout(function () { $this.find('.night_hide').css('display','block'); $this.find('h3').css('display','none'); },150); }); $night_part_li.mouseleave(function () { var $this = $(this).find('.night_hide'); clearTimeout(time1); $this.fadeOut(); $(this).find('h3').css('display','block'); }); //热门专业选择 var $major_left = $('.major_left ul li'), $major_part = $('.major_part'); $major_left.on('click',function () { var index = $major_left.index(this), temp = $major_part.eq(index); $major_left.css('width','170px'); $major_left.css('background-color','#6699CC'); $(this).animate({width:'220px'},100); $(this).css('background-color','#996666'); $major_part.css('display','none'); temp.fadeIn(); }); //院校推荐 var $major_school = $('.major_school'); $major_school.mouseenter(function () { $(this).stop(); $(this).animate({height:'50%'},500); }); $major_school.mouseleave(function () { $(this).stop(); $(this).animate({height:'40px'},500); }); });<file_sep>/** * Created by SHINING on 2017/3/28. */ //用户数据库 var mongoose = require('mongoose'); //分类的表结构 module.exports = new mongoose.Schema({ //考试名称 Test_name:String, //考试顺序 Test_order:{ type: Number, default: 0 }, Test_url:{ type: String, default: '/' }, Test_count:{ type:Number, default: 0 } });<file_sep>/** * Created by SHINING on 2017/3/20. */ /* * 登录模块的js代码 * */ $(function () { var $login = $('#login'), $loginBox = $('#loginBox'), $register = $('#register'), $username = $('#username'), $logout = $('#logout'), $registerBox = $('#registerBox'), $inputEmail = $('#inputEmail'), $inputEmail2 = $('#inputEmail2'), $phone = $('#registerBox .phone'), $password1 = $('#password'), $password2 = <PASSWORD>'), $password = $('#registerBox .password'), $repassword2 = $('#repassword2'), $repassword = $('#registerBox .repassword'), $tips = $('#registerBox .tips a'), $tips2 = $('#loginBox .tips2'), news = '', //用户名 0代表success 1代表出错 2代表默认 news2 = '', //密码 news3 = ''; //二次密码 //打开登录面板 $login.on('click',function () { //alert('a'); $loginBox.show(); $registerBox.hide(); }); //打开注册面板 $register.on('click',function () { $registerBox.show(); $loginBox.hide(); }); //关闭面板 $loginBox.find('span').on('click',function () { $loginBox.hide(); $inputEmail.val(''); $password1.val(''); $tips2.html(''); }); $registerBox.find('span').on('click',function () { $registerBox.hide(); $inputEmail2.val(''); $password2.val(''); $repassword2.val(''); $tips.html(''); $phone.html('请填写手机号码或者邮箱'); $phone.css('color','#999'); $password.html('密码<PASSWORD>,区分大小写'); $password.css('color','#999'); $repassword.html('请再次填写密码'); $repassword.css('color','#999'); }); //新用户注册和已有帐号 $loginBox.find('.zhuce li a').on('click',function () { $loginBox.hide(); $registerBox.show(); }); $registerBox.find('.denglu li a').on('click',function () { $registerBox.hide(); $loginBox.show(); }); //用户名检测函数 function nameCheck(value) { var phone = /^1\d{10}$/, eMail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, $value = value; $.ajax({ type: 'post', url: '/api/user/register/namecheck', data: { username: $value, news: function () { if($value === ''){ news = '2'; return '2'; }else{ if(phone.test($value) || eMail.test($value)){ news = '0'; return '0'; }else{ news = '1'; return '1'; } } } }, dataType: 'json', success: function (data) { if(data.code === 1 || data.code === 2){ $phone.html(data.message); $phone.css('color','#a94442'); }else if(data.code === 3){ $phone.html(data.message); $phone.css('color','#3c763d'); }else { $phone.html(data.message); $phone.css('color','#999'); } } }); } //密码检测函数 function passwordCheck(value) { var $value = value; $.ajax({ type: 'post', url: '/api/user/register/passwordcheck', data:{ password: $value, news2: function () { if(!$value){ news2 = '2'; return '2'; }else{ if($value.length >= 6 && $value.length<=16){ news2 = '0'; return '0'; }else{ news2 = '1'; return '1'; } } } }, dataType: 'json', success: function (data) { if(data.code === 5){ $password.html(data.message); $password.css('color','#<PASSWORD>'); }else if(data.code === 6){ $password.html(data.message); $password.css('color','#<PASSWORD>'); }else { $password.html(data.message); $password.css('color','#999'); } } }); } //密码二次检测函数 function repasswordCheck(value) { var $value = value; $.ajax({ type: 'post', url: '/api/user/register/repasswordcheck', data: { repassword: $value, news3: function () { if(!$value){ news3 = '2'; return '2'; }else{ if( $password2.val() === $value){ news3 = '0'; return '0'; }else{ news3 = '1'; return '1'; } } } }, dataType: 'json', success: function (data) { if(data.code === 8){ $repassword.html(data.message); $repassword.css('color','#<PASSWORD>'); }else if(data.code === 9){ $repassword.html(data.message); $repassword.css('color','#<PASSWORD>'); }else { $repassword.html(data.message); $repassword.css('color','#999'); } } }); } //实时检测用户名的正确性 $inputEmail2.on('input propertychange',function () { nameCheck($(this).val()); }); //实时检测密码是否正确 $password2.on('input propertychange',function (){ passwordCheck($(this).val()); }); //实时检测二次密码是否一致 $repassword2.on('input propertychange',function (){ repasswordCheck($(this).val()); }); //注册 $registerBox.find('button').on('click',function () { if(!$inputEmail2.val()){ $phone.html('帐号不能为空!'); $phone.css('color','#a94442'); } if(!$password2.val()){ $password.html('密码不能为空!'); $password.css('color','#<PASSWORD>'); } if(!$repassword2.val()){ $repassword.html('二次密码不能为空!'); $repassword.css('color','#<PASSWORD>'); } /* * 当没有错误的时候才发送ajax请求 * */ if(news === '0' && news2 === '0' && news3 === '0'){ $.ajax({ type: 'post', url: '/api/user/register', data: { username: $registerBox.find('[name = "username"]').val(), password: $registerBox.find('[name = "password"]').val(), repassword: $registerBox.find('[name = "repassword"]').val() }, dataType: 'json', success: function (data) { var time = 3, stop; $tips.html(data.message + time + '秒后跳转登录页面'); stop = setInterval(function () { time--; $tips.html(data.message + time + '秒后跳转登录页面'); if(time === 0){ clearInterval(stop); $registerBox.hide(); $loginBox.show(); } },1000); $tips.on('click',function () { clearInterval(stop); $registerBox.hide(); $loginBox.show(); }); } }); } }); $inputEmail.on('input propertychange',function () { if(!$(this).val() && !$password1.val()){ $tips2.html(''); $tips2.css('color','#a94442'); } }); $password1.on('input propertychange',function (){ if(!$(this).val() && !$inputEmail.val()){ $tips2.html(''); $tips2.css('color','#a94442'); } }); //登录模块 $loginBox.find('button').on('click',function () { //通过ajax提交请求 $.ajax({ type: 'post', url: '/api/user/login', data:{ username: $loginBox.find('[name = "username"]').val(), password: $loginBox.find('[name = "password"]').val() }, dataType: 'json', success: function (data) { if(data.code === 11){ $tips2.html('用户名或者密码不能为空!'); }else if(data.code === 12){ $tips2.html('用户名不存在!'); }else if(data.code === 13){ $tips2.html('密码不正确!'); }else{ $tips2.html('登录成功!'); $tips2.css('color','#3c763d'); window.location.reload(); //重载页面 } } }); }); //退出 $logout.on('click',function () { $.ajax({ url: '/api/user/logout', success: function (data) { if(!data.code){ window.location.reload(); } } }); }); /* * 留言提交 * */ var $submit = $('#submit'), $tel = $('#tel'), $name = $('#name'), $word = $('#word'); $submit.on('click',function () { $.ajax({ type: 'post', url: '/api/leave_message', data: { word: $word.val(), name: $name.val(), tel: $tel.val() }, dataType: 'json', success: function (res) { alert(res.leave_message); $tel.val(''); $name.val(''); $word.val(''); } }); }); });<file_sep>/** * Created by SHINING on 2017/3/19. */ /* * 用户信息数据库 * */ //用户数据库 var mongoose = require('mongoose'); //用户的表结构 module.exports = new mongoose.Schema({ //用户名 username:String, //密码 password:String, //是否是管理员 isAdmin:{ type: Boolean, default: false } //管理员最好不要记录在cookies中,否则以后可能会有漏洞 }); <file_sep>/** * Created by SHINING on 2017/3/19. */ var mongoose = require('mongoose'); var teachersSchema = require('../schemas/teachers'); module.exports = mongoose.model('Teacher',teachersSchema);<file_sep>/** * Created by SHINING on 2017/3/28. */ $(function () { /* * 侧栏免费通话 * */ var $tel_logo = $('.tel_logo'), $tel_call = $('.tel_call'); $tel_logo.on('click',function () { $tel_call.show(); $tel_logo.hide(); }); $tel_call.find('em').on('click',function () { $tel_logo.show(); $tel_call.hide(); }); /* * 导航展示 * */ var $nav_head = $('.nav_head'), width = $('.navigation').css('width'); width = parseInt(width); $nav_head.find('.nav_content').css('width',width + 'px'); /* * 手动图片轮转 * */ var $bg_btn = $('.bg_btn li'), $bg_part = $('.bg_part'), $big = $('.big'); $bg_btn.on('mouseover',function () { var index = $bg_btn.index(this), temp1 = $bg_part.children().eq(index).find('a'), temp2 = $big.children().eq(index); $bg_btn.css('background','#fff'); $(this).css('background','#337ab7'); if(temp1.css('display') === 'block'){ return ; } //图片全部隐藏 $big.find('div').animate({opacity: 0.9},100); $bg_part.find('a').animate({opacity: 0.9},100); $big.find('div').css('display','none'); $bg_part.find('a').css('display','none'); //对应图片显示 temp2.animate({opacity:1}); temp1.animate({opacity:1}); temp1.css('display','block'); temp2.css('display','block'); picNum = index; }); /* * 自动图片轮转 * */ var picNum = 0, $bgBtn = $('.bg_btn'); picNum = picGo(picNum); var time1 = setInterval(function () { picNum = picGo(picNum); },4000); function picGo(picNum) { var i = picNum; if(i > 3){ i = 0; $bgBtn.children().eq(0).triggerHandler('mouseover'); i++; }else{ $bgBtn.children().eq(picNum).triggerHandler('mouseover'); i++; } return i; } /* * 留学攻略、咨询 * */ var $school_news_title = $('.school_news_title'), $school_news_move = $('.school_news_move'); $school_news_title.find('a').on('mouseover',function () { var index = $school_news_title.find('a').index(this), temp = $school_news_move.children().eq(index); $school_news_title.find('a').css('color','#818181'); $(this).css('color','#337ab7'); $school_news_move.find('div').css('display','none'); temp.css('display','block'); }); /* * 各留学的mouseover事件 * */ var $study_abroad_nav_li = $('.study_abroad_nav ul li'); $study_abroad_nav_li.mouseenter(function () { var $parent = $(this).closest('.study_abroad_nav'), $parent2 = $(this).closest('.study_abroad_content').find('.study_abroad_num'), backColor = $(this).css('background-color'), index = $parent.find('li').index(this), temp = $parent2.eq(index); if(backColor === 'rgb(255, 255, 255)' || backColor === '#fff'){ }else{ $parent.find('li').css('background-color',backColor); $parent.find('a').css('color','#fff'); $(this).css('background-color','#fff'); $(this).find('a').css('color',backColor); $parent2.animate({opacity: 0},50); $parent2.css('display','none'); temp.css('display','block'); temp.animate({opacity: 1},50); } }); /* * 高分案例mouseover事件 * */ var $case_title_a = $('.case_title a'); $case_title_a.on('mouseover',function () { var $parent = $(this).closest('.case_title').find('a'), index = $parent.index(this), $parent2 = $(this).closest('.study_abroad_case').find('.case_content'), temp = $parent2.eq(index); if(temp.css('display') === 'block'){ }else{ $parent.css('background-color','#fff'); $(this).css('background-color','#337ab7'); $parent2.animate({opacity: 0},100); $parent2.css('display','none'); temp.css('display','block'); temp.animate({opacity: 1},100); } }); /* * 案例下的mouseover事件 * */ var $case_content_p = $('.case_content p'); $case_content_p.on('mouseover',function () { var $parent = $(this).closest('.case_content'), index = $parent.find('p').index(this), $parent2 = $parent.find('ul'), temp = $parent2.eq(index); if(temp.css('display') === 'block'){ }else{ $parent2.animate({opacity: 0},50); $parent2.css('display','none'); temp.css('display','block'); temp.animate({opacity: 1},300); } }); /* * 能力培训mouseover事件 * */ var $training_list_li = $('.training_list li'), $training_list_a = $('.training_list li a'), $training_block = $('.training_block'); $training_list_li.mouseenter(function () { var index = $training_list_li.index(this), temp = $training_block.eq(index); $training_block.css('display','none'); $training_list_a.css('color','#fff'); $(this).find('a').css('color','#333'); temp.css('display','block'); }); });<file_sep>/** * Created by SHINING on 2017/3/28. */ var mongoose = require('mongoose'); var abroad_navsSchema = require('../schemas/abroad_navs'); module.exports = mongoose.model('Abroad_nav',abroad_navsSchema);<file_sep>/** * Created by SHINING on 2017/3/28. */ //用户数据库 var mongoose = require('mongoose'); //导航内容的表结构 module.exports = new mongoose.Schema({ //关联字段 abroad:{ //类型 type: mongoose.Schema.Types.ObjectId, //引用 ref: 'Abroad' }, abroad_nav:{ type: mongoose.Schema.Types.ObjectId, ref: 'Abroad_nav' }, //文章标题名称 Abroad_content_name: String, Abroad_content_order: { type: Number, default: 10 }, Abroad_content_url: { type: String, default: '/' }, Abroad_content_markdown: String, Abroad_content_hot: { type: Number, default: 0 } });<file_sep>/** * Created by SHINING on 2017/3/28. */ //用户数据库 var mongoose = require('mongoose'); //导航内容的表结构 module.exports = new mongoose.Schema({ //关联字段 navigation:{ //类型 type: mongoose.Schema.Types.ObjectId, //引用 ref: 'Navigation' }, //导航内容标题 Nav_title: String, Nav_title_order: { type: Number, default: 0 }, Nav_title_count:{ type: Number, default: 0 } });<file_sep>/** * Created by SHINING on 2017/3/28. */ //用户数据库 var mongoose = require('mongoose'); //分类的表结构 module.exports = new mongoose.Schema({ //地区名 Area_name:String, //地区顺序 Area_order:{ type: Number, default: 0 }, //地区学校数 Area_count:{ type:Number, default:0 } });<file_sep>/** * Created by SHINING on 2017/3/19. */ /* * 前台路由 * */ var express = require('express'), router = express.Router(), Navigation = require('../models/Navigation'), Nav_title = require('../models/Nav_title'), Nav_content = require('../models/Nav_content'), Area = require('../models/Area'), School = require('../models/School'), Abroad = require('../models/Abroad'), Abroad_nav = require('../models/Abroad_nav'), Abroad_content = require('../models/Abroad_content'), Abroad_enroll = require('../models/Abroad_enroll'), Test = require('../models/Test'), Training = require('../models/Training'), Training_content = require('../models/Training_content'), Teacher = require('../models/Teacher'), markdown = require('markdown').markdown, Abroad_transparent = require('../models/Abroad_transparent'), Abroad_t_title = require('../models/Abroad_t_title'), fs = require('fs'), data; /* * 处理分页的函数 * */ function setArrFont(sum) { var arr = []; for(var i = 0;i<sum;i++){ arr[i] = i+1; } return arr; } function setArrEnd(sum) { var arr = [], a = sum; for(var i = 0;i<5;i++){ arr[i] = a; a--; } return arr.reverse(); } function calculatePages(count) { data.count = count; //计算总页数 data.pages = Math.ceil(count / data.limit); data.pagesFont = setArrFont(data.pages); data.pagesEnd = setArrEnd(data.pages); //取值不能超过pages data.page = Math.min(data.page, data.pages); //取值不能小于1 data.page = Math.max(data.page, 1); //跳过的条数 data.skip = (data.page - 1) * data.limit; } /* * 处理通用数据,用于前台展示的数据 * */ router.use(function (req, res, next) { data = { userInfo: req.userInfo, limit: 20 //每页显示的数量 }; Navigation.find().sort({Nav_order:1}).then(function (navigations) { data.navigations =navigations; }).then(function () { return Nav_title.find().populate('navigation').sort({navigation:1,Nav_title_order:1}); }).then(function (rs) { data.nav_titles =rs; }).then(function () { return Nav_content.find().populate(['navigation','nav_title']).sort({navigation:1,nav_title:1,Nav_content_order:1}); }).then(function (rs) { data.nav_contents = rs; }).then(function () { return Abroad.find().sort({_id:-1}); }).then(function (rs) { data.abroads = rs; }).then(function () { return Abroad_nav.find().populate('abroad').sort({abroad:-1,Abroad_nav_order:1}); }).then(function (rs) { data.abroad_navs = rs; }).then(function () { return Abroad_content.find({Abroad_content_order:{$lt:8}}).populate(['abroad','abroad_nav']).sort({abroad:-1,abroad_nav:-1,Abroad_content_order:1}); }).then(function (rs) { data.abroad_contents = rs; }).then(function () { return Abroad_enroll.find({Abroad_enroll_order:{$lt:5}}).populate(['abroad','school','test1','test2']).sort({abroad:1,_id:-1}); }).then(function (rs) { data.abroad_enrolls =rs; }).then(function () { return Test.find().sort({Test_order:1}); }).then(function (rs) { data.tests = rs; }).then(function () { return Training.find().populate('test').sort({test:1,Training_order:1}); }).then(function (rs) { data.trainings = rs; }).then(function () { return Training_content.find({Training_content_order:{$lt:4}}).populate(['test','training']).sort({test:1,training:1,Training_content_order:1}); }).then(function (rs) { data.training_contents = rs; }).then(function () { return Teacher.find({Teacher_order: {$lt: 6}}).sort({Teacher_order: 1}); }).then(function (rs) { data.teachers = rs; next(); }); }); /* * 首页 * */ router.get('/',function (req, res) { School.find().sort({School_love: -1}).limit(6).then(function (rs) { data.hot_schools = rs; Abroad_transparent.find().sort({Abroad_t_order: 1}).then(function (rs) { data.abroad_transparents = rs; Abroad_t_title.find().sort({Abroad_t_title_order: 1}).populate('abroad_transparent').then(function (rs) { data.abroad_t_titles = rs; res.render('main/index',data); }); }); }); }); /* * 首页学校搜索 * */ router.post('/',function (req, res) { var school_name = req.body.school_name || ''; data.page = Number(req.query.page || 1); if(school_name){ School.find({School_zn:school_name}).count().then(function (count) { data.count = count; //计算总页数 data.pages = Math.ceil(count / data.limit); data.pagesFont = setArrFont(data.pages); data.pagesEnd = setArrEnd(data.pages); //取值不能超过pages data.page = Math.min(data.page, data.pages); //取值不能小于1 data.page = Math.max(data.page, 1); data.skip = (data.page - 1) * data.limit; School.find({School_zn:school_name}).populate('area').limit(data.limit).skip(data.skip).then(function (rs) { data.schools = rs; res.render('main/school_index',data); }); }); }else{ School.find().count().then(function (count) { data.count = count; //计算总页数 data.pages = Math.ceil(count / data.limit); data.pagesFont = setArrFont(data.pages); data.pagesEnd = setArrEnd(data.pages); //取值不能超过pages data.page = Math.min(data.page, data.pages); //取值不能小于1 data.page = Math.max(data.page, 1); data.skip = (data.page - 1) * data.limit; School.find().populate('area').limit(data.limit).skip(data.skip).then(function (rs) { data.schools = rs; res.render('main/school_index',data); }); }); } }); /* * 全部学校 * */ router.get('/school',function (req, res) { var area = req.query.school_area || '', call = Number(req.query.call) || 0, call2 = Number(req.query.call2) || 0, rank = Number(req.query.school_rank) || 0, a = 0, b = 0; data.page = Number(req.query.page || 1); data.area = area; data.call = call; data.call2 = call2; data.rank = rank; switch(rank){ case 0: break; case 1: a = 1;b = 10; break; case 2: a = 10;b = 20; break; case 3: a = 20;b = 50; break; case 4: a = 50;b = 100; break; case 5: a = 100;b = 150; break; case 6: a = 150;b = 9999; break; } if(area && !rank){ //当有区域没有排名的时候 Area.findOne({Area_name:area}).then(function (rs) { School.find({area:rs._id}).count().then(function (count) { calculatePages(count); School.find({area:rs._id}).populate('area').sort({School_rank:1}).limit(data.limit).skip(data.skip).then(function (rs) { data.schools = rs; res.render('main/school_index',data); }); }); }); }else if(area && rank){ //当有区域有排名的时候 Area.findOne({Area_name:area}).then(function (rs) { School.find({area:rs._id,School_rank:{$gte:a,$lte:b}}).count().then(function (count) { calculatePages(count); School.find({area:rs._id,School_rank:{$gte:a,$lte:b}}).populate('area').sort({School_rank:1}).limit(data.limit).skip(data.skip).then(function (rs) { data.schools = rs; res.render('main/school_index',data); }); }); }); }else if(!area && rank){ //当没区域有排名的时候 School.find({School_rank:{$gte:a,$lte:b}}).count().then(function (count) { calculatePages(count); School.find({School_rank:{$gte:a,$lte:b}}).populate('area').sort({School_rank:1}).limit(data.limit).skip(data.skip).then(function (rs) { data.schools = rs; res.render('main/school_index',data); }); }); }else{ School.find().count().then(function (count) { calculatePages(count); School.find().populate('area').limit(data.limit).skip(data.skip).then(function (rs) { data.schools = rs; res.render('main/school_index',data); }); }); } }); /* * 学校页面的搜索 * */ router.post('/school',function (req, res) { var school_name = req.body.school_name || ''; data.page = Number(req.query.page || 1); if(school_name){ School.find({School_zn:school_name}).count().then(function (count) { calculatePages(count); School.find({School_zn:school_name}).populate('area').limit(data.limit).skip(data.skip).then(function (rs) { data.schools = rs; res.render('main/school_index',data); }); }); }else{ School.find().count().then(function (count) { calculatePages(count); School.find().populate('area').limit(data.limit).skip(data.skip).then(function (rs) { data.schools = rs; res.render('main/school_index',data); }); }); } }); /* * 首页本科 * */ router.get('/undergraduate',function (req, res) { res.render('main/undergraduate_index',data); }); /* * 文章首页 * */ router.get('/Abroad_article',function (req, res) { var article_rank = req.query.article_rank, article_type = req.query.article_type, article_abroad = req.query.article_abroad; data.page = Number(req.query.page || 1); data.article_rank = article_rank; data.article_type = article_type; data.article_abroad = article_abroad; var temp = [], articles = []; data.articles = []; function articleAbroad(rs) { var arr = []; for(var content in rs){ if(rs[content].abroad.Abroad_name === article_abroad) { arr.push(rs[content]); } } return arr.length?arr:rs; } function articleType(rs) { var arr = []; for(var content in rs){ if(rs[content].abroad_nav.Abroad_nav_name === article_type) { arr.push(rs[content]); } } return arr.length?arr:rs; } function getLimit(articles) { for(var i = (data.page - 1) * data.limit; i < (data.page) * data.limit; i++ ){ if(articles[i]){ data.articles.push(articles[i]); } } } if(article_rank){ if(article_rank === '最新上传'){ Abroad_content.find().populate(['abroad','abroad_nav']).sort({_id: -1}).then(function (rs) { temp = articleType(rs); articles = articleAbroad(temp); data.length = articles.length; calculatePages(articles.length); getLimit(articles); res.render('main/article_list_layout',data); }); }else { Abroad_content.find().populate(['abroad','abroad_nav']).sort({Abroad_content_hot: -1}).then(function (rs) { temp = articleType(rs); articles = articleAbroad(temp); data.length = articles.length; calculatePages(articles.length); getLimit(articles); res.render('main/article_list_layout',data); }); } }else { Abroad_content.find().populate(['abroad','abroad_nav']).sort({_id: -1}).then(function (rs) { temp = articleType(rs); articles = articleAbroad(temp); data.length = articles.length; calculatePages(articles.length); getLimit(articles); res.render('main/article_list_layout',data); }); } }); /* * 文章阅读页面 * */ router.get('/Abroad_article/content',function (req, res) { var id = req.query.id; Abroad_content.findById(id).populate(['abroad','abroad_nav']).then(function (rs) { data.abroad_content = rs; var hot = Number(rs.Abroad_content_hot) + 1; var article_markdown = rs.Abroad_content_markdown || ''; Abroad_content.update({ _id: id },{ Abroad_content_hot: hot }).then(function () { fs.open('views/main/markdown.html','w',function (err, fd) { if(article_markdown){ var writeBuffer = new Buffer(markdown.toHTML(article_markdown)); }else { var writeBuffer = new Buffer('<p>该文章内容为空!</p>'); } var bufferPosition = 0, bufferLength = writeBuffer.length, filePosition = null; fs.writeSync(fd,writeBuffer,bufferPosition,bufferLength,filePosition); Abroad_content.find().populate(['abroad','abroad_nav']).sort({Abroad_content_hot: -1}).limit(10).then(function (rs) { data.abroad_contents = rs; res.render('main/article_content',data); }); }); }); }); }); /* * 总文章页面 * */ router.get('/articles',function (req, res) { var id = req.query.id, content; Abroad_transparent.findById(id).then(function (rs) { if(rs){ data.article_name = rs.Abroad_t_name; data.article_hot = Number(rs.Abroad_t_hot) + 1; content = rs.Abroad_t_content; data.article_all = rs; Abroad_transparent.update({ _id: id },{ Abroad_t_hot: data.article_hot }).then(function () { articleShow(); }); } Abroad_t_title.findById(id).then(function (rs) { if(rs){ data.article_name = rs.Abroad_t_title; data.article_hot = Number(rs.Abroad_t_title_hot) + 1; content = rs.Abroad_t_title_content; data.article_all = rs; Abroad_t_title.update({ _id: id },{ Abroad_t_title_hot: data.article_hot }).then(function () { articleShow(); }); } Nav_content.findById(id).then(function (rs) { if(rs){ data.article_name = rs.Nav_content_name; data.article_hot = Number(rs.Nav_content_hot) + 1; content = rs.Nav_content_url; data.article_all = rs; Nav_content.update({ _id: id },{ Nav_content_hot: data.article_hot }).then(function () { articleShow(); }); } }); }); }); function articleShow () { fs.open('views/main/markdown_articles.html','w',function (err, fd) { if(content){ var writeBuffer = new Buffer(markdown.toHTML(content)); }else { var writeBuffer = new Buffer('<p>该文章内容为空!</p>'); } var bufferPosition = 0, bufferLength = writeBuffer.length, filePosition = null; fs.writeSync(fd,writeBuffer,bufferPosition,bufferLength,filePosition); Abroad_content.find().populate(['abroad','abroad_nav']).sort({Abroad_content_hot: -1}).limit(10).then(function (rs) { data.abroad_contents = rs; res.render('main/articles',data); }); }); } }); //返回出去给app.js module.exports = router;<file_sep>英国留学网站 =========== *********** ### 网址:[海外留学官网](http://172.16.17.32)                                                           ### 管理员帐号和密码均为:admin *********** 该网站是本人的毕业设计,具体需求是提供一个良好的交互界面,展示该公司的英国本科、研究生、中学生留学服务。网站分为前台和后台,前台页面是一列居中布局,行为由jQuery完成;后台基于Node.js,后台页面利用bootstrap组件样式实现。 #### 前台页面利用swig模版引擎,从后台数据库读取数据,渲染页面,前台首页index的板块框架从上到下每一部分分别是: 1. 登录条(包含logo和注册登录操作) 2. 导航条 3. 图片轮转 4. 学校板块 5. 留学流程板块 6. 英国本科留学板块 7. 研究生留学板块 8. 中学留学板块 9. 能力培训板块 10. 教师阵容板块 11. 联系方式、地址 12. 底部链接、版权 #### 后台语言为Node.js,利用Express框架和其他一些模块: * body-parser:处理浏览器post提交的数据 * cookies:保存浏览器登录信息 * mongoose:用来管理mongodb的数据 * swig:模版引擎,用于解决前后端分离 * formidable:实现文件上传 #### 文件夹以及文件解释 * app.js为启动文件 * view存放前后台的前端页面 * schemas存放数据结构 * router存放前后端路由、ajax路由 * public存放css样式、js、字体fonts和图片images <file_sep>{% extends '../layout.html' %} {% block main %} <ol class="breadcrumb"> <li><a href="/" target="_blank">官网首页</a></li> <li><span>学校列表</span></li> </ol> <h3 style="font-size: 24px;font-weight: bold; line-height: 50px">学校列表</h3> <table class="table table-hover table-striped"> <tr> <th>学校中文名称</th> <th>学校英文名称</th> <th>学校地区</th> <th>学校排名</th> <th>录取人数</th> <th>学校url</th> <th>学校图片名称</th> <th>操作</th> </tr> {% for school in schools %} <tr> <td>{{school.School_zn}}</td> <td>{{school.School_en}}</td> <td>{{school.area.Area_name}}</td> <td>{{school.School_rank}}</td> <td>{{school.School_enroll}}</td> <td>{{school.School_url}}</td> <td>{{school.School_img}}</td> <td> <a href="/admin/school/edit?id={{school._id.toString()}}">修改</a> | <a href="/admin/school/delete?id={{school._id.toString()}}">删除</a> </td> </tr> {% endfor %} </table> {%include '../page.html'%} {% endblock %}<file_sep>/** * Created by SHINING on 2017/3/28. */ //用户数据库 var mongoose = require('mongoose'); //导航内容的表结构 module.exports = new mongoose.Schema({ //关联字段 test:{ //类型 type: mongoose.Schema.Types.ObjectId, //引用 ref: 'Test' }, training:{ type: mongoose.Schema.Types.ObjectId, ref: 'Training' }, //文章标题名称 Training_content_name: String, Training_content_order: { type: Number, default: 10 }, Training_content_url: { type: String, default: '/' }, Training_content_markdown: String, Training_content_hot: { type: Number, default: 0 } });<file_sep>/** * Created by SHINING on 2017/3/19. */ //加载express模块 var express = require('express'), //加载模版处理模块 swig = require('swig'), //加载数据库模块 mongoose = require('mongoose'), //加载body-parser,用来处理post提交过来的数据 bodyParser = require('body-parser'), //加载cookies模块 Cookies = require('cookies'), //创建app应用 => NodeJs Http.createServer(); app = express(); /* * 定义当前应用所使用的模版引擎 * 第一个参数:模版引擎的名称,同时也是模版文件的后缀;第二个参数表示用于解释处理模版内容的解释方法 * */ app.engine('html',swig.renderFile); //设置模版文件存放的目录,第一个参数必须是views,第二个参数是目录 app.set('views','./views'); //注册所使用的模版引擎,第一个参数必须是 view engine,第二个参数和app.engine这个方法中定义的模版引擎的名称(第一个参数)是一致的 app.set('view engine','html'); /* * 设置静态文件托管 * 当访问的url以/public开始,那么直接返回对应__dirname + '/public'下的文件 * */ app.use('/public',express.static(__dirname + '/public')); //body-parser设置,用于接收post提交过来的数据 app.use( bodyParser.urlencoded({extended: true})); //在开发过程当中,需要取消模版缓存,但在上线后这个缓存还是有必要的,可以让用户快速加载 swig.setDefaults({cache:false}); //读取数据模型,用于检测是否是管理员 var User = require('./models/User'); /* * 设置cookie * */ app.use(function (req, res, next) { req.cookies = new Cookies(req, res); req.userInfo = {}; if(req.cookies.get('userInfo')){ try{ //如果存在cookies信息,尝试去以json方式解释它 req.userInfo = JSON.parse(req.cookies.get('userInfo')); //获取当前登录用户的类型,是否是管理员 User.findById(req.userInfo.id).then(function (rs) { req.userInfo.isAdmin = Boolean(rs.isAdmin); next(); }); }catch (e){ next(); } }else { next(); } }); /* * 根据不同的功能划分模块,对应访问router下的不同js文件 * */ app.use('/admin',require('./routers/admin')); app.use('/api',require('./routers/api')); app.use('/',require('./routers/main')); //连接数据库 mongoose.connect('mongodb://localhost:27019/overseasstudywebsite',function (err) { if(err){ console.log('数据库连接失败'); console.log(err); }else{ console.log('数据库连接成功'); //监听http请求 app.listen(8082); } }); <file_sep>/** * Created by SHINING on 2017/3/28. */ var mongoose = require('mongoose'); var abroad_enrollsSchema = require('../schemas/abroad_enrolls'); module.exports = mongoose.model('Abroad_enroll',abroad_enrollsSchema);<file_sep>/** * Created by SHINING on 2017/3/28. */ var mongoose = require('mongoose'); var abroad_contentsSchema = require('../schemas/abroad_contents'); module.exports = mongoose.model('Abroad_content',abroad_contentsSchema);<file_sep>/** * Created by SHINING on 2017/3/28. */ //用户数据库 var mongoose = require('mongoose'); //分类的表结构 module.exports = new mongoose.Schema({ //关联字段,地区 area:{ //类型 type: mongoose.Schema.Types.ObjectId, //引用 ref: 'Area' }, //学校名 School_zn:String, School_en:String, //学校排名顺序 School_rank:{ type: Number, default: 0 }, //学校url School_url: { type: String, default: '/' }, //学校图片 School_img: String, //点赞数 School_love:{ type:Number, default:0 }, //录取人数 School_enroll:{ type: Number, default: 0 } });<file_sep>/** * Created by SHINING on 2017/3/28. */ var mongoose = require('mongoose'); var areasSchema = require('../schemas/areas'); module.exports = mongoose.model('Area',areasSchema);<file_sep>/** * Created by SHINING on 2017/3/28. */ var mongoose = require('mongoose'); var navigationsSchema = require('../schemas/navigations'); module.exports = mongoose.model('Navigation',navigationsSchema);<file_sep>/** * Created by SHINING on 2017/3/28. */ //用户数据库 var mongoose = require('mongoose'); //导航内容的表结构 module.exports = new mongoose.Schema({ //关联字段 navigation:{ //类型 type: mongoose.Schema.Types.ObjectId, //引用 ref: 'Navigation' }, nav_title:{ type: mongoose.Schema.Types.ObjectId, ref: 'Nav_title' }, //标题内容名称 Nav_content_name: String, Nav_content_order: { type: Number, default: 0 }, Nav_content_url: String, Nav_content_hot: { type: Number, default: 0 } });<file_sep>/** * Created by SHINING on 2017/3/19. */ /* * ajax接口路由 * */ var express = require('express'), router = express.Router(); //数据库 var User = require('../models/User'), Navigation = require('../models/Navigation'), Nav_title = require('../models/Nav_title'), Nav_content = require('../models/Nav_content'), Abroad = require('../models/Abroad'), Abroad_nav = require('../models/Abroad_nav'), Abroad_content = require('../models/Abroad_content'), School = require('../models/School'), Test = require('../models/Test'), Training = require('../models/Training'), Leave_message = require('../models/Leave_message'), Training_content = require('../models/Training_content'); //返回统一格式 var responseData; //定下初始格式 router.use(function (req, res, next) { responseData = { code: 0, message: '' }; next(); }); /* * 用户注册 * 注册逻辑 * * 1.用户名不能为空 * 2.密码不能为空 * 3.两次输入密码必须一致 * * 2.用户名是否已经被注册 * */ router.post('/user/register',function (req, res) { var username = req.body.username, password = req.body.password; new User({ username: username, password: <PASSWORD> }).save().then(function (rs) { responseData.message = '注册成功'; res.json(responseData); }); }); /* * 实时检测帐号的正确性 * */ router.post('/user/register/namecheck',function (req, res) { var username = req.body.username, news = req.body.news; if(news === '1'){ responseData.code = 2; responseData.message = '手机号码或者邮箱不正确!'; res.json(responseData); }else if(news === '2'){ responseData.code = 4; responseData.message = '请填写手机号码或者邮箱'; res.json(responseData); }else{ User.findOne({ username: username //返回的是一个promise对象 }).then(function (userInfo) { //表示数据库有该记录 if (userInfo) { responseData.code = 1; responseData.message = '用户名已经被注册'; res.json(responseData); }else{ responseData.code = 3; responseData.message = '用户名可用'; res.json(responseData); } }); } }); /* * 实时验证密码的正确性 * */ router.post('/user/register/passwordcheck',function (req, res) { var password = req.body.password, news2 = req.body.news2; if(news2 === '1'){ responseData.code = 5; responseData.message = '密码位数请控制在6~16个字符!'; res.json(responseData); }else if(news2 === '0'){ responseData.code = 6; responseData.message = '密码可用'; res.json(responseData); }else{ responseData.code = 7; responseData.message = '密码6~16个字符,区分大小写'; res.json(responseData); } }); /* * 实时验证二次密码的正确性 * */ router.post('/user/register/repasswordcheck',function (req, res) { var news3 = req.body.news3; if(news3 === '1'){ responseData.code = 8; responseData.message = '两次输入的密码不一致'; res.json(responseData); }else if(news3 === '0'){ responseData.code = 9; responseData.message = '密码正确'; res.json(responseData); }else{ responseData.code = 10; responseData.message = '请再次填写密码'; res.json(responseData); } }); /* * 登录模块的操作 * */ router.post('/user/login',function (req, res) { var username = req.body.username, password = req.body.password; if(username === '' || password === ''){ responseData.code = 11; responseData.message = '用户名或者密码不能为空!'; res.json(responseData); }else{ User.findOne({ username: username }).then(function (rs) { if(!rs){ responseData.code = 12; responseData.message = '用户名不存在!'; res.json(responseData); return Promise.reject(); }else{ User.findOne({ username: rs.username, password: <PASSWORD> }).then(function (rs) { if(!rs){ responseData.code = 13; responseData.message = '密码不正确!'; res.json(responseData); return Promise.reject(); } responseData.code = 14; responseData.message = '登录成功!'; responseData.userInfo = { id: rs._id, username: rs.username }; //发送一个信息到浏览器,通过头信息的方式发送给服务端 req.cookies.set('userInfo',JSON.stringify({ //保存成字符串,存在userInfo里面 id: rs._id, username: rs.username })); res.json(responseData); }); } }) } }); /* * 退出 * */ router.get('/user/logout',function (req, res) { req.cookies.set('userInfo', null); res.json(responseData); }); /* * 导航标题内容二级联动菜单 * */ router.post('/navigation/title/content/add',function (req, res) { var navigation = req.body.navigation; if(navigation === ''){ }else{ Nav_title.find({ navigation: navigation }).sort({Nav_title_order:1}).then(function (rs) { responseData.nav_titles = rs; res.json(responseData); }) } }); /* * 导航标题内容修改二级联动菜单 (经验证,该菜单不需要设置!多余!) * */ router.post('/navigation/title/content/edit',function (req, res) { var navigation = req.body.navigation, id = req.headers.referer, re = /.*id=([^&]*).*/; id = id.replace(re,"$1"); if(navigation === ''){ }else{ Nav_title.find({ navigation: navigation }).populate('navigation').sort({Nav_title_order:1}).then(function (rs) { responseData.nav_titles = rs; }).then(function () { Nav_content.findOne({ _id: id }).populate('nav_title').then(function (nav_content) { responseData.nav_content = nav_content; res.json(responseData); }); }); } }); /* * 留学文章标题添加、修改二级联动菜单 * */ router.post('/study_abroad/nav/content/add',function (req, res) { var abroad = req.body.abroad; if(abroad === ''){ }else{ Abroad_nav.find({ abroad: abroad }).populate('abroad').sort({Abroad_nav_order:1}).then(function (rs) { responseData.abroad_navs = rs; res.json(responseData); }); } }); /* * 留学文章标题添加、修改二级联动菜单 * */ router.post('/training/content/add',function (req, res) { var test = req.body.test; if(test === ''){ }else{ Training.find({test: test}).populate('test').sort({Training_content_order:1}).then(function (rs) { responseData.trainings = rs; res.json(responseData); }) } }); /* * 学校点赞 * */ router.post('/school',function (req, res) { var school_id = req.body.school; if(school_id){ School.findById(school_id).then(function (rs) { var temp = rs.School_love + 1; School.update({ _id: school_id },{ School_love: temp }).then(function (rs) { responseData.ok = rs.ok; responseData.love = temp; res.json(responseData); }); }); } }); /* * 文章阅读数统计 * */ router.post('/Abroad_article',function (req, res) { var article_id = req.body.article; if(article_id){ Abroad_content.findById(article_id).then(function (rs) { var temp = rs.Abroad_content_hot + 1; Abroad_content.update({ _id: article_id },{ Abroad_content_hot: temp }).then(function () { res.json(responseData); }); }); } }); /* * 获取留言信息 * */ router.post('/leave_message',function (req, res) { var word = req.body.word || '', name = req.body.name, tel = req.body.tel; new Leave_message({ name: name, tel: tel, leave_message: word }).save().then(function () { responseData.leave_message = '感谢您的留言!'; res.json(responseData); }) }); //返回出去给app.js module.exports = router;
ab36e2e573f929b46b59a3df2c2b16cea2def356
[ "JavaScript", "HTML", "Markdown" ]
30
JavaScript
a294465800/overseasstudywebsite
bc88cf9795cf410c82f6b29480f23c900a8ed2a1
db9e29bfa70c6019ec72049a3f11b6a0e637b35d
refs/heads/master
<repo_name>KID421/HC_TPS_ArrowLegend<file_sep>/UnityProject/Assets/Scripts/LearnCoroutine.cs using UnityEngine; using System.Collections; // 引用 系統.集合 API public class LearnCoroutine : MonoBehaviour { // 傳回類型 IEnumerator 傳回等待時間 public IEnumerator DelayEffect() { print("開始協程"); yield return new WaitForSeconds(3); // 傳回 新 等待秒數(秒) print("三秒後"); yield return new WaitForSeconds(3); print("再三秒後"); } private void Start() { // 啟動協程(協程名稱()) StartCoroutine(DelayEffect()); } } <file_sep>/UnityProject/Assets/Scripts/RandomSkill.cs using UnityEngine; using UnityEngine.UI; using System.Collections; // [添加元件(類型(任何元件類型))] - 套用此腳本時執行 [RequireComponent(typeof(AudioSource))] public class RandomSkill : MonoBehaviour { #region 欄位 [Header("技能隨機圖片")] public Sprite[] spritesRandom; [Header("技能圖片")] public Sprite[] sprites; [Header("間隔時間"), Range(0f, 1f)] public float speed = 0.1f; [Header("次數"), Range(1, 10)] public int count = 3; [Header("音效區域")] public AudioClip soundRandom; public AudioClip soundSkill; [Header("技能名稱")] public string[] skillsName = { "連射", "添加弓箭", "前後", "左右", "添加血量", "添加傷害", "添加攻速", "添加爆爆" }; private Image imgSkill; private AudioSource aud; private Text textSkill; #endregion private int randomIndex; private Button btn; private GameObject objSkill; private void Start() { imgSkill = GetComponent<Image>(); aud = GetComponent<AudioSource>(); btn = GetComponent<Button>(); textSkill = transform.GetChild(0).GetComponent<Text>(); // 變形.取得子物件(索引值) objSkill = GameObject.Find("隨機技能"); StartCoroutine(StartRandom()); // 啟動協程(開始隨機()) btn.onClick.AddListener(ChooseSkill); // 按鈕.點擊事件.增加聆聽者(方法) } /// <summary> /// 選取技能 /// </summary> private void ChooseSkill() { print("選取技能:" + skillsName[randomIndex]); objSkill.SetActive(false); // 隨機技能.啟動設定(取消) } /// <summary> /// 開始隨機效果 /// </summary> /// <returns></returns> public IEnumerator StartRandom() { btn.interactable = false; // 取消互動 for (int j = 0; j < count; j++) { for (int i = 0; i < spritesRandom.Length; i++) { imgSkill.sprite = spritesRandom[i]; // 技能圖片.圖片 = 圖片隨機[索引值] aud.PlayOneShot(soundRandom, 0.1f); // 音源.播放一次音效(音效片段,音量) yield return new WaitForSeconds(speed); // 等待 } } randomIndex = Random.Range(0, sprites.Length); // 隨機值 = 隨機.範圍(最小,最大) imgSkill.sprite = sprites[randomIndex]; // 技能圖片.圖片 = 技能圖片[隨機值] textSkill.text = skillsName[randomIndex]; // 技能文字.文字 = 技能名稱[隨機值] aud.PlayOneShot(soundSkill, 0.7f); // 音源.播放一次音效(音效片段,音量) btn.interactable = true; // 啟動互動 } } <file_sep>/UnityProject/Assets/Scripts/Player.cs using UnityEngine; using System.Linq; // 引用 查詢語法 LinQ (Qurery) using System.Collections.Generic; // 引用 系統.集合.一般 public class Player : MonoBehaviour { #region 欄位 [Header("移動速度"), Range(1, 200)] public float speed = 20; [Header("玩家資料")] public PlayerData data; [Header("武器")] public GameObject knife; private float timer; private Transform firePoint; private Joystick joy; private Transform target; private Rigidbody rig; private Animator ani; private LevelManager levelManager; // 關卡管理器 private HpBarControl hpControl; // 血條控制器 #endregion // public Enemy[] enemys; // 缺點:數量無法改變 public List<Enemy> enemys; // 怪物清單 (存取方式與陣列相同) public List<float> enemysDistance; // 怪物距離 #region 事件 private void Start() { rig = GetComponent<Rigidbody>(); // 剛體欄位 = 取得元件<泛型>() ani = GetComponent<Animator>(); // target = GameObject.Find("目標").GetComponent<Transform>(); // 寫法 1 target = GameObject.Find("目標").transform; // 寫法 2 joy = GameObject.Find("虛擬搖桿").GetComponent<Joystick>(); levelManager = FindObjectOfType<LevelManager>(); // 透過類型尋找物件 hpControl = transform.Find("血條系統").GetComponent<HpBarControl>(); // 變形.尋找("子物件") firePoint = transform.Find("發射位置"); hpControl.UpdateHpBar(data.hpMax, data.hp); // 更新血條 } // 固定更新:固定一秒 50 次 - 物理行為 private void FixedUpdate() { Move(); } private void Update() { // 測試區域 if (Input.GetKeyDown(KeyCode.Alpha1)) Attack(); if (Input.GetKeyDown(KeyCode.Alpha2)) Dead(); } // 觸發事件:碰到勾選 IsTrigger 物件執行一次 private void OnTriggerEnter(Collider other) { if (other.tag == "傳送區域") { if (levelManager.isBoss) { levelManager.ShowResult(); } else { levelManager.StartCoroutine("LoadLevel"); } } } #endregion #region 方法 /// <summary> /// 移動玩家方法 /// </summary> private void Move() { float h = joy.Horizontal; // 虛擬搖桿水平 float v = joy.Vertical; // 虛擬搖桿垂直 rig.AddForce(-h * speed, 0, -v * speed); // 剛體.增加推力(水平,0,垂直) // 取得此物件變型元件 // 原寫:GetComponent<Transform>() // 簡寫:transform Vector3 posPlayer = transform.position; // 玩家座標 = 取得玩家.座標 Vector3 posTarget = new Vector3(posPlayer.x - h, 0, posPlayer.z - v); // 目標座標 = 新 三維向量(玩家.X - 搖桿.X,Y,玩家.Z - 搖桿.Z) target.position = posTarget; // 目標.座標 = 目標座標 posTarget.y = posPlayer.y; // 目標.Y = 玩家.Y (避免吃土) transform.LookAt(posTarget); // 變形.看著(座標) // 水平 1、-1 // 垂直 1、-1 // 動畫控制器.設定布林值(參數名稱,布林值) ani.SetBool("跑步開關", h != 0 || v != 0); if (h == 0 && v == 0) Attack(); // 如果 水平與垂直 皆為 0 就 攻擊 } /// <summary> /// 攻擊方法 /// </summary> private void Attack() { if (timer < data.cd) // 如果 計時器 < 資料.冷卻 { timer += Time.deltaTime; // 累加時間 } else { timer = 0; // 歸零 // 1. 取得所有敵人 enemys.Clear(); // 清除清單 (刪除清單內容) enemys = FindObjectsOfType<Enemy>().ToList(); // 透過類型尋找複數物件 (傳回陣列) // ToList 將陣列轉換為清單 List // 沒有怪物:過關行為 if (enemys.Count == 0) { levelManager.PassLevel(); return; } ani.SetTrigger("攻擊觸發"); // 播放攻擊動畫 SetTrigger("參數名稱") // 2. 取得所有敵人距離 // 陣列數量:Length // 清單數量:Count enemysDistance.Clear(); // 清除清單 for (int i = 0; i < enemys.Count; i++) // 迴圈執行 { float dis = Vector3.Distance(transform.position, enemys[i].transform.position); // 取得距離 enemysDistance.Add(dis); // 清單.加入(資料) } // 3. 取得最短距離 float min = enemysDistance.Min(); // 取得最短距離 int index = enemysDistance.IndexOf(min); // 取得最短距離的編號 Vector3 enemyTarget = enemys[index].transform.position; enemyTarget.y = transform.position.y; transform.LookAt(enemyTarget); GameObject bullet = Instantiate(knife, firePoint.position, firePoint.rotation); // 生成(子彈,座標,角度) bullet.GetComponent<Rigidbody>().AddForce(transform.forward * data.bulletPower); // 取得子彈剛體並添加推力 // 暫存子彈.添加元件<子彈>(); bullet.AddComponent<Bullet>(); bullet.GetComponent<Bullet>().damage = data.attack; bullet.GetComponent<Bullet>().player = true; } } /// <summary> /// 玩家受傷方法:扣血、更新血條、顯示傷害值 /// </summary> /// <param name="damage">玩家受多少傷害</param> public void Hit(float damage) { data.hp -= damage; // 血量 扣除 傷害值 data.hp = Mathf.Clamp(data.hp, 0, 10000); // 血量 夾在 0 - 10000 hpControl.UpdateHpBar(data.hpMax, data.hp); // 血量控制系統.更新血條(目前血量,最大血量) if (data.hp == 0) Dead(); // 如果 血量 為 0 呼叫死亡方法 StartCoroutine(hpControl.ShowDamage(damage)); // 血量控制器.顯示傷害值 } /// <summary> /// 死亡方法 /// </summary> private void Dead() { if (ani.GetBool("死亡動畫")) return; // 如果死亡動畫為勾選就跳出 ani.SetBool("死亡動畫", true); // 播放死亡動畫 SetBool("參數名稱", 布林值) this.enabled = false; // this 此類別 - enabled 是否啟動 StartCoroutine(levelManager.CountDownRevival()); // 啟動協程 } /// <summary> /// 復活方法 /// </summary> public void Revival() { this.enabled = true; // 此腳本.啟動 = 開啟 data.hp = data.hpMax; // 血量恢復為最大值 hpControl.UpdateHpBar(data.hpMax, data.hp); // 更新血條 ani.SetBool("死亡動畫", false); // 動畫設為沒有死亡 levelManager.CloseRevival(); // 關卡管理器.關閉復活畫面 } #endregion } <file_sep>/UnityProject/Assets/Scripts/LearnFor.cs using UnityEngine; public class LearnFor : MonoBehaviour { public LearnArray learnArray; private void Start() { // while 當 // 當 () 布林值為 true 一直執行 {} 敘述 int count = 50; while (count > 0) { print("while 迴圈:" + count); count--; } // for // (初始值;條件;迭代器) // 條件為 true 時執行 {} for (int i = 0; i < 10; i++) { print("for 迴圈:" + i); } for (int i = 0; i < learnArray.players.Length; i++) { print(learnArray.players[i].name); } } } <file_sep>/README.md # HC_TPS_ArrowLegend 赫綵站前 - 3D 弓箭傳說 <file_sep>/UnityProject/Assets/Scripts/CameraControl.cs using UnityEngine; namespace KID { public class CameraControl : MonoBehaviour { [Header("速度"), Range(0, 100)] public float speed = 1.5f; [Header("上方限制")] public float top; [Header("下方限制")] public float bottom; private Transform player; private void Start() { player = GameObject.Find("玩家").transform; } // 在 Update 之後執行:適合做攝影機、物件追蹤 private void LateUpdate() { Track(); } /// <summary> /// 攝影機追蹤玩家方法 /// </summary> private void Track() { Vector3 posPlayer = player.position; // 玩家.座標 Vector3 posCamera = transform.position; // 變形.座標 posPlayer.x = 0; // 限制 X 在 0 posPlayer.y = 16; // 限制 Y 在 16 (原攝影機 Y) posPlayer.z += 15; // 往玩家後面位移 // 玩家.z = 數學.夾住(玩家.z,上限,下限) posPlayer.z = Mathf.Clamp(posPlayer.z, top, bottom); // 變形.座標 = 三維向量.插值(攝影機,玩家,百分比) transform.position = Vector3.Lerp(posCamera, posPlayer, 0.5f * Time.deltaTime * speed); } } } <file_sep>/UnityProject/Assets/Scripts/HpBarControl.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class HpBarControl : MonoBehaviour { private Image imgHp; private Text textHp; private Text textDamage; // Awake 喚醒事件:在 Start 之前執行一次 private void Awake() { imgHp = transform.GetChild(1).GetComponent<Image>(); textHp = transform.GetChild(2).GetComponent<Text>(); textDamage = transform.GetChild(3).GetComponent<Text>(); } private void Update() { AngleControl(); } /// <summary> /// 角度控制:讓血條保持世界座標角度為原本角度 35, -180, 0 /// </summary> private void AngleControl() { // 變形元件.歐拉角度 = 新 三維向量() - 世界座標 //transform.localEulerAngles - 區域座標 transform.eulerAngles = new Vector3(35, -180, 0); } /// <summary> /// 更新血條圖片長度與文字內容,需要提供最大與目前血量 /// </summary> /// <param name="hpMax">最大血量</param> /// <param name="hpCurrent">目前血量,受傷後的血量</param> public void UpdateHpBar(float hpMax, float hpCurrent) { imgHp.fillAmount = hpCurrent / hpMax; // 圖片.填滿數值 = 目前 / 最大 textHp.text = hpCurrent.ToString(); // 文字.文字內容 = 目前.轉字串() } /// <summary> /// 顯示傷害值效果:傷害值往上移動 /// </summary> /// <param name="damage">要顯示的傷害值</param> /// <returns></returns> public IEnumerator ShowDamage(float damage) { //Vector3 posOriginal = textDamage.transform.position; // 取得原始位置 textDamage.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 70); textDamage.text = "-" + damage; // 更新傷害值 = 接收傷害 for (int i = 0; i < 20; i++) { //textDamage.transform.position += new Vector3(0, 0.07f, 0); // 傷害值往上移動 (transform.position.y += 值) textDamage.GetComponent<RectTransform>().anchoredPosition += new Vector2(0, 5); yield return new WaitForSeconds(0.001f); // 等待 } //textDamage.transform.position = posOriginal; // 位置 = 原始位置 textDamage.text = ""; // 文字 = "" } } <file_sep>/UnityProject/Assets/Scripts/LearnLerp.cs using UnityEngine; public class LearnLerp : MonoBehaviour { private Vector3 a = new Vector3(0, 0, 0); private Vector3 b = new Vector3(10, 10, 10); public Color red = Color.red; public Color blue = Color.blue; public Color newColor; public float hp = 50; private void Start() { // 認識插值 Lerp print(Mathf.Lerp(0, 10, 0.7f)); print(Vector3.Lerp(a, b, 0.5f)); newColor = Color.Lerp(red, blue, 0.5f); print(Mathf.Clamp(hp, 0, 100)); } } <file_sep>/UnityProject/Assets/Scripts/Zombie.cs using UnityEngine; public class Zombie : EnemyNear { } <file_sep>/UnityProject/Assets/Scripts/MenuManager.cs using UnityEngine; using UnityEngine.SceneManagement; public class MenuManager : MonoBehaviour { [Header("玩家資料")] public PlayerData data; /// <summary> /// 載入關卡 /// </summary> public void LoadLevel() { data.hp = data.hpMax; // 進入關卡前將血量 = 血量最大值 SceneManager.LoadScene("關卡1"); } /// <summary> /// 購買血量 +500 /// </summary> public void BuyHp_500() { data.hpMax += 500; // 血量最大值遞增 500 data.hp = data.hpMax; // 血量 = 血量最大值 } /// <summary> /// 購買攻擊 +50 /// </summary> public void BuyAtk_50() { data.attack += 50; // 攻擊力遞增 50 } } <file_sep>/UnityProject/Assets/Scripts/Enemy.cs using UnityEngine; using UnityEngine.AI; public class Enemy : MonoBehaviour { [Header("敵人資料")] public EnemyData data; // 敵人資料 (腳本化物件:共用) [Header("金幣")] public GameObject coin; protected NavMeshAgent agent; // 導覽代理器 protected Transform player; // 玩家變形 protected Animator ani; // 動畫控制器 protected float timer; // 計時器 private HpBarControl hpControl; // 血條控制器 private float hp; // 個別的血量 (個別擁有) private void Start() { // 先取得元件 ani = GetComponent<Animator>(); agent = GetComponent<NavMeshAgent>(); agent.speed = data.speed; hp = data.hpMax; player = GameObject.Find("玩家").transform; agent.SetDestination(player.position); hpControl = transform.Find("血條系統").GetComponent<HpBarControl>(); // 變形.尋找("子物件") hpControl.UpdateHpBar(data.hpMax, hp); // 血量控制系統.更新血條(目前血量,最大血量) } private void Update() { Move(); } // protected 不允許外部類別存取,允許子類別存取 protected virtual void Attack() { timer = 0; // 計時器 歸零 ani.SetTrigger("攻擊觸發"); // 攻擊動畫 } // virtual 虛擬:讓子類別可以複寫 protected virtual void Move() { agent.SetDestination(player.position); // 代理器.設定目的地(玩家.座標) Vector3 posTarget = player.position; // 區域變數 目標座標 = 玩家.座標 posTarget.y = transform.position.y; // 目標座標.y = 本身.y transform.LookAt(posTarget); // 看著(目標座標) if (agent.remainingDistance <= data.stopDistance) // 如果 距離 <= { Wait(); } else { agent.isStopped = false; // 代理器.是否停止 = 否 ani.SetBool("跑步開關", true); // 開啟跑步開關 } } protected virtual void Wait() { agent.isStopped = true; // 代理器.是否停止 = 是 agent.velocity = Vector3.zero; // 代理器.加速度 = 零 ani.SetBool("跑步開關", false); // 關閉跑步開關 if (timer <= data.cd) // 如果 計時器 <= 冷卻時間 { timer += Time.deltaTime; // 時間累加 } else { Attack(); // 否則 計時器 > 冷卻時間 攻擊 } } public void Hit(float damage) { hp -= damage; // 血量 扣除 傷害值 hp = Mathf.Clamp(hp, 0, 10000); // 血量 夾在 0 - 10000 hpControl.UpdateHpBar(data.hpMax, hp); // 血量控制系統.更新血條(目前血量,最大血量) if (hp == 0) Dead(); // 如果 血量 為 0 呼叫死亡方法 StartCoroutine(hpControl.ShowDamage(damage)); // 血量控制器.顯示傷害值 } private void Dead() { if (ani.GetBool("死亡動畫")) return; ani.SetBool("死亡動畫", true); this.enabled = false; Destroy(gameObject, 0.2f); CreateCoin(); } private void CreateCoin() { // (int) 強制轉型:將浮點數轉為整數 - 去小數點 int r = (int)Random.Range(data.coinRange.x, data.coinRange.y); for (int i = 0; i < r; i++) { Instantiate(coin, transform.position + transform.up * 1, Quaternion.identity); } } } <file_sep>/UnityProject/Assets/Scripts/EnemyData.cs using UnityEngine; // 建立素材選項(檔案名稱,選項名稱) [CreateAssetMenu(fileName = "敵人資料", menuName = "KID/EnemyData")] public class EnemyData : ScriptableObject // 腳本化物件 將資料儲存於 Project { [Header("血量"), Range(100, 3000)] public float hp = 100; [Header("血量最大值"), Range(100, 3000)] public float hpMax; [Header("攻擊力"), Range(1, 1000)] public float attack = 10; [Header("移動速度"), Range(0, 100)] public float speed = 1.5f; [Header("攻擊冷卻時間"), Range(1, 10)] public float cd = 3.5f; [Header("停止距離"), Range(1, 1000)] public float stopDistance = 1.5f; [Header("近戰攻擊距離"), Range(0, 10)] public float attackRange = 1.8f; [Header("攻擊延遲時間"), Range(0, 10)] public float attackDelay = 0.8f; [Header("遠攻離發射子彈位置位移"), Tooltip("X 不要調整,Y 調整高度,Z 調整前後")] public Vector3 attackOffset; [Header("遠攻子彈飛行速度"), Range(1, 2000)] public float bulletSpeed; [Header("金幣最小與最大值")] public Vector2 coinRange; }<file_sep>/UnityProject/Assets/Scripts/Dragon.cs using UnityEngine; public class Dragon : EnemyFar { } <file_sep>/UnityProject/Assets/Scripts/Bullet.cs using UnityEngine; public class Bullet : MonoBehaviour { public float damage; // 接收遠攻敵人的攻擊力 public bool player; // 判斷武器是誰擁有的,true 玩家,false 怪物 private void OnTriggerEnter(Collider other) { if (!player) // 如果子彈不是玩家的 { if (other.tag == "Player") // 如果 碰到物件.標籤 為 "Player" { other.GetComponent<Player>().Hit(damage); // 碰到物件.取得元件<Player>().受傷(攻擊力); } } if (player) // 如果子彈是玩家的 { if (other.tag == "Enemy") // 如果 標籤 為 "Enemy" { other.GetComponent<Enemy>().Hit(damage); } } } } <file_sep>/UnityProject/Assets/Scripts/PlayerData.cs using UnityEngine; [CreateAssetMenu(fileName = "玩家資料", menuName = "KID/玩家資料")] public class PlayerData : ScriptableObject { [Header("血量")] public float hp = 200; [Header("最大血量:不會改變")] public float hpMax = 200; [Header("攻擊冷卻"), Range(0, 3)] public float cd = 2.5f; [Header("發射速度"), Range(0, 3000)] public int bulletPower = 1000; [Header("攻擊力"), Range(0, 3000)] public float attack = 30; } <file_sep>/UnityProject/Assets/Scripts/Item.cs using UnityEngine; public class Item : MonoBehaviour { /// <summary> /// 是否過關 /// </summary> public bool pass; [Header("道具音效")] public AudioClip sound; private Transform player; private AudioSource aud; private void Start() { aud = GetComponent<AudioSource>(); player = GameObject.Find("玩家").transform; HandleCollision(); } private void Update() { GoToPlayer(); } /// <summary> /// 管理碰撞 /// </summary> private void HandleCollision() { Physics.IgnoreLayerCollision(10, 8); // 忽略圖層碰撞(圖層1,圖層2) Physics.IgnoreLayerCollision(10, 9); } /// <summary> /// 前往玩家 /// </summary> private void GoToPlayer() { if (pass) { transform.position = Vector3.Lerp(transform.position, player.position, 0.7f * 20 * Time.deltaTime); if (Vector3.Distance(transform.position , player.position) < 2.3f) // 如果 金幣與玩家距離 < 2.3 { aud.PlayOneShot(sound, 0.3f); // 播放音效 Destroy(gameObject, 0.25f); // 刪除(物件,延遲時間) } } } } <file_sep>/UnityProject/Assets/Scripts/EnemyNear.cs using UnityEngine; using System.Collections; public class EnemyNear : Enemy { protected override void Attack() { base.Attack(); StartCoroutine(DelayAttack()); // 啟動協程 } private IEnumerator DelayAttack() { yield return new WaitForSeconds(data.attackDelay); RaycastHit hit; // 射線碰撞資訊 - 存放射線碰到的內容 // out 存放參數資訊 // 物理.射線碰撞(中心點,方向,射線碰撞資訊,長度) if (Physics.Raycast(transform.position + new Vector3(0, 1, 0), transform.forward,out hit, data.attackRange)) { //print("打到東西惹~" + hit.collider.gameObject); hit.collider.GetComponent<Player>().Hit(data.attack); // 取得玩家元件.受傷方法(怪物.攻擊力) } } // Ctrl + M O 摺疊 // Ctrl + M L 展開 // 事件:繪製圖示 private void OnDrawGizmos() { Gizmos.color = Color.red; // 圖示.顏色 = 顏色 // 前方:transform.forward // 右方:transform.right // 上方:transform.up // 圖示.繪製射線(中心點,方向) Gizmos.DrawRay(transform.position + new Vector3(0, 1, 0), transform.forward * data.attackRange); } } <file_sep>/UnityProject/Assets/Scripts/AdsManager.cs using UnityEngine; using UnityEngine.Advertisements; // 引用 廣告 API // C# 僅能繼承一個類別,可以實作多個介面(裝備) public class AdsManager : MonoBehaviour, IUnityAdsListener { private string googleID = "3436899"; // Google 專案 ID private bool testMode = false; // 測試模式:允許在 Unity 內側試 private string placemnetRevival = "revival"; // 廣告類型:復活 private Player player; // 玩家腳本 public static bool lookAd; // 靜態 布林值 是否看廣告 private void Start() { Advertisement.AddListener(this); // 廣告.添加監聽腳本(此腳本); Advertisement.Initialize(googleID, testMode); // 廣告.初始化(ID,測試模式); player = FindObjectOfType<Player>(); // 透過類型尋找物件 } /// <summary> /// 顯示廣告 /// </summary> public void ShowAD() { if (Advertisement.IsReady(placemnetRevival)) // 如果 廣告.是否準備完成(廣告 ID) { lookAd = true; // 看廣告 = 是 Advertisement.Show(placemnetRevival); // 廣告.顯示(廣告 ID) } } public void OnUnityAdsReady(string placementId) { } public void OnUnityAdsDidError(string message) { } public void OnUnityAdsDidStart(string placementId) { } /// <summary> /// 廣告完成 /// </summary> public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) { if (placementId == placemnetRevival) // 如果 玩家看的廣告 ID = 復活廣告 ID { switch (showResult) // switch 判斷式(廣告結果) { case ShowResult.Failed: // 狀況 1 失敗: print("廣告失敗"); break; case ShowResult.Skipped: // 狀況 2 略過: print("廣告略過"); break; case ShowResult.Finished: // 狀況 3 失敗: print("廣告成功"); GameObject.Find("玩家").GetComponent<Player>().Revival(); // 復活方法 break; } } } }<file_sep>/UnityProject/Assets/Scripts/EnemyFar.cs using UnityEngine; using System.Collections; // 引用 系統.集合 API public class EnemyFar : Enemy { [Header("子彈物件")] public GameObject bullet; protected override void Attack() { base.Attack(); StartCoroutine(CreateBullet()); // 啟動協程 } /// <summary> /// 產生子彈 /// </summary> private IEnumerator CreateBullet() { yield return new WaitForSeconds(data.attackDelay); // 等待 Vector3 pos = new Vector3(0, data.attackOffset.y, 0); // 區域變數 座標 = 新 三維向量(0,位移.Y,0) // 座標:本身.座標 + 座標 + 前方 * 座標.Z GameObject tempBullet = Instantiate(bullet, transform.position + pos + transform.forward * data.attackOffset.z, Quaternion.identity); // 實例化 // 暫存子彈.取得元件<剛體>().增加推力(角色.前方 * 資料.子彈速度) tempBullet.GetComponent<Rigidbody>().AddForce(transform.forward * data.bulletSpeed); // 暫存子彈.添加元件<子彈>(); tempBullet.AddComponent<Bullet>(); // 暫存子彈.取得元件<子彈>().攻擊力 = 資料.攻擊力 tempBullet.GetComponent<Bullet>().damage = data.attack; tempBullet.GetComponent<Bullet>().player = false; } } <file_sep>/UnityProject/Assets/Scripts/LearnArray.cs using UnityEngine; public class LearnArray : MonoBehaviour { public int enemy1 = 50; public int enemy2 = 150; public int enemy3 = 90; // 陣列:類型[] public int[] enemys; public float[] speeds; public GameObject[] enemyObjs; // 宣告陣列方式 public int[] array1; // 定義數量0陣列 public int[] array2 = new int[10]; // 定義數量10陣列 public int[] array3 = { 100, 200, 300 }; // 定義指定資料陣列 public GameObject[] players; // 喚醒事件:在 Start 之前執行一次 private void Awake() { // 存取陣列 // 取得:陣列名稱[索引值] print("取得第二筆資料:" + array3[2]); // 設定:陣列名稱[索引值] = 值 array3[2] = 999; // 陣列數量 print("陣列 2 數量:" + array2.Length); // 遊戲物件.透過標籤尋找物件(標籤名稱) - 傳回遊戲物件陣列 players = GameObject.FindGameObjectsWithTag("Player"); } } <file_sep>/UnityProject/Assets/Plugins/iOS/UnityAdsUtilities.h inline const char * UnityAdsCopyString(const char * string) { char * copy = (char *)malloc(strlen(string) + 1); strcpy(copy, string); return copy; } /** * Returns the size of an Il2CppString */ inline size_t Il2CppStringLen(const ushort* str) { const ushort* start = str; while (*str) ++str; return str - start; } /** * Converts an ushort string to an NSString */ inline NSString* NSStringFromIl2CppString(const ushort* str) { size_t len = Il2CppStringLen(str); return [[NSString alloc] initWithBytes:(const void*)str length:sizeof(ushort) * len encoding:NSUTF16LittleEndianStringEncoding]; } <file_sep>/UnityProject/Assets/Scripts/LevelManager.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; public class LevelManager : MonoBehaviour { [Header("是否一開始顯示隨機技能")] public bool showRandomSkill; [Header("是否自動開門")] public bool autoOpenDoor; [Header("隨機技能介面")] public GameObject randomSkill; [Header("是否為魔王關")] public bool isBoss; private Animator door; // 門 private Image cross; // 轉場畫面 private CanvasGroup panelRevival; // 復活畫面 private Text textCountRevival; // 復活倒數秒數 private GameObject panelResult; // 結算畫面 private AdsManager adManager; private void Start() { door = GameObject.Find("門").GetComponent<Animator>(); cross = GameObject.Find("轉場畫面").GetComponent<Image>(); adManager = FindObjectOfType<AdsManager>(); panelRevival = GameObject.Find("復活畫面").GetComponent<CanvasGroup>(); textCountRevival = panelRevival.transform.Find("倒數秒數").GetComponent<Text>(); panelRevival.transform.Find("看廣告復活").GetComponent<Button>().onClick.AddListener(adManager.ShowAD); panelResult = GameObject.Find("結算畫面"); panelResult.GetComponent<Button>().onClick.AddListener(BackToMenu); // 按鈕.點擊.增加監聽者(方法名稱) if (autoOpenDoor) Invoke("OpenDoor", 6); // 延遲調用("方法名稱",延遲時間) if (showRandomSkill) ShowRandomSkill(); } /// <summary> /// 返回選單場景 /// </summary> private void BackToMenu() { SceneManager.LoadScene("選單畫面"); } /// <summary> /// 顯示結算畫面 /// </summary> public void ShowResult() { panelResult.GetComponent<CanvasGroup>().alpha = 1; // 透明 = 1 panelResult.GetComponent<CanvasGroup>().interactable = true; // 互動 = 可 panelResult.GetComponent<CanvasGroup>().blocksRaycasts = true; // 阻擋 = 是 panelResult.GetComponent<Animator>().SetTrigger("結算畫面觸發"); // 啟動動畫 int currentLevel = SceneManager.GetActiveScene().buildIndex; // 取得目前關卡索引值 panelResult.transform.Find("關卡名稱").GetComponent<Text>().text = "LV:" + currentLevel; } /// <summary> /// 顯示隨機技能介面 /// </summary> private void ShowRandomSkill() { randomSkill.SetActive(true); } /// <summary> /// 播放開門動畫 /// </summary> private void OpenDoor() { door.SetTrigger("開門"); // 動畫控制器.設定觸發("參數名稱") } /// <summary> /// 載入關卡 /// </summary> private IEnumerator LoadLevel() { int sceneIndex = SceneManager.GetActiveScene().buildIndex; // 區域變數 場景索引值 = 場景管理器.取得目前場景().索引值 AsyncOperation ao = SceneManager.LoadSceneAsync(++sceneIndex); // 載入場景資訊 = 載入場景(++場景索引值) ao.allowSceneActivation = false; // 載入場景資訊.是否允許切換 = 否 while (!ao.isDone) // 當(載入場景資訊.是否完成 為 否) { print(ao.progress); cross.color = new Color(1, 1, 1, ao.progress); // 轉場畫面.顏色 = 新 顏色(1,1,1,透明度) // ao.progress 載入進度 0 - 0.9 yield return new WaitForSeconds(0.01f); if (ao.progress >= 0.9f) ao.allowSceneActivation = true; // 當 載入進度 >= 0.9 允許切換 } } /// <summary> /// 復活畫面倒數方法 /// </summary> public IEnumerator CountDownRevival() { panelRevival.alpha = 1; // 顯示復活畫面 panelRevival.interactable = true; // 可互動 panelRevival.blocksRaycasts = true; // 阻擋射線 for (int i = 3; i >= 0; i--) // 迴圈跑三次:3、2、1、0 { textCountRevival.text = i.ToString(); // 更新復活倒數秒數 yield return new WaitForSeconds(1); // 等待一秒 } panelRevival.alpha = 0; // 隱藏復活畫面 panelRevival.interactable = false; // 不可互動 panelRevival.blocksRaycasts = false; // 不阻擋射線 if (!AdsManager.lookAd) // 如果 沒有看廣告 { SceneManager.LoadScene("選單畫面"); // 倒數完回到選單畫面 } AdsManager.lookAd = false; // 沒看 } /// <summary> /// 關閉復活畫面 /// </summary> public void CloseRevival() { StopCoroutine(CountDownRevival()); panelRevival.alpha = 0; // 隱藏復活畫面 panelRevival.interactable = false; // 不可互動 panelRevival.blocksRaycasts = false; // 不阻擋射線 } /// <summary> /// 過關:場景上沒有任何怪物時前往下一關 /// </summary> public void PassLevel() { OpenDoor(); // 開門 Item[] items = FindObjectsOfType<Item>(); // 所有道具 for (int i = 0; i < items.Length; i++) { items[i].pass = true; } } }
77faea067552823493a857ae9df0038867ab24fe
[ "Markdown", "C#", "C" ]
22
C#
KID421/HC_TPS_ArrowLegend
8cab074c283d8c082ea791ffe48d184143cbb17a
e0583a398931fa2862f648ad92e8b0e9b6d64727
refs/heads/master
<file_sep># Authors: <NAME> <<EMAIL>> # <NAME> # <NAME> # License: BSD 3 clause import pickle import numpy as np import pytest from sklearn.utils.testing import assert_array_equal from sklearn.utils.fixes import MaskedArray from sklearn.utils.fixes import _joblib_parallel_args from sklearn.utils.fixes import _object_dtype_isnan def test_masked_array_obj_dtype_pickleable(): marr = MaskedArray([1, None, 'a'], dtype=object) for mask in (True, False, [0, 1, 0]): marr.mask = mask marr_pickled = pickle.loads(pickle.dumps(marr)) assert_array_equal(marr.data, marr_pickled.data) assert_array_equal(marr.mask, marr_pickled.mask) @pytest.mark.parametrize('joblib_version', ('0.11', '0.12.0')) def test_joblib_parallel_args(monkeypatch, joblib_version): import sklearn.utils._joblib monkeypatch.setattr(sklearn.utils._joblib, '__version__', joblib_version) if joblib_version == '0.12.0': # arguments are simply passed through assert _joblib_parallel_args(prefer='threads') == {'prefer': 'threads'} assert _joblib_parallel_args(prefer='processes', require=None) == { 'prefer': 'processes', 'require': None} assert _joblib_parallel_args(non_existing=1) == {'non_existing': 1} elif joblib_version == '0.11': # arguments are mapped to the corresponding backend assert _joblib_parallel_args(prefer='threads') == { 'backend': 'threading'} assert _joblib_parallel_args(prefer='processes') == { 'backend': 'multiprocessing'} with pytest.raises(ValueError): _joblib_parallel_args(prefer='invalid') assert _joblib_parallel_args( prefer='processes', require='sharedmem') == { 'backend': 'threading'} with pytest.raises(ValueError): _joblib_parallel_args(require='invalid') with pytest.raises(NotImplementedError): _joblib_parallel_args(verbose=True) else: raise ValueError @pytest.mark.parametrize("dtype, val", ([object, 1], [object, "a"], [float, 1])) def test_object_dtype_isnan(dtype, val): X = np.array([[val, np.nan], [np.nan, val]], dtype=dtype) expected_mask = np.array([[False, True], [True, False]]) mask = _object_dtype_isnan(X) assert_array_equal(mask, expected_mask)
296d854b1c3b41618a3fd63387569dff1bc24d20
[ "Python" ]
1
Python
nthon/scikit-learn
b3d716c92496e3145fca2f0301ec9829caf85f2d
07306a671e6e5eeebab4c6cea69258816e291d05
refs/heads/master
<repo_name>massaoud/prototypebackend<file_sep>/src/app/models/transport.js import mongoose from 'mongoose'; const transportSchema = new mongoose.Schema({ id: { type: Number, required: true }, cargo_capacity: { type: String }, consumables: { type: String }, cost_in_credits: { type: String }, cargo_capacity: { type: String }, created: { type: Date }, crew: { type: String }, edited: { type: Date }, length: { type: String }, manufacturer: { type: String }, max_atmospering_speed: { type: String }, model: { type: String } ,name: { type: String } , passengers: { type: String } }); module.exports = mongoose.model('Transport', transportSchema, 'Transport'); <file_sep>/src/app/models/species.js import mongoose from 'mongoose'; const speciesSchema = new mongoose.Schema( { id: { type: Number, required: true }, average_height: { type: String }, average_lifespan: { type: String }, classification: { type: Date }, created: { type: Date }, designation: { type: String }, edited: { type: Date }, eye_colors: { type: String }, hair_colors: { type: String }, eye_colors: { type: String }, homeworld: { type: String }, eye_colors: { language: String }, name: { type: String }, skin_colors: { type: String }, people: [{ type: Number }] }, { toJSON: { virtuals: true } } ); module.exports = mongoose.model('Species', speciesSchema, 'species'); <file_sep>/src/app/models/starships.js import mongoose from 'mongoose'; const starshipsSchema = new mongoose.Schema({ id: { type: Number, required: true }, MGLT: { type: String }, hyperdrive_rating: { type: String }, starship_class: { type: String }, pilotes: [{type:Number}] }); module.exports = mongoose.model('StarsShips', starshipsSchema); <file_sep>/src/app/app.js import express from 'express'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import morgan from 'morgan'; import cookieParser from 'cookie-parser'; import cors from 'cors'; require('dotenv').config(); import task1Router from './routes/task1Router'; import task2Router from './routes/task2Router'; import task3Router from './routes/task3Router'; import task4Router from './routes/task4Router'; const app = express(); const port = process.env.PORT; app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); /* **********************BEGIN DB CONNECTION **************************** */ mongoose .connect(process.env.DATABASE, { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: false }) .then(() => console.log('DATABASE CONNECTED')); /* **********************END DB CONNECTION **************************** */ /* ********************** MIDDLEWARE **************************** */ app.use(morgan('dev')); app.use(bodyParser.json()); app.use(cookieParser()); app.use(cors()); /* ********************** **************************** */ /* ********************** ROUTE MIDDLEWARE **************************** */ app.use('/api', task1Router); app.use('/api', task2Router); app.use('/api', task3Router); app.use('/api', task4Router); /* ********************** **************************** */ <file_sep>/src/app/models/vehicles.js import mongoose from 'mongoose'; const vehicleSchema = new mongoose.Schema( { id: { type: Number, required: true }, vehicle_class: { type: String }, pilots: [{ type: Number }] }, //{ toObject: { virtuals: true } }, ); /********************** VIRTUAL JOIN BETWEEN FILMS VEHICLES ************************/ vehicleSchema.virtual('films_vehicles', { ref: 'Films', localField: 'id', foreignField: 'vehicles', options: { sort: { number: 1 } } }); module.exports = mongoose.model('Vehicles', vehicleSchema); <file_sep>/src/app/controllers/task2Controller.js import People from '../models/people'; import Films from '../models/films'; import Planets from '../models/planets'; exports.task2s = (req, res) => { People.aggregate( [ { $lookup: { from: Films.collection.name, localField: 'id', foreignField: 'characters', as: 'films' } }, { $project: { _id: 1, id: 1, name: 1, totalFilms: { $size: '$films' } } }, { $group: { _id: '$totalFilms', response: { $push: { _id: '$_id', id: '$id', name: '$name', numberOfFilm: '$totalFilms' } } } }, { $sort: { numberOfFilm: -1 } }, { $limit: 1 } ], function(err, result) { if (err) { next(err); } else { res.json(result[0].response); } } ); }; <file_sep>/README.md # prototypebackend set up env by creating .env with this configuration PORT=8000 DATABASE = URL TO MONGODB <file_sep>/src/app/models/films.js import mongoose from 'mongoose'; const filmsSchema = new mongoose.Schema({ id: { type: Number, required: true }, created: { type: Date }, director: { type: String }, edited: { type: Date }, episode_id: { type: Number }, opening_crawl: { type: String }, producer: { type: String }, release_date: { type: String }, title: { type: String }, characters: [{type:Number}], planets: [{type:Number}], vehicles: [{type:Number}], species: [{type:Number}], starships: [{type:Number}] }); module.exports = mongoose.model('Films', filmsSchema);<file_sep>/src/app/controllers/task1Controller.js import Films from '../models/films'; exports.task1 = (req, res) => { Films.aggregate( [ { $project: { _id: 1, id: 1, title: 1, director: 1, edited: 1, episode_id: 1, opening_crawl: 1, producer: 1, release_date: 1, nbr: { $size: '$characters' } } }, { $group: { _id: '$nbr', response: { $push: { id: '$id', title: '$title', numberOfCharacter: { $max: '$nbr' } } } } }, { $sort: { numberOfCharacter: -1 } }, { $limit: 1 } ], function(err, result) { if (err) { next(err); } else { res.json(result[0].response); } } ); }; <file_sep>/src/app/models/user-security.js import mongoose from 'mongoose'; import crypto from 'crypto'; import uuidv1 from 'uuid/v1'; import { stringify } from 'querystring'; const userSecutitySchema = new mongoose.Schema({ email: { type: String, trim: true, required: true, unique: 32 }, password: { type: String, required: true }, salt: String, role: { type: Number, default: 0 } }); userSecutitySchema.virtual('password').set(password => { this.password = <PASSWORD>; this.salt = uuidv1(); this.hashed_password = this.encryptPassword(password); }); <file_sep>/src/app/models/planets.js import mongoose from 'mongoose'; const planetsSchema = new mongoose.Schema({ id: { type: Number, required: true }, climate: { type: String }, created: { type: Date }, diameter: { type: String }, edited: { type: Date }, gravity: { type: String }, name: { type: String }, orbital_period: { type: String }, population: { type: String }, rotation_period: { type: String }, surface_water: { type: String }, terrain: { type: String } }, { toJSON: { virtuals: true } }) /********************** VIRTUAL JOIN BETWEEN FILMS PLANETS ************************/ planetsSchema.virtual('films_planets', { ref: 'Films', localField: 'id', foreignField: 'planets' }); /********************** VIRTUAL JOIN BETWEEN PEOPLES PLANETS ************************/ planetsSchema.virtual('pilots', { ref: 'People', localField: 'id', foreignField: 'homeworld' }); module.exports = mongoose.model('Planets', planetsSchema); <file_sep>/src/app/models/people.js import mongoose from 'mongoose'; const peopleSchema = new mongoose.Schema( { id: { type: Number, required: true }, birth_year: { type: String }, created: { type: Date }, edited: { type: Date }, eye_color: { type: String }, gender: { type: String }, hair_color: { type: String }, height: { type: String }, homeworld: { type: Number }, mass: { type: String }, name: { type: String }, skin_color: { type: String } }, { toJSON: { virtuals: true } } ); /********************** VIRTUAL JOIN BETWEEN FILMS PEOPLES ************************/ peopleSchema.virtual('films_characters', { ref: 'Films', localField: 'id', foreignField: 'characters' }); /********************** VIRTUAL JOIN BETWEEN SPECIES PEOPLES ************************/ peopleSchema.virtual('people_species', { ref: 'Species', localField: 'id', foreignField: 'people' }); /********************** VIRTUAL JOIN BETWEEN VEHICLES PEOPLES ************************/ peopleSchema.virtual('people_vehicles', { ref: 'Vehicles', localField: 'id', foreignField: 'pilots' }); module.exports = mongoose.model('People', peopleSchema, 'people');
d30730ec5f22be9d4500258faa1df68960555ecb
[ "JavaScript", "Markdown" ]
12
JavaScript
massaoud/prototypebackend
e388952ca44b8455294492d490b17a9a8b0043c3
db49ae3b3a11d795660a8819ee3b863fda88825c
refs/heads/master
<repo_name>apalad1/Arknights-Gacha-Rate-Simulator<file_sep>/AKgacha.java import java.util.*; public class AKgacha { static int rollcounter = 1; public static void main(String[] args) { //initial prompt Scanner userinput = new Scanner(System.in); System.out.println("Do you want to roll? press y to roll anything else will not"); String yousaid = userinput.nextLine(); while(yousaid.equals("y")) { System.out.println("roll# " + rollcounter); int x = roll(); System.out.println("probability % hit is " + x); rarity(x, rollcounter); //asks if you wanna roll again or not, changes 'yousaid' if you dont want to keep going***** System.out.println("stop? press n"); String response = userinput.nextLine(); if(response.equals("n")) { yousaid = "n"; } rollcounter++; } } public static int roll(){ Random rand = new Random(); int r = rand.nextInt(100)+1; return r; } public static int rarity(int x, int roll_counter) { //*****PITY COUNTER INCREASE if rollcounter is 51 or higher********************************* if(rollcounter>=51) { int pitycounter = rollcounter - 50; x = x - (pitycounter*2); System.out.println("6* rate up increase!!! " + (2+(pitycounter*2)) + "%"); }else { int pitycounter = 0; x = x - pitycounter; } //*****DETERMINE THE RARITY, if its '6star' set the rollcounter to 0************************* if(x<10) { System.out.println("GOLD"); if(x<3) { System.out.println("6stars!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); rollcounter = 0; return rollcounter; } else System.out.println("5stars"); } else { System.out.println("meh"); if(x<60) { System.out.println("4stars"); } else { System.out.println("3stars"); } } //at this point rollcounter is still 0 if it did hit 6* return 0; } }
4517b8784680a19a46a5cb4011b09e353225a288
[ "Java" ]
1
Java
apalad1/Arknights-Gacha-Rate-Simulator
bb5845b25490325eab0c144349f0894e91e1b8c4
062258cea5ba66e31d62284d674052e4492a5a96
refs/heads/master
<file_sep># socket.io chat example This is an example of a chat app using the library socket.io. <file_sep>const express = require('express') const path = require('path') const app = express() const staticFolderPath = path.resolve(`${__dirname}/../static`) app.use(express.static(staticFolderPath)) app.listen(8080) <file_sep>const { createServer } = require('http') const express = require('express') const socketIo = require('socket.io') const app = express() const server = createServer(app) const io = socketIo(server) io.on('connection', socket => { console.log('a user connected') socket.on('chat message', message => { io.emit('chat message', message) }) socket.on('disconnect', () => { console.log('user disconnected') }) }) server.listen(3000) <file_sep>const socket = io('http://localhost:3000') const $ = document.querySelector.bind(document) $('form') .addEventListener('submit', (event) => { socket.emit('chat message', $('#m').value) $('#m').value = '' event.preventDefault() }) socket.on('chat message', message => { const li = document.createElement('li') li.appendChild(document.createTextNode(message)) $('#messages').appendChild(li) })
32826d35277990adb0cf49ccad04faa6c45008c5
[ "Markdown", "JavaScript" ]
4
Markdown
otaviopace/socketio-chat-example
690a4be5e6c657300c0258f93a71ab1d1f836707
57f14ae3d78b39b592af53560cb2ff42c090791f
refs/heads/master
<repo_name>gummiks/diffuser_k2_followup<file_sep>/src/gkastro.py #!/usr/bin/python # -*- coding: utf-8 -*- # File: gkastro.py # Created: 2016-03-31 by gks """ Description: Helpful for astronomy """ from __future__ import print_function import numpy as np import datetime import math import os norm_mean_sub = lambda x: x - np.nanmean(x) norm_mean = lambda x: x/np.nanmean(x) norm_median = lambda x: x/np.median(x) compactString = lambda string: string.replace(' ', '').replace('-', '').lower() cosd = lambda x : np.cos(np.deg2rad(x)) sind = lambda x : np.sin(np.deg2rad(x)) def make_dir(dirname,verbose=True): try: os.makedirs(dirname) if verbose==True: print("Created folder:",dirname) except OSError: if verbose==True: print(dirname,"already exists. Skipping") def round_sig(x, sig=2,return_round_to=False): """ Roundint to *sig* significant digits INPUT: x - number to round sig - significant digits """ if (np.isnan(x)) & (return_round_to==False): return 0. if (np.isnan(x)) & (return_round_to==True): return 0., 0 if (x==0.) & (return_round_to==False): return 0. if (x==0.) & (return_round_to==True): return 0., 0 round_to = sig-int(math.floor(np.log10(abs(x))))-1 num = round(x, round_to) if np.abs(num) > 1e-4: num = str(num).ljust(round_to+2,"0") # pad with 0 if needed else: num = "{0:.{width}f}".format(num,width=round_to-1) if return_round_to==False: return num #return round(x, round_to) else: return num, round_to #return round(x,round_to), round_to
9127fe6f9a755e21b28f85cd9bbfb41e07517b46
[ "Python" ]
1
Python
gummiks/diffuser_k2_followup
79d788a68ef6e0d0b31ad3d3ce46c215ee94447b
44acc96dfa2135a649b10a846975db779f0b47af
refs/heads/master
<file_sep>import React from 'react'; import { Grid, Button, Typography, Toolbar, AppBar } from "@material-ui/core"; import pokeball from "./pokeball.png"; import mypoke from "./fight.png"; import Swal from 'sweetalert2' const catchList = JSON.parse(localStorage.getItem('myData')) || []; const MyPokemon = () => { console.log(catchList); const remove = () => { const done = localStorage.removeItem('myData'); Swal.fire({ // Swal Setting's title: 'Namaste!', text: 'You released all your Pokemons!', icon: 'success' }).then((done) => { // Reload the Page window.location.reload(); }); } return ( <React.Fragment> <AppBar position="fixed" color="primary" className="appBar "> <Toolbar> <a href="/pokemon-pokeapi"><img src={pokeball} alt="hompage" /></a> <a href="/myPokemon"><img className="tab-icon mg-left" alt="my-pokemon" src={mypoke} /></a> <Typography className="txt_desc-2">My Pokemon</Typography> </Toolbar> </AppBar> <br /><br /><br /><br /> <Grid container spacing={3} className="center" justify="center" alignItems="center"> {catchList.map(i => ( <Grid item xs={12} fluid> <img src={`https://pokeres.bastionbot.org/images/pokemon/${i.id}.png`} className="image_poke_2" alt="Pokemon" /> <Typography className="name-pokemon">{i.name}</Typography> </Grid> )) } <Button color="secondary" className="center" variant="contained" onClick={remove}>Release All Pokemon</Button> </Grid> </React.Fragment> ) }; export default MyPokemon;<file_sep>import React from 'react'; import Pokedex from "./Pokedex"; import Pokemon from "./Pokemon"; import MyPokemon from "./myPokemon"; import { Route, Switch } from "react-router-dom"; import "./style.css"; function App() { return ( <Switch> <Route exact path="/pokemon-pokeapi" render={(props) => <Pokedex {...props} />} /> <Route exact path="/myPokemon" render={(localStorage) => <MyPokemon {...localStorage} />} /> <Route exact path="/:pokemonId" render={(props) => <Pokemon {...props} />} /> </Switch> ); } export default App;
be34746306d00ba9bc0920e53a5c7ec6bdf56220
[ "JavaScript" ]
2
JavaScript
cleoputra/pokemon-pokeapi
5ef1031a31876bf4e60e600e8640f57a164e8691
64f8b5ab537e9f0d0bfb44caa7cca86ffbf5f7a4
refs/heads/master
<file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Picture.create!( :title => "Colored Strawberries", :artist => "Bill", :url => "http://www.lovethispic.com/uploaded_images/15792-Colored-Strawberries.jpg" ) Picture.create!( :title => "How to Prepare Strawberries", :artist => "Produce Made Simple", :url => "http://producemadesimple.ca/wp-content/uploads/2013/07/how-to-prepare-strawberries.jpg" ) Picture.create!( :title => "Chocolate Covered Strawberries Made In An Ice Cube Tray", :artist => "Haley", :url => "http://www.cheaprecipeblog.com/wp-content/uploads/2012/10/Chocolate-Strawberries-In-An-Ice-Cube-Tray-2.jpg" )
7892826620253b8e36b7d1c42e1a162bab6f622e
[ "Ruby" ]
1
Ruby
margaretyjkim/photogur
5867312061d21bcd148c9a15eebc577302503b30
c26446771ee8971e5156e70c7408ffddc21c5b68
refs/heads/main
<file_sep><?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Modelos\Comentario; use App\Modelos\Persona; use App\Modelos\Producto; class ComentarioController extends Controller { public function comentuser($id=null){ $producto= new Producto(); if (Persona::find($id)){ $comentarios = $Comentarios::table(Comentario) ->join(Persona, 'comentarios.persona_id', '=', 'personas.id') ->join(Producto, 'comentarios.producto_id', '=', 'productos.id') ->select('personas.nombre', 'productos.nombre', 'comentarios.titulo','comentarios.comentario') ->where('personas.id','=',$id) ->get(); return response()->json(["Comentarios del usuario"=>$comentarios],200); } return response()->json(["No se encontro el usuario"],200); } }
097fb700ce56b3c856b41496bbc6828031946181
[ "PHP" ]
1
PHP
Cesar-D56/ActividadLaravel
0f64248390e0ac1d0f6ccc6993cf0f8e20c59d2e
47433fd6c1d6a10040ea8d00ba909311819591be
refs/heads/master
<file_sep>class Post < ActiveRecord::Base attr_accessible :body, :title has_many :comments belongs_to :user validates :title, :presence => true validates :body, :presence => true validates :user_id, presence: true end
56f6e4a902d07a3d19e6652fd6d30ffa9d836989
[ "Ruby" ]
1
Ruby
liangkaile/MiniBlog-AuthorizationPractice
94fe5dc02d269ed84135ba420c387f6586e512fb
a34c767afd6f0d4a59fdbd349ed36b7792e2774c
refs/heads/master
<repo_name>djllap/crackin-the-code-interview<file_sep>/Ch 2 - Linked Lists/2.1.rb # Write the code to remove duplicates from an unsorted Linked List # FOLLOW UP: Solve without using a temporary memory buffer require_relative './linkedList.rb' l = Linked_List.new l.insert('hi') l.insert('ho') l.insert('awesome') l.insert('beef') l.insert('hi') l.insert('hi') l.insert('awesome') def remove_with_buffer(list) prev = list.head buffer = [prev.val] while (prev and prev.next) do node = prev.next if buffer.include? node.val prev.next = node.next else buffer.push(node.val) end prev = prev.next end end def remove_without_buffer (list) node = list.head while node runner = node while runner and runner.next if runner.next.val == node.val runner.next = runner.next.next end runner = runner.next end node = node.next end end <file_sep>/Ch 2 - Linked Lists/2.6.rb # Given a circular linked list, implement an algorithm which # returns the node at the beginning of the loop. # # DEFINITION: # Circular linked list: A (corrupt) linked list in which a node's # next pointer points to an earlier node, so as to make a loop # in the linked list def findLoopBeginning(list) slow = fast = list.head while fast.next slow = slow.next fast = fast.next.next break if slow == fast end return unless slow == fast tracer = list.head until tracer == slow slow = slow.next tracer = tracer.next end slow end <file_sep>/Ch 1 - Strings/1.5.rb # Implement a method to perform basic string compression # using the counts of repeated characters. For instance, # the string 'aabcccccaaa' would become 'a2b1c5a3'. If the # compressed string would not become smaller than the original # string, return the original string. You can assume the string # only has upper and lowercase letters a-z. def compress str comp = '' currChar = str[0] i = 1 count = 1 while i < str.length if str[i] == currChar i += 1 count += 1 else comp += "#{currChar}#{count}" count = 0 currChar = str[i] i += 1 end end comp += "#{currChar}#{count+1}" str.length > comp.length ? comp : str end p compress('aaaabbbbbbbbcca')<file_sep>/Ch 2 - Linked Lists/linkedList.rb class Node attr_accessor :val, :next def initialize(val, next_node) @val = val @next = next_node end end class Linked_List attr_accessor :head def insertAtHead(val) @head = Node.new(val, @head) end def insertAtTail(val) unless @head return insertAtHead(val) end node = @head while node.next node = node.next end node.next = Node.new(val, nil) end def print node = @head str = "#{node.val}" while (node = node.next) do str += " -> #{node.val}" end p str end end<file_sep>/Ch 1 - Strings/1.1.rb # Implement an algorithm to determine if a string has all unique characters def unique? str [*'a'..'z', *'A'..'Z'].none? {|c| str.count(c) > 1} end <file_sep>/Ch 2 - Linked Lists/2.2.rb # Implement an algorithm to find the nth to last element of a linked list def nth_from_last list, n node = nth = list.head n.times do raise RuntimeError.new "No nth element present. List too short." unless node node = node.next end while (node) node = node.next nth = nth.next end nth.val end <file_sep>/Ch 1 - Strings/1.5.js // Implement a method to perform basic string compression // using the counts of repeated characters. For instance, // the string 'aabcccccaaa' would become 'a2b1c5a3'. If the // compressed string would not become smaller than the original // string, return the original string. You can assume the string // only has upper and lowercase letters a-z. function compressStr(str) { if (!str.length) return str; let currChar = str[0]; let currCount = 1; let comp = ''; let i = 1; while(i < str.length) { if (str[i] === currChar) { currCount++; } else { comp += `${currChar}${currCount+1}`; currCount = 0; currChar = str[i]; } i++; } if (currCount) comp += `${currChar}${currCount}`; return (str.length <= comp.length) ? str : comp; } console.log(compressStr('ljnaeflknaefeeeeeeeeeeeeeeee'));<file_sep>/Ch 1 - Strings/1.1.js // Implement an algorithm to determine if a string has all unique characters const hasOnlyUniqueChars = (str) => { const map = {}; for (let i=0; i<str.length; i++) { const char = str[i]; if (map[char]) return false; map[char] = true; } return true; }; <file_sep>/Ch 2 - Linked Lists/2.4.rb # Write code to partition a linked list around a value x, such # that all nodes less than x come before all nodes greater or # equal to x. def partitionList list, x prev = list.head node = prev.next while node if (node.val < x) prev.next = node.next node.next = list.head list.head = node node = prev.next else prev = prev.next node = prev ? prev.next : nil end end end <file_sep>/Ch 1 - Strings/1.7.rb # Write an algorithm such that if an element in a MxN matrix # is 0, its entire row and column are set to 0. def matrixZero m rows = [] cols = [] (0..m.length-1).each { |row| (0..m[0].length-1).each { |col| if m[row][col] == 0 rows.push(row) unless rows.include?(m[row][col]) cols.push(col) unless cols.include?(m[row][col]) end } } (0..m.length-1).each { |row| (0..m[0].length-1).each { |col| if rows.include?(row) or cols.include?(col) m[row][col] = 0 end } } m end matrix = [ [1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1] ] p matrixZero(matrix)<file_sep>/Ch 1 - Strings/1.4.rb # Write a method to replace all spaces in a string with '%20'. # You may assume that the string has sufficient space at the # end of the string to hold the extra characters, and that you # are given the 'true' length of the string # # EXAMPLE # input: '<NAME> ', 13 # output: Mr%20John%20Smith def urlize str, len (0..str.length-1).each {|i| if str[i] == ' ' j = str.length - 1 while j > i + 2 str[j] = str[j-2]; j -= 1 end str[i] = '%' str[i+1] = '2' str[i+2] = '0' end } str end <file_sep>/Ch 2 - Linked Lists/2.5.rb # You have two numbers represented by a linked list, # where each node contains a single digit. The digits # are stored in reverse order, such that the 1's digit # is at the head of the list. Write a function that # adds the two numbers and returns the sum as a linked list def sumTwoLists l1, l2 n1 = l1.head n2 = l2.head carry = 0 sumList = Linked_List.new while n1 or n2 v1 = n1 ? n1.val : 0 v2 = n2 ? n2.val : 0 sum = v1 + v2 + carry digit = (sum > 9) ? sum % 10 : sum carry = (sum > 9) ? 1 : 0 sumList.insertAtTail(digit) n1 = n1.next if n1 n2 = n2.next if n2 end sumList.insertAtTail(carry) if carry > 0 sumList.print end <file_sep>/Ch 1 - Strings/1.8.rb # Assume you have a method substring? which checks if one # word is a substring of another. Given two strings, s1 and # s2, write code to check if s2 is a rotation of s1 using only # one call to substring? def rotation? s1, s2 substring?(s1*2, s2) end <file_sep>/Ch 1 - Strings/1.1a.rb # Implement an algorithm to determine if a string has all # unique characters without using additional data structures. def unique? string string.each_char{|c| return false if string.index(c) != string.rindex(c)} true end <file_sep>/Ch 1 - Strings/1.3.rb # Given two strings, write a method to decide if one is a permutation of the other def isPermutation? str1, str2 str1.length == str2.length and str1.sum == str2.sum end <file_sep>/Ch 2 - Linked Lists/2.3.rb # Implement an algorithm to delete a node in the middle of # a singly linked list given access only to that node. def deleteNode node node.val = node.next.val node.next = node.next.next end<file_sep>/Ch 1 - Strings/1.6.rb # Given an image represented by a NxN matrix, where # each pixel in the image is 4 bytes, write a method # to rotate the image by 90 degrees. Can you do this in place? def rotate matrix min = 0; max = matrix.length-1 while min < max and max >= matrix.length/2 dif = 0 while min + dif < max t1 = matrix[min][min+dif] t2 = matrix[min+dif][max] t3 = matrix[max][max-dif] t4 = matrix[max-dif][min] matrix[min][min+dif] = t4 matrix[min+dif][max] = t1 matrix[max][max-dif] = t2 matrix[max-dif][min] = t3 dif += 1 end min += 1 max -= 1 end matrix end m = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] p rotate(m)
7a6f6aeed6a32422f5c34271ee0e9af4d16ec126
[ "JavaScript", "Ruby" ]
17
Ruby
djllap/crackin-the-code-interview
399149ce41d05e30ccceef46100723cc5376dfa8
af3001fe44445bfb3d68d1acffb653409e4e4133
refs/heads/master
<repo_name>jackshing326/GenericDelegateEvent<file_sep>/GenericDelegateEvent/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Collections; using System.Threading; namespace GenericDelegateEvent { //http://w-tay.blogspot.com/2016/07/c-delegate-and-event.html public partial class Form1 : Form { //Generic GenericSetOne<int> _GenericSet; GenericSetTwo<int, Product> _GenericSetTwo; //Delegate public delegate void SDelegate(); //DelegateEvent public event SDelegate _SDelegate; //Thread //要用這個Lock就會有順續 static Object obj = new Object(); Thread _t = null; Thread _t2 = null; Task[] taskArray = null; public delegate void UpdateUI(Control _Control, string Context); //public event UpdateUI _UpdateUIEvent; public Form1() { InitializeComponent(); } public void UpdateText(Control _ct, string Context) { if (_ct.InvokeRequired) { UpdateUI _UpdateUI = new UpdateUI(UpdateText); // _UpdateUI.Invoke(_ct, Context); _ct.Invoke(_UpdateUI, _ct, Context); } else { tb_Context.Text += Context + " \r\n"; } } void init() { _GenericSet = new GenericSetOne<int>(); _GenericSetTwo = new GenericSetTwo<int, Product>(); } void Sett() { for (int index = 0; index < 10; index++) { _GenericSet.Add(index); } for (int index = 0; index < 10; index++) { Product _pt = new Product(); _pt.ItemNo = index + 1; _pt.Price = (float)(index + 1) * (float)(1.12); _pt.Name = "This is " + (index + 1).ToString() + "th Product"; _GenericSetTwo.Add(index, _pt); } } private void btn_Run_Click(object sender, EventArgs e) { tb_Context.Text = ""; string Select = cb_Select.SelectedItem.ToString(); UpdateText(this.tb_Context, Select); if (Select == "Generic" || Select == "Delegate" || Select == "DelegateEvent") { int DicAll = _GenericSetTwo.GetCount(); int ListAll = _GenericSet.GetCount(); for (int index = 0; index < ListAll; index++) { int Result = _GenericSet.Get(index); UpdateText(this.tb_Context, Result.ToString()); } UpdateText(this.tb_Context, "--------------------------"); for (int index = 0; index < ListAll; index++) { Product Result = _GenericSetTwo.Get(index); UpdateText(this.tb_Context, Result.ItemNo.ToString()); UpdateText(this.tb_Context, Result.Name.ToString()); UpdateText(this.tb_Context, Result.Price.ToString()); } } else { if (Select == "Thread") { // _t.Start(); // _t.Join(); // _t2.Start(); for (int i = 0; i < 10; i++) { _t = new Thread(NameThreadA); _t.Start("This is _t " + i.ToString() + "th Thread"); _t2 = new Thread(NameThreadB); _t2.Start("This is _t2 " + i.ToString() + "th Thread"); } } else if (Select == "ThreadPool") { for (int i = 0; i < 10; i++) { object _oo = "This is " + i.ToString() + "th Thread"; ThreadPool.QueueUserWorkItem(new WaitCallback(NameThread), "This is " + i.ToString() + "th Thread"); } } else if (Select == "Task") { taskArray = new Task[10]; for (int i = 0; i < 10; i++) { object oo = "This is taskA " + i.ToString() + "th Thread"; taskArray[i] = new Task(() => NameThread(oo)); taskArray[i].Start(); } } } } private void cb_Select_SelectedIndexChanged(object sender, EventArgs e) { if (cb_Select.SelectedItem.ToString() == "Generic") { init(); Sett(); } else if (cb_Select.SelectedItem.ToString() == "Delegate") { SDelegate _initDelegate = new SDelegate(init); SDelegate _SettDelegate = new SDelegate(Sett); } else if (cb_Select.SelectedItem.ToString() == "DelegateEvent") { _SDelegate += init; _SDelegate += Sett; _SDelegate.Invoke(); } else if (cb_Select.SelectedItem.ToString() == "Thread") { } else if (cb_Select.SelectedItem.ToString() == "Task") { } } public void NameThread(object Context) { lock (obj) { UpdateText(this.tb_Context, Context.ToString()); } } public void NameThreadA(object Context) { lock (obj) { UpdateText(this.tb_Context, Context.ToString()); } _t2.Join(); } public void NameThreadB(object Context) { lock (obj) { UpdateText(this.tb_Context, Context.ToString()); } } public void ForThread() { lock (obj) { UpdateText(this.tb_Context, "For First"); init(); Sett(); int DicAll = _GenericSetTwo.GetCount(); int ListAll = _GenericSet.GetCount(); for (int index = 0; index < ListAll; index++) { int Result = _GenericSet.Get(index); UpdateText(this.tb_Context, Result.ToString()); } UpdateText(this.tb_Context, "--------------------------"); for (int index = 0; index < ListAll; index++) { Product Result = _GenericSetTwo.Get(index); UpdateText(this.tb_Context, Result.ItemNo.ToString()); UpdateText(this.tb_Context, Result.Name.ToString()); UpdateText(this.tb_Context, Result.Price.ToString()); } } } public void ForThread2() { lock (obj) { UpdateText(this.tb_Context, "For Second"); //init(); //Sett(); int DicAll = _GenericSetTwo.GetCount(); int ListAll = _GenericSet.GetCount(); for (int index = 0; index < ListAll; index++) { int Result = _GenericSet.Get(index); UpdateText(this.tb_Context, Result.ToString()); } UpdateText(this.tb_Context, "--------------------------"); for (int index = 0; index < ListAll; index++) { Product Result = _GenericSetTwo.Get(index); UpdateText(this.tb_Context, Result.ItemNo.ToString()); UpdateText(this.tb_Context, Result.Name.ToString()); UpdateText(this.tb_Context, Result.Price.ToString()); } } } public void ForTask() { UpdateText(this.tb_Context, "For First"); init(); Sett(); int DicAll = _GenericSetTwo.GetCount(); int ListAll = _GenericSet.GetCount(); for (int index = 0; index < ListAll; index++) { int Result = _GenericSet.Get(index); UpdateText(this.tb_Context, Result.ToString()); } UpdateText(this.tb_Context, "--------------------------"); for (int index = 0; index < ListAll; index++) { Product Result = _GenericSetTwo.Get(index); UpdateText(this.tb_Context, Result.ItemNo.ToString()); UpdateText(this.tb_Context, Result.Name.ToString()); UpdateText(this.tb_Context, Result.Price.ToString()); } } public void ForTask2() { UpdateText(this.tb_Context, "For Second"); //init(); //Sett(); int DicAll = _GenericSetTwo.GetCount(); int ListAll = _GenericSet.GetCount(); for (int index = 0; index < ListAll; index++) { int Result = _GenericSet.Get(index); UpdateText(this.tb_Context, Result.ToString()); } UpdateText(this.tb_Context, "--------------------------"); for (int index = 0; index < ListAll; index++) { Product Result = _GenericSetTwo.Get(index); UpdateText(this.tb_Context, Result.ItemNo.ToString()); UpdateText(this.tb_Context, Result.Name.ToString()); UpdateText(this.tb_Context, Result.Price.ToString()); } } public void ForThreadPool(object _a) { lock (obj) { init(); Sett(); int DicAll = _GenericSetTwo.GetCount(); int ListAll = _GenericSet.GetCount(); for (int index = 0; index < ListAll; index++) { int Result = _GenericSet.Get(index); UpdateText(this.tb_Context, Result.ToString()); } UpdateText(this.tb_Context, "--------------------------"); for (int index = 0; index < ListAll; index++) { Product Result = _GenericSetTwo.Get(index); UpdateText(this.tb_Context, Result.ItemNo.ToString()); UpdateText(this.tb_Context, Result.Name.ToString()); UpdateText(this.tb_Context, Result.Price.ToString()); } } } } } <file_sep>/GenericDelegateEvent/CollectionMethod.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenericDelegateEvent { public class GenericSetOne<T> { private List<T> GenericSetList = new List<T>(); public void Add(T item) { GenericSetList.Add(item); } public bool Del(T item) { return GenericSetList.Remove(item); } public T Get(T item) { if (GenericSetList.Contains(item)) { return item; } else { return default(T); } } public int GetCount() { return GenericSetList.Count; } } public class GenericSetTwo<T, R> { private Dictionary<T, R> GenericSetDictionary = new Dictionary<T, R>(); public void Add(T item, R _r) { GenericSetDictionary.Add(item, _r); } public bool Del(T item) { return GenericSetDictionary.Remove(item); } public R Get(T item) { if (GenericSetDictionary.ContainsKey(item)) { return GenericSetDictionary[item]; } else { return default(R); } } public int GetCount() { return GenericSetDictionary.Count; } } public class Product { public int ItemNo; public float Price; public string Name; } }
a0b3944c5b2a86997881af84bd28e7593c927aba
[ "C#" ]
2
C#
jackshing326/GenericDelegateEvent
bf4c1c285faaa27177a36bed1915a83c9f124c47
5d5d51e1209cbe3e48bedce80d7649571492e9a0
refs/heads/master
<repo_name>ljtinney/phrg-bachelor-todo-pca-001<file_sep>/lib/bachelor.rb def get_first_name_of_season_winner(data, season) data[season].each do |contestant| if contestant ["status"] == "Winner" return contestant["name"].split.first end end end def get_contestant_name(data, occupation) contestant_name = " " data.each do |season, people| people.each do |contestant| if contestant["occupation"] == occupation contestant_name = contestant["name"] end end end contestant_name end def count_contestants_by_hometown(data, hometown) # count = 0 # data.each do |season, people| # people.each do |contestant| # if contestant["hometown"] == hometown # count += 1 # end # end # end # count data.inject(0) do |count_total, (_season, people)| count_total + people.inject(0) do |count_per_season, contestant| contestant["hometown"] == hometown ? count_per_season + 1 : count_per_season end end end def get_occupation(data, hometown) data.each do |season, people| people.each do |contestant| if contestant["hometown"] == hometown return contestant["occupation"] end end end end def get_average_age_for_season(data, season) count = 0 data[season].each do |contestant| contestant_age = contestant["age"].to_i count = contestant_age + count end puts count (count.to_f / data[season].length).round end
3df232bdd643d853166960264c61d48961c73c78
[ "Ruby" ]
1
Ruby
ljtinney/phrg-bachelor-todo-pca-001
96946e5936c77839ba8ab483046bc40ed8d5ad8b
757902819517e6ead266dc4ee7fce7057d88ae85
refs/heads/master
<file_sep>let hw: string = "Hello, World"; let myname: string = "Hungggggg"; console.log(hw, myname);<file_sep>"use strict"; var hw = "Hello, World"; var myname = "Hungggggg"; console.log(hw, myname);
943a0492bb5adcb3fdccd0b10fe887f6fc84e11d
[ "JavaScript", "TypeScript" ]
2
TypeScript
dinhh23/typescript
e680fd52715d0b6fba3c1e84a71c5552851545af
de90e9ccd3a776a5d18bf7cc26c5b53d8d3c5ae2
refs/heads/master
<repo_name>carlosmuvi/serverless-bootie<file_sep>/handlers/index.js export {default as hello} from './hello'; export {default as getEvents} from './get-events';<file_sep>/services/MeetupEventService.js import EventService from './EventService'; import getMeetup from 'meetup-api'; import Event from '../domain/Event'; const meetup = getMeetup({ key: '<KEY>' }); const SOURCE_NAME = "meetup"; export default class MeetupEventService extends EventService { getEvents({query}) { return new Promise((resolve, reject) => { meetup.getOpenEvents({ lat: query.lat, lon: query.lng, time: this._getFormattedTimeInterval(query), page: 200 }, this._onMeetupApiResponse(resolve, reject)); }); } _getFormattedTimeInterval(query) { return query.startTime + "," + query.endTime; } _onMeetupApiResponse(resolve, reject) { return (error, response) => { if (error) { reject(error); } else { resolve(this._mapToDomainModel(response)); } }; } _mapToDomainModel(response) { return response.results .filter(item => item.venue) .filter(item => item.venue.lat != 0 && item.venue.lon != 0) .map(item => { return new Event( `${SOURCE_NAME}-${item.id}`, item.name, item.event_url, item.time, {lat: item.venue.lat, lng: item.venue.lon}, item.yes_rsvp_count + item.maybe_rsvp_count, 5, SOURCE_NAME, item.venue.address_1 ) }) } }<file_sep>/handlers/get-events.js import moment from 'moment'; import MeetupEventService from '../services/MeetupEventService'; import EventbriteEventService from '../services/EventbriteEventService'; import FacebookEventService from '../services/FacebookEventService'; const MEETUP = 'meetup'; const EVENTBRITE = 'eventbrite'; const FACEBOOK = 'facebook'; const DEFAULT_PROVIDERS = `${EVENTBRITE},${MEETUP},${FACEBOOK}`; function getEventsHandler(event, context, callback) { const query = event.query; const {providers, startTime, endTime} = query; if (!endTime) { query.startTime = moment(parseInt(startTime)).startOf('day').valueOf(); query.endTime = moment(parseInt(startTime)).endOf('day').valueOf(); } const providerServices = getProviderServices(providers || DEFAULT_PROVIDERS); Promise.all(providerServices.map(service => { return service.getEvents({query}); })).then(providerResponses => { callback(null, providerResponses.reduce((acc, events) => { return acc .concat(events) .sort((a, b) => b.time - a.time) }, [])); }).catch(error => { callback(null, error); }); } function getProviderServices(providers) { const providersArray = providers.split(','); return providersArray.map(p => getEventProvider(p.trim())); } function getEventProvider(provider) { let service; switch (provider) { case MEETUP: service = new MeetupEventService(); break; case EVENTBRITE: service = new EventbriteEventService(); break; case FACEBOOK: service = new FacebookEventService(); break; default: throw new Error(`Unrecognized provider: ${provider}`); } return service; } export default getEventsHandler;
11ceab2d87c015f961a9922236737284544028ec
[ "JavaScript" ]
3
JavaScript
carlosmuvi/serverless-bootie
88e8cc21f0561ff0a4054da21e98da71fe0d9ddc
d3efa138bfb7d00c5edf4c555c962d4eef289c4c
refs/heads/master
<file_sep>package main import ( "fmt" "os" "github.com/juju/cmd" ) func main() { ctx, err := cmd.DefaultContext() if err != nil { fmt.Fprintf(os.Stderr, "failed to create command context: %v", err) os.Exit(1) } exitcode := cmd.Main(newExtMigrateCommand(), ctx, os.Args[1:]) os.Exit(exitcode) } <file_sep>package main import ( "time" "github.com/juju/cmd" "github.com/juju/errors" "github.com/juju/juju/api" "github.com/juju/juju/api/controller" "github.com/juju/juju/api/migrationmaster" "github.com/juju/juju/api/watcher" "github.com/juju/juju/cmd/modelcmd" coremigration "github.com/juju/juju/core/migration" "gopkg.in/juju/names.v2" "gopkg.in/macaroon.v1" ) func newExtMigrateCommand() cmd.Command { return modelcmd.WrapController(&extMigrateCommand{}) } // extMigrateCommand initiates a model migration. type extMigrateCommand struct { modelcmd.ControllerCommandBase model string targetController string machineTag names.MachineTag machinePassword string machineNonce string } type migrateAPI interface { InitiateMigration(spec controller.MigrationSpec) (string, error) } const migrateDoc = ` Runs an externally controlled migration ` // Info implements cmd.Command. func (c *extMigrateCommand) Info() *cmd.Info { return &cmd.Info{ Name: "migrate", Args: "<model-name> <target-controller-name> <machine-tag> <machine-password> <machine-nonce>", Purpose: "Migrate a hosted model to another controller.", Doc: migrateDoc, } } // Init implements cmd.Command. func (c *extMigrateCommand) Init(args []string) error { if len(args) < 1 { return errors.New("model not specified") } if len(args) < 2 { return errors.New("target controller not specified") } if len(args) < 3 { return errors.New("machine tag not specified") } if len(args) < 4 { return errors.New("machine password not specified") } if len(args) < 5 { return errors.New("machine nonce not specified") } if len(args) > 5 { return errors.New("too many arguments specified") } c.model = args[0] c.targetController = args[1] // This is just for testing purposes. A real external migration // tool would ssh a binary (perhaps itself) over to a controller // host and run it after the migration had been triggered. This // could then retrieve the controller machine creds from the local // agent conf and connect to the source controller itself. It // would get the target controller's API details via the // MigrationStatus API. tag, err := names.ParseMachineTag(args[2]) if err != nil { return err } c.machineTag = tag c.machinePassword = args[3] c.machineNonce = args[4] return nil } func (c *extMigrateCommand) modelUUID() (string, error) { modelUUIDs, err := c.ModelUUIDs([]string{c.model}) if err != nil { return "", errors.Trace(err) } return modelUUIDs[0], nil } func (c *extMigrateCommand) getMigrationSpec() (*controller.MigrationSpec, error) { store := c.ClientStore() modelUUID, err := c.modelUUID() if err != nil { return nil, err } controllerInfo, err := store.ControllerByName(c.targetController) if err != nil { return nil, err } accountInfo, err := store.AccountDetails(c.targetController) if err != nil { return nil, err } var macs []macaroon.Slice if accountInfo.Macaroon != "" { mac := new(macaroon.Macaroon) if err := mac.UnmarshalJSON([]byte(accountInfo.Macaroon)); err != nil { return nil, errors.Annotate(err, "unmarshalling macaroon") } macs = []macaroon.Slice{{mac}} } return &controller.MigrationSpec{ ExternalControl: true, ModelUUID: modelUUID, TargetControllerUUID: controllerInfo.ControllerUUID, TargetAddrs: controllerInfo.APIEndpoints, TargetCACert: controllerInfo.CACert, TargetUser: accountInfo.User, TargetPassword: accountInfo.Password, TargetMacaroons: macs, }, nil } func (c *extMigrateCommand) connectMigrationMaster() (*migrationmaster.Client, error) { store := c.ClientStore() controllerInfo, err := store.ControllerByName(c.ControllerName()) if err != nil { return nil, err } modelUUID, err := c.modelUUID() if err != nil { return nil, err } apiInfo := &api.Info{ Addrs: controllerInfo.APIEndpoints, CACert: controllerInfo.CACert, ModelTag: names.NewModelTag(modelUUID), Tag: c.machineTag, Password: <PASSWORD>, Nonce: c.machineNonce, } apiConn, err := api.Open(apiInfo, api.DialOpts{}) if err != nil { return nil, err } return migrationmaster.NewClient(apiConn, watcher.NewNotifyWatcher), nil } // Run implements cmd.Command. func (c *extMigrateCommand) Run(ctx *cmd.Context) error { spec, err := c.getMigrationSpec() if err != nil { return err } api, err := c.NewControllerAPIClient() if err != nil { return err } id, err := api.InitiateMigration(*spec) if err != nil { return err } ctx.Infof("Migration started with ID %q", id) time.Sleep(5 * time.Second) masterClient, err := c.connectMigrationMaster() if err != nil { return err } ctx.Infof("Set phase to ABORT") err = masterClient.SetPhase(coremigration.ABORT) if err != nil { return err } ctx.Infof("Set phase to ABORTDONE") err = masterClient.SetPhase(coremigration.ABORTDONE) if err != nil { return err } return nil }
b467b9f0b27ebc019ac92dddb712ca60780c67d4
[ "Go" ]
2
Go
mjs/extmigration
47393b694a0f79329309b909b3e8be82d97fb193
cb22cb77adffcb841645fe8446b141257cd5474e
refs/heads/master
<repo_name>RalucaPenciuc/Homework-Management2<file_sep>/LAB9-2/validation/NotaValidator.cs using LAB9_2.domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.validation { class NotaValidator : IValidator<Nota> { public void Validate(Nota nota) { if (nota.Id.Key.Id == null || nota.Id.Key.Id.Equals("")) throw new ValidationException("ID Student invalid! \n"); if (nota.Id.Value.Id == null || nota.Id.Value.Id.Equals("")) throw new ValidationException("ID Tema invalid! \n"); if (nota.Valoare < 0 || nota.Valoare > 10) throw new ValidationException("Nota invalida! \n"); if (nota.SaptamanaPredare < 1 || nota.SaptamanaPredare > 14) throw new ValidationException("Saptamana de predare invalida! \n"); } } } <file_sep>/LAB9-2/validation/StudentValidator.cs using LAB9_2.domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.validation { class StudentValidator : IValidator<Student> { public void Validate(Student student) { if (student.Id == null || student.Id.Equals("")) throw new ValidationException("ID invalid! \n"); if (student.Nume == null || student.Nume.Equals("")) throw new ValidationException("Nume invalid! \n"); if (student.Grupa <= 110 || student.Grupa >= 938) throw new ValidationException("Grupa invalida! \n"); } } } <file_sep>/LAB9-2/repository/AbstractFileRepository.cs using LAB9_2.domain; using LAB9_2.repository; using LAB9_2.validation; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.repository { abstract class AbstractFileRepository<ID, E> : AbstractCRUDRepository<ID, E> where E : IHasID<ID> { protected string filename; public AbstractFileRepository(IValidator<E> validator, string filename) : base(validator) { this.filename = filename; } protected abstract void LoadFromFile(); protected abstract void WriteToFile(E entity); protected abstract void WriteToFileAll(); public new List<E> FindAll() { return base.FindAll(); } public E JustSave(E entity) { E result = base.Save(entity); return result; } public new E Save(E entity) { E result = base.Save(entity); if (result == null) WriteToFile(entity); return result; } public new E Delete(ID Id) { E result = base.Delete(Id); WriteToFileAll(); return result; } public new E Update(E entity) { E result = base.Update(entity); WriteToFileAll(); return result; } } } <file_sep>/LAB9-2/repository/NotaRepository.cs using LAB9_2.domain; using LAB9_2.validation; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.repository { class NotaRepository : AbstractCRUDRepository<KeyValuePair<Student, Tema>, Nota> { public NotaRepository(IValidator<Nota> validator) : base(validator) { } } } <file_sep>/LAB9-2/repository/TemaFileRepository.cs using LAB9_2.domain; using LAB9_2.validation; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace LAB9_2.repository { class TemaFileRepository : AbstractFileRepository<string, Tema> { public TemaFileRepository(IValidator<Tema> validator, string filename) : base(validator, filename) { LoadFromFile(); } protected override void LoadFromFile() { using (StreamReader streamReader = new StreamReader(filename)) { string line; while( (line = streamReader.ReadLine()) != null) { string[] fields = line.Split(';'); Tema tema = new Tema(fields[0], fields[1], int.Parse(fields[2]), int.Parse(fields[3])); JustSave(tema); } streamReader.Close(); } } protected override void WriteToFile(Tema entity) { using (StreamWriter streamWriter = new StreamWriter(filename, true)) { string tema = entity.Id + ";" + entity.Descriere + ";" + entity.Deadline + ";" + entity.Startline; streamWriter.WriteLine(tema); streamWriter.Flush(); } } protected override void WriteToFileAll() { using (StreamWriter streamWriter = new StreamWriter(filename, true)) { List<Tema> teme = FindAll(); foreach (Tema entity in teme) { string tema = entity.Id + "," + entity.Descriere + "," + entity.Deadline + "," + entity.Startline; streamWriter.WriteLine(tema); } streamWriter.Flush(); } } } } <file_sep>/LAB9-2/domain/Nota.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.domain { class Nota : IHasID<KeyValuePair<Student, Tema>> { public KeyValuePair<Student, Tema> Id { get; set; } public double Valoare; public int SaptamanaPredare; public string Feedback; public Nota(KeyValuePair<Student, Tema> Id, double Valoare, int SaptamanaPredare, string Feedback) { this.Id = Id; this.Valoare = Valoare; this.SaptamanaPredare = SaptamanaPredare; this.Feedback = Feedback; } public override string ToString() { return "IdStudent<" + Id.Key.Id + "> IdTema<" + Id.Value.Id + "> Nota<" + Valoare + "> SaptamanaPredare<" + SaptamanaPredare + "> Feedback<" + Feedback + ">"; } } } <file_sep>/LAB9-2/Program.cs using LAB9_2.console; using LAB9_2.domain; using LAB9_2.repository; using LAB9_2.service; using LAB9_2.validation; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2 { class Program { static void Main(string[] args) { IValidator<Student> StudentValidator = new StudentValidator(); IValidator<Tema> TemaValidator = new TemaValidator(); IValidator<Nota> NotaValidator = new NotaValidator(); StudentFileRepository StudentRepo = new StudentFileRepository(StudentValidator, "D:/Documente/ANUL 2/Semestrul 1/Metode Avansate De Programare/LABORATOARE/LAB9/LAB9-2/LAB9-2/studenti.txt"); TemaFileRepository TemaRepo = new TemaFileRepository(TemaValidator, "D:/Documente/ANUL 2/Semestrul 1/Metode Avansate De Programare/LABORATOARE/LAB9/LAB9-2/LAB9-2/teme.txt"); NotaFileRepository NotaRepo = new NotaFileRepository(NotaValidator, StudentRepo, TemaRepo, "D:/Documente/ANUL 2/Semestrul 1/Metode Avansate De Programare/LABORATOARE/LAB9/LAB9-2/LAB9-2/note.txt"); Service Serv = new Service(StudentRepo, TemaRepo, NotaRepo); UI Consola = new UI(Serv); Consola.Run(); ////------------------------ //List<Student> cars = new List<Student>(); //cars.Add(new Student("1", "ana", 221)); //cars.Add(new Student("2", "ana1", 222)); //cars.Add(new Student("3", "ana2", 221)); //cars.Add(new Student("4", "ana3", 223)); //cars.Add(new Student("5", "ana4", 221)); //cars.Add(new Student("6", "ana5", 222)); //IEnumerable<IGrouping<int, Student>> carGroups = cars.GroupBy(c => c.Grupa); ////----------------- //foreach (IGrouping<int, Student> g in carGroups) //{ // Console.WriteLine(g.Key); // foreach (Student c in g) // Console.WriteLine(c); //} //Console.ReadKey(); } } } <file_sep>/LAB9-2/repository/StudentFileRepository.cs using LAB9_2.domain; using LAB9_2.validation; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace LAB9_2.repository { class StudentFileRepository : AbstractFileRepository<string, Student> { public StudentFileRepository(IValidator<Student> validator, string filename) : base(validator, filename) { LoadFromFile(); } protected override void LoadFromFile() { using (StreamReader streamReader = new StreamReader(filename)) { string line; while ( (line = streamReader.ReadLine()) != null) { string[] fields = line.Split(';'); Student student = new Student(fields[0], fields[1], int.Parse(fields[2])); JustSave(student); } streamReader.Close(); } } protected override void WriteToFile(Student entity) { using (StreamWriter streamWriter = new StreamWriter(filename, true)) { string student = entity.Id + ";" + entity.Nume + ";" + entity.Grupa.ToString(); streamWriter.WriteLine(student); streamWriter.Flush(); } } protected override void WriteToFileAll() { using (StreamWriter streamWriter = new StreamWriter(filename, true)) { List<Student> studenti = FindAll(); foreach (Student entity in studenti) { string student = entity.Id + "," + entity.Nume + "," + entity.Grupa.ToString(); streamWriter.WriteLine(student); } streamWriter.Flush(); } } } } <file_sep>/LAB9-2/console/UI.cs using LAB9_2.domain; using LAB9_2.service; using LAB9_2.validation; using System; using System.Collections.Generic; using System.Linq; namespace LAB9_2.console { class UI { private Service Serv; public UI(Service Serv) { this.Serv = Serv; } public void PrintMenu() { Console.WriteLine("11. Afiseaza toti studentii."); Console.WriteLine("12. Afiseaza toate temele."); Console.WriteLine("13. Afiseaza toate notele"); Console.WriteLine("21. Adauga un nou student."); Console.WriteLine("22. Adauga o tema noua."); Console.WriteLine("23. Adauga o nota unui student pentru o tema."); Console.WriteLine("3. Sterge un student existent."); Console.WriteLine("4. Actualizeaza datele unui student."); Console.WriteLine("5. Prelungeste deadline-ul unei teme."); Console.WriteLine("61. Notele la o anumita tema."); Console.WriteLine("62. Notele unui student."); Console.WriteLine("63. Notele studentilor dintr-o grupa, la o tema."); Console.WriteLine("64. Notele dintr-o anumita perioada."); Console.WriteLine("71. Nota de laborator a fiecarui student."); Console.WriteLine("72. Cea mai grea tema."); Console.WriteLine("73. Studentii care pot intra in examen."); Console.WriteLine("74. Studentii care au predat la timp toate temele."); Console.WriteLine("0. EXIT \n"); } public void UiPrintAllStudents() { foreach(Student student in Serv.FindAllStudents()) { Console.WriteLine(student); } Console.WriteLine("\n"); } public void UiPrintAllTeme() { foreach(Tema tema in Serv.FindAllTeme()) { Console.WriteLine(tema); } Console.WriteLine("\n"); } public void UiPrintAllNote() { foreach(Nota nota in Serv.FindAllNote()) { Console.WriteLine(nota); } Console.WriteLine("\n"); } public void UiSaveStudent() { Console.Write("Introduceti ID-ul studentului: "); String Id = Console.ReadLine(); Console.Write("Introduceti numele studentului: "); String Nume = Console.ReadLine(); Console.Write("Introduceti grupa studentului: "); int.TryParse(Console.ReadLine(), out int Grupa); if (Serv.SaveStudent(Id, Nume, Grupa) != 0) Console.WriteLine("Student adaugat cu succes! \n"); } public void UiSaveTema() { Console.Write("Introduceti ID-ul temei: "); String Id = Console.ReadLine(); Console.Write("Introduceti o descriere a temei: "); String Descriere = Console.ReadLine(); Console.Write("Introduceti saptamana deadline a temei: "); int.TryParse(Console.ReadLine(), out int Deadline); Console.Write("Introduceti saptamana startline a temei: "); int.TryParse(Console.ReadLine(), out int Startline); if (Serv.SaveTema(Id, Descriere, Deadline, Startline) != 0) Console.WriteLine("Tema adaugata cu succes! \n"); } public void UiSaveNota() { Console.Write("Introduceti ID-ul studentului: "); String IdStudent = Console.ReadLine(); Console.Write("Introduceti ID-ul temei: "); String IdTema = Console.ReadLine(); Console.Write("Introduceti valoarea notei: "); double.TryParse(Console.ReadLine(), out double Valoare); Console.Write("Introduceti saptamana de predare a temei: "); int.TryParse(Console.ReadLine(), out int Predata); Console.Write("Dati un feedback temei: "); String Feedback = Console.ReadLine(); int result = Serv.SaveNota(IdStudent, IdTema, Valoare, Predata, Feedback); if (result == 1) Console.WriteLine("Nota adaugata cu succes! \n"); else if (result == 0) Console.WriteLine("Nota existenta! \n"); else Console.WriteLine("Student sau tema inexistenta! \n"); } public void UiDeleteStudent() { Console.Write("Introduceti ID-ul studentului: "); String Id = Console.ReadLine(); if (Serv.DeleteStudent(Id) != 0) Console.WriteLine("Student sters cu succes! \n"); else Console.WriteLine("Studentul nu exista! \n"); } public void UiUpdateStudent() { Console.Write("Introduceti ID-ul studentului: "); String Id = Console.ReadLine(); Console.Write("Introduceti noul nume al studentului: "); String NumeNou = Console.ReadLine(); Console.Write("Introduceti noua grupa a studentului: "); int.TryParse(Console.ReadLine(), out int GrupaNoua); if (Serv.UpdateStudent(Id, NumeNou, GrupaNoua) != 0) Console.WriteLine("Student actualizat cu succes! \n"); else Console.WriteLine("Student inexistent! \n"); } public void UiExtendDeadline() { Console.Write("Introduceti ID-ul temei: "); String Id = Console.ReadLine(); Console.Write("Introduceti numarul de saptamani adaugate la deadline: "); int.TryParse(Console.ReadLine(), out int NrWeeks); if (Serv.ExtendDeadline(Id, NrWeeks) != 0) Console.WriteLine("Deadline extins cu succes! \n"); else Console.WriteLine("Tema nu exista! \n"); } public void UiFilter1() { Console.Write("Introduceti ID-ul temei: "); String IdTema = Console.ReadLine(); List<Nota> result = Serv.NoteTema(IdTema); foreach(Nota nota in result) { Console.WriteLine(nota); } Console.WriteLine("\n"); } public void UiFilter2() { Console.Write("Introduceti ID-ul studentului: "); String IdStudent = Console.ReadLine(); List<Nota> result = Serv.NoteStudent(IdStudent); foreach(Nota nota in result) { Console.WriteLine(nota); } Console.WriteLine("\n"); } public void UiFilter3() { Console.Write("Introduceti numarul grupei: "); int.TryParse(Console.ReadLine(), out int Grupa); Console.Write("Introduceti ID-ul temei: "); String IdTema = Console.ReadLine(); List<Nota> result = Serv.NoteStudentiGrupaTema(Grupa, IdTema); foreach(Nota nota in result) { Console.WriteLine(nota); } Console.WriteLine("\n"); } public void UiFilter4() { Console.WriteLine("READ ME: Formatul datei este dd-mm-yyyy"); Console.Write("Introduceti data de inceput: "); string DataInceput = Console.ReadLine(); Console.Write("Introduceti data de sfarsit: "); string DataSfarsit = Console.ReadLine(); List<Nota> result = Serv.NotePerioadaCalendaristica(DataInceput, DataSfarsit); foreach(Nota nota in result) { Console.WriteLine(nota); } Console.WriteLine("\n"); } public void UiRaport1() { var result = Serv.NotaLaboratorStudent(); foreach(KeyValuePair<Student, double> x in result) { Console.WriteLine("Studentul {0} are media {1}", x.Key, x.Value); } } public void UiRaport2() { var result = Serv.CeaMaiGreaTema(); Console.WriteLine("Cea mai grea tema este:\n {0} \ncu media: \n {1} \n", result.Key, result.Value); } public void UiRaport3() { var result = Serv.StudentiCareDauExamen(); Console.WriteLine("Studentii care pot da examenul sunt: "); foreach(Student student in result) { Console.WriteLine(student); } Console.WriteLine("\n"); } public void UiRaport4() { var result = Serv.StudentiTemelePredateLaTimp(); Console.WriteLine("Studentii care au predat toate temele la timp: "); foreach (Student student in result) { Console.WriteLine(student); } Console.WriteLine("\n"); } public void Run() { int cmd = -1; PrintMenu(); while (cmd != 0) { Console.Write("Introduceti comanda: "); bool result = int.TryParse(Console.ReadLine(), out cmd); try { switch (cmd) { case 11: UiPrintAllStudents(); break; case 12: UiPrintAllTeme(); break; case 13: UiPrintAllNote(); break; case 21: UiSaveStudent(); break; case 22: UiSaveTema(); break; case 23: UiSaveNota(); break; case 3: UiDeleteStudent(); break; case 4: UiUpdateStudent(); break; case 5: UiExtendDeadline(); break; case 61: UiFilter1(); break; case 62: UiFilter2(); break; case 63: UiFilter3(); break; case 64: UiFilter4(); break; case 71: UiRaport1(); break; case 72: UiRaport2(); break; case 73: UiRaport3(); break; case 74: UiRaport4(); break; case 0: break; } } catch (ValidationException ve) { Console.WriteLine(ve.Message); } catch (ArgumentNullException) { Console.WriteLine("Id-ul nu poate fi null! \n"); } catch (ArgumentException) { Console.WriteLine("Entitate existenta! \n"); } } } } } <file_sep>/LAB9-2/domain/Tema.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.domain { class Tema : IHasID<string> { public string Id { get; set; } public string Descriere { get; set; } public int Deadline { get; set; } public int Startline { get; set; } public Tema(string Id, string Descriere, int Deadline, int Startline) { this.Id = Id; this.Descriere = Descriere; this.Deadline = Deadline; this.Startline = Startline; } public override string ToString() { return "Id<" + Id + "> Descriere<" + Descriere + "> Deadline<" + Deadline + "> Startline<" + Startline + ">"; } public override bool Equals(object obj) { var tema = obj as Tema; return tema != null && Id == tema.Id; } public override int GetHashCode() { return 2108858624 + EqualityComparer<string>.Default.GetHashCode(Id); } } } <file_sep>/LAB9-2/repository/TemaRepository.cs using LAB9_2.domain; using LAB9_2.validation; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.repository { class TemaRepository : AbstractCRUDRepository<string, Tema> { public TemaRepository(IValidator<Tema> validator) : base(validator) { } } } <file_sep>/LAB9-2/repository/NotaFileRepository.cs using LAB9_2.domain; using LAB9_2.repository; using LAB9_2.validation; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace LAB9_2.repository { class NotaFileRepository : AbstractFileRepository<KeyValuePair<Student, Tema>, Nota> { StudentFileRepository Studenti; TemaFileRepository Teme; public NotaFileRepository(IValidator<Nota> validator, StudentFileRepository Studenti, TemaFileRepository Teme, string filename) : base(validator, filename) { this.Studenti = Studenti; this.Teme = Teme; LoadFromFile(); } protected override void LoadFromFile() { using (StreamReader streamReader = new StreamReader(filename)) { string line; while ( (line = streamReader.ReadLine()) != null ) { string[] fields = line.Split(';'); Student student = Studenti.FindOne(fields[0]); Tema tema = Teme.FindOne(fields[1]); Nota nota = new Nota(new KeyValuePair<Student, Tema>(student, tema), double.Parse(fields[2]), int.Parse(fields[3]), fields[4]); JustSave(nota); } streamReader.Close(); } } protected override void WriteToFile(Nota entity) { using (StreamWriter streamWriter = new StreamWriter(filename, true)) { string nota = entity.Id.Key.Id + ";" + entity.Id.Value.Id + ";" + entity.Valoare.ToString() + ";" + entity.SaptamanaPredare.ToString() + ";" + entity.Feedback; streamWriter.WriteLine(nota); streamWriter.Flush(); } } protected override void WriteToFileAll() { using (StreamWriter streamWriter = new StreamWriter(filename, true)) { List<Nota> note = FindAll(); foreach (Nota entity in note) { string nota = entity.Id.Key + "," + entity.Id.Value + "," + entity.Valoare.ToString() + "," + entity.SaptamanaPredare.ToString() + "," + entity.Feedback; streamWriter.WriteLine(nota); } streamWriter.Flush(); } } } } <file_sep>/LAB9-2/service/Service.cs using LAB9_2.domain; using LAB9_2.repository; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace LAB9_2.service { class Service { private StudentFileRepository StudentRepo; private TemaFileRepository TemaRepo; private NotaFileRepository NotaRepo; public Service(StudentFileRepository StudentRepo, TemaFileRepository TemaRepo, NotaFileRepository NotaRepo) { this.StudentRepo = StudentRepo; this.TemaRepo = TemaRepo; this.NotaRepo = NotaRepo; } public List<Student> FindAllStudents() { return StudentRepo.FindAll(); } public List<Tema> FindAllTeme() { return TemaRepo.FindAll(); } public List<Nota> FindAllNote() { return NotaRepo.FindAll(); } public int SaveStudent(String Id, String Nume, int Grupa) { Student student = new Student(Id, Nume, Grupa); Student result = StudentRepo.Save(student); if (result == null) return 1; return 0; } public int SaveTema(String Id, String Descriere, int Deadline, int Startline) { Tema tema = new Tema(Id, Descriere, Deadline, Startline); Tema result = TemaRepo.Save(tema); if (result == null) return 1; return 0; } public int SaveNota(String IdStudent, String IdTema, double Valoare, int SaptamanaPredare, string Feedback) { Student student = StudentRepo.FindOne(IdStudent); Tema tema = TemaRepo.FindOne(IdTema); if (student == null || tema == null) return -1; int Deadline = tema.Deadline; if (SaptamanaPredare - Deadline > 2) Valoare = 0; else Valoare = Valoare - 2.5 * (SaptamanaPredare - Deadline); Nota nota = new Nota(new KeyValuePair<Student, Tema>(student, tema), Valoare, SaptamanaPredare, Feedback); Nota result = NotaRepo.Save(nota); if (result == null) return 1; return 0; } public int DeleteStudent(String Id) { Student result = StudentRepo.Delete(Id); if (result == null) return 0; return 1; } public int DeleteTema(String Id) { Tema result = TemaRepo.Delete(Id); if (result == null) return 0; return 1; } public int UpdateStudent(String Id, String NumeNou, int GrupaNoua) { Student student = new Student(Id, NumeNou, GrupaNoua); Student result = StudentRepo.Update(student); if (result == null) return 1; return 0; } public int UpdateTema(String Id, String DescriereNoua, int DeadlineNou, int StartlineNou) { Tema tema = new Tema(Id, DescriereNoua, DeadlineNou, StartlineNou); Tema result = TemaRepo.Update(tema); if (result == null) return 1; return 0; } public int GetAdaptedWeek(int CurrentWeek) { if (CurrentWeek >= 39 && CurrentWeek <= 51) CurrentWeek = CurrentWeek - 39; else if (CurrentWeek == 52 || CurrentWeek == 53 || CurrentWeek == 1) CurrentWeek = 12; else if (CurrentWeek > 1 && CurrentWeek < 4) CurrentWeek = CurrentWeek + 11; else if (CurrentWeek >= 4 && CurrentWeek <= 8) CurrentWeek = 14; else CurrentWeek = CurrentWeek - 8; return CurrentWeek; } public int ExtendDeadline(String Id, int NrWeeks) { Tema tema = TemaRepo.FindOne(Id); if (tema != null) { int CurrentWeek = GetAdaptedWeek(CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday)); if (CurrentWeek <= tema.Deadline) { int DeadlineNou = tema.Deadline + NrWeeks; return UpdateTema(tema.Id, tema.Descriere, DeadlineNou, tema.Startline); } } return 0; } public List<Nota> NoteTema(string IdTema) { List<Nota> note = FindAllNote(); var result = (from nota in note where nota.Id.Value.Id == IdTema select nota).ToList(); return result; } public List<Nota> NoteStudent(string IdStudent) { List<Nota> note = FindAllNote(); var result = (from nota in note where nota.Id.Key.Id == IdStudent select nota).ToList(); return result; } public List<Nota> NoteStudentiGrupaTema(int Grupa, string IdTema) { List<Nota> note = FindAllNote(); var result = (from nota in note where nota.Id.Value.Id == IdTema && StudentRepo.FindOne(nota.Id.Key.Id).Grupa == Grupa select nota).ToList(); return result; } public List<Nota> NotePerioadaCalendaristica(string DataInceput, string DataSfarsit) { List<Nota> note = FindAllNote(); DateTime inceput = DateTime.Parse(DataInceput); int BeginWeek = GetAdaptedWeek(CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(inceput, CalendarWeekRule.FirstDay, DayOfWeek.Monday)); DateTime sfarsit = DateTime.Parse(DataSfarsit); int EndWeek = GetAdaptedWeek(CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(sfarsit, CalendarWeekRule.FirstDay, DayOfWeek.Monday)); var result = (from nota in note where BeginWeek <= nota.SaptamanaPredare && nota.SaptamanaPredare <= EndWeek select nota).ToList(); return result; } public List<KeyValuePair<Student, double>> NotaLaboratorStudent() { var result = from nota in FindAllNote() group nota by nota.Id.Key into grup select new KeyValuePair<Student, double>(grup.Key, grup.Average(x => { double suma = grup.Sum(y => (TemaRepo.FindOne(y.Id.Value.Id).Deadline - TemaRepo.FindOne(y.Id.Value.Id).Startline) * y.Valoare); double sumaPondere = grup.Sum(y => TemaRepo.FindOne(y.Id.Value.Id).Deadline - TemaRepo.FindOne(y.Id.Value.Id).Startline); return suma / sumaPondere; })); return result.ToList(); } public KeyValuePair<Tema, double> CeaMaiGreaTema() { var result = from nota in FindAllNote() group nota by nota.Id.Value into grup select new KeyValuePair<Tema, double>(grup.Key, grup.Min(x => { double suma = grup.Sum(y => y.Valoare); double cate = grup.Count(); return suma / cate; })); return result.ToList().First(); } public IEnumerable<Student> StudentiCareDauExamen() { var result = from medie in NotaLaboratorStudent() where medie.Value >= 4 select medie.Key; return result; } public IEnumerable<Student> StudentiTemelePredateLaTimp() { var result = from nota in FindAllNote() group nota by nota.Id.Key into grup where grup.Count() == (from nota in grup where nota.SaptamanaPredare == TemaRepo.FindOne(nota.Id.Value.Id).Deadline select nota).Count() select grup.Key; return result; } } } <file_sep>/LAB9-2/validation/TemaValidator.cs using LAB9_2.domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.validation { class TemaValidator : IValidator<Tema> { public void Validate(Tema tema) { if (tema.Id == null || tema.Id.Equals("")) throw new ValidationException("ID invalid! \n"); if (tema.Descriere == null || tema.Descriere.Equals("")) throw new ValidationException("Descriere invalida! \n"); if (tema.Deadline < 1 || tema.Deadline > 14 || tema.Deadline < tema.Startline) throw new ValidationException("Deadline invalid! \n"); if (tema.Startline < 1 || tema.Startline > 14 || tema.Startline > tema.Deadline) throw new ValidationException("Startline invalid! \n"); } } } <file_sep>/LAB9-2/validation/ValidationException.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.validation { class ValidationException : Exception { public ValidationException(string Exception) : base(Exception) { } } } <file_sep>/README.md # Homework-Management2 Proiectul Homework-Management implementat in C#, interfata de tip consola, datele citite din fisiere text. <file_sep>/LAB9-2/repository/AbstractCRUDRepository.cs using LAB9_2.domain; using LAB9_2.validation; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.repository { abstract class AbstractCRUDRepository<ID, E> : ICRUDRepository<ID, E> where E : IHasID<ID> { Dictionary<ID, E> Entities; readonly IValidator<E> validator; public AbstractCRUDRepository(IValidator<E> validator) { Entities = new Dictionary<ID, E>(); this.validator = validator; } public E FindOne(ID Id) { bool result = Entities.TryGetValue(Id, out E entity); return result ? entity : default(E); } public List<E> FindAll() { return Entities.Values.ToList(); } public E Save(E entity) { validator.Validate(entity); Entities.Add(entity.Id, entity); return default(E); } public E Delete(ID Id) { Entities.TryGetValue(Id, out E entity); bool result = Entities.Remove(Id); return result ? entity : default(E); } public E Update(E entity) { validator.Validate(entity); bool result = Entities.ContainsValue(entity); if (result) { Entities[entity.Id] = entity; return default(E); } return entity; } } } <file_sep>/LAB9-2/repository/ICRUDRepository.cs using LAB9_2.domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.repository { internal interface ICRUDRepository<ID, E> { /** * @DO: Search an entity * @RETURN: the entity with the specified id; null - if there is no entity with the given id * @PARAM id - the id of the entity to be returned; id must not be null * **/ E FindOne(ID Id); /** * @DO: Return all entities * **/ List<E> FindAll(); /** * @DO: Save the given entity * @RETURN: null- if the given entity is saved; the entity - otherwise (id already exists) * @PARAM entity; entity must be not null * @THROWS ValidationException if the entity is not valid * **/ E Save(E entity); /** * @DO: Removes the entity with the specified id * @RETURN: the removed entity; null - if there is no entity with the given id * @PARAM id; id must be not null * **/ E Delete(ID Id); /** * @DO: Update the entity with the same Id as the Entity * @RETURN: null - if the entity is updated; the entity - otherwise (e.g id does not exist). * @PARAM entity; entity must not be null * @THROWS ValidationException if the entity is not valid. * **/ E Update(E Entity); } } <file_sep>/LAB9-2/repository/StudentRepository.cs using LAB9_2.domain; using LAB9_2.validation; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.repository { class StudentRepository : AbstractCRUDRepository<string, Student> { public StudentRepository(IValidator<Student> validator) : base(validator) { } } } <file_sep>/LAB9-2/domain/Student.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LAB9_2.domain { class Student : IHasID<string> { public string Id { get; set; } public string Nume { get; set; } public int Grupa { get; set; } public Student(string Id, string Nume, int Grupa) { this.Id = Id; this.Nume = Nume; this.Grupa = Grupa; } public override string ToString() { return "Id<" + Id + "> Nume<" + Nume + "> Grupa<" + Grupa + ">"; } public override bool Equals(object obj) { var student = obj as Student; return student != null && Id == student.Id; } public override int GetHashCode() { return 2108858624 + EqualityComparer<string>.Default.GetHashCode(Id); } } }
846ffa3b663662c0b2ccd32cb6c0631c66ea45af
[ "Markdown", "C#" ]
20
C#
RalucaPenciuc/Homework-Management2
546d911ca67fe0748dd1a7e6908fbb7c60ebec28
00c02f7b8f2c982df773d6aec1b124cbd4750427
refs/heads/master
<repo_name>62nK/DarkBright_Detector_ANN<file_sep>/InputImagePane.java import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; public class InputImagePane extends Pane implements Constants { private double[] input; private int size; public InputImagePane(int size){ this.size = size; input = new double[size]; randomGenerator(); } public double[] getInput() { return input; } public void draw(){ clear(); drawSquares(); } private void drawSquares(){ Rectangle[] squares = new Rectangle[size]; for(int y=0; y<(int)Math.sqrt(size); y++) for(int x=0; x<(int)Math.sqrt(size); x++){ squares[y*(int)Math.sqrt(size)+x] = new Rectangle(20+x*SQUARE_SIZE, y*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE); squares[y*(int)Math.sqrt(size)+x].setFill(input[y*(int)Math.sqrt(size)+x]==WHITE_PIXEL? Color.WHITE:Color.BLACK); squares[y*(int)Math.sqrt(size)+x].setStroke(Color.GREY); } getChildren().addAll(squares); } public void randomGenerator(){ for(int index=0; index<size; index++) input[index] = Math.random()>=0.5?WHITE_PIXEL:BLACK_PIXEL; } private void clear(){ getChildren().clear(); } }
721f0921194cc0981114991ceec222ebd136aa13
[ "Java" ]
1
Java
62nK/DarkBright_Detector_ANN
1492491810f89e5770c59f9ff8c31e7366d123cc
ecd7bf4fe4c3321aae6ec7bb72e3ebabcac771ea
refs/heads/master
<file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'Directives'; show:boolean=false; isSE:boolean=true; isDeveloper:boolean=true; inputValue:string='HYD'; teamName:string="IND" getProducts():number{ return 2; } employees:any[]= [ {name:"venkat",age:25,city:"hyd",salary:"100k",empImg:"https://in.bmscdn.com/iedb/movies/images/mobile/thumbnail/xlarge/darbar-et00116717-07-11-2019-06-14-06.jpg"}, {name:"srinivas",age:35,city:"pune",salary:"100k"}, {name:"siva",age:36,city:"blr",salary:"900k"}, {name:"udhay",age:39,city:"mum",salary:"90k"}, {name:"sai",age:45,city:"hyd",salary:"170k"}, ] cricketTeams:any[]=[ {teamName:"IND",players:[{name:"Kohli",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, {teamName:"AUS",players:[{name:"Warner",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, {teamName:"ENG",players:[{name:"Root",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, {teamName:"SA",players:[{name:"Dekock",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, {teamName:"NZ",players:[{name:"Taylor",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, ] movies=[ "test1","test2" ] } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; @Pipe({ name:"employeeAgePipe" }) export class EmployeeAgePipe implements PipeTransform{ transform(age:string):number{ let currentYear= new Date().getFullYear(); let employeeDob= new Date(age).getFullYear(); let empAge=currentYear-employeeDob; console.log(empAge) return empAge; // console.log("employee dob"+employeeDob) } }<file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'Directives'; show:boolean=true; employees:any[]= [ {name:"venkat123",age:25,city:"hyd",salary:"100k",empImg:"https://in.bmscdn.com/iedb/movies/images/mobile/thumbnail/xlarge/darbar-et00116717-07-11-2019-06-14-06.jpg"}, {name:"srinivas",age:35,city:"pune",salary:"100k"}, {name:"siva",age:36,city:"blr",salary:"900k"}, {name:"udhay",age:39,city:"mum",salary:"90k"}, {name:"sai",age:45,city:"hyd",salary:"170k"}, ] cricketTeams:any[]=[ {teamName:"India",players:[{name:"Kohli",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, {teamName:"Aus",players:[{name:"Warner",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, {teamName:"England",players:[{name:"Root",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, {teamName:"SA",players:[{name:"Dekock",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, {teamName:"NZ",players:[{name:"Taylor",role:"batsman"},{name:"Rohith",role:"batsman"},{name:"Dhawan",role:"batsman"}]}, ] movies=[ "test1","test2" ] } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-pipes', templateUrl: './pipes.component.html', styleUrls: ['./pipes.component.scss'] }) export class PipesComponent { title="Welcome to VLR" months:any[]=["JAN","FEB","MARCH","APR","MAY","JUN"]; employee={ name:"sri", age:23 } numberValue=126; today=new Date(); } <file_sep>import { PipeTransform, Pipe } from '@angular/core'; @Pipe({ name:"employeePipe" }) export class EmployeeTitlePipe implements PipeTransform{ transform(name:string,gender:string,city:string):string{ // console.log(city) if(gender.toLowerCase()=="male"){ return "Mr."+ name; } else{ return "Miss."+ name; } } }
18868a1ebc48b4cc8dc2e8ec7935989373b94425
[ "TypeScript" ]
5
TypeScript
VLR-angular7/angular_code
ba38775cf755ce8e91f68be008d0928869014255
278faa2f68c059aa0cb0e1715bca3430cbae9b20
refs/heads/master
<repo_name>theblackbeard/bb-api-nodejs<file_sep>/system/middleware/auth.js 'use strict'; const jwt = require('jwt-simple'); const config = require('../config'); const User = require('../../app/models/user'); exports.requireLogin = (req, res, next)=> { let token = _getToken(req.headers); if(token){ let decoded = _decodedThis(token); User.findOne({ _id: decoded._id }, {password: 0}, (err, user) => { if(err) console.log(err); if(!user){ return res.status(403).send({success: false, msg: 'Authentication failed. User not found'}); }else{ return next(); } }) }else{ console.log("nao") return res.status(403).send({success: false, msg: 'Authentication failed. No Token Provided'}) } }; let _getToken = function(headers){ if(headers && headers.authorization){ var parted = headers.authorization.split(' '); if (parted.length === 2) { return parted[1]; } else { return null; } } else { return null; } }; let _decodedThis = function(_token){ let _userInfo = jwt.decode(_token, config.SECRET); let _user = ({_id: _userInfo._id, name: _userInfo.name, email: _userInfo.email}); return _user; } <file_sep>/app/models/article.js 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const _validate = (v) => v.length >= 3; const _set = (v) => v.toLowerCase(); const _setName = (v) => v.toLowerCase().split(" ").join("-"); const _getTags = tags => tags.join(','); const _setTags = tags => tags.toLowerCase().split(','); const ArticleSchema = new Schema({ title : { type: String, require: true, validate: [_validate, 'Title must be have less 3 chars'], set: _set }, name: { type: String, require: true, set: _setName, index: true }, body: { type: String, require: true, validate: [_validate, 'Body must be have less 3 chars'], set: _set }, cover:{ type: Schema.Types.Mixed, require: true }, gallery : Schema.Types.Mixed, tags: { type: [], get: _getTags, set: _setTags, trim: true }, views: { type: Number, default: 0 }, active: { type: Boolean, default: false }, author: { type: Schema.ObjectId, ref: 'User' }, links: [], comments: [{ name: {type: String, default: ''}, body: {type: String, default: ''}, email:{type: String, default: ''}, }], created_at: { type: Date, default: Date.now } }); ArticleSchema.statics = { changeCS: function(name, option, cb){ return this.update({name: name},{$set: {active: JSON.parse(option)}}, cb); }, plusView: function(name, cb){ return this.update({name: name}, {$inc : {views: 1}}, cb); } } module.exports = mongoose.model('Article', ArticleSchema);<file_sep>/app/models/tag.js 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const _validate = (v) => v.length >= 3; const _set = (v) => v.toLowerCase().split(','); const TagSchema = new Schema({ title: { type: String, require: true, validate: [_validate, 'Title Must be have 3 chars'], set: _set, unique: true } }); module.exports = mongoose.model('Tag', TagSchema);<file_sep>/server.js 'use strict'; const express = require('express'); const helmet = require('helmet'); const cors = require('cors'); const security = require('./system/middleware/security'); const app = express(); const config = require('./system/config.js'); const morgan = require('morgan'); const router = require('./system/router.js'); const bodyParser = require('body-parser'); const passport = require('passport'); require('./system/database')(config); require('./system/passport')(passport, config); app.use(helmet()); app.use(security.policy); app.use(cors({origin: 'http://seu-site.com.br'})); //app.use(cors({origin: '*'})); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(morgan('dev')); app.use('/api', router); app.use(passport.initialize()); app.listen(config.PORTSERVER, config.IPSERVER, () => { console.log('Server Running on ' , config.IPSERVER + ': ' + config.PORTSERVER); }); <file_sep>/app/controllers/user-controller.js 'use strict' const User = require('../models/user'); const assign = require('object-assign'); const jwt = require('jwt-simple'); const config = require('../../system/config'); exports.load = (req, res, next, idUser) => { User.findOne({_id: req.params.idUser}, {password: 0}, function(err, user){ if(err) return next(res.json({'success': false , 'msg': 'User not found!'})); req.user = user; next(); }) } exports.index = (req, res) =>{ User.find({}, {password: 0}, (err, users) => { if(err) console.log(err); if(users.length == 0) users = 'No Users Found!'; return res.json({'success': true, 'users': (users) || 'No Users Found!'}); }); }; exports.show = (req, res) => { const user = req.user || 'User not found!'; return res.json({'success': true, 'user': user}); } exports.store = (req, res) => { User.create(req.body, (err,result) => { if(err) return res.json({'success': false, 'msg': (err.errors || err.errmsg) }); return res.json({'success': true, 'msg': 'User Created Successfuly!', 'data': result}); }); }; exports.update = (req, res) => { const oldUserData = req.user; assign(oldUserData, req.body); oldUserData.save((err, result)=>{ if(err) return res.json({'success': 'false', 'msg': err}); return res.json({'success': true, 'msg': 'User Updated Successfuly', 'data': result }) }); }; exports.delete = (req, res) => { const user = req.user; if(user){ user.remove((err) => { if(err) return res.json({'success': 'false', 'msg': err}); return res.json({'success': true, 'msg': 'User deleted successfuly!'}) }) }else{ return res.json({'success': false, 'msg': 'This user does not exists anymore!!'}) } }; exports.auth = (req, res) => { User.findOne({ email: req.body.email }, function(err, user){ if(err) return console.log(err); if(!user){ return res.json({success: false, 'msg': 'Auth failed, User not found'}); }else{ user.comparePassword(req.body.password, (err, isMatch) => { if(isMatch && !err){ let token = jwt.encode(user, config.SECRET); return res.json({'success': true, token: 'JWT ' + token}); }else{ return res.json({'success': false, msg: 'Auth failed, Wrong password'}); } }) } }) }; <file_sep>/app/controllers/article-controller.js 'use strict' const Article = require('../models/article'); const assign = require('object-assign'); exports.load = (req, res, next, name) => { Article.findOne({name: req.params.name}, function(err, article){ if(err) return next(res.json({'success': false , 'message': 'Article not found!'})); req.article = article; next(); }) }; exports.index = (req, res) => { req.query.q = req.query.q ? {active: req.query.q} : {}; Article.find(req.query.q,(err, articles) =>{ if(err) console.log(err); if(articles.length == 0) articles = 'No Articles Found!'; return res.json({'success': true, 'articles': (articles || 'No Articles Found!')}); }) } exports.show = (req, res) => { const article = req.article || 'Article not found!!'; return res.json({'success': true, 'article': article}); }; exports.name = (req, res) => { const article = {name: req.params.name}; res.json(article); }; exports.store = (req, res) => { const article = req.body; article.name = article.title; article.tags = article.tags || 'uncategorized'; if(Object.keys(article.tags).length==0) article.tags = 'uncategorized'; article.author = req.user Article.create(article, (err, result) => { if(err) return res.json({'success': false, 'msg': (err.errors || err.errmsg) }); return res.json({'success': true, 'msg': 'Article Created Successfuly!', 'data': result}); }) }; exports.update = (req, res) => { const oldArticleData = req.article; const editArticle = req.body; editArticle.name = editArticle.title; editArticle.tags = editArticle.tags || 'uncategorized'; if(Object.keys(editArticle.tags).length==0) editArticle.tags = 'uncategorized'; oldArticleData.author = req.user; assign(oldArticleData, editArticle); oldArticleData.save((err, result)=>{ if(err) return res.json({'success': false, 'msg': err}); return res.json({'success': true, 'msg': 'Article Updated Successfuly', 'data': result }) }) }; exports.delete = (req, res) => { const article = req.article; if(article){ article.remove((err) => { if(err) return res.json({'success': 'false', 'msg': err}); return res.json({'success': true, 'msg': 'Article deleted successfuly!'}); }) }else{ return res.json({'success': false, 'msg': 'This Article does not exists anymore!'}) } }; exports.changeCs = (req, res) => { const article = req.article; const option = req.query.option; if(article && option){ Article.changeCS(article.name, option, (err, result) => { if(err) return res.json({'success': 'false', 'msg': err}); return res.json({'success': true, 'msg': 'Article Status Changed!', 'data': result}); }) }else{ return res.json({'success': false, 'msg': 'This Article does not exists anymore!'}) } }; exports.plusView = (req, res) => { const article = req.article; if(article){ Article.plusView(article.name, (err, result) => { if(err) return res.json({'success': 'false', 'msg': err}); return res.json({'success': true, 'msg': 'Article Viewed', 'data': result}); }); }else{ return res.json({'success': false, 'msg': 'This Article does not exists anymore!'}) } } <file_sep>/app/controllers/tag-controller.js 'use strict'; const Tag = require('../models/tag'); const Article = require('../models/article'); exports.load = (req, res, next, nameTag) => { Tag.findOne({title: req.params.nameTag}, function(err, tag){ if(err) return next(res.json({'success': false , 'message': 'Tag not found!'})); req.tag = tag; next(); }) }; exports.index = (req, res) => { Tag.find({}, (err, tags) => { if(err) console.log(err); if(tags.length == 0) tags = 'No Tag Found!'; return res.json({'success': true, 'tags': (tags || 'No Tags Found!')}); }) }; exports.indexSync = (req, res) => { Tag.find({}, (err, tags) => { if(err) return console.log(err); return res.json(tags) }) }; exports.show = (req, res) => { const query = {tags: req.params.name}; Article.find(query, (err, articles) => { if(err) return res.json({success:false, msg: err}); return res.json({success:true, articles: articles}) }) }; exports.store = (req, res) => { let tags = _thisTags(req.body.title); Tag.create(tags, (err, result) => { if(err) return res.json({'success': false, 'msg': (err.errors || err.errmsg) }); return res.json({'success': true, 'msg': 'Tag Created Successfuly!', 'data': result}); }) }; exports.delete = (req, res) => { const tag = req.tag; if(tag){ tag.remove((err) => { if(err) return res.json({'success': false, 'msg': err}); return res.json({'success': true, 'msg': 'Tag deleted successfuly!'}); }) }else{ return res.json({'success': false, 'msg': 'This Tag does not exists anymore!'}) } } let _thisTags = function (string) { let newTags = []; let tags = string.split(','); tags.forEach(function(tag){ newTags.push({'title': tag}); }) return newTags; } <file_sep>/app/models/profile.js 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const _validate = (v) => v.length >= 3; const ProfileSchema = new Schema({ body: { type: String, require: true, validate: [_validate, 'Body must be have less 3 chars!'] }, created_at: { type: Date, default: Date.now } }); ProfileSchema.statics = { isOne: function(cb){ return this.count().exec(cb); } } module.exports = mongoose.model('Profile', ProfileSchema);<file_sep>/app/controllers/about-controller.js 'use strict'; const Profile = require('../models/profile'); const assign = require('object-assign'); exports.load = (req, res, next, idProfile) => { Profile.findOne({_id: req.params.idProfile}, function(err, profile){ if(err) return next(res.json({'success': false , 'message': 'Profile not found!'})); req.profile = profile; next(); }) }; exports.index = (req, res) => { Profile.findOne({}, (err, profile) =>{ if(err) console.log(err); return res.json({'success': true, 'profile': (profile || 'No Profile Found!')}); }) }; exports.show = (req, res) => { const profile = req.profile || 'Profile not found!'; return res.json({'success': true, 'profile': profile}); }; exports.store = (req, res) => { Profile.isOne((err, value) => { if(err) return console.log(err); if(value < 1){ Profile.create(req.body, (err, result) => { if(err) return res.json({'success': false, 'msg': (err.errors || err.errmsg) }); return res.json({'success': true, 'msg': 'Profile Created Successfuly!', 'data': result}); }) }else{ return res.json({'success': false, 'msg': 'A profile already exists' }); } }) }; exports.update = (req, res) => { const oldProfileData = req.profile; assign(oldProfileData, req.body); oldProfileData.save((err, result)=>{ if(err) return res.json({'success': false, 'msg': err}); return res.json({'success': true, 'msg': 'Profile Updated Successfuly', 'data': result }) }) }; exports.delete = (req, res) => { const profile = req.profile; if(profile){ profile.remove((err) => { if(err) return res.json({'success': false, 'msg': err}); return res.json({'success': true, 'msg': 'Profile deleted successfuly!'}) }) }else{ return res.json({'success': false, 'msg': 'This profile does not exists anymore!'}) } };
f230c044d4e22ceaa69d042ec6931019930267d0
[ "JavaScript" ]
9
JavaScript
theblackbeard/bb-api-nodejs
933c02d58f262c9dffa23a4203f2c13d2636ba4d
d055c04e9df576557163256b77a3a818e59c4003
refs/heads/master
<repo_name>haridoss1802/IBmLabs<file_sep>/Factorial.py # FACTORIAL '''n=int(input("Enter number")) factorial=1 if n<0: print("Enter positive integers") elif n==0: print(factorial) else: for i in range(1,n+1): factorial =factorial *i print(factorial)''' <file_sep>/LCM.py # LCM '''def lcm(x,y): greater=x if x>y else y while True: if greater%x==0 and greater%y==0: lcm=greater break greater+=1 return lcm num1=int(input("Enter the number1")) num2=int(input("Enter number2")) print("The lcm(num1,num2))''' # HCF def compute_hcf(x,y): if x>y: smaller=x else: smaller=y for i in range(1,smaller+1): if x%i==0 and y%i==0: hcf=i return hcf x=int(input("Enter the number")) y=int(input("Enter another number")) print(compute_hcf(x,y))<file_sep>/Conversion.py # COVERSION # implicit conversion is done by the computer # explicit is done by the users '''a,b=3,2 print(int(a/b),a,b) print('value of a is {} and b is {}'.format(a,b)) print('value of a is {a1} and b is {b1}',a1=10,b1=20) list=[1,2,3] set=(1,2,3,4,5) tuple1=tuple(list) print(tuple1) print(eval(2+3)) print(int(2+3))''' dec=int(input("")) print(bin(dec)) print(hex(dec)) print(oct(dec))<file_sep>/Calendar.py # CALENDAR '''import calendar month=int(input("Enter month")) year=int(input("Enter year")) print(calendar.month(year,month)) print(calendar.calendar(year))''' <file_sep>/Basics.py '''a=1+2+3\ 4+5+6 print(a)''' """if True: print("true")""" # MULTIPLE VARIABLE DECLARATION '''num1,num3,string1=10,30.0,"sting" print(type(num1)) #print(c) print(num3) print(string1)''' # LIST, TUPLE '''a=[1,2,"string"] t=(1,2,"string") print(a[0]) print(a[0:3]) print(t[0:2]) set1=(1,1,2,2,2,3,3) print(set1) ''' # STRINGS b="hello hari" print(b[0:5]) # import # from file_name import class_name: '''import calendar calendar.path''' '''print(2**3) #power function # is, is not,in,not in a='hari' b='doss' print('h' in b)''' # https://www.programiz.com/
57ce6ce84d46c601a793f353feef052cfc5583f2
[ "Python" ]
5
Python
haridoss1802/IBmLabs
230183defd2b7567d3cc1b81af758ae84ae30b40
6241a5e84c067b7421142e379a8ce15ae770ac96
refs/heads/master
<repo_name>urnix/meteor-universe-autoform-select<file_sep>/package.js 'use strict'; Package.describe({ name: 'artemi:universe-autoform-select', summary: 'Custom "afUniverseSelect" input type for AutoForm, with the appearance as selectize', version: '0.3.11', git: 'https://github.com/urnix/meteor-universe-autoform-select.git' }); Package.onUse(function (api) { api.versionsFrom('1.2.1'); if (!api.addAssets) { api.addAssets = function (files, platform) { api.addFiles(files, platform, {isAsset: true}); }; } api.use(['ecmascript', 'templating', 'underscore'], 'client'); api.use('aldeed:autoform@6.2.0'); api.use('artemi:universe-selectize@0.1.23', 'client'); api.addFiles([ 'universe-autoform-select.html', 'universe-autoform-select.js' ], 'client'); });
0f4e9ca1471e127e7e4f7c086de67ff53c06683d
[ "JavaScript" ]
1
JavaScript
urnix/meteor-universe-autoform-select
efcec60ae2fe3f5b38502836e8e1b694ca4ac060
11738d2f93f172ed435783535a4e9db3eae4cda8
refs/heads/master
<file_sep># POO Repositório da aula de Programação Orientada a Objetos - Fatec SJC <file_sep>package app; import java.util.*; import main.AsciiArt; import main.Controle; import main.Menu; import pessoa.Pessoa; public class App { public static void main(String[] args) { AsciiArt.printAsciiArt("BANCADA FUNDO"); Menu menu = new Menu(); int op = 1000; while (op != 0) { menu.imprimirMenu(); Controle ctl = new Controle(); op = ctl.opcao(); Controle x = new Controle(); List<Pessoa> pessoas = new ArrayList<Pessoa>(); switch (op) { case 1: System.out.println("Digite o nome do aluno:"); //Pessoa a = new Pessoa(x.texto()); //pessoas.add(a); break; case 2: for ( Pessoa i : pessoas) { System.out.println(i.getNome()); } break; case 0: break; default: menu.imprimirMenu(); break; } } } }
e40bd21bf02750eec8b3fc9dcb270ee84eccc999
[ "Markdown", "Java" ]
2
Markdown
MaguinhoD/POO
700f2055706beefa36c47dda73cd01093117d8f4
91d7d2b3074044cf0eedc106753a88bdd26f50b4
refs/heads/master
<file_sep>echo Connect read ~/Library/Android/sdk/platform-tools/adb tcpip 5555 echo Disconnect, connect to DIRECT WiFi read ~/Library/Android/sdk/platform-tools/adb connect 192.168.49.1:5555 <file_sep>package org.firstinspires.ftc.teamcode.tests import com.qualcomm.robotcore.eventloop.opmode.OpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import com.qualcomm.robotcore.hardware.Servo import com.qualcomm.robotcore.util.Range /** * Provides the ability to test individual servos and survey their positions. * Before running this test, set hardware device "Test_Servo" to the desired port in configuration. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ @TeleOp(name = "ServoDirectTest", group = "Pragmaticos") class ServoDirectTest : OpMode() { private val TICK_CHANGE = 0.01 lateinit var servo: Servo override fun init() { servo = hardwareMap.servo.get("Test_Servo") } override fun loop() { with(gamepad1) { var nextPosition = servo.position if (left_bumper) nextPosition += TICK_CHANGE if (right_bumper) nextPosition -= TICK_CHANGE nextPosition = Range.clip(nextPosition, 0.0, 1.0) servo.position = nextPosition telemetry.addData("Current Servo Position", nextPosition) telemetry.update() } } }<file_sep>package org.firstinspires.ftc.teamcode.io import com.qualcomm.robotcore.hardware.DcMotor import com.qualcomm.robotcore.hardware.Servo /** * Describes tasks that the glyph manipulator (collectorIn + platform) is capable of doing. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ interface IGlyphManipulator { // Hardware output devices val collectorLeft: DcMotor val collectorRight: DcMotor val bucketPour: Servo val offsideBucketPour: Servo val glyphRectifiers: Set<Servo> // Getter/setter manipulations /** * The power of motors that run the flywheels that actuate the glyph through the feeder mechanism. * When set to a positive value, the flywheels pull the glyph toward the bucket. * When set to a negative value, the flywheels push the glyph out of the feeder. */ var collectorPower: Double /** * Analog controls for the bucket-tilting servos. * * POURING_POS represents the position when the platform is lifted. * UNPOURING_POS represents the position when the platform is flat. * */ // A shadow variable is recommended for implementation. var bucketPourPos: Double /** * Analog controls for the rectifier servos. * * RECTIFYING_POS represents the position when the rectifier is engaged. * UNRECTIFYING_POS represents the position when the rectifier is out of the way. */ var rectifierPos: Double // Autonomous-optimized methods /** * Places the glyph into the cryptobox in front in an optimized way. * This method can block if necessary. */ fun placeGlyph() }<file_sep>package org.firstinspires.ftc.teamcode.config import android.util.Log import android.util.NoSuchPropertyException import java.io.File import java.io.FileNotFoundException import java.io.FileReader import java.io.IOException import java.util.* /** * Provides abstraction of a singular configuration file in internal storage. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ class ConfigFile(val filename: String) { companion object { // The location of configuration files const val CONFIG_PATH = "/storage/self/primary/FIRST/config" } val properties = Properties() init { // Populate Properties try { FileReader(File(CONFIG_PATH, filename)).use { file -> properties.load(file) } // Hardware is not initialized at this point. } catch (ferrno: FileNotFoundException) { Log.e("ConfigFile error!", "Internal storage file $filename not found") throw ferrno } catch (io: IOException) { Log.e("ConfigFile error!", "Internal storage file $filename cannot be accessed (${io.message}") throw io } } operator fun get(key: String): String = properties.getProperty(key) ?: throw NoSuchPropertyException("$key in $this") // Typed Get /** * Retrieves a double-precision floating point number from the file with the given property key. * * @param key The key of the requested value * @returns The requested value * @throws NumberFormatException If the value is not a valid double */ @Throws(NumberFormatException::class) fun getDouble(key: String): Double = this[key].toDouble() /** * Retrieves an integer from the file with the given property key. * * @param key The key of the requested value * @returns The requested value * @throws NumberFormatException If the value is not a valid integer */ @Throws(NumberFormatException::class) fun getInteger(key: String): Int = this[key].toInt() /** * Retrieves a boolean from the file with the given property key. * * Only two values are valid: * - `"true"` (true) * - `"false"` (false) * * @param key The key of the requested value * @returns The requested value * @throws InvalidPropertiesFormatException If the value is not a valid boolean representation */ @Throws(InvalidPropertiesFormatException::class) fun getBoolean(key: String): Boolean = when (this[key]) { "true" -> true "false" -> false else -> throw InvalidPropertiesFormatException( "getBoolean called on non-boolean ConfigFile value '${this[key]}'") } /** * Retrieves a list of strings from the file, delimited by commas (","), from the file with the given property key. * * There is no way to detect malformed lists. * @param key The key of the requested value * @returns The requested value */ fun getStringList(key: String): List<String> = this[key].split(",") override fun toString(): String = "[ConfigFile $filename (${properties.size} pairs)]" } <file_sep>package org.firstinspires.ftc.teamcode.io; import com.qualcomm.robotcore.hardware.ColorSensor; import com.qualcomm.robotcore.hardware.Servo; import org.firstinspires.ftc.teamcode.AllianceColor; import org.firstinspires.ftc.teamcode.drivetrain.IDrivetrain; import org.jetbrains.annotations.NotNull; /** * Created by E-Man on 11/17/2017. */ public class JewelKnocker implements IJewelKnocker { private ColorSensor color; private Servo arm; private final double down = 0; private final double up = 1; private final boolean turn = true; public AllianceColor detect() { int Red = color.red(); int Blue = color.blue(); if (Red > Blue) return AllianceColor.RED; if (Blue > Red) return AllianceColor.BLUE; return null; } public void removeJewel(boolean towardCorner) { final IDrivetrain drivetrain = Hardware.INSTANCE.getDrivetrain(); if (towardCorner) { drivetrain.turn(5 / 18 * Math.PI); } else { drivetrain.turn(5 / 18 * -Math.PI); // Removes jewel that's farther from the corner } } @NotNull @Override public ColorSensor getColor() { return color; } @NotNull @Override public Servo getArm() { return arm; } @Override public void lowerArm() { arm.setPosition(down); } @Override public void raiseArm() { arm.setPosition(up); } } <file_sep>package org.firstinspires.ftc.teamcode.telemetry /** * A reference implementation of ITelemetry. * @author <NAME> */ class Telemetry(private val telem: org.firstinspires.ftc.robotcore.external.Telemetry) : ITelemetry { override var autoClear: Boolean get() = telem.isAutoClear set(value) { telem.isAutoClear = value } override var autoUpdate = false init { this.telem.addData("Hello World", "Telemetry Initialized!") flush() } override fun write(caption: String, data: String) { this.telem.addData(caption, data) if (autoUpdate) flush() } override fun error(info: String) { this.telem.addData("[ERROR]", info) if (autoUpdate) flush() } override fun warning(info: String) { this.telem.addData("[WARN]", info) if (autoUpdate) flush() } override fun data(label: String, data: Any) { this.telem.addData("DATA: " + label, data) if (autoUpdate) flush() } override fun fatal(info: String) { this.telem.addData("--- FATAL ", " ERROR ---") this.telem.addData("Error Info", info) if (autoUpdate) flush() } // FIXME("repetition") Is there a way to prevent repetition of any kind that accomplishes autoUpdate logic? // Failed solutions: // if (autoUpdate) flush() // fun maybeUpdate() = if (autoUpdate) flush() override fun flush() { this.telem.update() } }<file_sep>package org.firstinspires.ftc.teamcode.tests import com.qualcomm.robotcore.eventloop.opmode.Autonomous import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode import org.firstinspires.ftc.teamcode.config.ConfigFile /** * Tests for the test.properties configuration file and puts all key-value entries to telemetry. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ @Autonomous(name = "ConfigurationTest", group = "Pragmaticos") class ConfigurationTest : LinearOpMode() { lateinit var config: ConfigFile override fun runOpMode() { config = ConfigFile("test.properties") waitForStart() // Print internal storage directory telemetry.addData("File path", ConfigFile.CONFIG_PATH) for ((key, value) in config.properties.entries) { telemetry.addData(key.toString(), value) } telemetry.update() while (opModeIsActive()); } }<file_sep>package org.firstinspires.ftc.teamcode.tests import com.qualcomm.robotcore.eventloop.opmode.OpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import com.qualcomm.robotcore.hardware.ColorSensor import com.qualcomm.robotcore.hardware.Servo /** * Tests the JewelArm and the JewelSensor with no external dependencies. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ @TeleOp(name = "JewelTest", group = "Pragmaticos") class JewelTest : OpMode() { lateinit var color: ColorSensor lateinit var arm: Servo override fun init() { with(hardwareMap) { color = colorSensor.get("JewelSensor") arm = servo.get("JewelArm") } } override fun loop() { arm.position = gamepad1.left_trigger.toDouble() when { color.red() > color.blue() -> telemetry.addData("I saw", "Red") color.blue() > color.red() -> telemetry.addData("I saw", "Blue") else -> telemetry.addData("I didn't see", "Anything") } telemetry.update() } }<file_sep>package org.firstinspires.ftc.teamcode.telemetry /** * Defines the ways in which the other parts of the program can access the telemetry features. * Ideally, no direct access to the "telemetry" field in the OpMode classes should be permitted * in any other part of the program except when initializing ITelemetry. * Structurally similar to logging by storing the history of telemetry messages by default. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ interface ITelemetry { /** * Determines whether written data will be cleared in the buffer when flush() is called. * Should be mapped to setAutoClear and isAutoClear in FTC's API. */ var autoClear: Boolean /** * Determines whether all written data will be flushed immediately, thus cancelling out the * effect of calling flush() itself. */ var autoUpdate: Boolean /** * Writes a message to telemetry. * Similar to addData() * * @param caption Caption of the message * @param data Data of the message */ fun write(caption: String, data: String) /** * Writes an error to telemetry. * * @param info The error message */ fun error(info: String) /** * Writes a warning to telemetry. * * @param info The warning message */ fun warning(info: String) /** * Writes data to telemetry. * * @param label Name of data * @param data Data */ fun data(label: String, data: Any) /** * Writes a fatal message to telemetry. * Ideally, the OpMode is expected to end immediately after this method is called. * * @param info Diagnostic info about the fatal error */ fun fatal(info: String) /** * Flushes all added messages to the screen and clears the buffer. */ fun flush() } <file_sep>package org.firstinspires.ftc.teamcode.autonomous /** * An annotation class that allows tasks (functions) to have metadata, aiding decisions. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ @Retention(AnnotationRetention.RUNTIME) annotation class Task( /** * The magnitude of the benefit as a result of executing this task successfully. * Value should be in range of [0, 1]. * * This value is used extensively in the decision-making process as the immediate reward. */ val priority: Double, /** * The risk for failure in executing this task, both detected and undetected * (regardless of return value) * Value should be in range of [0, 1]. * * This value should derive from the outcomes of test sessions to thoroughly optimize the * decisions that the robot makes in Autonomous. * * This value is used extensively in the decision-making process as the probability value. */ val reliability: Double )<file_sep>package org.firstinspires.ftc.teamcode.tests import com.qualcomm.robotcore.eventloop.opmode.OpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import com.qualcomm.robotcore.hardware.DcMotor import com.qualcomm.robotcore.hardware.DcMotorSimple import com.qualcomm.robotcore.hardware.Servo /** * Provides straightforward bindings from hardware to gamepad, enabling the testing of the glyph * mechanism. Little to no abstraction is present between the gamepad API and the DcMotor/Servo API. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ @TeleOp(name = "GlyphTest", group = "Pragmaticos") class GlyphTest : OpMode() { // -- Hardware output devices -- private lateinit var flywheelLeft: DcMotor private lateinit var flywheelRight: DcMotor private lateinit var bucketPour: Servo // -- Default power values -- private val POUR_ADDEND = 0.02 private val FLYWHEEL_POWER = 0.6 private val references = listOf( "THE" to "GLYPH TEST", "Ⓑ" to "Right flywheel", "Ⓧ" to "Left flywheel", "D-pad ▲" to "Pour bucket", "D-pad ▼" to "Unpour bucket", "Left trigger" to "Left rectifier" ) override fun init() { with(hardwareMap.dcMotor) { flywheelLeft = get("FlywheelLeft") flywheelRight = get("FlywheelRight") } bucketPour = hardwareMap.servo.get("BucketPour") telemetry.addData("Output devices", "Recognized") // Inverse direction of mirrored motors flywheelLeft.direction = DcMotorSimple.Direction.REVERSE references.forEach { (fst, snd) -> telemetry.addData(fst, snd) } telemetry.update() } override fun loop() { with(gamepad1) { on(b, FLYWHEEL_POWER) { flywheelRight.power = it } on(x, FLYWHEEL_POWER) { flywheelLeft.power = it } if (!dpad_down || !dpad_up) { on(dpad_up, POUR_ADDEND) { bucketPour.position += it } on(dpad_down, -POUR_ADDEND) { bucketPour.position += it } } // Perhaps could be more sophisticated and pleasing to the eye } } fun on(input: Boolean, power: Double, todo: (Double) -> Unit) = todo(if (input) power else 0.0) }<file_sep>package org.firstinspires.ftc.teamcode.drivetrain import com.qualcomm.robotcore.hardware.DcMotor import org.locationtech.jts.math.Vector2D /** * The IDrivetrain interface describes the methods available from a drivetrain to other parts of the program. * The actual drivetrain manager shall implement this interface. * * @author <NAME> * For team: Lightning (4410) * * FIRST - Gracious Professionalism * * # A WORD ON DIRECTIONS * * In this implementation of the Drivetrain interface, directions are represented similar to * how a vector is represented mathematically. To understand this relationship, assume that the * robot is at the origin on a four-quadrant 2D graph; The robot is facing up, or in the * positive y direction. Moving forward is equivalent a directly upward vector, or `(0, 1)`. To * strafe in the rear-leftServo direction, for example, use the vector `(-1, -1)`. Vectors have * scale, so `-1 <= value <= 1` does not have to be true all the time. If the caller would like * to move the robot a longer distance, just multiply the values. * * A complete mapping from direction to the corresponding 1-unit vector is provided below. * * - ↑ = (0, 1) * - ↗ = (1, 1) * - → = (1, 0) * - ↘ = (1, -1) * - ↓ = (0, -1) * - ↙ = (-1, -1) * - ← = (-1, 0) * - ↖ = (-1, 1) * * ## Motivation * * This system provides the flexibility that allows path-finding algorithms to manipulate * directions. For example, the forward and rightServo vectors can be summed to produce the up-rightServo * diagonal vector. * * ## Synthetic Movements * * If you decide to send a vector like `(2, 1)` to `move()`, the robot will most likely move * in a path that coincides with the vector segment (straight). By altering motor power, the robot * is capable of moving in any direction. * * _These vectors are discouraged because there is no guarantee for the order in which the * robot moves. This could potentially lead to conflict with obstacles._ * * ## Technically... * * The vector is represented by a `Vector2D` object. This class is included with JTS Topology * Suite. An enum-like class named `VectorDirection` is included with * this interface for Don't-Let-Me-Think readable code, in which case the method will be * invoked like this: `drivetrain.move(VectorDirection.FORWARD)` */ interface IDrivetrain { /** * Checks if any of the drivetrain motors are busy. * @return True if any drivetrain motor is busy, otherwise false */ val isBusy: Boolean /** * @return The default power that would be used when move(), turn(), etc. is called without * a power value. */ val defaultPower: Double /** * Whether precise actuation is engaged. When it is engaged, all output power values from TeleOp * functions are multiplied by an implementation-specific value (0,1), which reduces movement * speeds. */ var isUsingPrecisePower: Boolean /** * This enum contains values that point to each motor in the drivetrain. * This is useful for directly sending commands to the individual motors. */ enum class MotorPtr(var isFront: Boolean, var isLeft: Boolean) { FRONT_LEFT(true, true), FRONT_RIGHT(true, false), // │ │ // ├─── ROBOT! ───┤ // │ │ REAR_LEFT(false, true), REAR_RIGHT(false, false) } /** * Moves the robot according to the specified vector in default power. * If any motor in the drivetrain is busy when this is called, it will block until no motors are busy. * Ideal for Autonomous (LinearOpMode). * * @param vector The vector to move the robot in. See comment above for how it works. */ fun move(vector: Vector2D) /** * Moves the robot according to the specified vector in the specified power. * If any motor in the drivetrain is busy when this is called, it will block until no motors are busy. * Ideal for Autonomous (LinearOpMode) * * @param vector The vector to move the robot in. See comment above for how it works. * @param power The power, (0, 1], to set the motor(s) to. */ fun move(vector: Vector2D, power: Double) /** * Starts moving the robot at the default speed according to the specified direction. * Ideal for TeleOp (OpMode) * @param direction A vector from and only from {@see VectorDirection}. */ fun startMove(direction: Vector2D) /** * Starts moving the robot at the given speed according to the specified direction. * Ideal for TeleOp (OpMode) * @param direction A vector from and only from {@see VectorDirection}. * @param power Power, [0.0, 1.0], to set the necessary motors to */ fun startMove(direction: Vector2D, power: Double) /** * Sets the power of all drivetrain motors to 0, thus stopping the robot. */ fun stop() /** * Turns the robot in position for the given amount of radians (of change applied to the robot's * orientation) at the default motor power. * Ideal for Autonomous * @param radians The amount of radians to rotate the robot for, [[-2π, 2π]] */ fun turn(radians: Double) /** * Turns the robot in position for the given amount of radians (of change applied to the robot's * orientation) at the given motor power. * Ideal for Autonomous * @param radians The amount of radians to rotate the robot for, [[-2π, 2π]] * @param power The power multiplier to set the motor to, (0, 1] */ fun turn(radians: Double, power: Double) /** * Starts rotating the robot in place in the given direction. * * @param isCounterClockwise true if counter-clockwise rotation desired */ fun startTurn(isCounterClockwise: Boolean) /** * Starts rotating the robot in place with the given power multiplier for motors. * A positive given power value will cause the robot to rotate counter-clockwise. * * @param power The power multiplier, [-1, 1] */ fun startTurn(power: Double) /** * Moves and turns the robot simultaneously in the direction of the given movement vector. * Due to limits on motor power (-1 <= x <= 1), they may be scaled down to fit that range, * thus the resulting powers are not guaranteed to be consistent across different `power` or * `turnPower` inputs for the same `movement` and `turnClockwise` inputs. For example, a large * `turnPower` value may greatly reduce movement speed. * * @param movement Direction of movement relative to the current orientation of the robot * @param power Speed of movement, (0, 1] * @param turnClockwise True if turning clockwise, otherwise counter-clockwise * @param turnPower Speed of turning, (0, 1] */ fun actuate(movement: Vector2D, power: Double, turnClockwise: Boolean, turnPower: Double) /** * Gets the DcMotor object at the specified position relative to the robot. * @param ptr The motor's position relative to the robot * @return The specified motor */ fun getMotor(ptr: MotorPtr): DcMotor } <file_sep>package org.firstinspires.ftc.teamcode.drivetrain import com.qualcomm.robotcore.hardware.DcMotor import com.qualcomm.robotcore.hardware.DcMotorSimple import com.qualcomm.robotcore.util.Range import com.qualcomm.robotcore.util.RobotLog import org.firstinspires.ftc.teamcode.config.ConfigUser import org.locationtech.jts.algorithm.Angle import org.locationtech.jts.math.Vector2D /** * An implementation of IDrivetrain that was done on October 4, 2017. * * @author <NAME> * For team: Lightning (4410) * * FIRST - Gracious Professionalism */ class Drivetrain( /** * The default power setting. Used when `move` or `startMove` is called without the 2nd argument. */ override val defaultPower: Double, /** * A mapping from MotorPtrs to DcMotor instances. */ private val motors: Map<IDrivetrain.MotorPtr, DcMotor>) : IDrivetrain { init { // Reverse the direction of motors on the left. forEachOf( IDrivetrain.MotorPtr.FRONT_LEFT, IDrivetrain.MotorPtr.REAR_LEFT ) { it.direction = DcMotorSimple.Direction.REVERSE } // Preciseness of movement is crucial in AcsNavigator. // Don't let the motors drift. motors.values.forEach { it.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.BRAKE } // Reset the encoders. setMotorMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER) setMotorMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER) } // CONFIGURATION class Config : ConfigUser("Drivetrain/config.properties") { val ticksPerRevolution = file.getInteger("TicksPerRevolution") val inchesPerRevolution = file.getDouble("InchesPerRevolution") val ticksPerCircularSpin = file.getInteger("TicksPerCircularSpin") val countUsingTime = file.getBoolean("CountUsingTime") val msPerMovedInch = file.getInteger("MsPerMovedInch") val msPerCircularSpin = file.getInteger("MsPerCircularSpin") val precisePowerMultiplier = file.getDouble("PrecisePowerMultiplier") } private val config = Config() // END CONFIGURATION /** * When true, this multiplies the final power output of the motors by a value specified in the config * (as "PrecisePowerMultiplier"). This feature intends to help the driver make precise movements * when necessary, such as when unloading glyphs. */ override var isUsingPrecisePower: Boolean = false private val preciseMultiplier: Double get() = if (isUsingPrecisePower) config.precisePowerMultiplier else 1.0 /** * Defines a pair of diagonal motors. Useful for Mecanum manipulation. * The naming convention for enum constants depend on in which direction the wheels, when * rotating in positive power, take the robot. * * @author Michael */ private enum class MotorDiagonalPair(val motors: Array<IDrivetrain.MotorPtr>, val displayName: String) { RIGHT(arrayOf( IDrivetrain.MotorPtr.FRONT_LEFT, IDrivetrain.MotorPtr.REAR_RIGHT), "FL RR pair"), LEFT(arrayOf( IDrivetrain.MotorPtr.FRONT_RIGHT, IDrivetrain.MotorPtr.REAR_LEFT), "FR RL pair"); override fun toString(): String = displayName } /* # A DISCOVERY ABOUT MECANUM DIRECTIONS (0, 1) -> (1, 1) x+1 FWD (1, 1) -> (1, 0) y-1 RIGHT-FWD (1, 0) -> (1, -1) y-1 RIGHT (1, -1) -> (0, -1) x-1 RIGHT-BWD (0, -1) -> (-1, -1) x-1 BWD (-1, -1) -> (-1, 0) y+1 LEFT-BWD (-1, 0) -> (-1, 1) y+1 LEFT (-1, 1) -> (0, 1) x+1 LEFT-FWD Conclusion: a 45-degree clockwise rotation will convert an input vector to a vector where the x value is the relative target position for the RIGHT pair and the y value is the <...> for the LEFT pair. Power calculation: - Rotate vector 45 deg - Scale vector to have absolute value of at least one component be 1 ((-1, -0.4), (0.3, 1)) - Multiply vector by given power value - Assign components to diagonal pairs Target position calculation: - Rotate vector 45 deg - Convert both components from inches to revolutions, then to ticks - Assign converted ticks to diagonal pairs Duration calculation: - Rotate vector 45 deg - Convert both components from inches to milliseconds, then divide both by power value - Sleep for converted milliseconds (then stop motors) */ /** * Calculates a mapping from the diagonal pairs of motors to their power from * any arbitrary vector. * @param vec The vector indicating the direction to move in * @param power Power multiplier, (0, 1] * @return A mapping from a diagonal pair of motors to their desired power */ private fun getMovementPowers(vec: Vector2D, power: Double): Map<MotorDiagonalPair, Double> { val directionPowers = normalize(vec.rotate(Angle.toRadians(315.0))).multiply(power) return mapOf( MotorDiagonalPair.RIGHT to directionPowers.x, MotorDiagonalPair.LEFT to directionPowers.y ) } // Power has range [-1, 1] // Positive power means clockwise turning private fun getTurnPowers(power: Double): Map<IDrivetrain.MotorPtr, Double> { if (power == 0.0) { // No turning, 0 power return this.motors.keys.map { it to power }.toMap() } return mapOf( IDrivetrain.MotorPtr.REAR_LEFT to power, IDrivetrain.MotorPtr.FRONT_LEFT to power, IDrivetrain.MotorPtr.REAR_RIGHT to -power, IDrivetrain.MotorPtr.FRONT_RIGHT to -power ) } /** * Converts a direction in which the caller wishes to travel to a mapping from diagonal pair to * that pair's desired target position in inches. * * @param direction A vector from the robot to the target position where the robot is at (0,0) * @return A mapping from a diagonal pair to its desired relative position in inches */ private fun directionToRelativeTargets(direction: Vector2D): Map<MotorDiagonalPair, Double> { val positions = direction.rotate(Angle.toRadians(315.0)) return mapOf( MotorDiagonalPair.RIGHT to positions.x, MotorDiagonalPair.LEFT to positions.y ) } /** * Scales the given vector proportionally into one whose max abs(component) is 1. * Creates a clone. * @param vec The vector to be normalized * @return The normalized vector */ private fun normalize(vec: Vector2D): Vector2D { if (vec.x == 0.0 && vec.y == 0.0) { return Vector2D(vec) } return vec.divide(Math.max(Math.abs(vec.x), Math.abs(vec.y))) } private fun checkPower(power: Double) { if (power == 0.0) { throw RuntimeException("power cannot be 0, the robot will not move") } if (power < 0) { throw RuntimeException("power ($power) cannot be negative, robot will move in opposite direction") } } // Same as startMove(), except without mode setting. Universal across encoder and non-encoder. private fun setMotorPowers(direction: Vector2D, multiplier: Double) { // Grab the pair -> power properties, then set the power of each motor in each pair to its mapped // value. getMovementPowers(direction, multiplier).entries // For each pair -> power entry .forEach { mapping -> forEachOf(*mapping.key.motors) { it.power = mapping.value RobotLog.ii(mapping.key.displayName, mapping.value.toString()) } } } private fun setRelativeTargetPosition(motor: DcMotor, relativeInch: Double) { // i in IPR in TPR tick // t = ─────── / ─────── * ────────── // 1 1 rot 1 rot val relativeTicks = relativeInch / config.inchesPerRevolution * config.ticksPerRevolution motor.targetPosition = motor.currentPosition + Math.round(relativeTicks).toInt() RobotLog.dd(motor.connectionInfo, "POS_SET C=${motor.currentPosition} T=$relativeTicks") } private fun forEachOf(vararg motors: IDrivetrain.MotorPtr, todo: (DcMotor) -> Unit) { motors.map(this::getMotor).forEach(todo) } private fun setMotorMode(mode: DcMotor.RunMode) { this.motors.values .forEach { it.mode = mode } } private fun dissolvePairMap(map: Map<MotorDiagonalPair, Double>): Map<IDrivetrain.MotorPtr, Double> = map.entries.map { (pair, power) -> pair.motors.map { it to power } }.flatten().toMap() private fun normalizeDoubleCircle(radians: Double): Double = Angle.normalizePositive(Math.abs(radians)) * (if (radians < 0.0) -1 else 1) /** * Moves the robot according to the specified vector in default power. * If any motor in the drivetrain is busy when this is called, it will block until no motors are busy. * Ideal for Autonomous (LinearOpMode). * * @param vector The vector to move the robot in. See comment above for how it works. */ override fun move(vector: Vector2D) = this.move(vector, defaultPower) /** * Moves the robot according to the specified vector in the specified power. * Blocks until the movement is finished. * Ideal for Autonomous (LinearOpMode) * * @param vector The vector to move the robot in. See comment above for how it works. * @param power The power, [0.0, 1.0], to set the motor(s) to. */ override fun move(vector: Vector2D, power: Double) { checkPower(power) // Vector with endpoint as origin means no movement if (vector.x == 0.0 && vector.y == 0.0) return RobotLog.i("Moving to $vector") if (config.countUsingTime) { setMotorMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER) val waitTime = config.msPerMovedInch * vector.length() / power setMotorPowers(vector, power) Thread.sleep(waitTime.toLong()) stop() } else { setMotorMode(DcMotor.RunMode.RUN_USING_ENCODER) // Determine the positional targets for each motor pair directionToRelativeTargets(vector).forEach { (pair, position) -> // Set the relative target position of all motors in the pair pair.motors.forEach { setRelativeTargetPosition(getMotor(it), position) } } setMotorMode(DcMotor.RunMode.RUN_TO_POSITION) setMotorPowers(vector, power) while (this.isBusy); stop() } } /** * Checks if any of the drivetrain motors are busy. * * @return True if any drivetrain motor is busy, otherwise false */ override val isBusy: Boolean get() = this.motors.values.any { it.isBusy } /** * Starts moving the robot at the default speed according to the specified direction. * NOTE: Overrides existing power * Ideal for TeleOp (OpMode) * * @param direction A vector from and only from {@see VectorDirection}. */ override fun startMove(direction: Vector2D) = this.startMove(direction, defaultPower) /** * Starts moving the robot at the given speed according to the specified direction. * NOTE: Overrides existing power * Ideal for TeleOp (OpMode) * * @param direction A vector from and only from {@see VectorDirection}. * @param power Power, [0.0, 1.0], to set the necessary motors to */ override fun startMove(direction: Vector2D, power: Double) { //this.setUsingEncoders(false) this.setMotorMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER) this.setMotorPowers(direction, power * preciseMultiplier) } /** * Sets the power of all drivetrain motors to 0, thus stopping the robot. */ override fun stop() { for (motor in this.motors.values) { motor.power = 0.0 } } /** * Turns the robot in position for the given amount of radians (of change applied to the robot's * orientation) at the default motor power. * * @param radians The amount of radians to rotate the robot for, [-2π, 2π] */ override fun turn(radians: Double) = turn(radians, defaultPower) /** * Turns the robot in position for the given amount of radians (of change applied to the robot's * orientation) at the given motor power. * * @param radians The amount of radians to rotate the robot for, [-2π, 2π] * @param power The power multiplier to set the motor to, (0, 1] */ override fun turn(radians: Double, power: Double) { if (radians == 0.0) return if (config.countUsingTime) { this.setMotorMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER) val waitTime = config.msPerCircularSpin * (Math.abs(radians) / 2 * Math.PI) / power val (leftPower, rightPower) = if (radians < 0.0) { power to -power } else { -power to power } forEachOf(IDrivetrain.MotorPtr.FRONT_RIGHT, IDrivetrain.MotorPtr.REAR_RIGHT) { it.power = rightPower } forEachOf(IDrivetrain.MotorPtr.FRONT_LEFT, IDrivetrain.MotorPtr.REAR_LEFT) { it.power = leftPower } Thread.sleep(waitTime.toLong()) stop() } else { // RUN_USING_ENCODER first this.setMotorMode(DcMotor.RunMode.RUN_USING_ENCODER) // Turn the radians into relative ticks for one side of the drivetrain, then the other side // is the negation of that value. val tickMagnitude = Math.round(normalizeDoubleCircle(radians) / (2 * Math.PI) * config.ticksPerCircularSpin) // !! Used to negate if below 0.0 // Wait for other motor operations to complete while (this.isBusy); forEachOf( IDrivetrain.MotorPtr.FRONT_RIGHT, IDrivetrain.MotorPtr.REAR_RIGHT ) { it.targetPosition = it.currentPosition + tickMagnitude.toInt() it.mode = DcMotor.RunMode.RUN_TO_POSITION it.power = power } forEachOf( IDrivetrain.MotorPtr.FRONT_LEFT, IDrivetrain.MotorPtr.REAR_LEFT ) { it.targetPosition = (it.currentPosition - tickMagnitude).toInt() it.mode = DcMotor.RunMode.RUN_TO_POSITION it.power = power } while (this.isBusy); stop() } } // Redundancy purposefully included to improve readability override fun startTurn(isCounterClockwise: Boolean) = if (isCounterClockwise) { startTurn(defaultPower) } else { startTurn(-defaultPower) } override fun startTurn(power: Double) { val validPower = Range.clip(power, -1.0, 1.0) * preciseMultiplier this.setMotorMode(com.qualcomm.robotcore.hardware.DcMotor.RunMode.RUN_WITHOUT_ENCODER) if (power == 0.0) { return } forEachOf( IDrivetrain.MotorPtr.FRONT_RIGHT, IDrivetrain.MotorPtr.REAR_RIGHT ) { it.power = validPower } forEachOf( IDrivetrain.MotorPtr.FRONT_LEFT, IDrivetrain.MotorPtr.REAR_LEFT ) { it.power = -validPower } } override fun actuate(movement: Vector2D, power: Double, turnClockwise: Boolean, turnPower: Double) { if (power == 0.0 && turnPower == 0.0) { stop() return } // Step 1: Get the movement powers val powers = dissolvePairMap(getMovementPowers(movement, power)).toMutableMap() // Step 2: Adjust by the turn powers val turnPowers = getTurnPowers( if (turnClockwise) turnPower else -turnPower) powers.entries.forEach { (ptr, pwr) -> powers[ptr] = pwr + turnPowers[ptr]!! } // Step 3: Scale to [-1, 1] if not in limits val scale = powers.values.map(Math::abs).max() ?: 0.0 if (scale > 1.0) { powers.entries.forEach { (ptr, pwr) -> powers[ptr] = pwr / scale } } // Step 4: Assign powers to motors, with preciseMultiplier setMotorMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER) for ((ptr, pwr) in powers) { this.getMotor(ptr).power = pwr * preciseMultiplier } } /** * Gets the DcMotor object at the specified position relative to the robot. * * @param ptr The motor's position relative to the robot * @return The DcMotor object representing the specified motor */ override fun getMotor(ptr: IDrivetrain.MotorPtr): DcMotor = this.motors[ptr]!! } <file_sep>package org.firstinspires.ftc.teamcode.autonomous import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark import org.firstinspires.ftc.teamcode.AllianceColor import org.firstinspires.ftc.teamcode.config.ConfigUser import org.firstinspires.ftc.teamcode.io.Hardware import org.locationtech.jts.algorithm.Angle import org.locationtech.jts.math.Vector2D /** * Provides basic abstraction of Autonomous movements. * * @author <NAME> * For team: 4410 * * FIRST - Gracious Professionalism */ class AutoNav : IAutoNav { class Config : ConfigUser("AutoNav/config.properties") { /** * Width between the MIDDLE of the cryptobox columns in inches. 7.63 according to game manual. */ val cryptoboxWidth = file.getDouble("CryptoboxWidth") /** * Vector from the starting point to the optimal position to place a glyph in the middle column * of the desired cryptobox, where the starting point is closer to a corner of the playing field and is red. * This vector may need to be temporarily adjusted for leaving the balancing stone, for it may * produce a slight inaccuracy in encoder-based positioning. */ // This vector's orientation is relative to the front of our robot in its starting position. // Given that the jewel arm is on the left, consider the starting position as the origin, and // positive y as up (in the diagram). // This vector will be flipped across the X axis when our alliance color is BLUE. val cryptoboxPositionCorner = Vector2D( file.getDouble("CryptoboxPositionCornerX"), file.getDouble("CryptoboxPositionCornerY") ) /** * Vector from the starting point to the optimal position to place a glyph in the middle column * of the desired cryptobox, where the starting point is farther to a corner of the playing field and is red. * This vector may need to be temporarily adjusted for leaving the balancing stone, for it may * produce a slight inaccuracy in encoder-based positioning. */ // This vector's orientation is relative to the front of our robot in its starting position. // Given that the jewel arm is on the left, consider the starting position as the origin, and // positive y as up (in the diagram). // This vector will be flipped across the X axis when our alliance color is BLUE. val cryptoboxPositionCentered = Vector2D( file.getDouble("CryptoboxPositionCenteredX"), file.getDouble("CryptoboxPositionCenteredY") ) /** * Distance from starting point to the ideal location of dropping the jewel arm. * It is assumed that looking from the wall to which the cryptobox key is attached, the robot * will ONLY move VERTICALLY for this distance in inches. In other words, the starting point * is lined up with the white line between the jewels. */ val jewelAccessOffset = file.getDouble("JewelAccessOffset") val drivePower = file.getDouble("DrivePower") } private val config = Config() private val isStartingOnCorner: Boolean get() = AutonomousBase.startingLeft == (AutonomousBase.alliance == AllianceColor.RED) /** * Currently performs the following to the given vector and returns the final modified output: * * - Mirror across the x axis if on BLUE alliance * * @param vec The initial vector to modify * @returns The final modified output */ private fun finalizeVector(vec: Vector2D): Vector2D { // Pipeline operation requires clone var out = Vector2D(vec) if (AutonomousBase.alliance == AllianceColor.BLUE) { out = Vector2D(out.x, -out.y) } return out } // Jewel arm on left side (negative x) override fun beginJewelKnock() { Hardware.drivetrain.move(Vector2D(config.jewelAccessOffset, 0.0), config.drivePower) } override fun endJewelKnock() { Hardware.drivetrain.move(Vector2D(-config.jewelAccessOffset, 0.0), config.drivePower) } override fun beginReadingVuMark() = Hardware.drivetrain.turn(Math.PI) // Turning 180 degrees has the same result regardless of direction of rotation override fun endReadingVuMark() = Hardware.drivetrain.turn(Math.PI) private fun instructionsToCryptoBox(): Pair<Vector2D, Double> { return if (isStartingOnCorner) // Same rotation for CORNER of both sides finalizeVector(config.cryptoboxPositionCorner) to -90.0 else // Red needs to turn 180deg for CENTERED, Red is lined up already finalizeVector(config.cryptoboxPositionCentered) to if (AutonomousBase.alliance == AllianceColor.RED) 0.0 else 180.0 } private fun instructionsToColumn(vuMark: RelicRecoveryVuMark): Vector2D { if (vuMark == RelicRecoveryVuMark.UNKNOWN) { Hardware.telemetry.warning("Instructions to UNKNOWN cryptobox column?!") return Vector2D(0.0, 0.0) } // NOTE: The robot MUST face the cryptobox before moving in this vector. return Vector2D(when (vuMark) { RelicRecoveryVuMark.LEFT -> -config.cryptoboxWidth RelicRecoveryVuMark.RIGHT -> config.cryptoboxWidth else -> 0.0 }, 0.0) } override fun goToCryptoBox(vuMark: RelicRecoveryVuMark) { val (movement, turnDeg) = instructionsToCryptoBox() with(Hardware.drivetrain) { move(Vector2D(0.0, movement.y), config.drivePower) move(Vector2D(movement.x, 0.0), config.drivePower) turn(Angle.toRadians(turnDeg), config.drivePower) move(instructionsToColumn(vuMark), config.drivePower) // FIXME repetition } } override fun returnFromCryptoBox(vuMark: RelicRecoveryVuMark) { val (movement, turnDeg) = instructionsToCryptoBox() with(Hardware.drivetrain) { move(instructionsToColumn(vuMark).negate(), config.drivePower) turn(Angle.toRadians(-turnDeg), config.drivePower) move(movement.negate(), config.drivePower) } } }<file_sep>package org.firstinspires.ftc.teamcode.io import com.qualcomm.robotcore.hardware.DcMotor import com.qualcomm.robotcore.hardware.Servo import com.qualcomm.robotcore.util.Range import org.firstinspires.ftc.teamcode.config.ConfigUser /** * A generic implementation of `IGlyphManipulator`. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ class GlyphManipulator( override val collectorLeft: DcMotor, override val collectorRight: DcMotor, override val bucketPour: Servo, override val offsideBucketPour: Servo, override val glyphRectifiers: Set<Servo>) : IGlyphManipulator { // CONFIGURATIONS val config = Config() class Config : ConfigUser("GlyphManipulator/config.properties") { val rectMax = file.getDouble("RectifierMax") val rectMin = file.getDouble("RectifierMin") val leftCollectorPower = file.getDouble("LeftCollectorPower") val rightCollectorPower = file.getDouble("RightCollectorPower") val pourMax = file.getDouble("PourMax") val pourMin = file.getDouble("PourMin") val pourTime = file.getInteger("PourTime") val pourIntermediate = file.getDouble("PourIntermediate") } // Shadow values for avoiding unnecessary calls to hardware // Values to apply during initialization private var _collectorPower: Double = 0.0 // DO NOT CHANGE INITIAL VALUE - DANGEROUS private var _bucketPourPos: Double = 0.0 // DO NOT CHANGE INITIAL VALUE - DANGEROUS private var _rectifierPos: Double = config.rectMax // Initialization should take place to ensure that shadow values and hardware state match // before applyState is called. init { // Apply scaleRange bucketPour.scaleRange(config.pourMin, config.pourMax) offsideBucketPour.scaleRange(config.pourMin, config.pourMax) glyphRectifiers.forEach { it.scaleRange(config.rectMin, config.rectMax) } applyState() Hardware.telemetry.write("GlyphManipulator", "Initialized") } /** * Applies the values of all shadow variables to hardware. */ private fun applyState() { collectorLeft.power = _collectorPower * config.leftCollectorPower collectorRight.power = _collectorPower * config.rightCollectorPower bucketPour.position = _bucketPourPos offsideBucketPour.position = _bucketPourPos glyphRectifiers.forEach { it.position = _rectifierPos } } override var collectorPower: Double get() = _collectorPower set(value) { _collectorPower = value applyState() } override var bucketPourPos: Double get() = _bucketPourPos set(value) { _bucketPourPos = Range.clip(value, 0.0, 1.0) applyState() } override var rectifierPos: Double get() = _rectifierPos set(value) { _rectifierPos = Range.clip(value, 0.0, 1.0) applyState() } override fun placeGlyph() { bucketPourPos = config.pourIntermediate Thread.sleep((config.pourTime * config.pourIntermediate).toLong() + 100) bucketPourPos = config.pourMax } // FIXME Redundancy - Factory functions? // Furthermore, this pattern can be found in some other hardware devices. It would be ideal to // generalize this pattern and reduce redundancy. }<file_sep>package org.firstinspires.ftc.teamcode.autonomous import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark /** * Describes functions that the Vuforia wrapper shall implement and what it should be able to do. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ interface IVuforia { /** * Initiate the tracking. * Should call trackables.activate(). */ fun startTracking() /** * Tries to read the VuMark that may be shown on camera. * May call `RelicRecoveryVuMark.from(template)`. * * @return The VuMark that was read */ fun readVuMark(): RelicRecoveryVuMark /** * Stop the tracking. * No clean-up code was found in the example class file. This function may be empty. */ fun stopTracking() }<file_sep>package org.firstinspires.ftc.teamcode.autonomous import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark /** * Describes methods provided by the autonomous navigation module for OpMode use. * * @author <NAME> * For team: 4410 * * FIRST - Gracious Professionalism */ interface IAutoNav { // The implementation should use info from DynamicConfig to determine the final drivetrain // instructions. /** * Moves from the starting point to the position in which jewel knocking is performed. */ fun beginJewelKnock() /** * Returns from the jewel-knocking position to the starting point. */ fun endJewelKnock() /** * Moves/turns from the starting position. to the position in which the phone's camera faces the VuMark. */ fun beginReadingVuMark() /** * Moves/turns from the position in which the phone's camera faces the VuMark to the starting position. */ fun endReadingVuMark() /** * Moves from the starting point to the position in which a glyph may be scored to the given * column of the appropriate cryptobox. */ fun goToCryptoBox(vuMark: RelicRecoveryVuMark) /** * Moves from the given column of the appropriate cryptobox back to the starting point. */ fun returnFromCryptoBox(vuMark: RelicRecoveryVuMark) }<file_sep>package org.firstinspires.ftc.teamcode.io import com.qualcomm.robotcore.hardware.ColorSensor import com.qualcomm.robotcore.hardware.Servo import org.firstinspires.ftc.teamcode.AllianceColor /** * The knocker of jewels, implemented for use in Autonomous. * Includes all functions necessary to control the knocker. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ interface IJewelKnocker { // I/O requirements val color: ColorSensor val arm: Servo /** * Lowers the knocker arm on which the color sensor is mounted. * Blocks until the arm has finished moving. */ fun lowerArm() /** * Reads from the ColorSensor and returns the TeamColor to which the values are closest. * @return The team color at which the color sensor seems to be looking, or null if the data is confusing. */ fun detect(): AllianceColor? /** * Moves or turns the robot in a way that knocks off a jewel in the direction specified by the * parameter, raises the arm, and returns to its position before the knock. * Blocks until the arm has finished moving. * * @param towardDetectedJewel Whether the jewel whose color is detected by color sensor shall be knocked off */ fun removeJewel(towardDetectedJewel: Boolean) /** * Raises the knocker arm on which the color sensor is mounted. * Blocks until the arm has finished moving. */ fun raiseArm() // The ideal scoring process: // - lowerArm() // - detect() == DynamicConfig.team ? // - removeJewel([result above]) // - raiseArm() }<file_sep>package org.firstinspires.ftc.teamcode.autonomous import com.qualcomm.robotcore.eventloop.opmode.Autonomous import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark import org.firstinspires.ftc.teamcode.AllianceColor import org.firstinspires.ftc.teamcode.config.ConfigUser import org.firstinspires.ftc.teamcode.io.Hardware import org.locationtech.jts.math.Vector2D import java.util.* /** * The base LinearOpMode procedure in which autonomous operation is performed. * Four actions that score points for us: * - Putting pre-loaded glyph into column * - The right column according to the VuMark * - Knocking off the right jewel * - Parking in the safe zone * * To use this base class, extend it while specifying its constructor parameters and put * the annotation on that class. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ open class AutonomousBase(val allianceColor: AllianceColor, val isStartingLeft: Boolean) : LinearOpMode() { companion object { // Statically available properties lateinit var alliance: AllianceColor var startingLeft: Boolean = true } class Config : ConfigUser("AutonomousBase/config.properties") { val taskSequence = file.getStringList("TaskSequence") val motorPower = file.getDouble("MotorPower") val useDecisionMaker = file.getBoolean("UseDecisionMaker") val useAutoCelebrator = file.getBoolean("UseAutoCelebrator") // Task definition decisions val jewelSenseAttempts = file.getInteger("JewelSenseAttempts") val jewelDisplacementMax = file.getDouble("JewelDisplacementMax") // For how much should it wait for Vuforia to recognize the VuMark? (in ms) val vuMarkTimeout = file.getInteger("VuMarkTimeout") val flywheelPower = file.getDouble("FlywheelPower") // For how long should it power the motors to shove the glyphs into place? (in ms) val glyphShoveTime = file.getInteger("GlyphShoveTime") } lateinit var config: Config lateinit var navigator: IAutoNav lateinit var vuforia: IVuforia lateinit var decider: DecisionMaker var vuMark: RelicRecoveryVuMark? = null /** * Main procedure for Autonomous. * * @throws InterruptedException */ @Throws(InterruptedException::class) override fun runOpMode() { if (!initAll()) return waitForStart() if (config.useDecisionMaker) { Hardware.telemetry.write("Task Decision Model", "Arbitrary") while (!decider.isDone && !isStopRequested) { runTask(decider.nextTask()!!) } } else { Hardware.telemetry.write("Task Decision Model", "Predefined") var useFailsafe = false val seqIt = config.taskSequence.iterator() while (seqIt.hasNext() && !isStopRequested) { if (runTask(seqIt.next()) != true) { Hardware.telemetry.error("Predefined task failure, fail-safe") useFailsafe = true break } } if (useFailsafe) { while (!decider.isDone && !isStopRequested) { val task = decider.nextTask() if (task != null) { runTask(task) } else { Hardware.telemetry.warning("Next task returned null while decider not done") } } } // We're finished, celebrate if enabled if (config.useAutoCelebrator) { try { val celebrator = AutoCelebrator() celebrator.startMusic("celebrate.wav") celebrator.begin { isStopRequested } } catch (exc: Exception) { Hardware.telemetry.fatal("Celebration failed: ${exc.message}") } } } } /** * Initializes all necessary systems for Autonomous operation. * Includes the following systems: * - Telemetry ╮ * - Drivetrain ├─ Hardware * - Manipulators│ * - Sensors ╯ * - Navigator (GameMap) * - VuMark Reading (Vuforia) * - Decision maker */ private fun initAll(): Boolean { try { // PRE-INIT - must be above all others config = Config() Hardware.init(this, config.motorPower) with(Hardware) { navigator = AutoNav() vuforia = Vuforia(opMode) decider = DecisionMaker() // No need to hold telemetry data back in a LinearOpMode Hardware.telemetry.autoClear = false Hardware.telemetry.autoUpdate = true // Assign properties to companion object alliance = allianceColor startingLeft = isStartingLeft Hardware.telemetry.data("Tasks", decider.nextTasks) } } catch (exc: Exception) { telemetry.addData("FATAL", "ERROR") telemetry.addData("Initialization failed", exc.message ?: "for a reason unknown to humankind") telemetry.update() return false } return true } /** * Executes the task with the given name verbosely. * @returns The result returned by the task */ private fun runTask(taskName: String): Boolean? { Hardware.telemetry.write("Performing next task", taskName) val result = decider.doTask(taskName, this) Hardware.telemetry.data("Task $taskName successful?", result ?: "there was a problem, so no") return result } // Tasks // TODO("testing pending") Optimize reliability coefficients object Tasks { @Task(priority = 30.0 / 85.0, reliability = 0.75) fun knockJewel(opMode: AutonomousBase): Boolean { /** Moves the arm for a random amount in either direction, bounded by a configured parameter.*/ fun armDisplacement() = (Random().nextDouble() - 0.5) * 2 * opMode.config.jewelDisplacementMax with(Hardware.knocker) { opMode.navigator.beginJewelKnock() lowerArm() run attempt@ { repeat(opMode.config.jewelSenseAttempts) { i -> Hardware.telemetry.write("Knock jewel attempt", (i + 1).toString()) opMode.sleep(1000) val colorDetected = detect() // If no concrete conclusion arises from the data, fail this task if (colorDetected != null) { // Knock off the jewel of color opposite to the team we're on Hardware.telemetry.write("Color detected", colorDetected.toString()) removeJewel(colorDetected != alliance) return@attempt } arm.position += armDisplacement() } } opMode.navigator.endJewelKnock() // Precisely restoring the start position is hopeless. If jewel not removed, give up return true } } @Task(priority = 10.0 / 85.0, reliability = 0.9) fun parkInSafeZone(opMode: AutonomousBase): Boolean { opMode.navigator.goToCryptoBox(RelicRecoveryVuMark.CENTER) opMode.sleep(2000) return true } @Task(priority = 30.0 / 85.0, reliability = 0.7) fun readVuMark(opMode: AutonomousBase): Boolean { with(opMode) { navigator.beginReadingVuMark() vuforia.startTracking() // Allow camera to focus opMode.sleep(3000) // Repeat until timeout or recognition val startTime = System.currentTimeMillis() while (System.currentTimeMillis() - startTime < opMode.config.vuMarkTimeout) { vuMark = vuforia.readVuMark() if (vuMark != null) break } vuforia.stopTracking() Hardware.telemetry.write("Read VuMark", vuMark?.name ?: "Failed") navigator.endReadingVuMark() // If its representation is known, it's successful return vuMark != RelicRecoveryVuMark.UNKNOWN } } @Task(priority = 15.0 / 85.0, reliability = 0.7) fun placeInCryptoBox(opMode: AutonomousBase): Boolean { fun moveForTime(direction: Vector2D, time: Int) { Hardware.drivetrain.startMove(direction) Thread.sleep(time.toLong()) Hardware.drivetrain.stop() } opMode.navigator.goToCryptoBox(opMode.vuMark ?: RelicRecoveryVuMark.RIGHT) with (Hardware) { glypher.collectorPower = opMode.config.flywheelPower glypher.placeGlyph() opMode.sleep(400) // Shove it just a bit drivetrain.move(Vector2D(0.0, 0.5)) glypher.collectorPower = 0.0 // Remove contact with glyph drivetrain.move(Vector2D(0.0, -1.0)) // Shove again moveForTime(Vector2D(0.0, 0.6), opMode.config.glyphShoveTime) moveForTime(Vector2D(0.0, -0.6), 250) glypher.bucketPourPos = 0.0 } return true } } } @Autonomous(name = "Auto Red Left", group = "Pragmaticos") class RedLeftAuto : AutonomousBase(AllianceColor.RED, true) @Autonomous(name = "Auto Red Right", group = "Pragmaticos") class RedRightAuto : AutonomousBase(AllianceColor.RED, false) @Autonomous(name = "Auto Blue Left", group = "Pragmaticos") class BlueLeftAuto : AutonomousBase(AllianceColor.BLUE, true) @Autonomous(name = "Auto Blue Right", group = "Pragmaticos") class BlueRightAuto : AutonomousBase(AllianceColor.BLUE, false) <file_sep>package org.firstinspires.ftc.teamcode /** * Provides data types that represent the color of a team in FTC. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ enum class AllianceColor { RED, BLUE; companion object { fun oppositeOf(color: AllianceColor) = when (color) { RED -> BLUE BLUE -> RED } } }<file_sep>package org.firstinspires.ftc.teamcode.config /** * Describes a customized type that allows individual modules to use configuration. * Upon extension, the following format is recommended: * ``` * class Config : ConfigUser("myfile.properties") { * val customItem = file.getDouble("CustomItem"); * ... * } * ``` * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ open class ConfigUser(filename: String) { val file = ConfigFile(filename) // All other fields shall be defined in classes extending this }<file_sep>~/Library/Android/sdk/platform-tools/adb push storage/* /storage/self/primary/FIRST/config<file_sep>package org.firstinspires.ftc.teamcode.teleop import com.qualcomm.robotcore.hardware.Gamepad /** * Provides a mechanism that stores the gamepad's state, allowing actions to be performed when a * given value of the gamepad *changes*. * * IMPORTANT: the `update` method should be called repetitively to trap gamepad changes * responsively. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism * * @constructor Listens for given GamepadProperties of the given Gamepad */ class GamepadListener(val pad: Gamepad, val rules: List<GamepadRule>) { /** * The state variable containing all necessary values. Each element's index corresponds to the same index in the keySet of this.rules. * * Example: Let rules be defined as follows: mapOf( * {it.x} to {x -> telem.data("X value updated, now", x)} * {it.y} to {y -> telem.data("Y value updated, now", y)} * ); the state list, being [true, false], means that previously {it.x} was activated and * {it.y} was not. */ var state: MutableList<Boolean> init { // Initialize state state = fetchState().toMutableList() } /** * Checks the necessary values on the gamepad and determines if they have changed. If this is * true, then call the callbacks as defined in the constructor. * * NOTE: Should be called repeatedly (i.e. added to loop() or init_loop()) to catch gamepad changes. * */ fun update() { fetchState() .zip(this.state) .forEachIndexed { index, (new, old) -> if (new != old) { // Change detected, call callback and update state rules[index].second(new) this.state[index] = new } } } private fun fetchState(): List<Boolean> = rules.map { it.first(pad) } } /** * Describes a binary (or transformed to binary) property of a gamepad. * * Examples: `{ it.left_bumper }` or `{ it.left_trigger > 0.3 }` */ typealias GamepadProperty = (Gamepad) -> Boolean /** * Describes what should be done when a GamepadProperty has changed. * * Examples: `Pair({ it.left_bumper }, { if (it) activateMotor() else deactivateMotor() }) */ typealias GamepadRule = Pair<GamepadProperty, Action> /** * Describes actions performed when there is a change in gamepad controls. * The argument will be the (new) value of the property to which this action corresponds in the * GamepadListener constructor. * * Example: with GamepadListener(gamepad1, mapOf( * {it.left_bumper} to {value -> telemetry.write("Update in value! left bumper now", value)} * )), "Update in value..." will show up on the driver station when the left bumper is pressed or released. */ typealias Action = (Boolean) -> Unit <file_sep>package org.firstinspires.ftc.teamcode.tests import com.qualcomm.robotcore.eventloop.opmode.OpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import org.firstinspires.ftc.teamcode.autonomous.IVuforia import org.firstinspires.ftc.teamcode.autonomous.Vuforia /** * Provides a basic demonstration / test of the capabilities of Vuforia at recognizing the VuMark. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ @TeleOp(name = "Vuforia Test", group = "Pragmaticos") class VuforiaTest : OpMode() { // Quick reference for the unacquainted val reference = listOf( "Introducing" to "...", "THE VUFORIA™" to " TESTER", "-----" to "-----", "Just let the desired camera on the robot controller" to "see the VuMark", "And watch" to "the magic happen", "-----" to "-----", "Disclaimer" to "May be the most addictive test here", "-----" to "-----" ) // Vuforia's wrapper var vuforia: IVuforia? = null override fun init() { reference.forEach { (fst, snd) -> telemetry.addData(fst, snd) } vuforia = Vuforia(this) vuforia!!.startTracking() telemetry.addData("Vuforia", "Initialized") telemetry.update() } override fun loop() { with(vuforia!!) { telemetry.addData("I'm seeing", readVuMark()) } telemetry.update() } override fun stop() { vuforia!!.stopTracking() } }<file_sep>package org.firstinspires.ftc.teamcode.tests import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import org.firstinspires.ftc.teamcode.io.Hardware import org.locationtech.jts.algorithm.Angle import org.locationtech.jts.math.Vector2D /** * Tests the drivetrain implementation and the hardware for correct operation of the motor encoders. * * @author <NAME> * For team: 4410 * */ @TeleOp(name = "EncoderTest", group = "Pragmaticos") class EncoderTest : LinearOpMode() { override fun runOpMode() { Hardware.init(this, 1.0) waitForStart() telemetry.addData("Y axis", "X axis: Diagonal: Turning") telemetry.update() Hardware.telemetry.autoUpdate = true with(Hardware.drivetrain) { move(Vector2D(0.0, 1.0)) move(Vector2D(1.0, 0.0)) move(Vector2D(1.0, 2.0)) turn(Angle.toRadians(90.0)) } } }<file_sep>repositories { maven { url 'https://repo.locationtech.org/content/repositories/jts-snapshots' } mavenCentral() } dependencies { compile 'org.locationtech.jts:jts-core:1.15.0-SNAPSHOT' // https://mvnrepository.com/artifact/com.sun.phobos/jsr223-api compile group: 'com.sun.phobos', name: 'jsr223-api', version: '1.0' compile project(':FtcRobotController') compile (name: 'RobotCore-release', ext: 'aar') compile (name: 'Hardware-release', ext: 'aar') compile (name: 'FtcCommon-release', ext: 'aar') compile (name:'Analytics-release', ext:'aar') compile (name:'WirelessP2p-release', ext:'aar') } <file_sep>package org.firstinspires.ftc.teamcode.autonomous import android.content.Context import com.qualcomm.robotcore.eventloop.opmode.OpMode import org.firstinspires.ftc.robotcore.external.ClassFactory import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables /** * Includes necessary abstractions of the Vuforia API for use by AutonomousMain. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ class Vuforia(opMode: OpMode, useCameraMonitor: Boolean = true) : IVuforia { companion object { // Setup procedures fun createLocalizer(context: Context, useCameraMonitor: Boolean): VuforiaLocalizer { // Initialize parameters for passing to the constructor of the localizer. val params = if (useCameraMonitor) { VuforiaLocalizer.Parameters(context.resources.getIdentifier( "cameraMonitorViewId", "id", context.packageName) ) } else { VuforiaLocalizer.Parameters() } params.vuforiaLicenseKey = "<KEY>" params.cameraDirection = VuforiaLocalizer.CameraDirection.FRONT return ClassFactory.createVuforiaLocalizer(params) } fun loadTrackables(localizer: VuforiaLocalizer): VuforiaTrackables = localizer.loadTrackablesFromAsset("RelicVuMark") fun loadTemplate(trackables: VuforiaTrackables): VuforiaTrackable { val template = trackables[0] template.name = "RelicVuMarkTemplate" return template } } // Constructs (initializes) the Vuforia trackables & localizer val localizer = createLocalizer(opMode.hardwareMap.appContext, useCameraMonitor) private val trackables = loadTrackables(localizer) private val template = loadTemplate(trackables) override fun startTracking() = trackables.activate() override fun readVuMark() = RelicRecoveryVuMark.from(template) override fun stopTracking() {} }<file_sep>PourRhythm=2,2,2,2,2,2,2,2,2,2,2,2,6,2 PourMovementTime=40 BPM=128 PourDown=0.0 PourUp=0.2<file_sep>package org.firstinspires.ftc.teamcode.io import com.qualcomm.robotcore.eventloop.opmode.OpMode import com.qualcomm.robotcore.hardware.DcMotorSimple import com.qualcomm.robotcore.hardware.Servo import org.firstinspires.ftc.teamcode.drivetrain.Drivetrain import org.firstinspires.ftc.teamcode.drivetrain.IDrivetrain import org.firstinspires.ftc.teamcode.telemetry.ITelemetry import org.firstinspires.ftc.teamcode.telemetry.Telemetry /** * Declares modules and hardware necessary to run both Autonomous and TeleOp. * Includes all code shared by both modes. * Both AutonomousBase and TeleOpMain should call `init()` as soon as the OpModes are started. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ object Hardware { lateinit var opMode: OpMode var motorPower: Double = 0.8 lateinit var drivetrain: IDrivetrain lateinit var telemetry: ITelemetry lateinit var glypher: GlyphManipulator lateinit var knocker: IJewelKnocker // LATEINIT - OpModes MUST initialize ASAP using this function, otherwise expect NPEs! fun init(_opMode: OpMode, _motorPower: Double) { // Assign to lateinit (has to stay above any other initialization procedure) opMode = _opMode motorPower = _motorPower telemetry = Telemetry(opMode.telemetry) try { with(opMode.hardwareMap) { // Mecanum wheels drivetrain = Drivetrain(motorPower, mapOf( IDrivetrain.MotorPtr.FRONT_LEFT to dcMotor.get("FrontLeft"), IDrivetrain.MotorPtr.FRONT_RIGHT to dcMotor.get("FrontRight"), IDrivetrain.MotorPtr.REAR_LEFT to dcMotor.get("RearLeft"), IDrivetrain.MotorPtr.REAR_RIGHT to dcMotor.get("RearRight") )) // Reverse direction of FlywheelRight motor & RectifierRight due to symmetry // Reverse BEFORE initializing GlyphManipulator dcMotor.get("FlywheelRight").direction = DcMotorSimple.Direction.REVERSE servo.get("RectifierRight").direction = Servo.Direction.REVERSE servo.get("OffsideBucketPour").direction = Servo.Direction.REVERSE // GlyphManipulator instance glypher = GlyphManipulator( collectorLeft = dcMotor.get("FlywheelLeft"), collectorRight = dcMotor.get("FlywheelRight"), bucketPour = servo.get("BucketPour"), offsideBucketPour = servo.get("OffsideBucketPour"), glyphRectifiers = setOf( servo.get("RectifierLeft"), servo.get("RectifierRight") )) knocker = AuxJewelKnocker( telemetry, drivetrain, color = colorSensor.get("JewelSensor"), arm = servo.get("JewelArm")) } } catch (exc: Exception) { telemetry.fatal( "Failed to initialize hardware: ${exc.message ?: "the robot, too, doesn't know why"}") opMode.requestOpModeStop() throw RuntimeException(exc) } } }<file_sep>package org.firstinspires.ftc.teamcode.tests import com.qualcomm.robotcore.eventloop.opmode.OpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import com.qualcomm.robotcore.hardware.ColorSensor /** * A utility program that reads color values from the sensor and writes them to telemetry. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ @TeleOp(name = "ColorTest", group = "Pragmaticos") class ColorTest : OpMode() { // The sensor lateinit var sensor: ColorSensor override fun init() { sensor = hardwareMap.get(ColorSensor::class.java, "JewelSensor") // Set the LED in the beginning sensor.enableLed(true) } override fun loop() { with(telemetry) { addData("Red", sensor.red()) addData("Green", sensor.green()) addData("Blue", sensor.blue()) addData("Alpha", sensor.alpha()) update() } } }<file_sep>package org.firstinspires.ftc.teamcode.autonomous import com.qualcomm.robotcore.util.ElapsedTime import org.firstinspires.ftc.teamcode.io.Hardware import kotlin.reflect.KCallable import kotlin.reflect.KClass import kotlin.reflect.full.findAnnotation /** * Defines the strategic logic used by the robot to decide which task to accomplish in a given state. * Employs recursive Depth-First Search while making decisions. * * @author <NAME> * For team: 4410 * * FIRST - Gracious Professionalism */ class DecisionMaker(tasks: KClass<AutonomousBase.Tasks> = AutonomousBase.Tasks::class) { // CONFIGURATIONS companion object { /** * The discount factor ("urgency coefficient"), [[0, 1]], describes how the preference * factor of tasks decay when they are planned to be executed in the future. * * This lambda determines the discount factor, optionally dynamically with dependence on how * many seconds have passed since the Autonomous period began. */ // The current lambda is linear, equivalent to f(x)=1 - x/30, where x is seconds elapsed val discountFactor = { timer: ElapsedTime -> 1.0 - (timer.seconds() / periodDuration) } /** * The duration of the Autonomous period in seconds. */ private val periodDuration = 30.0 } /** * Tasks available, immutable, reflective of all members of the given Tasks class that has the * Task annotation class. */ private val options = tasks.members.filter { it.annotations.any { it is Task } } .map { it.name to it } .toMap() /** * Gets the Task annotation of the callable itself. * * @throws NullPointerException If the callable does not have a Task annotation */ private val KCallable<*>.metadata: Task get() = findAnnotation()!! /** * A running timer, which is used for dynamic discountFactor determination. * The timer starts when the DecisionMaker is instantiated. */ private val timer: ElapsedTime = ElapsedTime() /** * A to-do list of tasks that are not executed yet. * (Guaranteed to be a subset of options) */ val nextTasks = options.keys.toMutableSet() /** * Whether there are remaining tasks in the to-do list. * * @see nextTasks */ val isDone: Boolean get() = nextTasks.isEmpty() /** * Performs the task with the given name (of a member of the given `Tasks` class), passing it the * given instance of AutonomousMain as a parameter. * * @param name Name of the task the caller wishes to execute * @param opMode The instance to pass to the task method * @return `null` when name parameter not in options or when task threw an exception, * otherwise whether the task succeeded */ fun doTask(name: String, opMode: AutonomousBase): Boolean? { return if (nextTasks.contains(name)) { try { // Reflection requires casting; if name in nextTasks, then it's in options val result = options.getValue(name).call(AutonomousBase.Tasks, opMode) as Boolean // If the task was successful, then remove it from the set of remaining ones if (result) nextTasks.remove(name) result } catch (exc: Exception) { Hardware.telemetry.error("doTask exception: ${exc.message}") null } } else null } // All possible states following the given state, analogous to the children of a tree node private fun nextStates(tasksPending: Set<String>) = tasksPending.map { tasksPending - it } private fun getMetadataFromName(name: String) = options[name]!!.metadata /** * Depending on the reliability and priority of each task, pick the next task to execute. * * @return `null` if there are no tasks remaining to do, otherwise the name of the chosen task */ fun nextTask(): String? { fun value(state: Set<String>, depth: Int = 0): Double = when (state.size) { // This case should never be reached unless nextTasks is empty, which means everything // has been accomplished and the robot is finished for autonomous. // Ideally it would be Double.MAX_VALUE, but due to suspected issues with overflowing // while calculating the sum, it has been reduced to 10 million. 0 -> 10_000_000.0 1 -> { val nextAction = getMetadataFromName(state.first()) nextAction.priority * nextAction.reliability * Math.pow(discountFactor(timer), depth.toDouble()) } else -> nextStates(state).map { value(it, depth + 1) }.sum() } if (this.isDone) return null return nextTasks .maxBy { value(nextTasks - it) } } }<file_sep>package org.firstinspires.ftc.teamcode.tests import com.qualcomm.robotcore.eventloop.opmode.Autonomous import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode import com.qualcomm.robotcore.hardware.DcMotor import com.qualcomm.robotcore.hardware.DcMotorSimple import com.qualcomm.robotcore.hardware.Servo /** * A rhythmic test of the BucketPour servos and the collector motors. */ @Autonomous(name = "Rhythmic", group = "Pragmaticos") class RhythmTest : LinearOpMode() { /* ELECTRONICS */ lateinit var leftPour: Servo lateinit var leftCollector: DcMotor lateinit var rightCollector: DcMotor companion object { /* POSITIONS and POWER */ const val POUR_DOWN = 0.0 const val POUR_UP = 0.3 const val COLLECTOR_POWER = 0.5 /* RHYTHM SPEED */ const val BPM = 300.0 } val drum = DrumAlternator(this) /* RHYTHM */ val piece = arrayOf( drum::alternate to arrayOf(2.0, 2.0, 2.0, 2.0), this::activateCollectors to arrayOf(2.0, 2.0, 1.0, 1.0, 2.0), drum::alternate to arrayOf(2.0, 2.0, 2.0, 2.0), this::activateCollectors to arrayOf(2.0, 2.0, 1.0, 1.0, 2.0) ) override fun runOpMode() { // Define electronics with(hardwareMap) { leftPour = servo.get("BucketPour") leftCollector = dcMotor.get("FlywheelLeft") rightCollector = dcMotor.get("FlywheelRight") } // Follow symmetry rightCollector.direction = DcMotorSimple.Direction.REVERSE telemetry.isAutoClear = false // Initialize instruments leftCollector.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.BRAKE rightCollector.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.BRAKE waitForStart() // Run through phrases for ((func, phrase) in piece) { runPhrase(func, phrase) } } fun activateCollectors() { leftCollector.power = COLLECTOR_POWER rightCollector.power = COLLECTOR_POWER sleep(100) leftCollector.power = 0.0 rightCollector.power = 0.0 } fun runPhrase(func: () -> Unit, phrase: Array<Double>) { for (beat in phrase) { func() sleep(Math.round(beat / (BPM / 60_000.0))) } } class DrumAlternator(val opMode: RhythmTest) { var isLeftDown: Boolean = false fun alternate() { opMode.leftPour.position = if (isLeftDown) POUR_UP else POUR_DOWN isLeftDown = !isLeftDown } } }<file_sep>package org.firstinspires.ftc.teamcode.io import com.qualcomm.robotcore.hardware.ColorSensor import com.qualcomm.robotcore.hardware.Servo import org.firstinspires.ftc.teamcode.AllianceColor import org.firstinspires.ftc.teamcode.config.ConfigUser import org.firstinspires.ftc.teamcode.drivetrain.IDrivetrain import org.firstinspires.ftc.teamcode.telemetry.ITelemetry import org.locationtech.jts.math.Vector2D /** * An auxiliary implementation of the IJewelKnocker interface for backup use. * For documentation on the individual methods, see IJewelKnocker. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ class AuxJewelKnocker(val telemetry: ITelemetry, val drivetrain: IDrivetrain, override val color: ColorSensor, override val arm: Servo) : IJewelKnocker { // CONFIGURATION class Config : ConfigUser("JewelKnocker/config.properties") { val servoDelay = file.getInteger("ServoDelay") // Servo positions val raisedPosition = file.getDouble("RaisedPosition") val loweredPosition = file.getDouble("LoweredPosition") // When to be certain that it is one color? val colorThreshold = file.getInteger("ColorThreshold") // Facing direction of the color sensor val isColorSensorFacingFront = file.getBoolean("IsColorSensorFacingFront") // How far to go when knocking a jewel off? val knockDistance = file.getDouble("KnockDistance") } val config = Config() init { // Lock the servo upon start raiseArm() } override fun lowerArm() { arm.position = config.loweredPosition Thread.sleep(config.servoDelay.toLong()) } override fun detect(): AllianceColor? { // Enable LED color.enableLed(true) // Allow values to stabilize Thread.sleep(600) val isBlue = color.blue() - color.red() > config.colorThreshold val isRed = color.red() - color.blue() > config.colorThreshold return when { isBlue && !isRed -> AllianceColor.BLUE isRed && !isBlue -> AllianceColor.RED else -> { telemetry.error("ColorSensor data is confusing") telemetry.data("RED", color.red()) telemetry.data("BLUE", color.blue()) null } } } override fun removeJewel(towardDetectedJewel: Boolean) { val initialVec = Vector2D( 0.0, (if (towardDetectedJewel == config.isColorSensorFacingFront) 1 else -1) * config.knockDistance) drivetrain.move(initialVec) raiseArm() drivetrain.move(initialVec.negate()) } override fun raiseArm() { arm.position = config.raisedPosition Thread.sleep(config.servoDelay.toLong()) } }<file_sep>package org.firstinspires.ftc.teamcode.tests import com.qualcomm.robotcore.eventloop.opmode.OpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import com.qualcomm.robotcore.hardware.DcMotor /** * A utility program that tests all drivetrain motors individually for potential hardware issues. * Does not involve IDrivetrain. * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ @TeleOp(name = "DrivetrainTest", group = "Pragmaticos") class DrivetrainTest : OpMode() { // -- MOTORS -- var frontLeft: DcMotor? = null var frontRight: DcMotor? = null var rearLeft: DcMotor? = null var rearRight: DcMotor? = null val allMotors = arrayOf(frontLeft, frontRight, rearLeft, rearRight) var usingEncoders = false // Quick reference for the unacquainted val reference: List<Pair<String, String>> = listOf( "Introducing" to "...", "THE DRIVE" to "TRAIN TESTER", "To test a particular motor," to "press the matching button on gamepad 1", "-----" to "-----", "Front left" to "Ⓨ", "Front right" to "Ⓑ", "Rear left" to "Ⓧ", "Rear right" to "Ⓐ", "Toggle whether encoders are used" to "Right Bumper", "-----" to "-----", "Disclaimer" to "May be addictive", "-----" to "-----" ) override fun init() { with(hardwareMap.dcMotor) { frontLeft = get("FrontLeft") frontRight = get("FrontRight") rearLeft = get("RearLeft") rearRight = get("RearRight") } reference.forEach { (fst, snd) -> telemetry.addData(fst, snd) } telemetry.update() } override fun loop() { map(frontLeft, gamepad1.y) map(frontRight, gamepad1.b) map(rearLeft, gamepad1.x) map(rearRight, gamepad1.a) if (gamepad1.right_bumper) onToggleEncoders() telemetry.update() } fun valueOfBool(value: Boolean): Double = if (value) 0.4 else 0.0 fun map(motor: DcMotor?, value: Boolean) { if (usingEncoders && value && !motor!!.isBusy) { motor.targetPosition = motor.currentPosition + 10 motor.power = 0.4 } else if (!usingEncoders) { motor!!.power = valueOfBool(value) } } private fun onToggleEncoders() { allMotors.forEach { it!!.mode = if (usingEncoders) DcMotor.RunMode.RUN_WITHOUT_ENCODER else DcMotor.RunMode.RUN_TO_POSITION } usingEncoders = !usingEncoders telemetry.addData("UsingEncoders now", usingEncoders) } }<file_sep>package org.firstinspires.ftc.teamcode.teleop import com.qualcomm.robotcore.eventloop.opmode.OpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import com.qualcomm.robotcore.util.Range import org.firstinspires.ftc.teamcode.config.ConfigUser import org.firstinspires.ftc.teamcode.io.Hardware import org.locationtech.jts.math.Vector2D /** * Main procedure for TeleOp during Relic Recovery. * As a quick reference, the following actions score points for our team during TeleOp/end game. * - Glyph stored in cryptobox * - Completed row of 3 or column of 4 * - Completed cipher * - Robot balanced on balancing stone * - (end game) Relic in Zone 1 thru 3 * - (end game) Relic upright bonus * * @author <NAME> * For team: 4410 (Lightning) * * FIRST - Gracious Professionalism */ @TeleOp(name = "TeleOp Main", group = "Pragmaticos") class TeleOpMain : OpMode() { // Configuration values class Config : ConfigUser("TeleOp/config.properties") { val motorPower = file.getDouble("MotorPower") val turnSpeed = file.getDouble("TurnSpeed") val glyphCollectorPower = file.getDouble("GlyphCollectorPower") val pourSensitivity = file.getDouble("PourSensitivity") val rectSensitivity = file.getDouble("RectifierSensitivity") } object InputColumns { lateinit var collectorIn: ChangeBasedInputColumn<Boolean> lateinit var collectorOut: ChangeBasedInputColumn<Boolean> lateinit var precisionMove: ChangeBasedInputColumn<Boolean> } private lateinit var config: Config override fun init() { // Initialize systems config = Config() Hardware.init(this, config.motorPower) // Initialize toggle input surfaces, which currently includes collectorIn use (A, gamepad 2) InputColumns.collectorIn = ChangeBasedInputColumn { gamepad2.a } InputColumns.collectorOut = ChangeBasedInputColumn { gamepad2.b } InputColumns.precisionMove = ChangeBasedInputColumn { gamepad1.x } // Lock the jewel arm Hardware.knocker.raiseArm() } override fun loop() { // Gamepad mappings with(Hardware) { fun Boolean.int() = if (this) 1.0 else 0.0 with(gamepad1) { // Drivetrain movement val moveVec = Vector2D( left_stick_x.toDouble(), -left_stick_y.toDouble()) telemetry.write("Move vector", moveVec.toString()) val turnPower = right_stick_x * config.motorPower * config.turnSpeed telemetry.write("Turn power", turnPower.toString()) drivetrain.actuate(moveVec, moveVec.length() / Math.sqrt(2.0) * config.motorPower, true, turnPower) // Triggers -> rectifier glypher.rectifierPos = Range.clip( glypher.rectifierPos + (left_trigger - right_trigger) * config.rectSensitivity, 0.0, 1.0) if (right_bumper) { Hardware.knocker.raiseArm() } // X button -> toggle -> precise movement InputColumns.precisionMove.onChange { _, new -> if (new) drivetrain.isUsingPrecisePower = !drivetrain.isUsingPrecisePower } } with(gamepad2) { fun openCloseBind(close: Boolean, open: Boolean, current: Boolean) = current != (close != open && current != open) // Bucket pour -> Left stick y, forward = vertical, backward = laid down glypher.bucketPourPos = Range.clip( glypher.bucketPourPos - left_stick_y.toDouble() * config.pourSensitivity, 0.0, 1.0) // Collector toggle between idle & pulling in -> A button // Push out -> B button InputColumns.collectorIn.onChange { _, new -> glypher.collectorPower = new.int() * config.glyphCollectorPower } InputColumns.collectorOut.onChange { _, new -> glypher.collectorPower = new.int() * -config.glyphCollectorPower } // Temporary solution: TODO } } // Messages only pertain to one loop Hardware.telemetry.flush() } // A button toggle collectorIn // Up/down lift // right stick up / down: bucket eject // right bumper open, left bumper close clamp /** * A class that retains input state and performs a given callback when the state changes. */ class ChangeBasedInputColumn<out T>(private val input: () -> T) { private var previousState = input() /** * Calls the given lambda if the input value has changed. Should be called only once during * each loop. */ fun onChange(todo: (T, T) -> Unit): T { val newState = input() if (newState != previousState) { todo(previousState, newState) previousState = newState } return newState } } }<file_sep># Lightning (Team 4410) Code _Relic Recovery_, 2017-2018 <file_sep>CryptoboxWidth=2.0 CryptoboxPositionCornerX=1.2 CryptoboxPositionCornerY=8 CryptoboxPositionCenteredX=-3.75 CryptoboxPositionCenteredY=6.245 JewelAccessOffset=0.65 DrivePower=0.5 <file_sep>package org.firstinspires.ftc.teamcode.autonomous import android.media.MediaPlayer import org.firstinspires.ftc.teamcode.config.ConfigFile import org.firstinspires.ftc.teamcode.config.ConfigUser import org.firstinspires.ftc.teamcode.io.Hardware import java.io.File /** * Don't you think the robot enjoys having the belief that it finished all the enabled tasks? * Here's where its loud percussive noise can really make a mark. */ class AutoCelebrator { class Config : ConfigUser("AutoCelebrator.properties") { // Music to play val pourRhythm = file.getStringList("PourRhythm").map(String::toInt) val pourMovementTime = file.getInteger("PourMovementTime") // Music parameters val BPM = file.getInteger("BPM") // Servo positions val pourDown = file.getDouble("PourDown") val pourUp = file.getDouble("PourUp") } private val config = Config() private val pour = Hardware.glypher.bucketPour private val media = MediaPlayer() init { with (Hardware.telemetry) { write("I'm", "Done!") write("Time to", "Celebrate") } } // Blocks when setting, if applicable. private var pourRaised: Boolean = false set(raised) { pour.position = if (raised) config.pourUp else config.pourDown if (raised != field) { Thread.sleep(config.pourMovementTime.toLong()) field = raised } } private fun playNote(time: Int) { if (time > 2 * config.pourMovementTime) Hardware.telemetry.warning("Can't keep up! Target time $time") val startTime = System.currentTimeMillis() pourRaised = false pourRaised = true while (System.currentTimeMillis() - startTime < time); } fun startMusic(name: String) { media.setDataSource(ConfigFile.CONFIG_PATH + File.pathSeparator + name) media.prepare() media.start() } fun stopMusic() = media.stop() fun begin(isStopRequested: () -> Boolean) = run block@ { config.pourRhythm.forEach { beat -> playNote(60_000 / config.BPM * beat) if (isStopRequested()) { return@block } } } }
45ad1b127d2e1a5e94afe1796a2af40448f0f97c
[ "Markdown", "INI", "Gradle", "Java", "Kotlin", "Shell" ]
38
Shell
ARC-Lightning/Relic_Recovery-2017-2018
8129a39a3a0b88522aec9a6a5f273781fbc3d69c
f01eb4717d2d9c8dd3ecaff45e93b7c030210a4b
refs/heads/master
<repo_name>froggugugugu/banchatest<file_sep>/public_html/app/webroot/js/src/app/controller/Main.js // {{{ 'BE.controller.Main', /** * @class BE.controller.Main * メインコントローラ */ Ext.define('BE.controller.Main', { // {{{ extend extend : 'Ext.app.Controller', // }}} // {{{ refs インスタンス化されたViewへの参照提供 get([R]efname) /* refs: [{ selector: 'xtype..',ref: 'localname' }], */ /* // }}} // {{{ views クラスへの参照提供 get(Xxxx)View views:[ 'Views' ], // }}} // {{{ models クラスへの参照提供 get(Xxxx)Model models:[ 'Models' ], // }}} // {{{ stores インスタンスへの参照提供 get(Xxxx)Store stores: [ 'Store' ], // }}}*/ // {{{ init //アプリケーション起動時にコールされる特別なメソッド //ApplicationのLaunch前にコールされる init: function() { //alert('hoge'); var me = this; me.control(me.bindItem); }, // {{{ bindItem bindItem: { // 作成 'usergrid' : { create: function(){ var me = this; alert('create dispatch'); me.getController('Usergrid').onCreate(); }, reset: function(){ var me = this; alert('reset dispatch'); me.getController('Usergrid').onReset(); }, save: function(){ var me = this; alert('save dispatch'); me.getController('Usergrid').onSave(); }, del: function(rowIndex){ var me = this; alert('save dispatch'); me.getController('Usergrid').onDelete(rowIndex); } /* hoge: function(){ var me = this; me.getController('Hoge').onHoge(); },*/ } } /* // }}} // }}} // {{{ onXXXX onXXXX: function() { console.log('hoge'); } */ // }}} }); // }}} <file_sep>/public_html/app/webroot/js/src/app.js Ext.ns('BE'); // Ext.Loader有効化 Ext.Loader.setConfig({ enabled: true, paths: { 'Ext': './ext/src', 'BE': './js/src' } }); //Bancha 初期化 Bancha.onModelReady('User',function(){ //alert('hoge'); // アプリケーション設定 Ext.application({ // Viewport自動生成 autoCreateViewport: true, // アプリケーション名 name: 'BE', // アプリケーションフォルダパス appFolder: './js/src/app', // 使用コントローラー定義 controllers: [ 'Main'//, //'Usergrid' ], // アプリケーション起動時イベントハンドラ launch: function() { } }); }); <file_sep>/public_html/app/webroot/js/src/app/view/Viewport.js // {{{ BE.view.Viewport Ext.define('BE.view.Viewport', { // {{{ requires requires: [ 'BE.view.Usergrid' ], // }}} // {{{ extend extend: 'Ext.container.Viewport', // }}} // {{{ layout layout: { type: 'border', padding: 5 }, // }}} // {{{ items items: [{ region: 'center', //html: 'hoge' xtype: 'usergrid' }/*,{ region: 'east', html: 'hoge' }*/] // }}} }); // }}} <file_sep>/public_html/app/webroot/js/src/app/store/user.js // {{{ 'BE.store.User', /** * @class BE.store.User * desctription */ /*Ext.define('BE.store.User', { // {{{ extend extend : 'Ext.data.Store', // }}} // {{{ model model: Bancha.getModel('User'), autoLoad: true // }}} });*/ // }}} <file_sep>/public_html/app/Test/Case/Controller/TblUsersControllerTest.php <?php App::uses('TblUsersController', 'Controller'); /** * TestTblUsersController * */ class TestTblUsersController extends TblUsersController { /** * Auto render * * @var boolean */ public $autoRender = false; /** * Redirect action * * @param mixed $url * @param mixed $status * @param boolean $exit * @return void */ public function redirect($url, $status = null, $exit = true) { $this->redirectUrl = $url; } } /** * TblUsersController Test Case * */ class TblUsersControllerTestCase extends CakeTestCase { /** * Fixtures * * @var array */ public $fixtures = array('app.tbl_user'); /** * setUp method * * @return void */ public function setUp() { parent::setUp(); $this->TblUsers = new TestTblUsersController(); $this->TblUsers->constructClasses(); } /** * tearDown method * * @return void */ public function tearDown() { unset($this->TblUsers); parent::tearDown(); } /** * testIndex method * * @return void */ public function testIndex() { } /** * testView method * * @return void */ public function testView() { } /** * testAdd method * * @return void */ public function testAdd() { } /** * testEdit method * * @return void */ public function testEdit() { } /** * testDelete method * * @return void */ public function testDelete() { } } <file_sep>/public_html/app/webroot/js/src/app/controller/Usergrid.js // {{{ 'BE.controller.Usergrid', /** * @class BE.controller.Usergrid * ユーザグリッドコントローラ */ Ext.define('BE.controller.Usergrid', { // {{{ extend extend : 'Ext.app.Controller', // }}} // {{{ refs インスタンス化されたViewへの参照提供 get([R]efname) refs: [{ selector: 'usergrid',ref: 'crudgrid' }], // }}} // {{{ views クラスへの参照提供 get(Xxxx)View /* views:[ ], */ // }}} // {{{ models クラスへの参照提供 get(Xxxx)Model // }}} // {{{ stores インスタンスへの参照提供 get(Xxxx)Store /* stores: [ 'User' ], */ // }}} }); // }}}
e25e3a2a621ed71b02ae9fda79095b84040c218d
[ "JavaScript", "PHP" ]
6
JavaScript
froggugugugu/banchatest
06979bec84ba9c63ef058a0c3a747dba52e0492a
0b04966f320cd7d1dc862fb4ba8fc6f3fdecec2f
refs/heads/master
<repo_name>victorfeijo/cormen<file_sep>/Python/Insertion.py # This algorithim is wrong, i need repair later! def insertion(a): for j in range(1, len(a)): key = a[j] i = j - 1 while i >= 0 and a[i] > key: a[i + 1] = a[i] i = i - 1 a[i + 1] = key print a b = insertion([12 , 4 , 5 , 6 , 8, 1, 11 , 7]) <file_sep>/README.md cormen ====== Algorithm by Cormen - Introduction to algorithms
56d6fe0a91fba70a3f04ac80e233144ece468f94
[ "Markdown", "Python" ]
2
Python
victorfeijo/cormen
c8e3ec614ff1da3e799bbdb282873068c25f1a04
990e76d9a22476e2d60706c1702bb9050336f4c1
refs/heads/master
<repo_name>mhickman/cdbi<file_sep>/build.gradle apply plugin: "java" apply plugin: "idea" apply plugin: "eclipse" repositories { mavenCentral() } group = "com.mhickman" task wrapper(type: Wrapper) { gradleVersion = "1.8" } dependencies { compile group: 'com.datastax.cassandra', name: 'cassandra-driver-core', version: '1.0.4' compile group: 'com.google.guava', name: 'guava', version: '15.0' testCompile group: 'junit', name: 'junit', version: '4.11' testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' }<file_sep>/src/main/java/com/mhickman/cdbi/CDBIInvocationHandler.java package com.mhickman.cdbi; import com.datastax.driver.core.Session; import com.google.common.collect.ImmutableMap; import com.mhickman.cdbi.annotation.CQLCreate; import com.mhickman.cdbi.annotation.CQLQuery; import com.mhickman.cdbi.annotation.CQLUpdate; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class CDBIInvocationHandler<T> implements InvocationHandler { private final Session session; private final ImmutableMap<Method, MethodHandler> methodHandlers; CDBIInvocationHandler(Session session, Class<T> clazz) { this.session = session; methodHandlers = mapMethods(clazz).build(); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (methodHandlers.containsKey(method)) { return methodHandlers.get(method).callMethod(method,args); } else { throw new IllegalStateException(); } } private ImmutableMap.Builder<Method, MethodHandler> mapMethods(Class<T> clazz) { ImmutableMap.Builder<Method, MethodHandler> methodMapBuilder = ImmutableMap.builder(); for (Method method : clazz.getMethods()) { if (method.getAnnotation(CQLCreate.class) != null) { String createStatement = method.getAnnotation(CQLCreate.class).value(); methodMapBuilder.put(method, new CreateMethodHandler(createStatement, session)); } else if(method.getAnnotation(CQLQuery.class) != null) { String queryStatement = method.getAnnotation(CQLQuery.class).value(); methodMapBuilder.put(method, new QueryMethodHandler(queryStatement, session)); } else if(method.getAnnotation(CQLUpdate.class) != null) { String updateStatement = method.getAnnotation(CQLUpdate.class).value(); methodMapBuilder.put(method, new UpdateMethodHandler(updateStatement, session)); } } return methodMapBuilder; } } <file_sep>/README.md [![Build Status](https://travis-ci.org/mhickman/cdbi.png)](https://travis-ci.org/mhickman/cdbi) CDBI ================= A convenience wrapper for the Datastax Cassandra driver. This is just a small personal project inspired mostly by the wonderful JDBI library written by <NAME>. <file_sep>/src/main/java/com/mhickman/cdbi/RowMapper.java package com.mhickman.cdbi; import com.datastax.driver.core.Row; /** * This interface is meant to be registered on a data access object to * automatically map rows from the result set to objects automatically. * <p/> * An implementation of this interface can either be registered with the * DAO interface directory via the {@code RegisterMapper} annotation, or * it can be registered for a specific method with the {@code Mapper} * annotation. * * @param <T> Class to be mapped to. * @author <NAME> - <EMAIL> */ public interface RowMapper<T> { /** * Returns a mapped {@code T} from a given {@code Row}. * * @param row * @return */ public T map(Row row); } <file_sep>/src/main/java/com/mhickman/cdbi/CreateMethodHandler.java package com.mhickman.cdbi; import com.datastax.driver.core.Session; import java.lang.reflect.Method; public class CreateMethodHandler extends AbstractMethodHandler { private final String createStatement; CreateMethodHandler(String createStatement, Session session) { super(session); this.createStatement = createStatement; } @Override public Object callMethod(Method method, Object[] args) { session.execute(createStatement); return null; } }
54050f635216336a95dc2a065e8040d9fa5cba4e
[ "Markdown", "Java", "Gradle" ]
5
Gradle
mhickman/cdbi
02b1ee373097ab4f816bb23ebb1c607d8ec09806
70aea0c25f2ac8bd100a27803cd487f383fdcf50
refs/heads/master
<file_sep>using Microsoft.AspNetCore.Mvc; using WebApplication.Models.In; using System; using System.Net.Http; using System.Net.Http.Headers; using WebApplication.Constants; using Microsoft.AspNetCore.Http; namespace WebApplication.Controllers { public class MenuController : Controller { public IActionResult Menu() { return View(); } public IActionResult Adicionar(ItemCompraIn item) { if (item is null) throw new ArgumentNullException(nameof(item)); using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var response = httpClient.GetStringAsync(new Uri(Services.UrlAdicionarItem)).Result; } return RedirectToAction("Menu", "Menu"); } } }<file_sep>namespace WebApplication.Models.To { public class ItensCompraTo { public int CodigoItem { get; set; } public string Item { get; set; } public int Quantidade { get; set; } public double Valor { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using WebApplication.Constants; using WebApplication.Models.In; using WebApplication.Models.To; namespace WebApplication.Controllers { public class CarrinhoController : Controller { public IActionResult CarrinhoCompras() { //var itens = BuscarItensCarrinho(); var itens = new List<ItemCompraIn>() { new ItemCompraIn { Nome = "Hulk", Preco = 26.00 }, new ItemCompraIn { Nome = "Hulk", Preco = 26.00 }, new ItemCompraIn { Nome = "<NAME>", Preco = 47.00 } }; return View(AgruparItensCarrinho(itens)); } public void Remover() { using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var response = httpClient.GetStringAsync(new Uri(Services.UrlRemoverItens)).Result; } } private List<ItensCompraTo> AgruparItensCarrinho(List<ItemCompraIn> itens) { return itens.GroupBy(x => x.Nome) .Select(s => new ItensCompraTo { Item = s.Key, Quantidade = s.Count(), Valor = (s.Count() * s.FirstOrDefault().Preco) }) .ToList(); } private List<ItemCompraIn> BuscarItensCarrinho() { var usuario = HttpContext.Session.GetString(Sessions.SessionUser); if (usuario is null) { throw new ArgumentNullException(nameof(usuario)); } using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var response = httpClient.GetStringAsync(new Uri(Services.UrlBuscarItens)).Result; } return new List<ItemCompraIn>(); } } }<file_sep>namespace WebApplication.Models.Out { public class BaseOut { public bool Sucesso { get; set; } public string Mensagem { get; set; } } } <file_sep>namespace WebApplication.Constants { public static class Services { public const string UrlAutenticacao = "https://localhost:44368/api/values"; public const string UrlAdicionarItem = "https://localhost:44368/api/values"; public const string UrlBuscarItens = "https://localhost:44368/api/values"; public const string UrlRemoverItens = "https://localhost:44368/api/values"; } } <file_sep>using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Net.Http; using System.Net.Http.Headers; using WebApplication.Constants; using WebApplication.Models; namespace WebApplication.Controllers { public class LoginController : Controller { public IActionResult Login() { ViewBag.UsuarioInvalido = false; return View(); } [HttpPost] public IActionResult Login(LoginIn loginBE) { ViewBag.UsuarioInvalido = true; try { //var login = RealizarLogin(loginBE); var login = new LoginOut { nomeUsuario = "Leticia", loginValido = true }; if(login.loginValido) { HttpContext.Session.SetString(Sessions.SessionUser, login?.nomeUsuario); ViewBag.Usuario = HttpContext.Session.GetString(Sessions.SessionUser); ViewBag.UsuarioInvalido = false; return RedirectToAction("Index", "Home", HttpContext.Session); } } catch (Exception ex) { ViewData["Message"] = $"Ocorreu um erro ao realizar o login. Por favor tente novamente. [{ex.Message}]"; } return View(); } private LoginOut RealizarLogin(LoginIn loginIn) { if (loginIn is null) { throw new ArgumentNullException(nameof(loginIn)); } using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var response = httpClient.GetStringAsync(new Uri(Services.UrlAutenticacao)).Result; return new LoginOut { nomeUsuario = response }; } } } }
882f60a1a382fed066816791634c54e88a7072a6
[ "C#" ]
6
C#
luiz7586/web-lanchonete_app
c4397334018f909b6e2c8dbaa73088b65b930a44
ce90f830e5ae6e908e4583c17f501554e92c2fc2
refs/heads/master
<file_sep>//set environment variables with the dotenv package require("dotenv").config(); // Required NPM Packages var inquirer = require('inquirer'); var Twitter = require('twitter'); var Spotify = require('node-spotify-api'); var request = require("request"); //To access exports from keys.js file var keys = require("./keys.js"); // fs is a core Node package for reading and writing files var fs = require("fs"); //object initialised for the constructors - Spotify & Twitter var spotify = new Spotify(keys.spotify); var client = new Twitter(keys.twitter); //array to store commands&name that needs to be written in logfile var logFile = []; //inquirer prompt to get user commands inquirer.prompt([{ type: "input", message: "Enter Your name: ", name: "username" }, { type: "list", message: "Your LIRI command: ", name: "command", choices: ["my-tweets", "spotify-this-song", "movie-this", "do-what-it-says"] }, ]).then(function (response) { var name = ""; //prompt ot get movie/song name only if the command choosen is spotify or movie if (response.command === "spotify-this-song" || response.command === "movie-this") { inquirer.prompt({ type: 'input', name: 'name', message: 'Movie/Song Name: ', }).then(function (result) { name = result.name; //function call console.log((response.username).toUpperCase() + ", Data for your " + (response.command).toUpperCase() + " from LIRI! \n"); commandExecution(response.command, name); }); } else { console.log((response.username).toUpperCase() + ", Data for your " + (response.command).toUpperCase() + " from LIRI! \n"); //function call commandExecution(response.command, name); } }); /*if the user specified command matches LIRI commands then the correspponding action takes place and logged */ function commandExecution(commands, name) { logFile.push(commands); switch (commands) { case "my-tweets": my_tweets(); log(); break; case "spotify-this-song": spotify_this_song(name); log(); break; case "movie-this": movie_this(name); log(); break; case "do-what-it-says": do_what_it_says(); log(); break; } } /*function for the my-tweets command, it shows last 20 tweets and their created datetime*/ function my_tweets() { var limit = 20; // get request to the Twitter API for my tweets and their createdat values client.get('statuses/user_timeline', function (error, tweets, response) { if (!error) { for (var i = 0; i < limit; i++) { if (tweets[i]) { console.log(tweets[i].text); console.log(tweets[i].created_at); console.log("____________________________"); } else { break; } } } else { console.log('Error occurred: ' + error); logFile.push(error); } }); } /*function for the spotify-this-song command, if song name is given in command line then it displays specific information for that song, else it takes default songname and displays its info*/ function spotify_this_song(songName) { //if songname is not given in command line if (songName === "") { songName = "The+Sign"; } // search request to the Spotify API for the given songname spotify.search({ type: 'album', query: songName, limit: 2 }, function (err, data) { if (err) { console.log('Error occurred: ' + err); logFile.push(err); } else { console.log("Artists: " + data.albums.items[0].artists[0].name); console.log("________"); console.log("The Song's Name: " + data.albums.items[0].name); console.log("________________"); console.log("Preview link from Spotify: " + data.albums.href); console.log("__________________________"); console.log("Album: " + data.albums.items[0].uri); console.log("______"); } }); //songname added to logfile to be logged logFile.push(songName); } /*function for the movie-this command, if movie name is given in command line then it displays specific information for that movie, else it takes default moviename and displays its info*/ function movie_this(movieName) { //if moviename is not given in command line if (movieName === "") { movieName = "<NAME>"; } // a request to the OMDB API with the movie specified request("http://www.omdbapi.com/?t=" + movieName + "&y=&plot=short&apikey=trilogy", function (error, response, body) { // If the request is successful (i.e. if the response status code is 200) if (!error && response.statusCode === 200) { var rtRating = "N/A"; if (JSON.parse(body).Ratings.length > 1) { rtRating = JSON.parse(body).Ratings[1].Value; } console.log("Title of the movie: " + JSON.parse(body).Title); console.log("___________________"); console.log("Year the movie came out: " + JSON.parse(body).Year); console.log("_______________________ "); console.log("IMDB Rating of the movie: " + JSON.parse(body).Rated); console.log("_________________________"); console.log("Rotten Tomatoes Rating of the movie: " + rtRating); console.log("___________________________________"); console.log("Country where the movie was produced: " + JSON.parse(body).Country); console.log("____________________________________"); console.log("Language of the movie: " + JSON.parse(body).Language); console.log("_____________________"); console.log("Plot of the movie: " + JSON.parse(body).Plot); console.log("_________________"); console.log("Actors in the movie: " + JSON.parse(body).Actors); console.log("___________________"); } }); //moviename added to logfile to be logged logFile.push(movieName); } /*function for the do-what-it-says command, this will take the text inside of random.txt and then uses it to call one of LIRI's commands */ function do_what_it_says() { fs.readFile("random.txt", "utf8", function (err, data) { // If the code experiences any errors it will log the error to the console. if (err) { console.log('Error occurred: ' + err); logFile.push(err); } var command = ""; var name = ""; //removes whitespaces from both sides of the text data = data.trim(); //splits the text with , separator and stores values in array var dataArr = data.split(","); //LIRI command first array item command = dataArr[0]; //songName or movieName if given second array item if (dataArr.length > 1) { name = dataArr[1]; //replace "" in name and concat movie or song name with + name = (name.replace('"', '').split(" ")).join("+"); } //function call to perform LIRI command read in the text file commandExecution(command, name); }); } /*function to concat the command line arguments with + for the names (movie or song) */ function concatString(nodeArgs) { var name = ""; for (var i = 3; i < nodeArgs.length; i++) { if (i > 3 && i < nodeArgs.length) { name = name + "+" + nodeArgs[i]; } else { name = nodeArgs[i]; } } return name; } /* function to write log file , logarray is used to write commands in the log file */ function log() { fs.appendFile("log.txt", logFile + "\n", function (err) { // If the code experiences any errors it will log the error to the console. if (err) { return console.log(err); } }); }
99deb7add9b810d9f530e9eaa26854435737a73b
[ "JavaScript" ]
1
JavaScript
priyaA01/liri-node-app
0441b1faff12bdc3e6a9042cfc22a0e638edb574
eb98b47e90ecf803aaa1cd4436bfdf691da1586b
refs/heads/master
<repo_name>wsfengfan/CVE-2019-2618-<file_sep>/CVE-2019-2618_test.py #coding=utf-8 import requests; import sys; print ''' 请依次输入 服务器IP或者域名 用户名 密码 检测CVE-2019-2618漏洞的存在 作者:wsfengfan474 ''' ip = sys.argv[1] user = sys.argv[2] password = sys.argv[3] headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", "Referer": "https://www.google.com/", "content-type": "multipart/form-data; boundary=----123456789killweb987654321kill9090", "username": user, "password": <PASSWORD>, "wl_upload_delta": "true", "wl_upload_application_name": "/../tmp/_WL_internal/bea_wls_internal/9j4dqk/war", } data = '----123456789killweb987654321kill9090\r\nContent-Disposition: form-data; name=\"test.jsp\"; filename=\"test.jsp\"\r\nContent-Type: false\r\n\r\n <%out.print("CVE-2019-2618_test_succeed");%> \r\n\r\n----123456789killweb987654321kill9090--' url = ip + "/bea_wls_deployment_internal/DeploymentService" response = requests.request("POST", url=url, data=data, headers=headers) print(response.text) print("可以查看相应的url,是否上传成功")<file_sep>/README.md # CVE-2019-2618-漏洞检测工具 根据提示依次输入服务器 url 用户名 密码 >例如:python3 CVE-2019-2618_test.py http://127.0.0.1 root root123 代码会返回response的主体内容,可以根据主体内容提供的url,查看是否上传成功. 程序内上传的文件名称为 "test.jsp". 正常上传成功,test.jsp显示为 "CVE-2019-2618_test_succeed".
e113aa07c6349b8a11149aacf66ad03c5a3e5c37
[ "Markdown", "Python" ]
2
Python
wsfengfan/CVE-2019-2618-
37a606c064491ad5335f76702034ad01010e99e4
72c707591cbd2239c5075214213bfbb29ce3ceaf
refs/heads/master
<file_sep>package com.example.alatmusik; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class MyDatabase extends SQLiteOpenHelper { private static int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "db_usaha"; private static final String tb_alatmusik = "tb_alatmusik"; private static final String tb_tk_id = "id"; private static final String tb_tk_nama = "nama"; private static final String tb_tk_kondisi = "kondisi"; private static final String tb_tk_harga = "harga"; private static final String CREATE_TABLE_HP = "CREATE TABLE " + tb_alatmusik + "(" + tb_tk_id + " INTEGER PRIMARY KEY ," + tb_tk_nama + " TEXT," + tb_tk_kondisi + " TEXT," + tb_tk_harga + " TEXT " + ")"; public MyDatabase (Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_HP); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public void CreateToko (AlatMusik mdNotif) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(tb_tk_id, mdNotif.get_id()); values.put(tb_tk_nama, mdNotif.get_nama()); values.put(tb_tk_kondisi, mdNotif.get_kondisi()); values.put(tb_tk_harga, mdNotif.get_harga()); db.insert(tb_alatmusik, null, values); db.close(); } public List<AlatMusik> ReadToko() { List<AlatMusik> judulModelList = new ArrayList<AlatMusik>(); String selectQuery = "SELECT * FROM " + tb_alatmusik; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { AlatMusik mdKontak = new AlatMusik(); mdKontak.set_id(cursor.getString(0)); mdKontak.set_nama(cursor.getString(1)); mdKontak.set_kondisi(cursor.getString(2)); mdKontak.set_harga(cursor.getString(3)); judulModelList.add(mdKontak); } while (cursor.moveToNext()); } db.close(); return judulModelList; } public int UpdateToko (AlatMusik mdNotif) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(tb_tk_nama, mdNotif.get_nama()); values.put(tb_tk_kondisi, mdNotif.get_kondisi()); values.put(tb_tk_harga, mdNotif.get_harga()); return db.update(tb_alatmusik, values, tb_tk_id + " = ?", new String[] { String.valueOf(mdNotif.get_id())}); } public void DeleteToko (AlatMusik mdNotif) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(tb_alatmusik, tb_tk_id+ " = ?", new String[]{String.valueOf(mdNotif.get_id())}); db.close(); } }<file_sep>package com.example.alatmusik; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainCreate extends AppCompatActivity { private MyDatabase db; private EditText Enama, Ekondisi, Eharga; private String Snama, Skondisi, Sharga; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_create); db = new MyDatabase(this); Enama = (EditText) findViewById(R.id.create_nama); Ekondisi = (EditText) findViewById(R.id.create_kondisi); Eharga = (EditText) findViewById(R.id.create_harga); Button btnCreate = (Button) findViewById(R.id.create_btn); btnCreate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snama = String.valueOf(Enama.getText()); Skondisi = String.valueOf(Ekondisi.getText()); Sharga = String.valueOf(Eharga.getText()); if (Snama.equals("")){ Enama.requestFocus(); Toast.makeText(MainCreate.this, "Silahkan isi nama AlatMusik", Toast.LENGTH_SHORT).show(); } else if (Skondisi.equals("")){ Ekondisi.requestFocus(); Toast.makeText(MainCreate.this, "Silahkan isi Kondisi AlatMusik", Toast.LENGTH_SHORT).show(); } else if (Sharga.equals("")){ Eharga.requestFocus(); Toast.makeText(MainCreate.this, "Silahkan isi Harga AlatMusik", Toast.LENGTH_SHORT).show(); } else { Enama.setText(""); Ekondisi.setText(""); Eharga.setText(""); Toast.makeText(MainCreate.this, "Data telah ditambah", Toast.LENGTH_SHORT).show(); db.CreateToko(new AlatMusik(null, Snama, Skondisi, Sharga)); Intent a = new Intent(MainCreate.this, MainActivity.class); startActivity(a); } } }); } }
31d088d1fec08a915e6d8d180656c7f0df81fb15
[ "Java" ]
2
Java
febryanalfaridzi057/SQLite_Alatmusik
b5d66a1449ca454893463f1aff4bb95da4ae8cce
c2f1e0db0ede1d37b3acab2d94a9b9ce42ab9ed5
refs/heads/master
<repo_name>SinLT/electron-vue3<file_sep>/src/main/main.ts import {resolve, join} from "path"; import { shell, app, BrowserWindow, globalShortcut, ipcMain, Tray, BrowserWindowConstructorOptions, Menu } from "electron"; import * as Socket from "socket.io-client"; import Log from "@/lib/log"; import ico from "@/assets/icon.ico"; import {IPC_MSG_TYPE, SOCKET_MSG_TYPE, WindowOpt} from "@/lib/interface"; import {Update} from "./update"; const config = require("@/lib/cfg/config.json"); declare global { namespace NodeJS { interface Global { sharedObject: { [key: string]: unknown } } } } global.sharedObject = {}; class Main { private static instance: Main; private mainWin: BrowserWindow = null; //当前主页 private windows: { [id: number]: WindowOpt } = {}; //窗口组 private appTray: Tray = null; //托盘 private socket: SocketIOClient.Socket = null; //socket static getInstance() { if (!Main.instance) Main.instance = new Main(); return Main.instance; } constructor() { } /** * 窗口配置 * */ browserWindowOpt(wh: number[]): BrowserWindowConstructorOptions { return { width: wh[0], height: wh[1], transparent: true, autoHideMenuBar: true, resizable: false, maximizable: false, frame: false, show: false, webPreferences: { contextIsolation: false, nodeIntegration: true, devTools: !app.isPackaged, webSecurity: false, enableRemoteModule: true } } } /** * 创建窗口 * */ createWindow(args: WindowOpt) { try { for (let i in this.windows) { if (this.windows[i] && this.windows[i].route === args.route && !this.windows[i].isMultiWindow) { BrowserWindow.fromId(Number(i)).focus(); return; } } let opt = this.browserWindowOpt([args.width, args.height]); if (args.parentId) { opt.parent = BrowserWindow.fromId(args.parentId); opt.x = parseInt((BrowserWindow.fromId(args.parentId).getPosition()[0] + ((BrowserWindow.fromId(args.parentId).getBounds().width - args.width) / 2)).toString()); opt.y = parseInt((BrowserWindow.fromId(args.parentId).getPosition()[1] + ((BrowserWindow.fromId(args.parentId).getBounds().height - args.height) / 2)).toString()); } else if (this.mainWin) { opt.x = parseInt((this.mainWin.getPosition()[0] + ((this.mainWin.getBounds().width - args.width) / 2)).toString()); opt.y = parseInt((this.mainWin.getPosition()[1] + ((this.mainWin.getBounds().height - args.height) / 2)).toString()); } opt.modal = args.modal || false; opt.resizable = args.resizable || false; let win = new BrowserWindow(opt); this.windows[win.id] = { route: args.route, isMultiWindow: args.isMultiWindow }; // //window加载完毕后显示 win.once("ready-to-show", () => win.show()); //默认浏览器打开跳转连接 win.webContents.on("new-window", async (event, url) => { event.preventDefault(); await shell.openExternal(url); }); // 打开开发者工具 if (!app.isPackaged) win.webContents.openDevTools(); //注入初始化代码 win.webContents.on("did-finish-load", () => { args.id = win.id; win.webContents.send("window-load", args); }); if (!app.isPackaged) win.loadURL(`http://localhost:${config.appPort}`).catch(err => Log.error(err)); else win.loadFile(join(__dirname, "./index.html")).catch(err => Log.error(err)); if (args.isMainWin) { //是否主窗口 if (this.mainWin) { delete this.windows[this.mainWin.id]; this.mainWin.close(); } this.mainWin = win; } } catch (e) { Log.error(e.toString()) } } /** * 关闭所有窗口 */ closeAllWindow() { for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).close(); } /** * 创建托盘 * */ async createTray() { try { const contextMenu = Menu.buildFromTemplate([{ label: "显示", click: () => { for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).show(); } }, { label: "退出", click: () => { app.quit(); } }]); this.appTray = new Tray(join(__dirname, `./${ico}`)); this.appTray.setContextMenu(contextMenu); this.appTray.setToolTip(app.name); this.appTray.on("double-click", () => { for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).show(); }) } catch (e) { Log.error(e); } } /** * 创建Socket * */ async createSocket() { this.socket = Socket.connect(config.socketUrl, {query: `Authorization=${global.sharedObject["Authorization"]}`}); this.socket.on("connect", () => Log.info("[Socket]connect")); // @ts-ignore this.socket.on("message", data => { if (data.type === SOCKET_MSG_TYPE.ERROR) { this.createWindow({ route: "/message", isMainWin: true, data: { title: "提示", text: data.value }, }); setTimeout(() => { this.closeAllWindow(); }, 10000) } for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).webContents.send("message-back", data); }); // @ts-ignore this.socket.on("error", msg => { Log.info(`[Socket]error ${msg.toString()}`); }); this.socket.on("disconnect", () => { Log.info("[Socket]disconnect"); setTimeout(() => { if (this.socket && this.socket.io.readyState === "closed") this.socket.open() }, 1000 * 60 * 3) }); this.socket.on("close", () => { Log.info("[Socket]close"); }); } /** * 初始化并加载 * */ async init() { app.allowRendererProcessReuse = true; if (!app.requestSingleInstanceLock()) { app.quit(); } else { app.on("second-instance", () => { // 当运行第二个实例时,将会聚焦到myWindow这个窗口 if (this.mainWin) { if (this.mainWin.isMinimized()) this.mainWin.restore(); this.mainWin.focus(); } }) } app.whenReady().then(() => { this.createWindow({isMainWin: true, width: 0, height: 0}); this.createTray(); }); app.on("window-all-closed", () => { if (process.platform !== "darwin") { app.quit(); } }) app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { this.createWindow({isMainWin: true, width: 0, height: 0}); } }) //获得焦点时发出 app.on("browser-window-focus", () => { //关闭刷新 globalShortcut.register("CommandOrControl+R", () => { }); }); //失去焦点时发出 app.on("browser-window-blur", () => { // 注销关闭刷新 globalShortcut.unregister("CommandOrControl+R"); }); //协议调起 let args = []; if (!app.isPackaged) args.push(resolve(process.argv[1])); args.push("--"); app.setAsDefaultProtocolClient(app.name, process.execPath, args); } async ipc() { /** * 主体 * */ //关闭 ipcMain.on("closed", (event, winId) => { if (winId) { BrowserWindow.fromId(Number(winId)).close(); if (this.windows[Number(winId)]) delete this.windows[Number(winId)]; } else { for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).close(); } }); //隐藏 ipcMain.on("hide", (event, winId) => { if (winId) { BrowserWindow.fromId(Number(winId)).hide(); } else { for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).hide(); } }); //显示 ipcMain.on("show", (event, winId) => { if (winId) { BrowserWindow.fromId(Number(winId)).show(); } else { for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).show(); } }); //最小化 ipcMain.on("mini", (event, winId) => { if (winId) { BrowserWindow.fromId(Number(winId)).minimize(); } else { for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).minimize(); } }); //复原 ipcMain.on("restore", (event, winId) => { if (winId) { BrowserWindow.fromId(Number(winId)).restore(); } else { for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).restore(); } }); //重载 ipcMain.on("reload", (event, winId) => { if (winId) { BrowserWindow.fromId(Number(winId)).reload(); } else { for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).reload(); } }); //重启 ipcMain.on("relaunch", () => { app.relaunch({args: process.argv.slice(1)}); }); //创建窗口 ipcMain.on("window-new", (event, args) => this.createWindow(args)); /** * socket * */ //初始化 ipcMain.on("socket-init", async () => { if (!this.socket) await this.createSocket(); }); //重新连接 ipcMain.on("socket-reconnection", async () => { if (this.socket && this.socket.io.readyState === "closed") this.socket.open(); }); /** * 检查更新 * */ ipcMain.on("update", (event, winId) => new Update(winId)); /** * 全局变量赋值 */ ipcMain.on("global-sharedObject", (event, args) => global.sharedObject[args.key] = args.value); /** * 消息反馈 */ ipcMain.on("message-send", (event, args) => { switch (args.type) { case IPC_MSG_TYPE.WIN: for (let i in this.windows) if (this.windows[i]) BrowserWindow.fromId(Number(i)).webContents.send("message-back", args); break; case IPC_MSG_TYPE.SOCKET: if (this.socket && this.socket.io.readyState === "open") this.socket.send(args); break; } }); } } /** * 启动 * */ (async () => { await Main.getInstance().ipc(); await Main.getInstance().init(); })() <file_sep>/src/renderer/index.ts import {createApp} from "vue"; import App from "./App.vue"; import {argsSymbol, createArgs} from "./store"; import router from "./router"; import {Init} from "./utils/ipc"; Init().then((Args) => { createApp(App as any) .use(router) .provide(argsSymbol, createArgs(Args)) .mount("#app"); }); <file_sep>/src/main/update.ts import {BrowserWindow, ipcMain} from "electron"; import {join} from "path"; import {autoUpdater} from "electron-updater"; import Log from "@/lib/log"; import {delDir} from "@/lib"; const config = require("@/lib/cfg/config.json"); /** * 更新模块 * */ export class Update { handleUpdate() { // @ts-ignore const updatePendingPath = join(autoUpdater.app.baseCachePath, config.updaterCacheDirName, 'pending'); delDir(updatePendingPath); } constructor(winId: number) { autoUpdater.removeAllListeners(); this.handleUpdate(); let win = BrowserWindow.fromId(winId); let message = { error: {code: 0, msg: "检查更新出错"}, checking: {code: 1, msg: "正在检查更新"}, updateAva: {code: 2, msg: "检测到新版本,正在下载"}, updateNotAva: {code: 3, msg: "现在使用的就是最新版本,不用更新"} }; // 本地开发环境,改变app-update.yml地址 if (process.env.NODE_ENV === 'development' && !(process.platform === 'darwin')) { autoUpdater.updateConfigPath = join(__dirname, 'out/win-unpacked/resources/app-update.yml') } // 这里的URL就是更新服务器的放置文件的地址 autoUpdater.setFeedURL({ provider: 'generic', url: config.updateFileUrl }); autoUpdater.on("error", () => { win.webContents.send("update-message", message.error); }); autoUpdater.on("checking-for-update", () => { win.webContents.send("update-message", message.checking); }); autoUpdater.on("update-available", () => { win.webContents.send("update-message", message.updateAva); }); autoUpdater.on("update-not-available", () => { win.webContents.send("update-message", message.updateNotAva); }); // 更新下载进度事件 autoUpdater.on("download-progress", (progressObj) => { win.webContents.send("download-progress", progressObj) }) // 下载完成事件 autoUpdater.on("update-downloaded", () => { ipcMain.on("update-downloaded", () => { // 关闭程序安装新的软件 autoUpdater.quitAndInstall(true); }); // 通知渲染进程现在完成 win.webContents.send("update-downloaded"); }); autoUpdater.checkForUpdates().catch(e => Log.error(e)); } }<file_sep>/resources/script/webpack.main.config.js const path = require("path"); const webpack = require("webpack"); const _externals = require("externals-dependencies"); const isEnvProduction = process.env.NODE_ENV === "production"; const isEnvDevelopment = process.env.NODE_ENV === "development"; module.exports = { devtool: isEnvDevelopment ? "source-map" : false, mode: isEnvProduction ? "production" : "development", target: "electron-main", externals: _externals(), entry: { main: "./src/main/main.ts" }, output: { filename: "[name].bundle.js", chunkFilename: "[id].bundle.js", path: path.resolve("dist") }, node: { global: false, __dirname: false, __filename: false }, module: { rules: [ { test: /\.ts$/, use: "ts-loader", exclude: /node_modules/ }, { test: /\.(png|svg|jpg|gif|ico)$/, use: [ "file-loader" ] } ] }, resolve: { extensions: [".tsx", ".ts", ".js"], alias: { "dist": path.resolve("dist"), "@": path.resolve("src") } }, optimization: { minimize: true }, plugins: [ new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify(isEnvProduction ? "production" : "development") }, "__VUE_PROD_DEVTOOLS__": JSON.stringify(false) }) ] }; <file_sep>/src/lib/index.ts import {existsSync, readdirSync, rmdirSync, statSync, unlinkSync} from "fs"; import {resolve} from "path"; import {remote} from "electron"; /** * 删除目录和内部文件 * */ export function delDir(path: string): void { let files = []; if (existsSync(path)) { files = readdirSync(path); files.forEach((file) => { let curPath = path + "/" + file; if (statSync(curPath).isDirectory()) { delDir(curPath); //递归删除文件夹 } else { unlinkSync(curPath); //删除文件 } }); rmdirSync(path); } } /** * 获取外部依赖文件路径(!文件必须都存放在lib/extern下 针对打包后外部依赖文件路径问题) * @param path lib/extern为起点的相对路径 * */ export function getExternPath(path: string): string { return remote.app.isPackaged ? resolve(__dirname, './lib/extern/' + path) : resolve('./src/lib/extern/' + path); }<file_sep>/resources/script/webpack.renderer.config.js const path = require("path"); const fs = require("fs"); const webpack = require("webpack"); const { name } = require("../../package.json"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const _externals = require("externals-dependencies"); const miniCssExtractPlugin = require("mini-css-extract-plugin"); const { VueLoaderPlugin } = require("vue-loader"); const isEnvProduction = process.env.NODE_ENV === "production"; const isEnvDevelopment = process.env.NODE_ENV === "development"; const config = { devtool: isEnvDevelopment ? "source-map" : false, mode: isEnvProduction ? "production" : "development", target: "electron-renderer", externals: _externals(), entry: { app: "./src/renderer/index.ts" }, output: { filename: "[name].bundle.view.js", chunkFilename: "[id].bundle.view.js", path: path.resolve("dist") }, node: { global: false, __dirname: false, __filename: false }, module: { rules: [ { test: /\.vue$/, loader: "vue-loader", options: { loader: { scss: "vue-style-loader!css-loader!sass-loader" } } }, { test: /\.ts$/, use: { loader: "ts-loader", options: { appendTsSuffixTo: [/\.vue$/] } }, exclude: /node_modules/ }, { test: /\.css$/, use: [{ loader: miniCssExtractPlugin.loader, options: { // you can specify a publicPath here // by default it use publicPath in webpackOptions.output publicPath: "../" } }, "css-loader" ] }, { // scss test: /\.scss$/, use: [ { loader: miniCssExtractPlugin.loader, options: { // you can specify a publicPath here // by default it use publicPath in webpackOptions.output publicPath: "../" } }, { loader: "css-loader" }, { loader: "sass-loader" } ] }, { test: /\.(png|svg|jpg|gif|ico)$/, use: [ "file-loader" ] }, { test: /\.(woff|woff2|eot|ttf|otf)$/, use: [ "file-loader" ] } ] }, resolve: { extensions: [".ts", ".js", ".vue", ".json"], alias: { "vue": "@vue/runtime-dom", "@": path.resolve("src") } }, optimization: { minimize: true }, plugins: [ new miniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: "[name].css", chunkFilename: "[id].css" }), new HtmlWebpackPlugin({ title: name, template: "./resources/script/index.html" }), new VueLoaderPlugin(), new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify(isEnvProduction ? "production" : "development") }, "__VUE_PROD_DEVTOOLS__": JSON.stringify(false) }) ] }; try { if (fs.statSync(path.join(__dirname, "../../src/lib/extern"))) { config.plugins.unshift(new CopyWebpackPlugin({ patterns: [ { from: "./src/lib/extern/**/*", to: "./lib/extern", transformPath(targetPath, absolutePath) { try { let path = targetPath.replace(/\\/g, "/"); return path.replace("src/lib/extern", ""); } catch (e) { return false; } } } ] })); } } catch (e) { console.log("... 无外部引入依赖 ..."); } module.exports = config; <file_sep>/README.md # electron-vue3 electron & vue3 一个多窗口模式的脚手架 ❗注意 `vue` or `vue-router` 版本 ## 引入外部依赖问题 所有外部依赖放入到 `src/lib/extern` 调用 `src/lib/index.ts` 内`getExternPath()` 方法可获取 调试和打包 对应路径 ## 安装依赖 运行命令 ```shell npm install or yarn ``` ### 安装中的网络问题 - `electron`: ```shell npm/yarn config set electron_mirror https://npm.taobao.org/mirrors/electron/ ``` ## 运行调试 运行命令 ```shell npm/yarn run dev:all ``` ## electron builder 配置 位于 resources/script/build.js 打包命令 ```shell npm/yarn run build ``` <file_sep>/src/lib/log.ts import {statSync, writeFileSync, mkdirSync, appendFileSync} from "fs"; import {resolve} from "path"; class Log { private static instance: Log; private readonly logFile: string = resolve("./logs"); static getInstance() { if (!Log.instance) Log.instance = new Log(); return Log.instance; } constructor() { try { statSync(this.logFile); } catch (e) { mkdirSync(this.logFile, {recursive: true}); } } format(is?: boolean): string { let date = new Date(); if (is) return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}` else return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`; } info(val: string): void { try { statSync(this.logFile + `/info-${this.format()}.log`); } catch (e) { writeFileSync(this.logFile + `/info-${this.format()}.log`, ""); } appendFileSync(this.logFile + `/info-${this.format()}.log`, `[${this.format(true)}] [info] ${val}\r\n`); } error(val: string): void { try { statSync(this.logFile + `/error-${this.format()}.log`); } catch (e) { writeFileSync(this.logFile + `/error-${this.format()}.log`, ""); } appendFileSync(this.logFile + `/error-${this.format()}.log`, `[${this.format(true)}] [error] ${val}\r\n`); } } export default Log.getInstance();
ac250c60a092689231071837062fbfd5e56214c2
[ "JavaScript", "TypeScript", "Markdown" ]
8
TypeScript
SinLT/electron-vue3
49353ff3ac9b26a90f15f137dc2c505e5b35a923
8c6be77408d9cdb241a520a0f04419a2851b5c64
refs/heads/master
<repo_name>abhimanyugupta90/scripts<file_sep>/Dropzone Action/Qiniu.dzbundle/action.rb # Dropzone Action Info # Name: Qiniu # Description: Upload file to Qiniu # Handles: Files # Creator: <NAME> # URL: http://yansu.org # OptionsNIB: ExtendedLogin # Events: Clicked, Dragged # KeyModifiers: Command, Option, Control, Shift # SkipConfig: No # RunsSandboxed: Yes # Version: 1.0 # MinDropzoneVersion: 3.0 # RubyPath: /usr/bin/ruby require 'qiniu' Qiniu.establish_connection! :access_key => ENV['username'], :secret_key => ENV['password'] ENV['http_proxy'] = "" def dragged puts $items.inspect local_file = $items[0] puts local_file put_policy = Qiniu::Auth::PutPolicy.new(ENV['server'], File.basename(local_file)) uptoken = Qiniu::Auth.generate_uptoken(put_policy) puts uptoken $dz.begin("Starting uploading...") $dz.determinate(true) $dz.percent(10) # copy to folder if (ENV['remote_path']) Rsync.do_copy([local_file], ENV['remote_path'], false) end $dz.percent(30) code, result, response_headers = Qiniu::Storage.upload_with_put_policy( put_policy, local_file ) $dz.percent(60) puts code puts result puts response_headers $dz.percent(100) $dz.finish("Url has been copied to clipboard.") if code != 200 $dz.fail("Upload failed.") else url = "#{ENV["root_url"]}/#{result["key"]}" $dz.url(url) end end def clicked system("open http://qiniu.com") end
0dd674cbf641f33fb0c811b286f75d1eb8b17064
[ "Ruby" ]
1
Ruby
abhimanyugupta90/scripts
52d8e53c063ca89513ecbd0e43d71789bf6cf615
e67a613351122053b6e1fed3c5bcb9e78476ebae
refs/heads/master
<repo_name>AlexBarbeau/Products-Deep-Learning<file_sep>/Application/__main__.py print("Importing Libraries..........") import numpy as np import tensorflow as tf import tensorflow_hub as hub from json import loads gpus = tf.config.list_physical_devices('GPU') if gpus: try: # Currently, memory growth needs to be the same across GPUs for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf.config.experimental.list_logical_devices('GPU') print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs") except RuntimeError as e: # Memory growth must be set before GPUs have been initialized print(e) print("Preparing..........") maxRating = 5 batchSize = 512 highestRating = 5.0 data = input("Name of the Json file in Data: ") output = input("Name of file to save model as in Models folder (No extension): ") print("Running..........") appliancesData = open("../Data/{}".format(data), 'r') # Opens data file. dataTable = [loads(line) for line in appliancesData] # Converts each line of data into a dictionary. # Makes list of tuples with the reviews tied to their ratings. reviews = list() ratings = list() for review in dataTable: reviews.append(review["reviewText"]) ratings.append(float(review["overall"])/highestRating) # Split lists. length = len(reviews) trainReviews, validationReviews, testReviews = np.split(reviews, [round(length * 0.3), round(length * 0.5)]) trainRatings, validationRatings, testRatings = np.split(ratings, [round(length * 0.3), round(length * 0.5)]) # Convert lists into tensors. trainData = tf.data.Dataset.from_tensor_slices((trainReviews, trainRatings)) validationData = tf.data.Dataset.from_tensor_slices((validationReviews, validationRatings)) testData = tf.data.Dataset.from_tensor_slices((testReviews, testRatings)) # Makes first layer. Used to convert text into numbers. embedding = "https://tfhub.dev/google/nnlm-en-dim50/2" hubLayer = hub.KerasLayer(embedding, input_shape=[], dtype=tf.string, trainable=True) # Creates model with 2 layers. model = tf.keras.Sequential() model.add(hubLayer) model.add(tf.keras.layers.Dense(16, activation='sigmoid')) model.add(tf.keras.layers.Dense(1)) model.summary() # Shows summary of the model. # Compiles model using logit, an optimizer and a chosen metric. model.compile(optimizer='adam', loss=tf.keras.losses.MeanSquaredError(), metrics = ['accuracy']) # Fits the model to the data. history = model.fit(trainData.shuffle(round(length*0.3)).batch(batchSize), epochs=10, validation_data=validationData.batch(batchSize), verbose=1) # Saves the model. model.save('Models/{}'.format(output)) # Evaluates the model's accuracy and loss. results = model.evaluate(testData.batch(batchSize), verbose=2) # Shows results of evaluation. print("Results:") for name, value in zip(model.metrics_names, results): print("%s: %.3f" % (name, value)) <file_sep>/Application/ui.py from tkinter import * from tkinter import scrolledtext, font, ttk import glob import random # Button command def buttonCommand(): textInput = reviewInput.get('1.0', 'end-1c') selectedFile = "../Models/" + dropdown.get() print(selectedFile, textInput) starNum = random.randint(1, 5) stars.config(text='★' * starNum) # Dropdown update def dropdownUpdate(*args): dirtyOptions = glob.glob('..\Models\*\\') if dirtyOptions: cleanOptions = [] for file in dirtyOptions: cleanOptions.append(file.lstrip('..\Models\\').rstrip('\\')) dropdown['values'] = cleanOptions else: dropdown['values'] = [''] # Create window root = Tk() root.title('Ratings AI') root.geometry('950x600') root.minsize(700, 500) # Fonts titleFont = font.Font(family="Lucida Console", size=18, weight='bold') instructionsFont = font.Font(family="Lucida Console", size=14) textFont = font.Font(family="Calibri", size=12) buttonFont = font.Font(family="Lucida Console", size=12) # UI Elements frame = Frame(root, bd=0, bg='white') frame.place(relx=0, rely=0, relheight=1, relwidth=1) title = Label(frame, text='Review Rating Suggester', font=titleFont, bg='white') title.place(relx=0.5, rely=0.125, width=500, y=-18, x=-250) instructions = Label(frame, text='Write a review and we\'ll suggest its rating:', font=instructionsFont, bg='white') instructions.place(relx=0.5, rely=0.25, width=500, y=-30, x=-250) reviewInput = scrolledtext.ScrolledText(frame, undo=True, padx=10, pady=10, bd=3, relief=GROOVE) reviewInput.configure(font=textFont) reviewInput.place(relx=0.25, rely=0.25, relheight=0.5, relwidth=0.5) buttonsFrame = Frame(root, bd=0, bg='white') buttonsFrame.place(relx=0.25, rely=0.75, relwidth=0.5, y=10, height=25) goButton = Button(buttonsFrame, text='Go', font=buttonFont, relief=GROOVE, command=buttonCommand) goButton.place(relx=0, rely=0, relwidth=0.3, height=25) options = [''] dropdown = ttk.Combobox(buttonsFrame, values=options, state="readonly", postcommand=dropdownUpdate) dropdownUpdate() dropdown.current(0) dropdown.bind("<<ComboboxSelected>>", dropdownUpdate) dropdown.place(relx=0.7, rely=0, relwidth=0.3, height=25) stars = Label(frame, text='', font=('bold', 30), fg='#FFA41D', bg='white') stars.place(relx=0.5, rely=0.875, width=200, y=-15, x=-100) # Run application root.mainloop()
1b1bb2178fdf99c66965a781322f732f90cf0c06
[ "Python" ]
2
Python
AlexBarbeau/Products-Deep-Learning
230bc028ecdc15f2d26e171314b199fd33f792c0
26cc92c27a985a7d855917443b4bd73650d4a004
refs/heads/master
<repo_name>nikolovGeorgi/python<file_sep>/Cubes/Histogram.py ## Draw Histogram - Asterix for every repeated value in a sequence def get_data(n): ''' :param n: referes to the size of list of integers the user needs to input. :return : list of integers. ''' data = [] # list to store the inputed integers for i in range(n): # i is only used as an iterator. data.append(verify_input('Enter one integer only: ')) # for each inputed integer - verify if its valid & if so add it to the data. return data def counting(data): ''' :param data: list of integers to check uniqueness and frequency of. :retrun : dictionary containing unique values and their frequency as a key-value pair. ''' frequency = {} # dictionary to store unique and re-appearing integers in the data, & to be returned seen = False # variable to confirm if an integer is unique or re-appearing for item in data: if item not in frequency.keys(): seen = False # if the current integer in the data has not been seen before, then it is unique. if not seen: frequency[item] = data.count(item) # if the current integer is unique then add it to our collection and count how many of it are in the data. seen = True # mark the integer as accounted for. return frequency # return collection def draw_histogram(frequency): ''' :param frequency: collection of unique integers and their re-appearance in a key-value pair. :return: Has no return. Only functionality is to print results. ''' print("\n\n\n----------- Histogram ----------------\n") for f in sorted(frequency.keys()): # sort the values in our data - to be printed in order print(f, '*'*frequency[f]) # add a star for each unique integer's appearance in the original data def verify_input(message): ''' :param message: accept a message to be printed to the console. :return value: inputed single positive integer value. If value type is correct - return it. ''' while True: # While no value errors try to get user input of type int. try: value = int(input(message)) # forcefully convert the input to int - if possible - if not return ValueError. if value < 0: raise ValueError # if inputed value is negative - raise a ValueError. except ValueError: # if there is a ValueError inform the user of it. print("Invalid Input. Please enter an integer value!") print() continue # Repeat the loop and ask the user for another value. Until a valid integer is inputed. else: return value # Once a valid integer is inputed -> break out by returning it to the requesting method. ## To keep the heap and global frame clean and effective: chain methods to bypass the need for storing unnecessary names. draw_histogram(counting(get_data(verify_input('How many data values? ')))) <file_sep>/Santa Stark vs Night King/README.md # The Great War Between Santa Stark vs Night King *<NAME>*, *<NAME>*, is preparing the defence of the North, and has made plans to defend against the *Night King of the White Walkers*, who has invaded the lands of the living with an army of wights, beginning the Great War. The battle commanders have analyzed a number of scenarios, and plans are being made. Key locations in the north are being defended. Scouting reports and ravens (of two- and three-eyed varieties) have provided accurate reports for the size of the Night King’s forces. One uncertainty remains, namely the quality of archers needed to defend the strongholds. The archers can still be trained, and there may be time to raise their skill level to the minimum level needed to guarantee victory. *<NAME>* needs to know the minimum skill for the archers in order to guarantee that the defence of the Northern strongholds. The skill of the human archers is represented by a floating point value *p* between 0 and 100, representing the percentage of wights destroyed by flaming arrows. If *p* = 0, then the archers have no skill, and none of the wights are destroyed by flaming arrows, and if *p* = 100, every targeted wight is destroyed. Due to uncertainties in battle, *p* is very likely to be well below 100, and due to natural random effects (like wind, or the night, full of terrors), the actual fraction of wights killed per volley will be random, in the range 0 through *p*. *<NAME>* requires an estimate of the value *p* that will guarantee victory. Since we don’t have a simple formula, we’ll have to simulate an attack repeatedly, using different values for *p*. We are seeking the smallest value for *p* that results in victory with a probability of 95%. *** **Initial conditions**. Suppose the area near the fortress is divided into a *N* by *N* square grid. The value of *N* depends on the scenario. The wights start out occupying the top row of the grid squares. Specifically, each grid square in the top row of the grid starts with an equal number of wights. As GoT fans know, even wights that are gruesomely damaged are still a threat, and therefore a fractional number of wights in a grid square makes sense. The starting number of wights depends on the scenario. *** **Movement of wights.** During an attack, the wights travel directly southward (towards the bottom of the grid), one grid square at a time, towards a fortress defended by humans. For the purposes of the simulation, you can imagine that the fortress is “below” the bottom row of grid squares. *** **Static Defences.** Each grid square contains some fortifications (barriers, traps, etc.) that defeat attacking wights. The strength of the fortifications in a grid square is represented by a non-negative integer called a fortification value. If the fortification value in a grid square is equal to *d*, then exactly *d* of the wights that enter that grid square do not make it to the grid square directly to the south in the next row. If *d* is larger than the number of wights entering the square, exactly zero of these are able to move south to the next square. *** **Active Defences.** Human archers have a limited range of 30 grid squares (no matter how big the battlefield is). If the wights are not within range, the archers do not fire. But if the wights are in range, the defending humans fire a volley of flaming arrows. The skill of the human archers is represented by an integer *p* be- tween 0 and 100. The archers are not completely consistent, so each volley of arrows destroys a random percentage between 0 and *p* percent of the wights that are not defeated by the fortifications in each square of the current grid row. The random percentage of wights destroyed is determined separately for each grid square. Wights in a grid square that are not defeated by the fortifications or destroyed by fire arrows make it to the next row. *** **Luck.** The fact that the archers are not consistent means that the outcome of an attack is based in part on luck. It is bad planning to count on luck being in your favour! The way to mitigate uncertainty like this is to repeat the scenario many times. Each simulated scenario might be more or less lucky, but if you repeat the simulation a large number of times, you can get a good idea of what should happen. For example, if you repeat the same scenario 1000 times (with the same initial conditions and archer skill), the proportion of successful defenses should tell you how confident you are that the humans will defend successfully. If the scenario results in 950 successes out of 1000 trials, you can say that the model predicts a 95% chance of a success. *** **Success** From the point of view of the defenders, success is determined by the number of wights that survive the attack, and reach the fortress. If the total number of wights that survive all the defences is less than some number *k*, then the defence was successful. The number *k* depends on the scenario. *Note*: Success is not determined by the number of wights that arrive in the bottom row, but the number who survive the bottom row; there are fortifications in the bottom row, and the archers will make one last desperate volley! *** **Scenario files.** The program inputs are to be read from a file. The first line of the file contains three numbers separated by commas: *N* (the size of the grid), *W* (the total number of wights in the attack), and *k*, the number of wights that must reach the fortress in order to capture it. After the first line, there are *N* more lines each containing *N* integers separated by commas which are the fortification strengths for each grid square in each row of the grid. *** **General problem statement.** Write a program which, given the grid size *N* , the total number of wights *W* (to be divided evenly across the top row of the grid), the strength of the fortifications in grid square, and the number of wights *k* that must reach the fortress in order to capture it, determine the minimum archer skill value *p* that gives the human forces at least a 95% chance of success. <file_sep>/Santa Stark vs Night King/src/tests.py import numpy as np N = 2 archers_range = 30 def volleys(attack): try: volley = np.random.uniform(low=0.0, high=float(attack), size=(N,N)) if N > archers_range: zeros = np.zeros((N - archers_range, N), dtype=float) volley_damage_variation = volley[N - archers_range:] return np.concatenate((zeros, volley_damage_variation)) else: return volley except: ValueError return np.zeros((N, N), dtype=float) print('════════════════════ Testing Volleys ════════════════════') volleys_tests = [ {'id': 0, 'inputs': [-5, 3, -1], 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 1, 'inputs': [.2], 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 2, 'inputs': [], 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 3, 'inputs': {}, 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 4, 'inputs': {0:2}, 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 5, 'inputs': {0:[2, 3]}, 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 6, 'inputs': {'00':2}, 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 7, 'inputs': {'00':2, 5: [123, 233]}, 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 8, 'inputs': None, 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 9, 'inputs': True, 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, {'id': 10, 'inputs': False, 'outputs': np.zeros((N, N), dtype=float), 'reason': 'Volley grid damage difference'}, ] for test in volleys_tests: attack = test['inputs'] expected = test['outputs'] result = volleys(attack) if not all(k in result for k in expected): print("Error in test #" + str(test['id']) + ":", test['reason'], '\n', attack, '\nyielded:\n', str(result) + ',\nbut expected:\n', expected) print() else: print("Volley test #" + str(test['id']), "has passed!!") print() ############################################################################## ############################################################################## ############################################################################## def find_nearest(array, value): try: return (np.abs(array - value)).argmin() except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) print('════════════════════ Testing find_nearest() ════════════════════') find_nearest_tests = [ {'id': 0, 'inputs': np.array([-5, 3, 5, 6, 11, 20, -1]), 'target': 10, 'outputs': 4, 'reason': "Target value out of list value's range"}, {'id': 1, 'inputs': np.array([.2]), 'target': 10, 'outputs': 0, 'reason': "Target value out of list value's range"}, {'id': 2, 'inputs': np.array([]), 'target': 10, 'outputs': None, 'reason': "Empty List"}, {'id': 3, 'inputs': {}, 'target': 10, 'outputs': None, 'reason': 'Type Mismatch'}, {'id': 4, 'inputs': {0:2}, 'target': 10, 'outputs': None, 'reason': 'Type Mismatch'}, {'id': 5, 'inputs': {0:[2, 3]}, 'target': 10, 'outputs': None, 'reason': 'Type Mismatch'}, {'id': 6, 'inputs': {'00':2}, 'target': 10, 'outputs': None, 'reason': 'Type Mismatch'}, {'id': 7, 'inputs': {'00':2, 5: [123, 233]}, 'target': 10, 'outputs': None, 'reason': 'Type Mismatch'}, {'id': 8, 'inputs': None, 'target': 10, 'outputs': None, 'reason': 'Type Mismatch'}, {'id': 9, 'inputs': np.array([1, 2, 3, 4, 5, 6]), 'target': 4, 'outputs': 3, 'reason': 'Type Mismatch'}, ] for test in find_nearest_tests: array_values = test['inputs'] target_value = test['target'] expected = test['outputs'] result = find_nearest(array_values, target_value) if result != expected: print("Error in test #" + str(test['id']) + ":", test['reason'], '\n', attack, '\nyielded:\n', str(result) + ',\nbut expected:\n', expected) print() else: print("Find Nearest() test #" + str(test['id']), "has passed!!") print() print() <file_sep>/Cubes/Sudoku.py ## Check the validity of Sudoku grid. import sys class Data: ''' Data class: Receives text file with field information. Imports Numerical Python library & Field Class to process the given information. Only knows of the file name given to it. Reads it and converts the information to __grid or field values, which then get returned as a list. Private methods should only be used by Data class. ''' def __init__(self, file): ''' Class constructor: Assigns passed in information to local variables. Sets local variables ''' self.file = self.__check_file_type(file) # Text file with field information self.__grid = [] # Private Grid values def __check_file_type(self, file): ''' Private Method. Checks if file type is string. ''' try: if isinstance(file, str): return file else: raise TypeError except ValueError as error: print('Inappropriate Value', error) except TypeError as error: print('Type Mismatch', error) def __read_file(self): ''' Private method. Reads text file.''' file = open(self.file,"r") self.__get_line_values(file) ## method call file.close() def __convert_line_values(self, line): ''' :method: Private method. removes new line character and commas. :param line: Current line read from file to be formated. :return: Does not return, just updates the existing list passed in as param. ''' try: return [int(value) for value in line.split(' ') if value] except ValueError as error: print('Inappropriate Value: ', error) except TypeError as error: print('Type Mismatch: ', error) def __generate_lines(self, lines): ''' :method: Private - creates a generator from all file lines after stripping them from a new line character. :param lines: list of all lines in the file given. :return: generator of all lines, converted to strings. ''' return (line.rstrip() for line in lines) def __get_line_values(self, lines): ''' :method: Private method. Converts each line into __grid values :param lines: list of all lines from the file. :return: Only updates class variable self.__grid ''' try: self.__grid = [self.__convert_line_values(k[0]) for k in (list(line.split(',') for line in self.__generate_lines(lines) if line))] except ValueError as error: print('Inappropriate Value: ', error) except TypeError as error: print('Type Mismatch: ', error) def __run_data(self): ''' Public method. Once called it beings a sequence to read the text file given. Converts the lines and removes all new line characters and commas. :return: List of two lists: Containing string data respectively to Grid information and Field Variables. ''' self.__read_file() def get_grid(self): ''' Public Method. Returns the grid when called. ''' self.__run_data() # Method Call to format file data return self.__grid def check_duplicates(lst): ''' :method: Private Method. Verifies duplicates - if any -> returns False - else True :param lst: accepts a list of integer values in range 1-9. :return: True if there is no duplicates, False if there is. ''' for k in lst: if k <= 0 or k > 9: return False if lst.count(k) > 1: return False return True def check_rows(grid): ''' :method: calls check_duplicate() to verify if there are any duplicates in a given row. :param grid: List of all rows and the values they reference. :return: True if there is no duplicates, False if there is. ''' for row in grid: if not check_duplicates(row): return False return True def check_columns(grid, grid_size): ''' :method: Columns can never be duplicate as a whole, because that would mean we have duplicate values in the rows -> which is what this method checks. :param grid: column list of values representing the integers stored in it. :param grid_size: size of the column :return if there's no duplicates return True, else False ''' for k in range(grid_size): if not check_duplicates([row[k] for row in grid]): return False return True def verify_sudoku(grid): ''' :method: Once file data is read and converted - verify_sudoku checks if the sequences are valid. :param grid: List of all 9 cubes and their sequences. :return: Prints to the console if the cube is valid or not. ''' if check_rows(grid) and check_columns(grid, len(grid)): return print('yes') else: return print('no') # # ignores variable names that wont be used more than once, leaving global stack empty upon complete execution. verify_sudoku(Data(sys.argv[1]).get_grid()) <file_sep>/Santa Stark vs Night King/src/field/convert_field.py class Field: """ Field class: Only knows of the file name given to it. Reads it and converts the information to __grid or field values, which then get returned as a list. Private methods should only be used by Field class. """ def __init__(self, file): ''' Class constructor: Assigns passed in information to local variables. Sets local variables ''' self.file = self.__check_file_type(file) # Text file with field information self.__file_values = [] # Private Variable holder for Field variables (N, W, k) self.__grid = [] # Private Grid values def __check_file_type(self, file): ''' Private Method. Checks if file type is string. ''' try: if isinstance(file, str): return file else: raise TypeError except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) def __read_file(self): ''' Private method. Reads text file.''' try: file = open(self.file,"r") self.__get_line_values(file) ## method call file.close() except TypeError as error: print('Type Mismatch -> ', error) def __get_line_values(self, lines): ''' Private method. Converts each line into __grid values, or field variables (N, W, k). ''' # :param lines: field text file lines try: for index, line in enumerate(lines): if index != 0: self.__grid.append(line) else: self.__file_values.append(line) except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) def __rs_line(self, line): ''' Private method. removes new line character and commas. ''' try: return line.rstrip().split(',') except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) def __clean_up_lines(self, lst): ''' Private method. Calls __rs_line() to remove uneeded infromation from the data. ''' # :param lst: list of strings to be cleaned up -> grid / field variables try: for index, row in enumerate(lst): lst[index] = self.__rs_line(row) except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) def data(self): ''' Public method. Once called it beings a sequence to read the text file given. Converts the lines and removes all new line characters and commas. :return: List of two lists: Containing string data respectively to Grid information and Field Variables. ''' self.__read_file() self.__clean_up_lines(self.__grid) self.__clean_up_lines(self.__file_values) return [self.__grid, self.__file_values] <file_sep>/Santa Stark vs Night King/src/main.py # Library for timing code execution. # Although "It avoids a number of common traps for measuring execution times.", it is still highly influenced by machine and system capabilities. # # Uncomment line 9 and last line prior to running to get processing time value. import timeit # print(timeit.timeit(""" from data import Data ## Imports Data class to convert file data. import numpy as np ## Numerical python is essential to optimizing processing time. files = [ '../fields/FistOfTheFirstMen.txt', '../fields/Hardhome.txt', '../fields/CastleBlack.txt', '../fields/Winterfell.txt' ] ## Select which file to use. # Main need for error handling is in convert_field, # because everything else depends on the results from reading the file. data = Data(files[3]) ## Set Grid & Variables. grid = data.get_grid() ## Acess public Data class method to grab grid data. variables = data.get_variables() ## Acess public Data class method to grab field variables data. ## Set Global Variables. N = int(variables[0]) # Grid size. W = variables[1] # Amount of Wights. (ENEMIES!!!) _k = variables[2] # More than this amount of survivos is simply allowed! archers_range = 30 # Archer's attack range. enemies = [W / N] * len(grid) # Convert enemies to fit grid. ## Create Clones for faster processing. # Data clones allow us to not override our original data when running thousands of simulations. # Once processed, reassigning the clones takes thousands of a second, compared to re-initializing the data, which may take for example 0.20 seconds. grid_clone = grid[:] enemy_clone = enemies[:] enemy_updates = enemy_clone ## Create Volleys depending on grid size and archer's range. def volleys(attack): try: volley = np.random.uniform(low=0.0, high=float(attack), size=(N,N)) if N > archers_range: zeros = np.zeros((N - archers_range, N), dtype=float) volley_damage_variation = volley[N - archers_range:] return np.concatenate((zeros, volley_damage_variation)) else: return volley except: ValueError return np.zeros((N, N), dtype=float) ## Stats print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print('No more than (' + str(_k) + ' - a fingernail) are allowed to live!!!!!!!!!') print() ## Methods def find_nearest(array, value): ''' Receives an array of survivors and a particular value. Then it finds the closest index to that value from the array and returns it. ''' try: return (np.abs(array - value)).argmin() except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) def refine_search(attack, *args): ''' Method that receives attack % and a value in the form of arguments. This allows us to call the method with a particular percent and do various amounts of iterrations on that percent. * Arguments are received in the form of a list. ** However we should only ever be passing a single value of how many simulations we would like to do. Thus we can simply call it's first index. ''' try: enemy_updates = enemy_clone # Reassigns the clone to a variable that will be used for updating the approaching enemies. survivors_sum = [] # List that adds all survivors per simulation. iterator = 0 # Variable to count simulations until it reaches the given amount of simulations to be made. while iterator < args[0]: volley_percents = 1 - volleys(attack) / (100) # Reformat the Volleys grid to percentages to simplify calculations. for row in range(N): ## for every row in the grid. tmp = enemy_updates - grid_clone[row] ## Temp temporarily holds the enemies data after they have received static defence's damage. ## Through the beauty of Numerical Python, we can instantly check if any value is under zero. tmp[tmp < 0] = 0 ## Thus if any enemy is killed by a trap, we can simply update its data with zero. enemy_updates = np.array(tmp * volley_percents[row]) ## We then update the enemies by applying the respective volley's % damage for that row. enemy_updates[enemy_updates < 0] = 0 ## Checking again if all enemies are killed per cell of that current row, and setting them to zero if so. survivors_sum.append(enemy_updates) # At the end we add the survivors of the current battle simulation to our list of all survivors. enemy_updates = enemy_clone # Resetting enemies for the next simulation. iterator += 1 # Increasing battle simulation value return sum(sum(survivors_sum)/len(survivors_sum)) # Returning the average amount of survivors for all simulations. except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) def quick_search(): ''' Method that we use for finding the closest percent value for p that we can start working with. ''' try: check_attack = 0 # we start with no archers and do a quick search for of their capabilities until we get a rough idea how strong they need to be in order to get less than the amount of survivors we need. # However to get a bit better understanding of that value than just a number, we do 10 battle simulations per percent. for check_attack in range(100): first_search_survivors = refine_search(check_attack, 10) if first_search_survivors < _k: # If we have found the value for p that we need. We return the attack % that has reached it. return check_attack return check_attack except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) def look_deeper(new_search_range): ''' Once we do a quick search and get approximate attack value, We do another search of specific range around that value. ''' try: survivors_book = {} ## We return a dictionary that holds survivors values per attack percent within the specific search range. for check_attack in new_search_range: survivors = refine_search(check_attack, 100) ## We do 100 battle simulations per value of the given search range. survivors_book[check_attack] = (survivors) return survivors_book except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) def unpack_survivors(search): ''' Method to unpack the survivors values from the survivors_book ''' try: return np.array([k for k in search.values()]) except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) def unpack_attacks(search): ''' Method to unpack the attack percent values from the survivors_book ''' try: return np.array([k for k in search.keys()]) except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) ## Quick Search # Get rough estimate at which attack percent to start refining our calculations. Like zooming slightly onto a photo. quick_search_results = quick_search() print("After a quick search of our archer's capabilities,") print(('\twe found that '+ str(quick_search_results) +'% will approximately be our target for training!').expandtabs(2)) print(('\tHowever we will continue refining our search to find a better estimate!').expandtabs(2)) print() ## Second search # Once we get initial attack value, we expand a search range around it (Example: 40 -> [38, 39, 40, 41, 42]). # Then we search again for a more accurate estimate with 100 battle simulations and once we receive the results -> # We find the attack and survivors rate at which we are under the amount of survivors needed to win in hand-to-hand with minimal archer's strength. second_search_range = np.arange(quick_search_results-2, quick_search_results+3, 1) second_search_results = look_deeper(second_search_range) second_search_survivors = unpack_survivors(second_search_results) second_search_attacks = unpack_attacks(second_search_results) second_search_indx = find_nearest(second_search_survivors, _k) print("For our second search we used range of attacks closest to our approximations!") print(('\tWe used'+ str(second_search_range) +' and found that,').expandtabs(2)) print(('\tthe closer strength we should aim for is '+ str(second_search_attacks[second_search_indx]) +'%').expandtabs(2)) print(('\tWhich gave us rough estimates of '+ str(second_search_survivors[second_search_indx]) +' survivors').expandtabs(2)) print(('\tHowever we are not yet fully satisfied and we will continue refining our search to find a better estimate!').expandtabs(2)) print() ## After our report to Sansa, we create another search of a more indepth range of values. ## Third search # We narrow the value range, but expand the depth of it to the thousands of a percent and repeat the previous process. third_search_range = np.arange(second_search_attacks[second_search_indx]-.5, second_search_attacks[second_search_indx]+.5, .025) third_search_results = look_deeper(third_search_range) third_search_survivors = unpack_survivors(third_search_results) third_search_atcks = unpack_attacks(third_search_results) ## Sort the survivors values from the third search third_search_sorted_values = sorted(third_search_results.values()) ## find the index of value corresponding to the nearest number of survivors that guarantee victory trd_srch_index = find_nearest(third_search_survivors, _k) print("For our third search we used the following range of attacks:") print(('\t'+ str(third_search_range)).expandtabs(2)) print() print(('\tWhich allows us to proudly say, in order to guarantee 95% defence success rate is,').expandtabs(2)) print(('\twe will need to train our archers to '+ str(third_search_atcks[trd_srch_index]) +'% of their maximum capabilities').expandtabs(2)) print(('\tWhich gave us rough estimates of '+ str(third_search_survivors[trd_srch_index]) +' survivors').expandtabs(2)) print(('\tHowever we are not yet fully satisfied and we will continue refining our search to find a better estimate!').expandtabs(2)) print() ## find previous surviros value in case current results are over the mark of _k third_search_previous_survivors_value = third_search_sorted_values[third_search_sorted_values.index(third_search_survivors[trd_srch_index])-1] # This is used in case we are slightly over the desired number, then we will for sure know that the previous one will guarantee us 95% rate. ## Assign the previous values for attack and survivors results from the third search after finding the closest survivors value to _k temp_third_search_atck_surv_pair = [(key, value) for key, value in third_search_results.items() if value == third_search_previous_survivors_value] def print_third_search_results(archers_atck, survivors_rate): ''' Method to pring final results to Sansa ''' try: print('We have come up with a plan your highness!!') print(' We have discovered that we only need ' + str(archers_atck) + '% to achieve the minimal of ' + str(survivors_rate) + ' survivors') print(('\tAnd if we use our exceptional hand-to-hand combatants,').expandtabs(2)) print(('we can assure our victory at minimal archer training!').expandtabs(2)) print() except ValueError as error: print('Inappropriate Value ->', error) except TypeError as error: print('Type Mismatch -> ', error) ## Once we have the final attack rate value, we verify one last time to make sure that it'll work, by running 1000 battle simulations on it. final_archer_attack = str(temp_third_search_atck_surv_pair[0][0]) final_survival_rate = str(temp_third_search_atck_surv_pair[0][1]) final_srv = 0 if third_search_survivors[trd_srch_index] > 100.0: print_third_search_results(final_archer_attack, final_survival_rate) final_srv = refine_search(final_archer_attack, 1000) else: print_third_search_results(third_search_atcks[trd_srch_index], third_search_survivors[trd_srch_index]) final_srv = refine_search(third_search_atcks[trd_srch_index], 1000) ## Final report to Sansa. print('However, our hearts tremble at the thought of losing to the wights, thus we decided to simulate a thousand battles with that training rate!!') print(' What we found is that we may still succeed with an average of', final_srv, 'survivors') print(('\tUnfortunatelly there are battle and nature uncertainties that could still cause to lose at an unfortunate 5% rate.').expandtabs(2)) print(('\tSo please be ware and keep that at mind when finilizing your decision!').expandtabs(2)) print() print('Time needed to Execute:') # """, number=1)) <file_sep>/elections/README.md # Elections ### Purpose of the app: 1. Open and read from a file containing data about votes cast in every district in Saskatchewan’s 2016 provincial election. 2. Open and read from a file containing data about candidate names for all parties in every district in Saskatchewan’s 2016 provincial election. 3. Calculate the election results, as follows: * Calculate the winning party for every electoral district. * The results will be written to a text le in tabular format. 4. Provide a report about the election, in terms of the winning party, the number of districts each party won, etc, displayed on the console. <file_sep>/elections/elections_app.py # <NAME> # Module Imports: import sys # Program Methods: def create_mapping(keys, values): ''' :param keys: list, the purpose of which is to be the keys of the resulting structure :param values: list, the purpose of which is to be the values of the keys for the resulting structure :return: returns a dictionary created by the keys and values ''' # result -> variable for the returning dictionary result = {} for index in range(0, len(keys)): # if possible (same length lists) -> create combining dictionary try: result[keys[index]] = values[index] # else -> return empty except: result = {} return result def index_district(votes, candidates, parties): ''' :param votes: a list of vote counts for an electoral district :param candidates: a list of the candidates for the district :param parties: a list of all the political party names for this election :return: a record created from combining the three input lists ''' vots = {} # Variable to hold the generated mapping for votes cands = {} # Variable to hold the generated mapping for candidates # Create maps for votes & candidates vots = create_mapping(parties, votes[1:]) cands = create_mapping(parties, candidates[1:]) # result -> variable holding the structure for specific district result = { 'Name': votes[0], 'Candidates': cands, 'Votes': vots } return result def index_all_districts(votes, candidates, parties): ''' :param votes: a list of vote counts for each electoral district :param candidates: a list of the candidates for each of the districts :param parties: a list of all the political party names for this election :return: database combining the three input lists ''' result = {} # variable holding the database structure temp_votes = [] # temporary variable for iteration of districts # Create database structure for index in range(0, len(votes)): temp_votes.append(votes[index][0]) temp_votes.extend(votes[index][1:]) result[votes[index][0]] = index_district(temp_votes, candidates[index], parties) # dump all temporary information before next iteration temp_votes = [] return result def find_winner(voted_names): ''' :param voted_names: a list of vote counts for each electoral district :return: database combining the three input lists ''' # If voted_names is valid return winner else return empty try: return ''.join([letter for letter in str(max(voted_names.items(), key=lambda k: k[1])) if letter.isupper()]) except: return {} def find_all_winners(database): ''' :param database: database containing every electoral district record :return: the same database with added new key-value pair to each district’s record: the new key will be ’Winner’, and its value will be the name of the winning party ''' temp = [] # temporary variable for holding winner per district record for district_record in database.values(): temp.append(find_winner(district_record['Votes'])) for winning_party_name, district in enumerate(database.keys()): database[district]['Winner'] = temp[winning_party_name] def read_party_names(vote_count_file): ''' :param vote_count_file: a string with the name of a vote count file :return: a list of the party names that appear on the first line of the file ''' # Attempt to open the text file, if invalid -> report error; else return participants try: return open(vote_count_file).readline().rstrip().split(',')[1:] except OSError as err: return "OS error: {}".format(err) def str_or_int(value): ''' :param value -> index from a list to be converted :return converted value as either string or integer ''' # If value cannot be converted to integer, then convert to string; else return integer try: return int(value) except ValueError: return str(value) def read_election_files(candidates_file, vote_counts_file): ''' :param candidates_file -> text file with candidates :param vote_counts_file -> text file with vote countes :return tuple with two lists; First holding all candidates, Second holding all votes ''' # res is a varialbe to hold the tuple construction res = ([], []) # Structure: ''' Candidates: - read each line after first line & convert to list - for each line -> strip return & split by commas * extend existing list of candidates in the resulting structure by passing the formated line Votes: - Same as Candidates, however: once each line is stripped from return & split * call str_or_int() method to convert its index value to either string or integer - extend existing list of votes in the resulting structure by passing the formated & edited line ''' res[0].extend([line.rstrip().split(',') for line in list(open(candidates_file, 'r'))[1:]]) res[1].extend([[str_or_int(index) for index in line.rstrip().split(',')] for line in list(open(vote_counts_file, 'r'))[1:]]) return res def write_election_results(write_to_file, district_database): ''' :param write_to_file -> name of desired file to be written to, in the form of a string :param district_database -> edited elections database # includes party winners :return -> has no return; writes to file instead ''' # fo -> variable to open a new file with written permissions only fo = open(write_to_file, 'w') for district_name, district_record in district_database.items(): for record_type, record_type_data in district_record.items(): if record_type == 'Winner': fo.write( district_name + ',' + str(district_record['Votes'][record_type_data]) + ',' + record_type_data + ',' + str(district_record['Candidates'][record_type_data]) + '\n' ) # close file once it's complete fo.close() def summary_report(participants, districts_won_by_party): ''' :param participants -> participating parties :param districts_won_by_party -> dictionary with the election winners and the number of districts they have won :return -> prints to the console ''' # winner holds the name of the winning party with most districts won winner = (max(districts_won_by_party, key=districts_won_by_party.get)) print() print('*****Election summary*****') print('Participating parties:', participants) print('Districts won by each party:', districts_won_by_party) print('{0} won the election with {1} districts'.format(winner, districts_won_by_party[winner])) print() def main(): ''' :method -> executes the program structurally and reports the results a file 'sk_elections_results_2016.scv' as well as to the console ''' # Read the provided text files - import & format the information parties = read_party_names('sk_election_candidates_2016.csv') (candidates, votes) = read_election_files('sk_election_candidates_2016.csv','sk_election_votecounts_2016.csv') # Create Database from the compiled information database = index_all_districts(votes, candidates, parties) find_all_winners(database) # Write a new file with the outcomes of the elections write_election_results('sk_elections_results_2016.csv', database) # Create temporary variable for storing all winning parties temp = [] for k in database.keys(): temp.append(database[k]['Winner']) # Sum up all winnings by participating party results = dict(zip(temp, [temp.count(i) for i in temp])) # Pass the needed information for the final report summary_report(parties, dict(sorted(results.items(), key=lambda x:x[1]))) # Execute program main() <file_sep>/Santa Stark vs Night King/src/data.py import numpy as np from field.convert_field import Field class Data: """ Data class: Receives text file with field information. Imports Numerical Python library & Field Class to process the given information. Only knows of the file name given to it. Reads it and converts the information to __grid or field values, which then get returned as a list. Private methods should only be used by Data class. """ def __init__(self, field): ''' Private method. Data constructor. ''' self.__field = field # Assigns passed in file to a private local variable for access within its scope. self.__data = self.__init_field() # Method call to initialize field and assigns its results to a local private variable def get_grid(self): ''' Public method. returns final grid information. ''' return self.__set_grid() # Method call def get_variables(self): ''' Public method. returns final field variables (N, W, k) information. ''' return self.__set_variables() # Method call # Numericalpy arrays consume less memory and provide availability to process full range operations without iterating each value. def __set_grid(self): ''' Private method. Accesses converted data from Field class and converts it to numerical python array of type float. ''' return np.array(self.__data[0], dtype=float) def __set_variables(self): ''' Private method. Accesses converted data from Field class and converts it to numerical python array of type float. ''' return np.array(self.__data[1][0], dtype=float) def __init_field(self): ''' Private method to initialize the field data. As result it returns List; index=0 == Grid data && index=1 == Field Variables''' return Field(self.__field).data() <file_sep>/Cubes/Latin Square.py ## Check if a square is Latin. Latin Square is a square in which the values in every row and column appear only once def get_grid_size(): ''' :method: Receives user input for the size of the square. If it's not a positive integer -> 1) inform the user 2) request another value :return: integer value representing the size of the square ''' while True: try: grid_size = int(input("Please enter size of the square: ")) # try to convert the value to integer, if it can't be - raise value error if grid_size <= 0: raise ValueError # if value is negative raise an error except ValueError: print("Invalid input. Please Enter a positive integer!") print() continue # if input value is not valid - continue the truthy state else: print("Thank you!") print() return grid_size # if input value is valid - return it (return breaks the truthy state of the loop) def get_rows_data(row, grid_size): ''' :method: Receives user input for the data in the current row of the square. If it's not of positive integers -> 1) inform the user 2) request another input :param row: used to reference the number of the current row in the square. :param grid_size: references the value that is the square size. :return: integer values representing the data in the current row of the square ''' while True: try: data = reformat_input(input("Enter data for row #" + str(row) + ": ")) if len(data) != grid_size: raise ValueError # if the input does not contain enough elements raise an error for k in data: if k > grid_size: raise ValueError # if the inputed element is greater than the needed value, raise an error except ValueError: print("Invalid input.") print("Please Enter a range of", grid_size, "positive integers (from 1 to", str(grid_size) + " inclusive) separated by space!") print() continue else: return data def data_init(grid_size): ''' :method: Asks the user to input integer values for each row in the square. :param grid_size: Holds the size of the square. :return: List of lists, each of which holds integers per row ''' return [get_rows_data(row, grid_size) for row in range(1, grid_size + 1)] def reformat_input(string_data): ''' :method: Receives a list of values, separated by space, as a string. Splits and converts to integer each value. :param string_data: list of stringed data to be converted to integer values before returning. :return: List of integer values - data of current row in the square. ''' return [int(k) for k in string_data.split()] def check_duplicates(lst): ''' :method: receives a list of integers values & checks for duplicates in it. :param lst: list of integer values ( current row of the square ) :return: False if the list contains duplicates, else returns the original list. ''' # Faster to keep it split, than in list comprehension -> allows to terminate sooner than later, if duplicate found. for k in lst: if lst.count(k) > 1: return False return lst def check_columns(grid, grid_size): ''' :method: For columns to be duplicate as a whole, they would create duplicate values in the rows, which is previously checked. Thus this method checks for duplicated values in the columns only. :param grid: column list of values representing the integers stored in it. :param grid_size: size of the column :return if there's no duplicates return True, else False ''' for k in range(grid_size): if not check_duplicates([row[k] for row in grid]): return False return True def check_rows(grid_data): ''' :method: receives a list of lists of integers, representing the rows. First checks if there's duplicated rows, then checks for duplicated values in each row. :param lst: list of lists of integers in the rows of the square. :return: True if no duplicates are found, or else - False ''' # Faster to keep it split, than in list comprehension -> allows to terminate sooner than later, if duplicate found. for row in grid_data: if not check_duplicates(row): return False ## Check for duplicate values in a row return True def check_latin(): ''' :method: receives a list of lists - the inputed row positive integers, and the size of the square :param lst: list of lists of inputed row positive integers :param grid: size of the square as a positive integer value :return: 'no' if the square is not Latin, and 'yes' if it is. ''' grid_size = get_grid_size() # variable name to reference the size of the square grid_data = data_init(grid_size) # list to hold all integers in the square, by rows try: if not check_rows(grid_data): raise ValueError if not check_columns(grid_data, grid_size): raise ValueError except ValueError: print('no') else: print('yes') check_latin() <file_sep>/README.md # Variety of small python problems. <file_sep>/UofS/fact.py gnikolov@Georgis-MacBook-Pro UofS (master) $ touch fact.py gnikolov@Georgis-MacBook-Pro UofS (master) $ git status On branch master Your branch is up-to-date with 'origin/master'. Untracked files: (use "git add <file>..." to include in what will be committed) ./ nothing added to commit but untracked files present (use "git add" to track) gnikolov@Georgis-MacBook-Pro UofS (master) $ cd .. gnikolov@Georgis-MacBook-Pro python (master) $ git status On branch master Your branch is up-to-date with 'origin/master'. Untracked files: (use "git add <file>..." to include in what will be committed) UofS/ nothing added to commit but untracked files present (use "git add" to track) gnikolov@Georgis-MacBook-Pro python (master) $ git add . UofS/ gnikolov@Georgis-MacBook-Pro python (master) $ git status On branch master Your branch is up-to-date with 'origin/master'. Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: UofS/fact.py gnikolov@Georgis-MacBook-Pro python (master) $ git commit -m "Added factorial stub function." [master 5104c13] Added factorial stub function. 1 file changed, 10 insertions(+) create mode 100644 UofS/fact.py gnikolov@Georgis-MacBook-Pro python (master) $ git status On branch master Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits) Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: UofS/fact.py no changes added to commit (use "git add" and/or "git commit -a") gnikolov@Georgis-MacBook-Pro python (master) $ git add . gnikolov@Georgis-MacBook-Pro python (master) $ git commit -m "Coded up a recursive implementation of factorial." [master b054e22] Coded up a recursive implementation of factorial. 1 file changed, 4 insertions(+), 1 deletion(-) gnikolov@Georgis-MacBook-Pro python (master) $ git add fact.py fatal: pathspec 'fact.py' did not match any files gnikolov@Georgis-MacBook-Pro python (master) $ git status On branch master Your branch is ahead of 'origin/master' by 2 commits. (use "git push" to publish your local commits) Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: UofS/fact.py no changes added to commit (use "git add" and/or "git commit -a") gnikolov@Georgis-MacBook-Pro python (master) $ git add . gnikolov@Georgis-MacBook-Pro python (master) $ git commit -m "Replaced the recursion in factorial() with a loop." [master 0646df4] Replaced the recursion in factorial() with a loop. 1 file changed, 4 insertions(+), 4 deletions(-) gnikolov@Georgis-MacBook-Pro python (master) $ cd UofS/ gnikolov@Georgis-MacBook-Pro UofS (master) $ git diff HEAD~1 HEAD -- fact.py diff --git a/UofS/fact.py b/UofS/fact.py index f480307..69804be 100644 --- a/UofS/fact.py +++ b/UofS/fact.py @@ -7,7 +7,7 @@ def factorial(n): Return: a non-negative integer ''' - if n == 0: - return 1 - else: - return n * factorial(n-1) + prod = 1 + for i in range (1, n): + prod = prod * i + return prod gnikolov@Georgis-MacBook-Pro UofS (master) $ git add fact.py gnikolov@Georgis-MacBook-Pro UofS (master) $ git commit -m "Fixed calculation error in factorial() loop version" [master fafe19f] Fixed calculation error in factorial() loop version 1 file changed, 3 insertions(+), 2 deletions(-) gnikolov@Georgis-MacBook-Pro UofS (master) $ git diff HEAD~1 HEAD -- fact.py diff --git a/UofS/fact.py b/UofS/fact.py index 69804be..15a9e18 100644 --- a/UofS/fact.py +++ b/UofS/fact.py @@ -8,6 +8,7 @@ def factorial(n): a non-negative integer ''' prod = 1 - for i in range (1, n): - prod = prod * i + while n >= 1: + prod = prod * n + n = n - 1 return prod gnikolov@Georgis-MacBook-Pro UofS (master) $ <file_sep>/Cubes/Magic Square.py ## Check if a 3x3 square is Magic Square. Middle value of a magic square is 5, and corners are even integers. class Input: """ Input class: Only knows of the file name given to it. Reads it and converts the information to __grid or field values, which then get returned as a list. Private methods should only be used by Field class. """ def __init__(self): ''' Class constructor: Assigns passed in information to local variables. Sets local variables ''' self._input = [] # Local protected variable. def run_input(self): ''' Public method. Gets user input, verifies it and returns it if correct. ''' duplicate = self.__get_input() # receives True or False depending if duplicates were found or not. while not duplicate: # if there are duplicates, continue asking for input untill there are no duplicates. duplicate = self.__get_input() print() print("Accepted Input: ", self._input) # if the input is correct, inform the user and return it. return self._input def __get_input(self): ''' :method: Private Method. Receives user input and converts it to integer values. Then it updates its class variable "self._input" and verifies it. :return: Method call to check user input. returns True or False. ''' self._input = self.__reformat_input(self.__receive_input()) return self.__check_input(self._input) def __receive_input(self): ''' Private Method. Prints to the console and returns user input.''' print("Please enter a sequence of unique integers,") return input("\tbetween 1-9 inclusive, separated by spaces: ".expandtabs(2)) def __reformat_input(self, lst): ''' :method: Private Method. Receives user input as a list with one string. Formats each value as integer and returns a new list. :param lst: List containing one string of values. :return: Converts the string of values to a list of integer values instead. Returns a new list. ''' return [int(k) for k in lst.split()] def __check_input(self, lst): ''' :method: Private Method. Verifies if the formated integer list contains the correct amount of numbers. :param lst: list of integer values. :return: True if there is no input errors. False if there is not enough numbers or if there is duplicates. ''' if len(lst) != 9: return False for k in lst: if lst.count(k) > 1: print('Duplicateup found!') print() return False return True def verify_magic(lst): ''' :method: Method to verify if received sequence of integers is a magic square. :param lst: list of nine integer values. :return: prints to the console if the sequence given by the user is a magic square or not. ''' if lst[4] != 5: return print("The Sequence Is Not A Magic Square!\n") for k in [lst[c] for c, i in enumerate(lst) if c % 2 == 0 and c != 4]: if k % 2 == 0: return print("The Sequence Is A Magic Square!\n") else: return print("The Sequence Is Not A Magic Square!\n") verify_magic(Input().run_input()) # calls Input class to initiate input request sequence. Then verifies that input and decides if it's a magic square.
e1ea9d2512dbc3c4e00fcfef2d8c2e2263990de4
[ "Markdown", "Python" ]
13
Python
nikolovGeorgi/python
b2567aeafd342116ba5928003fb13c7353014b3f
5486ece10333066245f8dfcb3d09757f4dd838b9
refs/heads/master
<repo_name>iremcemreo/pizza_otomasyon4<file_sep>/PizzaOtomasyon_BA/PizzaOtomasyon_BA/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PizzaOtomasyon_BA { public partial class Form1 : Form { public Form1() { InitializeComponent(); } List<PizzaCesitleri> pizzaCesitleri = new List<PizzaCesitleri>(); List<Ebatlar> ebatlar = new List<Ebatlar>(); List<Malzemeler> malzemeler = new List<Malzemeler>(); List<Siparis> siparisler = new List<Siparis>(); private void Form1_Load(object sender, EventArgs e) { pizzaCesitleri.Add(new PizzaCesitleri("Klasik", 14)); pizzaCesitleri.Add(new PizzaCesitleri("Karışık", 17)); pizzaCesitleri.Add(new PizzaCesitleri("ExtraVaganza", 21)); pizzaCesitleri.Add(new PizzaCesitleri("Italiano", 20)); pizzaCesitleri.Add(new PizzaCesitleri("Turkish", 23)); pizzaCesitleri.Add(new PizzaCesitleri("Tuna", 18)); pizzaCesitleri.Add(new PizzaCesitleri("SeaFeed", 19)); pizzaCesitleri.Add(new PizzaCesitleri("Kastamonu", 20)); pizzaCesitleri.Add(new PizzaCesitleri("Calypso", 24)); pizzaCesitleri.Add(new PizzaCesitleri("Akdeniz", 21)); pizzaCesitleri.Add(new PizzaCesitleri("Karadeniz", 21)); lbPizzalar.DataSource = pizzaCesitleri; lbPizzalar.DisplayMember = "_pizzaIsmi"; lbPizzalar.ValueMember = "_pizzaFiyat"; ebatlar.Add(new Ebatlar("Maxi", 2)); ebatlar.Add(new Ebatlar("Büyük", 1.75)); ebatlar.Add(new Ebatlar("Orta", 1.25)); ebatlar.Add(new Ebatlar("Küçük", 1)); cmbEbatlar.DataSource = ebatlar; cmbEbatlar.DisplayMember = "_ebatIsmi"; cmbEbatlar.ValueMember = "_ebatFiyatCarpani"; } private void btnHesapla_Click(object sender, EventArgs e) { HesaplaButonBas(); } private void btnSepeteEkle_Click(object sender, EventArgs e) { HesaplaButonBas(); malzemeler.Clear(); SiparisOlustur(); double toplamTutar = 0; foreach (Siparis item in siparisler) { Siparis sp = (Siparis)item; toplamTutar = toplamTutar + sp._sTutar; } lblToplamTutar.Text = toplamTutar.ToString(); } private void btnSiparisiOnayla_Click(object sender, EventArgs e) { MessageBox.Show("Toplam" + " " + lbSiparis.Items.Count + " " + "Adet siparişiniz" + Environment.NewLine + lblToplamTutar.Text + " " + "TL Tutarındadır."); } private void SiparisOlustur() { try { Siparis siparis = new Siparis(); siparis._sEbat = cmbEbatlar.Text.ToString(); if (rbKalinKenar.Checked) siparis._sKenarCesidi = rbKalinKenar.Text.ToString(); else siparis._sKenarCesidi = rbInceKenar.Text.ToString(); foreach (Control item in gbMalzemeler.Controls) { if (item is CheckBox) { CheckBox cb = (CheckBox)item; if (cb.Checked) { malzemeler.Add(new Malzemeler(cb.Text.ToString())); } } } siparis._sMalzemeler = malzemeler; siparis._sPizzaIsmi = lbPizzalar.Text.ToString(); siparis._sTutar = sTutar; lbSiparis.Items.Add(siparis.ToString()); siparisler.Add(siparis); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private double sTutar; private void HesaplaButonBas() { try { double kenarCesidi = 0; if (rbKalinKenar.Checked) { kenarCesidi = 2; } double tutar = 0, ebat, adet, pizzaFiyati; ebat = Convert.ToDouble(cmbEbatlar.SelectedValue); adet = Convert.ToDouble(txtAdet.Text); pizzaFiyati = Convert.ToDouble(lbPizzalar.SelectedValue); txtTutar.Text = ToplamHesapla(tutar, ebat, adet, pizzaFiyati, kenarCesidi).ToString(); sTutar = Convert.ToDouble(txtTutar.Text); } catch (Exception) { MessageBox.Show("Lütfen Adet Bölümüne Geçerli bir sayı giriniz."); } } private object ToplamHesapla(double tutar, double ebat, double adet, double pizzaFiyati, double kenarCesidi) { return tutar = ((adet * pizzaFiyati) * ebat) + (adet * kenarCesidi); } } } <file_sep>/PizzaOtomasyon_BA/PizzaOtomasyon_BA/Ebatlar.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PizzaOtomasyon_BA { public class Ebatlar { public string _ebatIsmi { get; private set; } public double _ebatFiyatCarpani { get; private set; } public Ebatlar(string ebatIsmi, double ebatFiyatCarpani) { this._ebatFiyatCarpani = ebatFiyatCarpani; this._ebatIsmi = ebatIsmi; } } } <file_sep>/PizzaOtomasyon_BA/PizzaOtomasyon_BA/PizzaCesitleri.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PizzaOtomasyon_BA { public class PizzaCesitleri { public string _pizzaIsmi { get; private set; } public double _pizzaFiyat { get; private set; } public PizzaCesitleri(string pizzaIsmi, double pizzaFiyat) { this._pizzaIsmi = pizzaIsmi; this._pizzaFiyat = pizzaFiyat; } } } <file_sep>/PizzaOtomasyon_BA/PizzaOtomasyon_BA/Siparis.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PizzaOtomasyon_BA { class Siparis { public string _sEbat { get; set; } public string _sPizzaIsmi { get; set; } public string _sKenarCesidi { get; set; } public List<Malzemeler> _sMalzemeler { get; set; } public double _sTutar { get; set; } private string malzeme; public override string ToString() { for (int i = 0; i < _sMalzemeler.Count; i++) { malzeme = malzeme + "," + _sMalzemeler[i]._malzemeIsmi.ToString(); } return _sEbat + " " + _sPizzaIsmi + " " + _sKenarCesidi + " " + malzeme + " " + _sTutar; } } }
15fbf199fe0e42492d2ccb5e26439c61f55c3680
[ "C#" ]
4
C#
iremcemreo/pizza_otomasyon4
fbc1ac44c17d61cc46be6b32b3c198960bf42206
a55d0ec4905b45ce5add76f8642473fd8575ba30
refs/heads/master
<file_sep># Postgres inside the cluster https://engineering.bitnami.com/articles/create-a-production-ready-postgresql-cluster-bitnami-kubernetes-and-helm.html cd /Users/dennis/demos/postgres wget https://raw.githubusercontent.com/helm/charts/master/stable/postgresql/values-production.yaml ROOT_PASSWORD= REPLICATION_PASSWORD= ## install using azure disk helm install --name postgres-disk stable/postgresql -f values-production-disk.yaml helm install --name postgres-disk stable/postgresql -f values-production-disk.yaml --set postgresqlPassword=<PASSWORD> --set replication.password=<PASSWORD> --set postgresqlDatabase=mydatabase --namespace=pdisk install metrics kubectl apply -f logging/postgres-amz-config.yaml https://www.peterbe.com/plog/how-i-performance-test-postgresql-locally-on-macos azure files mount options https://github.com/andyzhangx/Demo/blob/master/linux/azurefile/azurefile-mountoptions.md cat <<EOF | kubectl apply -f - kind: StorageClass apiVersion: storage.k8s.io/v1 metadata: name: azurefile provisioner: kubernetes.io/azure-file mountOptions: - dir_mode=0777 - file_mode=0777 - uid=1000 - gid=1000 - mfsymlinks - nobrl - cache=none parameters: skuName: Standard_LRS location: $LOCATION storageAccount: $STORAGE_ACCOUNT EOF kubectl run my-postgresql-client --tty -i --image bitnami/postgresql --env="ALLOW_EMPTY_PASSWORD=yes" kubectl run my-postgresql-client --rm --tty -i --image bitnami/postgresql --env="PGPASSWORD=$DB_PASSWORD" --command -- psql --host $DB_HOST -U $DB_USER postgres=# SELECT client_addr, state FROM pg_stat_replication; # create and insert data on the master ``` kubectl run my-release-postgresql-client --rm --tty -i --image bitnami/postgresql --env="PGPASSWORD=ROOT_<PASSWORD>" --command -- psql --host my-release-postgresql -U postgres postgres=# CREATE TABLE test (id int not null, val text not null); postgres=# INSERT INTO test VALUES (1, 'foo'); postgres=# INSERT INTO test VALUES (2, 'bar'); ``` # connect to the slave and verify data ``` kubectl exec -it my-release-postgresql-slave-0 -- bash bash> export PGPASSWORD=$DB_PASSWORD bash> psql --host $DB_HOST -U $DB_USER postgres=# SELECT * FROM test; DB_HOST=dzdemosql.postgres.database.azure.com DB_PASSWORD=<PASSWORD> DB_USER=dennis@dzdemosql psql -h $DB_HOST master $DB_USER ```<file_sep># Rancher https://rancher.com/docs/rancher/v2.x/en/installation/k8s-install/helm-rancher/ helm repo add rancher-latest https://releases.rancher.com/server-charts/latest kubectl create namespace cattle-system DNS=kvdns.eastus.cloudapp.azure.com helm upgrade rancher rancher-latest/rancher \ --namespace cattle-system --install \ --set hostname=$DNS<file_sep> ndzauthd2.northeurope.cloudapp.azure.com AD_APP_NAME="ndzauthd2-easy-auth-proxy" APP_HOSTNAME="ndzauthd2.northeurope.cloudapp.azure.com" HOMEPAGE=https://$APP_HOSTNAME REPLY_URLS=https://$APP_HOSTNAME/easyauth/signin-oidc https://ndzauthd2.northeurope.cloudapp.azure.com/easyauth/signin-oidc cat << EOF > manifest.json [ { "resourceAccess" : [ { "id" : "e1fe6dd8-ba31-4d61-89e7-88639da4683d", "type" : "Scope" } ], "resourceAppId" : "00000003-0000-0000-c000-000000000000" } ] EOF cat manifest.json CLIENT_ID=$(az ad app create --display-name $AD_APP_NAME --identifier-uris $REPLY_URLS --app-roles @manifest.json -o json | jq -r '.id') echo $CLIENT_ID OBJECT_ID=$(az ad app show --id $CLIENT_ID -o json | jq '.objectId' -r) echo $OBJECT_ID az ad app update --id $OBJECT_ID --set oauth2Permissions[0].isEnabled=false az ad app update --id $OBJECT_ID --set oauth2Permissions=[] # The newly registered app does not have a password. Use "az ad app credential reset" to add password and save to a variable. CLIENT_SECRET=$(az ad app credential reset --id $CLIENT_ID -o json | jq '.password' -r) echo $CLIENT_SECRET # Get your Azure AD tenant ID and save to variable AZURE_TENANT_ID=$(az account show -o json | jq '.tenantId' -r) echo $AZURE_TENANT_ID helm install --set azureAd.tenantId=$AZURE_TENANT_ID --set azureAd.clientId=$CLIENT_ID --set secret.name=easyauth-proxy-$AD_APP_NAME-secret --set secret.azureclientsecret=$CLIENT_SECRET --set appHostName=$APP_HOSTNAME --set tlsSecretName=$TLS_SECRET_NAME easyauth-proxy-$AD_APP_NAME ./charts/easyauth-proxy kubectl run easyauth-sample-pod --image=docker.io/dakondra/eak-sample:latest --expose --port=80 cat << EOF > ./sample-ingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: easyauth-sample-ingress-default annotations: nginx.ingress.kubernetes.io/auth-url: "https://\$host/easyauth/auth" nginx.ingress.kubernetes.io/auth-signin: "https://\$host/easyauth/login" nginx.ingress.kubernetes.io/auth-response-headers: "x-injected-userinfo,x-injected-name,x-injected-oid,x-injected-preferred-username,x-injected-sub,x-injected-tid,x-injected-email,x-injected-groups,x-injected-scp,x-injected-roles,x-injected-graph" cert-manager.io/cluster-issuer: letsencrypt-prod #nginx.ingress.kubernetes.io/rewrite-target: /\$1 spec: ingressClassName: nginx tls: - hosts: - $APP_HOSTNAME secretName: $TLS_SECRET_NAME rules: - host: $APP_HOSTNAME http: paths: - path: / pathType: Prefix backend: service: name: easyauth-sample-pod port: number: 80 --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: easyauth-sample-ingress-anonymous annotations: cert-manager.io/cluster-issuer: letsencrypt-prod spec: ingressClassName: nginx tls: - hosts: - $APP_HOSTNAME secretName: $TLS_SECRET_NAME rules: - host: $APP_HOSTNAME http: paths: - path: /Anonymous pathType: Prefix backend: service: name: easyauth-sample-pod port: number: 80 - path: /css pathType: Prefix backend: service: name: easyauth-sample-pod port: number: 80 - path: /js pathType: Prefix backend: service: name: easyauth-sample-pod port: number: 80 - path: /lib pathType: Prefix backend: service: name: easyauth-sample-pod port: number: 80 - path: /favicon.ico pathType: Exact backend: service: name: easyauth-sample-pod port: number: 80 - path: /EasyAuthForK8s.Sample.styles.css pathType: Exact backend: service: name: easyauth-sample-pod port: number: 80 --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: easyauth-sample-ingress-role-required annotations: nginx.ingress.kubernetes.io/auth-url: "https://\$host/easyauth/auth?role=RoleYouDontHave" nginx.ingress.kubernetes.io/auth-signin: "https://\$host/easyauth/login" nginx.ingress.kubernetes.io/auth-response-headers: "x-injected-userinfo,x-injected-name,x-injected-oid,x-injected-preferred-username,x-injected-sub,x-injected-tid,x-injected-email,x-injected-groups,x-injected-scp,x-injected-roles,x-injected-graph" cert-manager.io/cluster-issuer: letsencrypt-prod #nginx.ingress.kubernetes.io/rewrite-target: /\$1 spec: ingressClassName: nginx tls: - hosts: - $APP_HOSTNAME secretName: $TLS_SECRET_NAME rules: - host: $APP_HOSTNAME http: paths: - path: /RoleRequired pathType: Prefix backend: service: name: easyauth-sample-pod port: number: 80 --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: easyauth-sample-ingress-role-graph annotations: nginx.ingress.kubernetes.io/auth-url: "https://\$host/easyauth/auth?scope=User.Read&graph=%2Fme%3F%24select%3DdisplayName%2CjobTitle%2CuserPrincipalName" nginx.ingress.kubernetes.io/auth-signin: "https://\$host/easyauth/login" nginx.ingress.kubernetes.io/auth-response-headers: "x-injected-userinfo,x-injected-name,x-injected-oid,x-injected-preferred-username,x-injected-sub,x-injected-tid,x-injected-email,x-injected-groups,x-injected-scp,x-injected-roles,x-injected-graph" cert-manager.io/cluster-issuer: letsencrypt-prod #nginx.ingress.kubernetes.io/rewrite-target: /\$1 spec: ingressClassName: nginx tls: - hosts: - $APP_HOSTNAME secretName: $TLS_SECRET_NAME rules: - host: $APP_HOSTNAME http: paths: - path: /Graph pathType: Prefix backend: service: name: easyauth-sample-pod port: number: 80 EOF cat ./sample-ingress.yaml<file_sep>SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id TENANT_ID=$(az account show --query tenantId -o tsv) KUBE_GROUP="arclima10" # here enter the resources group name of your AKS cluster KUBE_NAME="arclima10" # here enter the name of your kubernetes resource LOCATION="eastus" # here enter the datacenter location KUBE_VNET_NAME="knets" # here enter the name of your vnet KUBE_FW_SUBNET_NAME="AzureFirewallSubnet" # this you cannot change APPGW_SUBNET_NAME="gw-1-subnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" # here enter the name of your ingress subnet KUBE_AGENT_SUBNET_NAME="aks-5-subnet" # here enter the name of your AKS subnet KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" # here enter the kubernetes version of your AKS KUBE_CNI_PLUGIN="azure" EXTENSIONPATH="~/Downloads/" echo 'registering providers...' az feature register --namespace Microsoft.Resources --name EUAPParticipation az provider register -n Microsoft.Resources --wait az feature register --namespace Microsoft.Kubernetes --name previewAccess az provider register --namespace Microsoft.Kubernetes --wait az feature register --namespace Microsoft.KubernetesConfiguration --name extensions az provider register --namespace Microsoft.KubernetesConfiguration --wait az feature register --namespace Microsoft.ExtendedLocation --name CustomLocations-ppauto az provider register --namespace Microsoft.ExtendedLocation --wait az provider register --namespace Microsoft.Web --wait echo 'installing extensions...' az extension add --name aks-preview az extension update --name aks-preview az extension add --yes --source $EXTENSIONPATH/appservice_kube-0.1.8-py2.py3-none-any.whl az extension add --yes --source $EXTENSIONPATH/connectedk8s-0.3.5-py2.py3-none-any.whl az extension add --yes --source $EXTENSIONPATH/customlocation-0.1.0-py2.py3-none-any.whl az extension add --yes --source $EXTENSIONPATH/k8s_extension-0.1.0-py2.py3-none-any.whl az account set --subscription $SUBSCRIPTION_ID az group create -n $KUBE_GROUP -l $LOCATION echo "setting up service principal" SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) sleep 5 # wait for replication az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP echo "setting up vnet" az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_FW_SUBNET_NAME --address-prefix 10.0.3.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $APPGW_SUBNET_NAME --address-prefix 10.0.2.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage echo "setting up aks" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --network-plugin $KUBE_CNI_PLUGIN --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --no-ssh-key az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME echo "setting up azure monitor" az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --location $LOCATION WORKSPACE_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME -o json | jq '.id' -r) az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons monitoring --workspace-resource-id $WORKSPACE_ID echo "setting up azure arc" az extension add --name connectedk8s az extension add --name k8sconfiguration az extension update --name connectedk8s az extension update --name k8sconfiguration export appId=$SERVICE_PRINCIPAL_ID export password=$<PASSWORD> export tenantId=$TENANT_ID export resourceGroup=$KUBE_GROUP export arcClusterName=$KUBE_NAME az connectedk8s connect --name $KUBE_NAME --resource-group $KUBE_GROUP export clusterId="$(az resource show --resource-group $resourceGroup --name $arcClusterName --resource-type "Microsoft.Kubernetes/connectedClusters" --query id)" export clusterId="$(echo "$clusterId" | sed -e 's/^"//' -e 's/"$//')" echo "setting up lima" ASELOCATION="northcentralusstage" az aks get-credentials -n $KUBE_NAME -g $KUBE_GROUP NODE_GROUP=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME -o tsv --query nodeResourceGroup) az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $NODE_GROUP az network public-ip create -g $NODE_GROUP -n limaegress --sku STANDARD IP=$(az network public-ip show -g $NODE_GROUP -n limaegress -o tsv --query ipAddress) AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME -o tsv --query id) az role assignment create --assignee abfa0a7c-a6b6-4736-8310-5855508787cd --role "Azure Kubernetes Service Cluster Admin Role" --scope $AKS_ID az extension add --source https://k8seazurecliextensiondev.blob.core.windows.net/azure-cli-extension/appservice_kube-0.1.7-py2.py3-none-any.whl az appservice kube create -g $KUBE_GROUP -n akse -l $ASELOCATION --aks $KUBE_NAME --static-ip $IP az appservice plan create -g $KUBE_GROUP -n kubeappsplan --kube-environment akse --kube-sku ANY az webapp list-runtimes --linux az webapp create -g $KUBE_GROUP -p kubeappsplan -n nodeapp1 --runtime "NODE|12-lts" az webapp create -g $KUBE_GROUP -p kubeappsplan -n AppName --runtime "NODE|12-lts" az webapp create -g $KUBE_GROUP -n kubeappsplan -n nodeapp1 --runtime "NODE|12-lts" az webapp create -g $KUBE_GROUP -n kubeappsplan -n nginx1 --deployment-container-image-name docker.io/nginx:latest az webapp create -g $KUBE_GROUP -p kubeappsplan -n corpapp1 -i myregistry.azurecr.io/imagename:tag az webapp create -g $KUBE_GROUP -p kubeappsplan -n dzacihello1 --deployment-container-image-name denniszielke/aci-helloworld az webapp create -g $KUBE_GROUP -p kubeappsplan -n dzacihello1 --deployment-container-image-name dzbuild.azurecr.io/aci-helloworld:latest az aks get-upgrades --resource-group $KUBE_GROUP --name $KUBE_NAME --output table az aks update --resource-group $KUBE_GROUP --name $KUBE_NAME --auto-upgrade-channel rapid <file_sep> https://github.com/weaveworks/flagger/blob/master/docs/gitbook/tutorials/flagger-smi-istio.md echo " apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: public-gateway namespace: istio-system spec: selector: istio: ingressgateway servers: - port: number: 80 name: http protocol: HTTP hosts: - "*" kubectl -n istio-system port-forward svc/flagger-grafana 3000:80 export REPO=https://raw.githubusercontent.com/weaveworks/flagger/master kubectl apply -f ${REPO}/artifacts/namespaces/test.yaml kubectl apply -f ${REPO}/artifacts/canaries/deployment.yaml kubectl apply -f ${REPO}/artifacts/canaries/hpa.yaml kubectl -n test apply -f ${REPO}/artifacts/loadtester/deployment.yaml kubectl -n test apply -f ${REPO}/artifacts/loadtester/service.yaml https://docs.flagger.app/usage/linkerd-progressive-delivery kubectl -n linkerd logs deployment/flagger -f | jq .msg kubectl -n linkerd port-forward svc/linkerd-grafana 3000:80 kubectl -n test run tester --image=quay.io/stefanprodan/podinfo:1.2.1 -- ./podinfo --port=9898 kubectl -n test exec -it $(kubectl -n test get pod -l run=tester -o jsonpath='{.items[0].metadata.name}') -- /bin/sh var=1; while true ; do var=$((var+1)) curl http://podinfo-primary:9898/status/500 curl http://podinfo-primary:9898/delay/1 curl http://podinfo-canary:9898/status/500 curl http://podinfo-canary:9898/delay/1 now=$(date +"%T") sleep 1 done var=1; while true ; do var=$((var+1)) curl http://podinfo-canary:9898/status/500 curl http://podinfo-canary:9898/delay/1 now=$(date +"%T") sleep 1 done ## SMI Failure injection https://linkerd.io/2019/07/18/failure-injection-using-the-service-mesh-interface-and-linkerd/<file_sep> kubectl -n linkerd logs deployment/flagger -f | jq .msg kubectl -n istio-system logs deployment/flagger -f | jq .msg kubectl -n test set image deployment/podinfo podinfod=quay.io/stefanprodan/podinfo:1.7.1<file_sep># AppGW Ingress Controller ## AGIC Config variables SUBSCRIPTION_ID=$(az account show --query id -o tsv) KUBE_NAME="dzgwenv1" AGIC_IDENTITY_NAME=$KUBE_NAME"-id" APPGW_NAME=$KUBE_NAME"-gw" KUBE_GROUP="infra" LOCATION="westeurope" NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION KUBE_VNET_NAME=$KUBE_NAME"-vnet" KUBE_GW_SUBNET_NAME="gw-1-subnet" KUBE_ACI_SUBNET_NAME="aci-2-subnet" KUBE_FW_SUBNET_NAME="AzureFirewallSubnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" KUBE_AGENT_SUBNET_NAME="aks-5-subnet" KUBE_AGENT2_SUBNET_NAME="aks-6-subnet" KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" SERVICE_PRINCIPAL_ID= SERVICE_PRINCIPAL_SECRET= ### deploy cluster ``` SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET ``` ### deploy vnet ``` az group create -n $KUBE_GROUP -l $LOCATION az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_GW_SUBNET_NAME --address-prefix 10.0.1.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ACI_SUBNET_NAME --address-prefix 10.0.2.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_FW_SUBNET_NAME --address-prefix 10.0.3.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT2_SUBNET_NAME --address-prefix 10.0.6.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage ``` ### deploy cluster ``` KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 1 --ssh-key-value ~/.ssh/id_rsa.pub --enable-vmss --network-plugin kubenet --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --pod-cidr 10.244.0.0/16 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --network-policy calico --enable-rbac --load-balancer-sku standard --enable-addons monitoring AKS_FQDN=$(az aks show -g ${KUBE_GROUP} -n ${KUBE_NAME} --query "fqdn" -o tsv) ``` ### deploy gateway ``` az network public-ip create \ --resource-group $KUBE_GROUP \ --name $APPGW_NAME-pip \ --allocation-method Static \ --sku Standard az network application-gateway create --name $APPGW_NAME --resource-group $KUBE_GROUP --location $LOCATION --capacity 2 --sku Standard_v2 --vnet-name $KUBE_NAME-vnet --subnet gw-1-subnet --http-settings-cookie-based-affinity Disabled --frontend-port 80 --http-settings-port 80 --http-settings-protocol Http --public-ip-address $APPGW_NAME-pip APPGW_NAME=$(az network application-gateway list --resource-group=$KUBE_GROUP -o json | jq -r ".[0].name") APPGW_RESOURCE_ID=$(az network application-gateway list --resource-group=$KUBE_GROUP -o json | jq -r ".[0].id") APPGW_SUBNET_ID=$(az network application-gateway list --resource-group=$KUBE_GROUP -o json | jq -r ".[0].gatewayIpConfigurations[0].subnet.id") ``` ### copy routetable ``` NODE_GROUP=$(az aks show -g ${KUBE_GROUP} -n ${KUBE_NAME} --query "nodeResourceGroup" -o tsv) AKS_AGENT_SUBNET_ID=$(az aks show -g ${KUBE_GROUP} -n ${KUBE_NAME} --query "agentPoolProfiles[0].vnetSubnetId" -o tsv) AKS_ROUTE_TABLE_ID=$(az network route-table list -g ${NODE_GROUP} --query "[].id | [0]" -o tsv) AKS_ROUTE_TABLE_NAME=$(az network route-table list -g ${NODE_GROUP} --query "[].name | [0]" -o tsv) AKS_NODE_NSG=$(az network nsg list -g ${NODE_GROUP} --query "[].id | [0]" -o tsv) az network route-table create -g $KUBE_GROUP --name $APPGW_NAME-rt APPGW_ROUTE_TABLE_ID=$(az network route-table show -g ${KUBE_GROUP} -n $APPGW_NAME-rt --query "id" -o tsv) az network nsg create --name $APPGW_NAME-rt --resource-group $KUBE_GROUP --location $LOCATION az network nsg rule create --name appgwrule --nsg-name $APPGW_NAME-rt --resource-group $KUBE_GROUP --priority 110 \ --source-address-prefixes '*' --source-port-ranges '*' \ --destination-address-prefixes '*' --destination-port-ranges '*' --access Allow --direction Inbound \ --protocol "*" --description "Required allow rule for AppGW." APPGW_NSG=$(az network nsg list -g ${KUBE_GROUP} --query "[].id | [0]" -o tsv) az network vnet subnet update --resource-group $KUBE_GROUP --route-table $APPGW_ROUTE_TABLE_ID --network-security-group $APPGW_NSG --ids $APPGW_SUBNET_ID AKS_ROUTES=$(az network route-table route list --resource-group $NODE_GROUP --route-table-name $AKS_ROUTE_TABLE_NAME) az network route-table route list --resource-group $NODE_GROUP --route-table-name $AKS_ROUTE_TABLE_NAME --query "[][name,addressPrefix,nextHopIpAddress]" -o tsv | while read -r name addressPrefix nextHopIpAddress; do echo "checking route $name" echo "creating new hop $name selecting $addressPrefix configuring $nextHopIpAddress as next hop" az network route-table route create --resource-group $KUBE_GROUP --name $name --route-table-name $APPGW_NAME-rt --address-prefix $addressPrefix --next-hop-type VirtualAppliance --next-hop-ip-address $nextHopIpAddress --subscription $SUBSCRIPTION_ID done az network route-table route list --resource-group $KUBE_GROUP --route-table-name $APPGW_NAME-rt ``` ### deploy aad pod identity https://github.com/Azure/aad-pod-identity/tree/master/charts/aad-pod-identity#configuration https://github.com/Azure/aad-pod-identity#deploy-the-azure-aad-identity-infra ``` helm repo add aad-pod-identity https://raw.githubusercontent.com/Azure/aad-pod-identity/master/charts helm install aad-pod-identity aad-pod-identity/aad-pod-identity kubectl apply -f https://raw.githubusercontent.com/Azure/aad-pod-identity/master/deploy/infra/deployment-rbac.yaml # For managed identity clusters, deploy the MIC exception by running - kubectl apply -f https://raw.githubusercontent.com/Azure/aad-pod-identity/v1.5.5/deploy/infra/deployment-rbac.yaml kubectl apply -f https://raw.githubusercontent.com/Azure/aad-pod-identity/master/deploy/infra/mic-exception.yaml az identity create -g $NODE_GROUP -n $AGIC_IDENTITY_NAME --subscription $SUBSCRIPTION_ID AGIC_MSI_CLIENT_ID=$(az identity show -n $AGIC_IDENTITY_NAME -g $NODE_GROUP -o json | jq -r ".clientId") echo "$AGIC_MSI_CLIENT_ID" AGIC_MSI_RESOURCE_ID=$(az identity show -n $AGIC_IDENTITY_NAME -g $NODE_GROUP -o json | jq -r ".id") echo $AGIC_MSI_RESOURCE_ID export IDENTITY_ASSIGNMENT_ID="$(az role assignment create --role Reader --assignee $AGIC_MSI_CLIENT_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourceGroups/$NODE_GROUP --query id -otsv)" export IDENTITY_ASSIGNMENT_ID="$(az role assignment create --role Reader --assignee $AGIC_MSI_CLIENT_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP --query id -otsv)" export IDENTITY_ASSIGNMENT_ID="$(az role assignment create --role Contributor --assignee $AGIC_MSI_CLIENT_ID --scope $APPGW_RESOURCE_ID --query id -otsv)" ``` deploy azure identity ``` cat <<EOF | kubectl apply -f - apiVersion: "aadpodidentity.k8s.io/v1" kind: AzureIdentity metadata: name: $AGIC_IDENTITY_NAME spec: type: 0 resourceID: $AGIC_MSI_RESOURCE_ID clientID: $AGIC_MSI_CLIENT_ID EOF kubectl get AzureIdentity $AGIC_IDENTITY_NAME -o yaml ``` deploy binding ``` cat <<EOF | kubectl apply -f - apiVersion: "aadpodidentity.k8s.io/v1" kind: AzureIdentityBinding metadata: name: $AGIC_IDENTITY_NAME-binding spec: azureIdentity: $AGIC_IDENTITY_NAME selector: $AGIC_IDENTITY_NAME EOF kubectl get AzureIdentityBinding $AGIC_IDENTITY_NAME-binding -o yaml ``` ### deploy agic ``` helm repo add application-gateway-kubernetes-ingress https://appgwingress.blob.core.windows.net/ingress-azure-helm-package/ helm repo update helm search repo application-gateway-kubernetes-ingress kubectl create namespace appgw helm install ingress-azure application-gateway-kubernetes-ingress/ingress-azure \ --namespace appgw \ --debug \ --set appgw.name=$APPGW_NAME \ --set appgw.resourceGroup=$KUBE_GROUP \ --set appgw.subscriptionId=$SUBSCRIPTION_ID \ --set appgw.usePrivateIP=false \ --set appgw.shared=false \ --set armAuth.type=aadPodIdentity \ --set armAuth.identityClientID=$AGIC_MSI_CLIENT_ID \ --set armAuth.identityResourceID=$AGIC_MSI_RESOURCE_ID \ --set rbac.enabled=true \ --set verbosityLevel=3 \ --set kubernetes.watchNamespace=default \ --set aksClusterConfiguration.apiServerAddress=$AKS_FQDN ``` from source ``` git clone https://github.com/Azure/application-gateway-kubernetes-ingress.git cd application-gateway-kubernetes-ingress/helm helm upgrade ingress-azure ./ingress-azure --install \ --namespace appgw \ --debug \ --set appgw.name=$APPGW_NAME \ --set appgw.resourceGroup=$KUBE_GROUP \ --set appgw.subscriptionId=$SUBSCRIPTION_ID \ --set appgw.usePrivateIP=false \ --set appgw.shared=false \ --set armAuth.type=aadPodIdentity \ --set armAuth.identityClientID=$AGIC_MSI_CLIENT_ID \ --set armAuth.identityResourceID=$AGIC_MSI_RESOURCE_ID \ --set rbac.enabled=true \ --set verbosityLevel=3 \ --set kubernetes.watchNamespace=default \ --set aksClusterConfiguration.apiServerAddress=$AKS_FQDN helm upgrade ingress-azure ./ingress-azure --install \ --namespace appgw \ --debug \ --set appgw.name=$APPGW_NAME \ --set appgw.resourceGroup=$KUBE_GROUP \ --set appgw.subscriptionId=$SUBSCRIPTION_ID \ --set appgw.usePrivateIP=false \ --set appgw.shared=false \ --set armAuth.type=aadPodIdentity \ --set armAuth.identityClientID=$AGIC_MSI_CLIENT_ID \ --set armAuth.identityResourceID=$AGIC_MSI_RESOURCE_ID \ --set rbac.enabled=true \ --set verbosityLevel=3 \ --set kubernetes.watchNamespace=default \ --set aksClusterConfiguration.apiServerAddress=$AKS_FQDN helm template ingress-azure ./ingress-azure \ --namespace appgw \ --debug \ --set appgw.name=$APPGW_NAME \ --set appgw.resourceGroup=$KUBE_GROUP \ --set appgw.subscriptionId=$SUBSCRIPTION_ID \ --set appgw.usePrivateIP=false \ --set appgw.shared=false \ --set armAuth.type=aadPodIdentity \ --set armAuth.identityClientID=$AGIC_MSI_CLIENT_ID \ --set armAuth.identityResourceID=$AGIC_MSI_RESOURCE_ID \ --set rbac.enabled=true \ --set verbosityLevel=3 \ --set kubernetes.watchNamespace=default \ --set aksClusterConfiguration.apiServerAddress=$AKS_FQDN ``` ### test ``` kubectl logs -n kube-system -l app=ingress-azure kubectl apply -f https://raw.githubusercontent.com/kubernetes/examples/master/guestbook/all-in-one/guestbook-all-in-one.yaml cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: guestbook annotations: kubernetes.io/ingress.class: azure/application-gateway spec: rules: - http: paths: - backend: serviceName: frontend servicePort: 80 EOF kubectl delete ingress guestbook kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/echo-server.yaml cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: dummy-logger annotations: kubernetes.io/ingress.class: azure/application-gateway spec: rules: - http: paths: - backend: serviceName: dummy-logger servicePort: 80 EOF kubectl delete ingress dummy-logger cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: dummy-logger-private annotations: kubernetes.io/ingress.class: azure/application-gateway appgw.ingress.kubernetes.io/use-private-ip: "true" spec: rules: - http: paths: - backend: serviceName: dummy-logger servicePort: 80 EOF cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: dummy-logger-private annotations: appgw.ingress.kubernetes.io/backend-path-prefix: /dummy kubernetes.io/ingress.class: azure/application-gateway appgw.ingress.kubernetes.io/use-private-ip: "true" appgw.ingress.kubernetes.io/backend-hostname: "dummy.example.com" spec: rules: - host: dummy.example.com http: paths: - path: /dummy/ backend: serviceName: dummy-logger servicePort: 80 EOF cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: echo-service annotations: appgw.ingress.kubernetes.io/backend-path-prefix: /echo kubernetes.io/ingress.class: azure/application-gateway appgw.ingress.kubernetes.io/use-private-ip: "true" appgw.ingress.kubernetes.io/backend-hostname: "src.example.com" spec: rules: - host: src.example.com http: paths: - path: /echo/ backend: serviceName: echo-service servicePort: 80 EOF cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: echo-service annotations: kubernetes.io/ingress.class: azure/application-gateway appgw.ingress.kubernetes.io/use-private-ip: "true" spec: rules: - host: src.example.com http: paths: - path: /echo/ backend: serviceName: echo-service servicePort: 80 - host: dummy.example.com http: paths: - path: /dummy/ backend: serviceName: dummy-logger servicePort: 80 EOF curl http://src.example.com --resolve src.example.com:80:10.0.4.100 curl http://dummy.example.com --resolve dummy.example.com:80:10.0.4.100 kubectl delete ingress dummy-logger-private cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: guestbook annotations: kubernetes.io/ingress.class: azure/application-gateway spec: rules: - http: paths: - backend: serviceName: frontend servicePort: 80 EOF ```<file_sep>package qdapr.acme; import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.HEAD; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import java.util.Set; @Path("/extensions") @RegisterRestClient(configKey = "invoke") public interface InvokeService { @GET @Path("/messages") Set<String> all(); @GET @Path("/messages/{id}") Set<String> getById(@PathParam("id") String stream); @HEAD @Path("/messages/{id}") Set<String> headById(@PathParam("id") String stream); @POST @Path("/messages/{id}") Set<String> postById(@PathParam("id") String stream); @DELETE @Path("/messages/{id}") Set<String> deleteById(@PathParam("id") String stream); } <file_sep># Terraform 0. Variables ``` export PATH=$PATH:$HOME/lib/terraform AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) AZURE_SUBSCRIPTION_NAME=$(az account show --query name -o tsv) AZURE_SUBSCRIPTION_ID=$(az account show --query id -o tsv) AZURE_MYOWN_OBJECT_ID=$(az ad signed-in-user show --query objectId --output tsv) TERRAFORM_STORAGE_NAME= TERRAFORM_RG_NAME=terraform LOCATION=westeurope ``` 1. Create a sp for terraform ``` az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/${SUBSCRIPTION_ID}" --name "terraform_sp" az ad sp create-for-rbac --role="Reader" --scopes="/subscriptions/${SUBSCRIPTION_ID}" --name "dz_aks_sp" ``` 2. Create storage for terraform state ``` az group create -n $TERRAFORM_RG_NAME -l $LOCATION az storage account create --resource-group $TERRAFORM_RG_NAME --name $TERRAFORM_STORAGE_NAME --location $LOCATION --sku Standard_LRS TERRAFORM_STORAGE_KEY=$(az storage account keys list --account-name $TERRAFORM_STORAGE_NAME --resource-group $TERRAFORM_RG_NAME --query "[0].value") az storage container create -n tfstate --account-name $TERRAFORM_STORAGE_NAME --account-key $TERRAFORM_STORAGE_KEY ``` 3. run terraform ``` terraform init -backend-config="storage_account_name=$TERRAFORM_STORAGE_NAME" -backend-config="container_name=tfstate" -backend-config="access_key=$TERRAFORM_STORAGE_KEY" -backend-config="key=codelab.microsoft.tfstate" ``` ``` terraform plan -out out.plan ``` ``` terraform apply out.plan ```<file_sep># VHD https://github.com/Azure/aks-engine/blob/master/docs/howto/troubleshooting.md vmss 429 https://github.com/Azure/aks-engine/issues/1860 https://github.com/Azure/AKS/issues/1278 az vmss update-instances -g <RESOURCE_GROUP_NAME> --name <VMSS_NAME> --instance-id <ID(number)> # enter ssh sudo wget https://raw.githubusercontent.com/andyzhangx/demo/master/dev/kubectl-enter sudo chmod a+x ./kubectl-enter ./kubectl-enter <node-name> # Periscope https://github.com/Azure/aks-periscope/blob/master/README.md ``` az aks kollect -g $KUBE_GROUP -n $KUBE_NAME STORAGE_ACCOUNT_KEY=$(az storage account keys list --account-name "dzt$KUBE_NAME" --resource-group $KUBE_GROUP --query "[0].value" | tr -d '"') az aks kollect -g $KUBE_GROUP -n $KUBE_NAME --storage-account "dzt$KUBE_NAME" --sas-token $STORAGE_ACCOUNT_KEY az aks kollect -g $KUBE_GROUP -n $KUBE_NAME ``` # Cleanup ``` kubectl delete ds aks-periscope -n aks-periscope kubectl delete secret azureblob-secret -n aks-periscope kubectl delete configmap containerlogs-config -n aks-periscope kubectl delete configmap kubeobjects-config -n aks-periscope ``` # Logs Relevant logs: /var/log/azure/cluster-provision.log /var/log/cloud-init-output.log /var/log/azure/custom-script/handler.log /opt/azure/provision-ps.log /var/log/waagent.log Provision script log output: /var/log/azure/cluster-provision.log Exit code from: /opt/azure/provision-ps.log See script run times: /opt/m Look up exit error codes: https://github.com/Azure/aks-engine/blob/master/parts/k8s/cloud-init/artifacts/cse_helpers.sh # TCP dump https://github.com/digeler/k8tcpappend # Snapshpt SUBSCRIPTION_ID=$(az account show --query id -o tsv) KUBE_VERSION=$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv) # here enter the kubernetes version of your AKS LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) az group create -n $KUBE_GROUP-1 -l $LOCATION -o none az aks create -g $KUBE_GROUP -n $KUBE_NAME --kubernetes-version $KUBE_VERSION --snapshot-id "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP-1/providers/Microsoft.ContainerService/snapshots/$KUBE_NAME-1" # Kappie kubectl create configmap ama-metrics-prometheus-config-node --from-file=./logging/ama-cilium-configmap.yaml -n kube-system kubectl port-forward $(kubectl get po -l dsName=ama-metrics-node -o name -n kube-system | head -n 1) 9090:9090 -n kube-system helm install kappie ./deploy/manifests/controller/helm/kappie/ --namespace kube-system --dependency-update kubectl create configmap ama-metrics-prometheus-config-node --from-file=logging/ama-cilium-configmap.yaml -n kube-system http://localhost:9090/targets SAS='' kappie capture create --blob-upload $SAS --namespace capture --pod-selectors="k8s-app=kube-dns" --namespace-selectors="kubernetes.io/metadata.name=kube-system" --duration=2m --no-wait=false kappie capture create --blob-upload $SAS --node-selectors "kubernetes.io/os=linux" --namespace calculator kubectl create secret generic blob-sas-url --from-literal blob-upload-url=$SAS echo $SAS | base64 --encode kubectl apply -f - <<EOF apiVersion: v1 data: blob-upload-url: $SAS kind: Secret metadata: name: blob-sas-url namespace: default type: Opaque EOF kubectl apply -f - <<EOF apiVersion: kappie.io/v1alpha1 kind: Capture metadata: name: capture-test spec: captureConfiguration: captureOption: duration: 30 captureTarget: nodeSelector: matchLabels: kubernetes.io/hostname: aks-nodepool1-22452897-vmss000000 outputConfiguration: hostPath: "/tmp/kappie" blockUpload: blob-sas-url EOF # Diagnostics # Set your Azure virtual machine scale set diagnostic variables. ``` KUBE_GROUP= KUBE_NAME= LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) SCALE_SET_NAME=$(az vmss list --resource-group $NODE_GROUP --query "[0].name" -o tsv) az storage account create --resource-group $NODE_GROUP --name $KUBE_NAME --location $LOCATION --sku Standard_LRS --access-tier hot --https-only false az vmss identity assign -g $NODE_GROUP -n $SCALE_SET_NAME wget https://raw.githubusercontent.com/Azure/azure-linux-extensions/master/Diagnostic/tests/lad_2_3_compatible_portal_pub_settings.json -O portal_public_settings.json my_vmss_resource_id=$(az vmss show -g $NODE_GROUP -n $SCALE_SET_NAME --query "id" -o tsv) sed -i "s#__DIAGNOSTIC_STORAGE_ACCOUNT__#$KUBE_NAME#g" portal_public_settings.json sed -i "s#__VM_RESOURCE_ID__#$my_vmss_resource_id#g" portal_public_settings.json my_diagnostic_storage_account_sastoken=$(az storage account generate-sas --account-name $KUBE_NAME --expiry 2037-12-31T23:59:00Z --permissions wlacu --resource-types co --services bt -o tsv) my_lad_protected_settings="{'storageAccountName': '$KUBE_NAME', 'storageAccountSasToken': <PASSWORD>'}" az vmss extension set --publisher Microsoft.Azure.Diagnostics --name LinuxDiagnostic --version 4.0 --resource-group $NODE_GROUP --vmss-name $SCALE_SET_NAME --protected-settings "${my_lad_protected_settings}" --settings portal_public_settings.json ```<file_sep>#!/bin/sh # # wget https://raw.githubusercontent.com/denniszielke/container_demos/master/scripts/aks_lima_v2.sh # chmod +x ./aks_udr_nsg_firewall.sh # bash ./aks_udr_nsg_firewall.sh # set -e # https://docs.microsoft.com/en-us/azure/virtual-network/virtual-networks-udr-overview#service-tags-for-user-defined-routes-preview KUBE_GROUP="hbspoke1" # here enter the resources group name of your AKS cluster KUBE_NAME="dzprivaks1" # here enter the name of your kubernetes resource LOCATION="westeurope" # here enter the datacenter location AKS_POSTFIX="-1" NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_"$AKS_POSTFIX"_nodes_"$LOCATION # name of the node resource group KUBE_VNET_NAME="knets" # here enter the name of your vnet KUBE_FW_SUBNET_NAME="AzureFirewallSubnet" # this you cannot change APPGW_SUBNET_NAME="gw-1-subnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" # here enter the name of your ingress subnet KUBE_AGENT_SUBNET_NAME="aks-5-subnet" # here enter the name of your AKS subnet POD_AGENT_SUBNET_NAME="pod-8-subnet" VNET_GROUP="hbhub1" # here enter the network resource group name HUB_VNET_NAME="hubnet1" # here enter the name of your hub net PREM_VNET_NAME="onpremnet1" # here enter the name of your onprem vnet FW_NAME="dzkubenetfw" # here enter the name of your azure firewall resource APPGW_NAME="dzkubeappgw" KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" # here enter the kubernetes version of your AKS AAD_GROUP_ID="9329d38c-5296-4ecb-afa5-3e74f9abe09f" #"77801859-4ac2-4492-9fa4-091a7f09a8df" # "9329d38c-5296-4ecb-afa5-3e74f9abe09f" # here the AAD group that will be used to lock down AKS authentication MY_OWN_OBJECT_ID=$(az ad signed-in-user show --query objectId --output tsv) # this will be your own aad object id SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id TENANT_ID=$(az account show --query tenantId -o tsv) USE_PRIVATE_LINK="false" # use to deploy private master endpoint USE_FW="true" USE_POD_SUBNET="true" az account set --subscription $SUBSCRIPTION_ID echo "using Kubernetes version $KUBE_VERSION" # az extension add --name azure-firewall # az extension update --name azure-firewall # az extension add --name aks-preview # az extension update --name aks-preview if [ $(az group exists --name $KUBE_GROUP) = false ]; then echo "creating resource group $KUBE_GROUP..." az group create -n $KUBE_GROUP -l $LOCATION -o none echo "resource group $KUBE_GROUP created" else echo "resource group $KUBE_GROUP already exists" fi if [ $(az group exists --name $VNET_GROUP) = false ]; then echo "creating resource group $VNET_GROUP..." az group create -n $VNET_GROUP -l $LOCATION -o none echo "resource group $VNET_GROUP created" else echo "resource group $VNET_GROUP already exists" fi echo "setting up k8s vnet" VNET_RESOURCE_ID=$(az network vnet list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_VNET_NAME')].id" -o tsv) if [ "$VNET_RESOURCE_ID" == "" ]; then echo "creating vnet $KUBE_VNET_NAME..." az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME --address-prefixes 10.0.4.0/22 172.16.0.0/18 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $POD_AGENT_SUBNET_NAME --address-prefix 172.16.0.0/22 -o none VNET_RESOURCE_ID=$(az network vnet show -g $KUBE_GROUP -n $KUBE_VNET_NAME --query id -o tsv) echo "created $VNET_RESOURCE_ID" else echo "vnet $VNET_RESOURCE_ID already exists" fi echo "setting up hub vnet" HUBVNET_RESOURCE_ID=$(az network vnet list -g $VNET_GROUP --query "[?contains(name, '$HUB_VNET_NAME')].id" -o tsv) if [ "$HUBVNET_RESOURCE_ID" == "" ]; then echo "creating vnet $HUB_VNET_NAME..." az network vnet create -g $VNET_GROUP -n $HUB_VNET_NAME --address-prefixes 10.0.0.0/22 -o none az network vnet subnet create -g $VNET_GROUP --vnet-name $HUB_VNET_NAME -n AzureFirewallSubnet --address-prefix 10.0.0.0/24 -o none az network vnet subnet create -g $VNET_GROUP --vnet-name $HUB_VNET_NAME -n $APPGW_SUBNET_NAME --address-prefix 10.0.1.0/24 -o none HUBVNET_RESOURCE_ID=$(az network vnet show -g $VNET_GROUP -n $HUB_VNET_NAME --query id -o tsv) az network vnet peering create -g $VNET_GROUP -n HubToSpoke1 --vnet-name $HUB_VNET_NAME --remote-vnet $VNET_RESOURCE_ID --allow-vnet-access -o none az network vnet peering create -g $KUBE_GROUP -n Spoke1ToHub --vnet-name $KUBE_VNET_NAME --remote-vnet $HUBVNET_RESOURCE_ID --allow-vnet-access -o none echo "created $HUBVNET_RESOURCE_ID" else echo "vnet $HUBVNET_RESOURCE_ID already exists" fi echo "setting up dns zone" if [ "$USE_PRIVATE_LINK" == "true" ]; then DNS_ZONE_ID=$(az network private-dns zone list -g $VNET_GROUP --query "[?contains(name, 'privatelink.$LOCATION.azmk8s.io')].id" -o tsv) if [ "$DNS_ZONE_ID" == "" ]; then az network private-dns zone create -g $VNET_GROUP -n privatelink.$LOCATION.azmk8s.io -o none az network private-dns link vnet create -g $VNET_GROUP -n hubzone -z privatelink.$LOCATION.azmk8s.io -v $HUBVNET_RESOURCE_ID -e true -o none az network private-dns link vnet create -g $VNET_GROUP -n k8szone -z privatelink.$LOCATION.azmk8s.io -v $VNET_RESOURCE_ID -e true -o none DNS_ZONE_ID=$(az network private-dns zone show -g $VNET_GROUP -n $KUBE_NAME --query id -o tsv) echo "created $DNS_ZONE_ID" else echo "dns zone $DNS_ZONE_ID already exists" fi fi echo "setting up azure firewall" if [ "$USE_FW" == "true" ]; then FW_PUBLIC_IP_ID=$(az network public-ip list -g $VNET_GROUP --query "[?contains(name, '$FW_NAME-ip')].id" -o tsv) if [ "$FW_PUBLIC_IP_ID" == "" ]; then echo "creating firewall ip" az network public-ip create -g $VNET_GROUP -n $FW_NAME-ip --sku STANDARD -o none FW_PUBLIC_IP_ID=$(az network public-ip show -g $VNET_GROUP -n $FW_NAME-ip --query id -o tsv) FW_PUBLIC_IP=$(az network public-ip show -g $VNET_GROUP -n $FW_NAME-ip -o tsv --query ipAddress) echo "created ip $FW_PUBLIC_IP_ID with ip $FW_PUBLIC_IP" else FW_PUBLIC_IP=$(az network public-ip show -g $VNET_GROUP -n $FW_NAME-ip -o tsv --query ipAddress) echo "firewall ip $FW_PUBLIC_IP_ID with ip $FW_PUBLIC_IP already exists" fi echo "setting up aks" FW_ID=$(az network firewall list -g $VNET_GROUP --query "[?contains(name, '$FW_NAME')].id" -o tsv) if [ "$FW_ID" == "" ]; then echo "creating firewall $FW_NAME in $VNET_GROUP" az network firewall create --name $FW_NAME --resource-group $VNET_GROUP --location $LOCATION -o none az network firewall ip-config create --firewall-name $FW_NAME --name $FW_NAME --public-ip-address $FW_NAME-ip --resource-group $VNET_GROUP --vnet-name $HUB_VNET_NAME FW_ID=$(az network firewall show -g $VNET_GROUP -n $FW_NAME --query id -o tsv) FW_PRIVATE_IP=$(az network firewall show -g $VNET_GROUP -n $FW_NAME --query "ipConfigurations[0].privateIpAddress" -o tsv) echo "created firewall $FW_ID" echo "setting up network rules" az network firewall network-rule create --firewall-name $FW_NAME --collection-name "time" --destination-addresses "*" --destination-ports 123 --name "allow network" --protocols "UDP" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "aks node time sync rule" --priority 101 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "dns" --destination-addresses "*" --destination-ports 53 --name "allow network" --protocols "Any" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "aks node dns rule" --priority 102 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "servicetags" --destination-addresses "AzureContainerRegistry" "AzureFrontDoor.FirstParty" "MicrosoftContainerRegistry" "AzureActiveDirectory" "AzureMonitor" --destination-ports "*" --name "allow service tags" --protocols "Any" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "allow service tags" --priority 110 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "hcp" --destination-addresses "AzureCloud.$LOCATION" --destination-ports "1194" --name "allow master tags" --protocols "UDP" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "allow aks link access to masters" --priority 120 echo "setting up application rules" az network firewall application-rule create --firewall-name $FW_NAME --resource-group $VNET_GROUP --collection-name 'aksfwar' -n 'fqdn' --source-addresses '*' --protocols 'http=80' 'https=443' --fqdn-tags "AzureKubernetesService" --action allow --priority 101 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "osupdates" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $VNET_GROUP --action "Allow" --target-fqdns "download.opensuse.org" "security.ubuntu.com" "packages.microsoft.com" "azure.archive.ubuntu.com" "changelogs.ubuntu.com" "snapcraft.io" "api.snapcraft.io" "motd.ubuntu.com" --priority 102 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "dockerhub" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $VNET_GROUP --action "Allow" --target-fqdns "*auth.docker.io" "*cloudflare.docker.io" "*cloudflare.docker.com" "*registry-1.docker.io" --priority 200 else echo "firewall $FW_ID already exists" FW_PRIVATE_IP=$(az network firewall show -g $VNET_GROUP -n $FW_NAME --query "ipConfigurations[0].privateIpAddress" -o tsv) fi # FIREWALL_WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace list --resource-group $KUBE_GROUP --query "[?contains(name, '$FW_NAME-lgw')].id" -o tsv) # if [ "$FIREWALL_WORKSPACE_RESOURCE_ID" == "" ]; then # echo "creating workspace $FW_NAME in $KUBE_GROUP" # az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $FW_NAME-lgw --location $LOCATION # else # echo "workspace $FIREWALL_WORKSPACE_RESOURCE_ID alreaedy exists" # fi else echo "ignore fw" fi echo "setting up user defined routes for host vnet" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" ROUTE_TABLE_RESOURCE_ID=$(az network route-table list --resource-group $KUBE_GROUP --query "[?contains(name, '$FW_NAME-rt')].id" -o tsv) if [ "$ROUTE_TABLE_RESOURCE_ID" == "" ]; then echo "creating route table $FW_NAME-rt in $KUBE_GROUP" az network route-table create -g $KUBE_GROUP --name $FW_NAME-rt if [ "$USE_FW" == "true" ]; then az network route-table route create --resource-group $KUBE_GROUP --name $FW_NAME --route-table-name $FW_NAME-rt --address-prefix 0.0.0.0/0 --next-hop-type VirtualAppliance --next-hop-ip-address $FW_PRIVATE_IP #else # az network route-table route create --resource-group $KUBE_GROUP --name $FW_NAME --route-table-name $FW_NAME-rt --address-prefix 0.0.0.0/0 --next-hop-type None fi az network route-table route create --resource-group $KUBE_GROUP --name "mcr" --route-table-name $FW_NAME-rt --address-prefix MicrosoftContainerRegistry --next-hop-type Internet az network route-table route create --resource-group $KUBE_GROUP --name "fd" --route-table-name $FW_NAME-rt --address-prefix AzureFrontDoor.FirstParty --next-hop-type Internet az network route-table route create --resource-group $KUBE_GROUP --name "aad" --route-table-name $FW_NAME-rt --address-prefix AzureActiveDirectory --next-hop-type Internet az network route-table route create --resource-group $KUBE_GROUP --name "adf" --route-table-name $FW_NAME-rt --address-prefix AzureFrontDoor.FirstParty --next-hop-type Internet az network route-table route create --resource-group $KUBE_GROUP --name "arm" --route-table-name $FW_NAME-rt --address-prefix AzureResourceManager --next-hop-type Internet az network route-table route create --resource-group $KUBE_GROUP --name "lb" --route-table-name $FW_NAME-rt --address-prefix GatewayManager --next-hop-type Internet az network route-table route create --resource-group $KUBE_GROUP --name "monitor" --route-table-name $FW_NAME-rt --address-prefix AzureMonitor --next-hop-type Internet az network route-table route create --resource-group $KUBE_GROUP --name "azure" --route-table-name $FW_NAME-rt --address-prefix AzureCloud.$LOCATION --next-hop-type Internet az network vnet subnet update --route-table $FW_NAME-rt --ids $KUBE_AGENT_SUBNET_ID az network route-table route list --resource-group $KUBE_GROUP --route-table-name $FW_NAME-rt else echo "routetable $ROUTE_TABLE_RESOURCE_ID already exists" fi echo "setting up user defined routes for pod vnet" KUBE_POD_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $POD_AGENT_SUBNET_NAME --query id -o tsv) POD_ROUTE_TABLE_RESOURCE_ID=$(az network route-table list --resource-group $KUBE_GROUP --query "[?contains(name, '$FW_NAME-pod-rt')].id" -o tsv) if [ "$POD_ROUTE_TABLE_RESOURCE_ID" == "" ]; then echo "creating route table $FW_NAME-pod-rt in $KUBE_GROUP" az network route-table create -g $KUBE_GROUP --name $FW_NAME-pod-rt if [ "$USE_FW" == "true" ]; then az network route-table route create --resource-group $KUBE_GROUP --name $FW_NAME --route-table-name $FW_NAME-pod-rt --address-prefix 0.0.0.0/0 --next-hop-type VirtualAppliance --next-hop-ip-address $FW_PRIVATE_IP # else # az network route-table route create --resource-group $KUBE_GROUP --name $FW_NAME --route-table-name $FW_NAME-pod-rt --address-prefix 0.0.0.0/0 --next-hop-type None fi az network route-table route create --resource-group $KUBE_GROUP --name "aad" --route-table-name $FW_NAME-pod-rt --address-prefix AzureActiveDirectory --next-hop-type Internet az network route-table route create --resource-group $KUBE_GROUP --name "monitor" --route-table-name $FW_NAME-pod-rt --address-prefix AzureMonitor --next-hop-type Internet az network route-table route create --resource-group $KUBE_GROUP --name "azure" --route-table-name $FW_NAME-pod-rt --address-prefix AzureCloud.$LOCATION --next-hop-type Internet az network vnet subnet update --route-table $FW_NAME-pod-rt --ids $KUBE_POD_SUBNET_ID az network route-table route list --resource-group $KUBE_GROUP --route-table-name $FW_NAME-pod-rt else echo "routetable $POD_ROUTE_TABLE_RESOURCE_ID already exists" fi ROUTE_TABLE_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --query routeTable.id -o tsv) KUBE_AGENT_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --query id -o tsv) KUBE_POD_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $POD_AGENT_SUBNET_NAME --query id -o tsv) if [ "$ROUTE_TABLE_ID" == "" ]; then echo "could not find routetable on AKS subnet $KUBE_AGENT_SUBNET_ID" else echo "using routetable $ROUTE_TABLE_ID with the following entries" ROUTE_TABLE_GROUP=$(az network route-table show --ids $ROUTE_TABLE_ID --query "[resourceGroup]" -o tsv) ROUTE_TABLE_NAME=$(az network route-table show --ids $ROUTE_TABLE_ID --query "[name]" -o tsv) echo "if this routetable does not contain a route for '0.0.0.0/0' with target VirtualAppliance or VirtualNetworkGateway then we will not need the outbound type parameter" az network route-table route list --resource-group $ROUTE_TABLE_GROUP --route-table-name $ROUTE_TABLE_NAME -o table echo "if it does not contain a '0.0.0.0/0' route then you should set the parameter IGNORE_FORCE_ROUTE=true" fi echo "setting up controller identity" AKS_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-id')].id" -o tsv)" if [ "$AKS_CLIENT_ID" == "" ]; then echo "creating controller identity $KUBE_NAME-id in $KUBE_GROUP" az identity create --name $KUBE_NAME-id --resource-group $KUBE_GROUP -o none sleep 5 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" sleep 5 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 25 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" sleep 5 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 5 # wait for replication az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $KUBE_POD_SUBNET_ID -o none if [ "$ROUTE_TABLE_ID" == "" ]; then echo "no route table used" else echo "assigning permissions on routetable $ROUTE_TABLE_ID" az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $ROUTE_TABLE_ID -o none fi if [ "$USE_PRIVATE_LINK" == "true" ]; then az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $DNS_ZONE_ID -o none az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $VNET_RESOURCE_ID -o none fi else echo "controller identity $AKS_CONTROLLER_RESOURCE_ID already exists" echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $KUBE_POD_SUBNET_ID -o none if [ "$ROUTE_TABLE_ID" == "" ]; then echo "no route table used" else echo "assigning permissions on routetable $ROUTE_TABLE_ID" az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $ROUTE_TABLE_ID -o none fi if [ "$USE_PRIVATE_LINK" == "true" ]; then az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $DNS_ZONE_ID -o none az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $VNET_RESOURCE_ID -o none fi fi echo "setting up aks" AKS_ID=$(az aks list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME$AKS_POSTFIX')].id" -o tsv) KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" KUBE_POD_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$POD_AGENT_SUBNET_NAME" if [ "$USE_PRIVATE_LINK" == "true" ]; then ACTIVATE_PRIVATE_LINK=" --enable-private-cluster --private-dns-zone $DNS_ZONE_ID --fqdn-subdomain spoke1" # --private-dns-zone none --enable-public-fqdn else ACTIVATE_PRIVATE_LINK="" #-outbound-type userDefinedRouting fi if [ "$AKS_ID" == "" ]; then echo "creating AKS $KUBE_NAME in $KUBE_GROUP" echo "using host subnet $KUBE_AGENT_SUBNET_ID" if [ "$USE_POD_SUBNET" == "true" ]; then echo "using pod subnet $KUBE_POD_SUBNET_ID" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --ssh-key-value ~/.ssh/id_rsa.pub --max-pods 250 --node-count 3 --min-count 3 --max-count 5 --enable-cluster-autoscaler --node-resource-group $NODE_GROUP --load-balancer-sku standard --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --pod-subnet-id $KUBE_POD_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --assign-identity $AKS_CONTROLLER_RESOURCE_ID --node-osdisk-size 300 --enable-managed-identity --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $TENANT_ID $ACTIVATE_PRIVATE_LINK -o none else az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --ssh-key-value ~/.ssh/id_rsa.pub --node-count 3 --min-count 3 --max-count 5 --enable-cluster-autoscaler --node-resource-group $NODE_GROUP --load-balancer-sku standard --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --assign-identity $AKS_CONTROLLER_RESOURCE_ID --node-osdisk-size 300 --enable-managed-identity --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $TENANT_ID $ACTIVATE_PRIVATE_LINK -o none fi #az aks update --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --auto-upgrade-channel rapid AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME$AKS_POSTFIX --query id -o tsv) echo "created AKS $AKS_ID" else echo "AKS $AKS_ID already exists" fi if [ "$USE_PRIVATE_LINK" == "true" ]; then echo " no credentials" else az aks get-credentials -g $KUBE_GROUP -n $KUBE_NAME$AKS_POSTFIX --admin fi echo "setting up azure monitor" WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace list --resource-group $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$WORKSPACE_RESOURCE_ID" == "" ]; then echo "creating workspace $KUBE_NAME in $KUBE_GROUP" az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --location $LOCATION -o none WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME -o json | jq '.id' -r) az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --addons monitoring --workspace-resource-id $WORKSPACE_RESOURCE_ID -o none OMS_CLIENT_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query addonProfiles.omsagent.identity.clientId -o tsv) az role assignment create --assignee $OMS_CLIENT_ID --scope $AKS_ID --role "Monitoring Metrics Publisher" else az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --addons monitoring --workspace-resource-id $WORKSPACE_RESOURCE_ID -o none OMS_CLIENT_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query addonProfiles.omsagent.identity.clientId -o tsv) az role assignment create --assignee $OMS_CLIENT_ID --scope $AKS_ID --role "Monitoring Metrics Publisher" fi HCP_IP=$(kubectl get endpoints -o=jsonpath='{.items[?(@.metadata.name == "kubernetes")].subsets[].addresses[].ip}') if [ "$HCP_IP" == "" ]; then echo "unable to find aks hcp ip" else az network route-table route create --resource-group $KUBE_GROUP --name "hcp" --route-table-name $FW_NAME-rt --address-prefix $HCP_IP/32 --next-hop-type Internet #az network route-table route delete --resource-group $KUBE_GROUP --name "azure" --route-table-name $FW_NAME-rt fi # az aks command invoke -g $KUBE_GROUP -n $KUBE_NAME$AKS_POSTFIX -c "kubectl get pods -n kube-system" # az aks command invoke -g <resourceGroup> -n <clusterName> -c "kubectl apply -f deployment.yaml -n default" -f deployment.yaml # az aks command invoke -g <resourceGroup> -n <clusterName> -c "kubectl apply -f deployment.yaml -n default" -f . # az aks command invoke -g <resourceGroup> -n <clusterName> -c "helm repo add bitnami https://charts.bitnami.com/bitnami && helm repo update && helm install my-release -f values.yaml bitnami/nginx" -f values.yaml # REGISTRY_NAME=dzprivate # kubectl run mcr-hello-world --quiet --image=mcr.microsoft.com/azuredocs/aks-helloworld:v1 --restart=OnFailure --port=80 --env="TITLE=it works" -- echo "Hello Kubernetes" # kubectl run mcr-nginx --quiet --image=mcr.microsoft.com/oss/nginx/nginx --restart=OnFailure -- echo "Hello Kubernetes" # kubectl run local-nginx --quiet --image=nginx:1.13.12-alpine --restart=OnFailure -- echo "Hello Kubernetes" # az acr import -n $REGISTRY_NAME --source docker.io/denniszielke/aci-helloworld:latest -t aci-helloworld:latest # az acr import -n $REGISTRY_NAME --source mcr.microsoft.com/azuredocs/aks-helloworld:v1 -t aks-helloworld:v1 # az acr import -n $REGISTRY_NAME --source docker.io/denniszielke/dummy-logger:latest -t dummy-logger:latest # az acr import -n $REGISTRY_NAME --source docker.io/centos -t centos # az acr repository list -n $REGISTRY_NAME # kubectl run acr-hello-world --quiet --image=dzprivate.azurecr.io/aks-helloworld:v1 --port=80 --restart=OnFailure --env="TITLE=it works" # kubectl run acr-hello-world --quiet --image=dzprivate.azurecr.io/aci-helloworld:latest --port=80 --restart=OnFailure # kubectl run acr-hello-world --quiet --image=dzprivate.azurecr.io/centis --port=80 --restart=OnFailure # kubectl expose pod acr-hello-world --port=80 --type=LoadBalancer <file_sep># Building a go rest api ## Installing go on ubuntu bash https://stefanprodan.com/2016/golang-bash-on-windows-installer/ ``` GOURL=https://gist.githubusercontent.com/stefanprodan/29d738c3049a8714297a9bdd8353f31c/raw/1f3ae2cf97cb2faff52a8a3d98f0b6415d86c810/win10-bash-go-install.sh curl -s -L $GOURL | sudo bash ``` or on ubuntu https://github.com/golang/go/wiki/Ubuntu ``` sudo apt-get install golang-go export GOPATH=$HOME/go export PATH=$PATH:$GOROOT/bin:$GOPATH/bin ``` ## Running the demo ``` docker run -e "INSTRUMENTATIONKEY=4c3d38bd-58e3-480e-9fe1" -e "PORT=3001" -p 8080:3001 gocalcbackend docker ps docker stop ``` <file_sep># Setting up Kafka https://github.com/dapr/samples/tree/master/5.bindings helm repo add incubator http://storage.googleapis.com/kubernetes-charts-incubator helm repo update kubectl create namespace kafka helm install dapr-kafka --namespace kafka incubator/kafka --set replicas=1 cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: testclient namespace: kafka spec: containers: - name: kafka image: confluentinc/cp-kafka:5.0.1 command: - sh - -c - "exec tail -f /dev/null" EOF<file_sep>var config = {} config.port = process.env.PORT || 8080; module.exports = config; <file_sep># Setup https://docs.microsoft.com/en-us/azure/machine-learning/tutorial-train-deploy-image-classification-model-vscode https://github.com/microsoft/MLOps cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: labels: app: samples-tf-mnist-demo name: samples-tf-mnist-demo spec: template: metadata: labels: app: samples-tf-mnist-demo spec: containers: - name: samples-tf-mnist-demo image: microsoft/samples-tf-mnist-demo:gpu args: ["--max_steps", "500"] imagePullPolicy: IfNotPresent resources: limits: nvidia.com/gpu: 1 restartPolicy: OnFailure EOF<file_sep># ACS ``` KUBE_NAME="dzstrg9" KUBE_GROUP="$KUBE_NAME" az aks nodepool list -g $KUBE_GROUP --cluster-name $KUBE_NAME -o table az aks nodepool update --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --name nodepool1 --labels acstor.azure.com/io-engine=acstor AKS_MI_OBJECT_ID=$(az aks show --name $KUBE_NAME --resource-group $KUBE_GROUP --query "identityProfile.kubeletidentity.objectId" -o tsv) AKS_NODE_RG=$(az aks show --name $KUBE_NAME --resource-group $KUBE_GROUP --query "nodeResourceGroup" -o tsv) az role assignment create --assignee $AKS_MI_OBJECT_ID --role "Contributor" --resource-group "$AKS_NODE_RG" az role assignment create --assignee $AKS_MI_OBJECT_ID --role "Reader" --resource-group "$KUBE_GROUP" az k8s-extension create --cluster-type managedClusters --cluster-name $KUBE_NAME --resource-group $KUBE_GROUP --name acs --extension-type microsoft.azurecontainerstorage --scope cluster --release-train prod --release-namespace acstor cat <<EOF | kubectl apply -f - apiVersion: containerstorage.azure.com/v1alpha1 kind: StoragePool metadata: name: azuredisk namespace: acstor spec: poolType: azureDisk: {} resources: requests: {"storage": 10Gi} EOF kubectl describe sp azuredisk -n acstor cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: azurediskpvc spec: accessModes: - ReadWriteOnce storageClassName: acstor-azuredisk # replace with the name of your storage class if different resources: requests: storage: 1Gi EOF cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: fiopod spec: nodeSelector: acstor.azure.com/io-engine: acstor volumes: - name: azurediskpv persistentVolumeClaim: claimName: azurediskpvc containers: - name: fio image: nixery.dev/shell/fio args: - sleep - "1000000" volumeMounts: - mountPath: "/volume" name: azurediskpv EOF kubectl exec -it fiopod -- fio --name=benchtest --size=800m --filename=/volume/test --direct=1 --rw=randrw --ioengine=libaio --bs=4k --iodepth=16 --numjobs=8 --time_based --runtime=60 ```<file_sep>from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/ip', methods=['GET']) def name(): return jsonify({'remoteip': request.remote_addr, 'realip': request.environ.get('HTTP_X_REAL_IP', request.remote_addr), 'remoteaddr': request.environ['REMOTE_ADDR'] }), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=8080)<file_sep># Installing JupyterHub in AKS ## create postgres db create postgres db ``` KUBE_GROUP=kub_ter_k_l_juphub KUBE_NAME=juphub LOCATION=westeurope STORAGE_ACCOUNT=dzjupyteruser PSQL_PASSWORD=$(openssl rand -base64 10) az postgres server create --resource-group $KUBE_GROUP --name $KUBE_NAME --location $LOCATION --admin-user myadmin --admin-password $PSQL_<PASSWORD> --sku-name GP_Gen4_2 --version 9.6 ``` lock up details ``` az postgres server show --resource-group $KUBE_GROUP --name $KUBE_NAME ``` connect to psql using shell.azure.com and create database for jupyterhub ``` psql --host=$KUBE_NAME.postgres.database.azure.com --username=myadmin@$KUBE_NAME --dbname=postgres --port=5432 CREATE DATABASE jupyterhub; ``` ## create storage account ``` az storage account create --resource-group MC_$(echo $KUBE_GROUP)_$(echo $KUBE_NAME)_$(echo $LOCATION) --name $STORAGE_ACCOUNT --location $LOCATION --sku Standard_LRS --kind StorageV2 --access-tier hot --https-only false ``` create azure file storage class ``` cat <<EOF | kubectl apply -f - kind: StorageClass apiVersion: storage.k8s.io/v1 metadata: name: azurefile provisioner: kubernetes.io/azure-file mountOptions: - dir_mode=0777 - file_mode=0777 - uid=1000 - gid=1000 parameters: skuName: Standard_LRS location: $LOCATION storageAccount: $STORAGE_ACCOUNT EOF ``` ## deploy jupyterhub without RBAC ``` openssl rand -hex 32 ``` create config.yaml with content ``` cat <<EOF >config.yaml singleuser: storage: capacity: 1Gi dynamic: storageClass: acstor-azuredisk EOF cat <<EOF >config.yaml proxy: secretToken: "774629f880afc0302830c19a9f09be4f59e98b242b65983cea7560e828df2978" hub: uid: 1000 cookieSecret: "774629f880afc0302830c19a9f09be4f59e98b242b65983cea7560e828df2978" rbac: enabled: true EOF ``` install jhub ``` helm repo add jupyterhub https://jupyterhub.github.io/helm-chart/ helm repo update RELEASE=jhub1 NAMESPACE=jhub1 helm upgrade --cleanup-on-fail \ --install $RELEASE jupyterhub/jupyterhub \ --namespace $NAMESPACE \ --create-namespace \ --values config.yaml kubectl get service --namespace jhub kubectl --namespace=jhub1 port-forward service/proxy-public 8080:http ``` cleanup ``` helm delete jhub --purge kubectl delete ns jhub ``` ## deploy jupyterhub in cluster with rbac create cloud provider azure files role ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: azurefilestore spec: accessModes: - ReadWriteMany storageClassName: azurefile resources: requests: storage: 5Gi EOF ``` ``` cat <<EOF | kubectl apply -f - apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: system:azure-cloud-provider rules: - apiGroups: [''] resources: ['secrets'] verbs: ['get','create'] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: system:azure-cloud-provider roleRef: kind: ClusterRole apiGroup: rbac.authorization.k8s.io name: system:azure-cloud-provider subjects: - kind: ServiceAccount name: persistent-volume-binder namespace: kube-system EOF ``` ``` openssl rand -hex 32 ``` create config.yaml with content ``` cat <<EOF >config.yaml proxy: secretToken: "774629f880afc0302830c19a9f09be4f59e98b242b65983cea7560e828df2978" hub: uid: 1000 cookieSecret: "774629f880afc0302830c19a9f09be4f59e98b242b65983cea7560e828df2978" db: type: postgres url: postgres+psycopg2://myadmin@$KUBE_NAME:$PSQL_PASSWORD@$KUBE_NAME.postgres.database.azure.com:5432/jupyterhub singleuser: storage: dynamic: storageClass: azurefile rbac: enabled: true EOF cat <<EOF >config.yaml proxy: secretToken: "774629f880afc0302830c19a9f09be4f59e98b242b65983cea7560e828df2978" hub: uid: 1000 cookieSecret: "774629f880afc0302830c19a9f09be4f59e98b242b65983cea7560e828df2978" rbac: enabled: true EOF ``` install jhub ``` RELEASE=jhub NAMESPACE=jhub helm upgrade --install $RELEASE jupyterhub/jupyterhub \ --namespace $NAMESPACE \ --version 0.7.0 \ --values config.yaml ``` cleanup ``` helm delete jhub --purge kubectl delete ns jhub ``` <file_sep># Deploy Azure resources ## Create vnet and identity (optional) This script will create a controller manager identity and a vnet with subnets, nsg ``` PROJECT_NAME="myaks2" LOCATION="westeurope" CONTROLLER_IDENTITY_NAME="my-controller" bash ./create.sh $PROJECT_NAME $LOCATION $CONTROLLER_IDENTITY_NAME ``` ## Deploy resources with bicep (vnet and identity must exist) This will deploy an AKS cluster using the template and require controller manager identity, aad group and vnet to be already created ``` PROJECT_NAME="myaks3" LOCATION="westeurope" CONTROLLER_IDENTITY_NAME="my-controller" SUBSCRIPTION_ID=$(az account show --query id -o tsv) AKS_SUBNET_RESOURCE_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$PROJECT_NAME/providers/Microsoft.Network/virtualNetworks/$PROJECT_NAME-vnet/subnets/$PROJECT_NAME-aks" AAD_GROUP_ID="0644b510-7b35-41aa-a9c6-4bfc3f644c58" bash ./deploy.sh $PROJECT_NAME $LOCATION $CONTROLLER_IDENTITY_NAME $AKS_SUBNET_RESOURCE_ID $AAD_GROUP_ID ``` <file_sep>#ACS Engine 0. Variables ``` SUBSCRIPTION_ID="" KUBE_GROUP="acsaksupgrad" KUBE_NAME="dz-acs" LOCATION="eastus" KUBE_VNET_NAME="KVNET" KUBE_AGENT_SUBNET_NAME="KVAGENTS" KUBE_MASTER_SUBNET_NAME="KVMASTERS" SERVICE_PRINCIPAL_ID= SERVICE_PRINCIPAL_SECRET= AAD_APP_ID= AAD_CLIENT_ID= TENANT_ID= GROUP_ID= MY_OBJECT_ID= YOUR_SSH_KEY=$(cat ~/.ssh/id_rsa.pub) ``` wget https://github.com/Azure/acs-engine/releases/download/v0.25.3/acs-engine-v0.25.3-darwin-amd64.tar.gz tar -zxvf acs-engine-*-darwin-amd64.tar.gz # Prepare variables ``` SP_NAME="acsupgrade" SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $SP_NAME -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET sed -e "s/AAD_APP_ID/$AAD_APP_ID/ ; s/AAD_CLIENT_ID/$AAD_CLIENT_ID/ ; s/SERVICE_PRINCIPAL_ID/$SERVICE_PRINCIPAL_ID/ ; s/SERVICE_PRINCIPAL_SECRET/$SERVICE_PRINCIPAL_SECRET/ ; s/TENANT_ID/$TENANT_ID/ ; s/ADMIN_GROUP_ID/$ADMIN_GROUP_ID/ ; s/SUBSCRIPTION_ID/$SUBSCRIPTION_ID/ ; s/KUBE_GROUP/$KUBE_GROUP/ ; s/GROUP_ID/$GROUP_ID/" acseng.json > acseng_out.json ``` # Prepare acs-engine ``` ./acs-engine generate acseng.json ``` # Deploy cluster ``` az login az account set --subscription $SUBSCRIPTION_ID ``` 1. Create the resource group ``` az group create -n $KUBE_GROUP -l $LOCATION ``` 2. Create VNETs ``` az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME --address-prefixes "172.16.0.0/16" -l $LOCATION --subnet-name $KUBE_MASTER_SUBNET_NAME --subnet-prefix "172.16.0.0/24" ``` 3. Create Subnets ``` az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_MASTER_SUBNET_NAME --address-prefix 172.16.0.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 172.16.5.0/24 ``` 4. Create cluster ``` az group deployment create \ --name $KUBE_NAME \ --resource-group $KUBE_GROUP \ --template-file "_output/$KUBE_NAME/azuredeploy.json" \ --parameters "_output/$KUBE_NAME/azuredeploy.parameters.json" ``` # Create cluster role binding ``` export KUBECONFIG=`pwd`/_output/$KUBE_NAME/kubeconfig/kubeconfig.$LOCATION.json # using rbac aad ssh -i ~/.ssh/id_rsa <EMAIL> \ kubectl create clusterrolebinding aad-default-cluster-admin-binding \ --clusterrole=cluster-admin \ --user 'https://sts.windows.net/<tenant-id>/#<user-id>' kubectl create clusterrolebinding aad-default-cluster-admin-binding --clusterrole=cluster-admin --user=https://sts.windows.net/$TENANT_ID/#$MY_OBJECT_ID #using rbac without aad ssh -i ~/.ssh/id_rsa <EMAIL>@dz-vnet-18.<EMAIL>e<EMAIL>.cloudapp.azure.com \ kubectl create serviceaccount dennis --namespace kube-system ssh -i ~/.ssh/id_rsa <EMAIL> \ kubectl create clusterrolebinding dennis --clusterrole=cluster-admin --serviceaccount=kube-system:dennis --namespace kube-system ssh -i ~/.ssh/id_rsa <EMAIL> \ kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep dennis-sa | awk '{print $1}') TOKEN= #Set kubectl context kubectl config set-cluster acs-cluster --server=$KUBE_MANAGEMENT_ENDPOINT --insecure-skip-tls-verify=true kubectl config set-credentials dennis --token=$TOKEN kubectl config set-context acs-context --cluster=acs-cluster --user=dennis kubectl config use-context acs-context ``` # Set up route table for kubenet routing ``` rt=$(az network route-table list -g $KUBE_GROUP | jq -r '.[].name') rt=k8s-master-31439917-routetable az network vnet subnet update -n k8s-subnet -g $KUBE_GROUP --vnet-name k8s-vnet-31439917 --route-table $rt ``` # Create internal Load Balancers https://docs.microsoft.com/en-us/azure/aks/internal-lb ``` apiVersion: v1 kind: Service metadata: name: azure-vote-front annotations: service.beta.kubernetes.io/azure-load-balancer-internal: "true" spec: type: LoadBalancer ports: - port: 80 selector: app: azure-vote-front ``` # Delete everything ``` az group delete -n $KUBE_GROUP ``` # upgrade ``` ./acs-engine orchestrators --orchestrator Kubernetes --version 1.10.5 cd ../acs-engine-v0.22.4-darwin-amd64 ./acs-engine upgrade \ --subscription-id $SUBSCRIPTION_ID \ --deployment-dir _output/$KUBE_NAME/ \ --location $LOCATION \ --resource-group $KUBE_GROUP \ --upgrade-version 1.10.5 \ --auth-method client_secret \ --client-id $SERVICE_PRINCIPAL_ID \ --client-secret $SERVICE_PRINCIPAL_SECRET ``` ``` ./acs-engine orchestrators --orchestrator Kubernetes --version 1.10.5 cd ../acs-engine-v0.22.4-darwin-amd64 EXPECTED_ORCHESTRATOR_VERSION=1.10.5 ./acs-engine upgrade \ --subscription-id $SUBSCRIPTION_ID \ --deployment-dir _output/$KUBE_NAME/ \ --location $LOCATION \ --resource-group $KUBE_GROUP \ --upgrade-version 1.10.5 \ --auth-method client_secret \ --client-id $SERVICE_PRINCIPAL_ID \ --client-secret $SERVICE_PRINCIPAL_SECRET ``` https://github.com/Azure/acs-engine/blob/master/docs/kubernetes/troubleshooting.md<file_sep># Using Helm ## Create your own helm chart 1. Create using draft Go to app folder and launch draft https://github.com/Azure/draft ``` draft create ``` 2. Create helm chart manually and modify accordingly ``` helm create multicalc APP_NS=calculator APP_IN=calc1 kubectl create namespace $APP_NS ``` Validate template ``` helm lint ./multicalchart ``` 3. Dry run the chart and override parameters ``` helm install --dry-run --debug ./multicalculatorv3 --name=calculator --set frontendReplicaCount=3 ``` 4. Make sure you have the app insights key secret provisioned ``` kubectl create secret generic appinsightsecret --from-literal=appinsightskey=$APPINSIGHTS_KEY --namespace $APP_NS kubectl delete secret appinsightsecret --namespace $APP_NS ``` 5. Install ``` az configure --defaults acr=dzkubereg az acr helm repo add CHARTREPO=dzkubereg helm upgrade $APP_IN ./multicalculatorv3 --namespace $APP_NS --install helm upgrade $APP_IN ./multicalculatorv3 --namespace $APP_NS --install --set replicaCount=1 helm upgrade $APP_IN ./multicalculatorv3 --namespace $APP_NS --install --set replicaCount=4 --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTS_KEY --set dependencies.usePodRedis=true ``` verify ``` helm list -n $APP_NS helm get values $APP_IN $APP_IN ``` 6. Change config and perform an upgrade ``` az monitor app-insights component create --app calc$KUBE_NAME --location $LOCATION --kind web -g $KUBE_GROUP --application-type web APPINSIGHTS_KEY= helm upgrade $APP_IN ./multicalculatorv3 --namespace $APP_NS --install --set replicaCount=4 --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTS_KEY --set dependencies.usePodRedis=true ``` If you have a redis secret you can turn on the redis cache ``` REDIS_HOST=.redis.cache.windows.net REDIS_AUTH= APPINSIGHTS_KEY= kubectl create secret generic rediscachesecret --from-literal=redishostkey=$REDIS_HOST --from-literal=redisauthkey=$REDIS_AUTH --namespace $APP_NS helm upgrade $APP_IN ./multicalculatorv3 --namespace $APP_NS --install --set replicaCount=4 --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTS_KEY --set dependencies.usePodRedis=true --set dependencies.useAzureRedis=true --set dependencies.redisHostValue=$REDIS_HOST --set dependencies.redisKeyValue=$REDIS_AUTH helm upgrade $APP_IN multicalculatorv3 --install --set backendReplicaCount=3 --set frontendReplicaCount=3 --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTS_KEY --set dependencies.useAzureRedis=true --set dependencies.redisHostValue=$REDIS_HOST --set dependencies.redisKeyValue=$REDIS_AUTH --set introduceRandomResponseLag=false --set introduceRandomResponseLagValue=0 --namespace $APP_NS helm upgrade $APP_IN multicalculatorv3 --install --set backendReplicaCount=3 --set frontendReplicaCount=3 --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTS_KEY --set dependencies.useAzureRedis=true --set dependencies.redisHostValue=$REDIS_HOST --set dependencies.redisKeyValue=$REDIS_AUTH --set introduceRandomResponseLag=true --set introduceRandomResponseLagValue=3 --namespace $APP_NS --dry-run --debug ``` Configure scaler ``` kubectl autoscale deployment calc2-multicalculatorv3-backend -n calculator --cpu-percent=20 --min=1 --max=5 kubectl get hpa -n calculator kubectl delete hpa calc1-multicalculatorv3-backend -n calculator kubectl scale deployment calc1-multicalculatorv3-backend --replicas=1 -n calculator ``` 7. See rollout history ``` helm history $APP_IN helm rollback $APP_IN 1 ``` 6. Cleanup ``` helm delete $APP_IN --purge ``` ## Helm repo in GitHub ``` cd phoenix helm package ./charts/multicalculator #This will create tgz file with chart in current directory helm repo index . #This will create index.yaml file which references my-app-chart.yaml git add . git commit -m "my-app-chart" git push ``` ``` helm repo add phoenix 'https://raw.githubusercontent.com/denniszielke/phoenix/master/' helm repo update helm repo list NAME URL stable https://kubernetes-charts.storage.googleapis.com local http://127.0.0.1:8879/charts my-github-helmrepo https://raw.githubusercontent.com/my_organization/my-github-helm-repo/master/ helm search repo phoenix NAME CHART VERSION APP VERSION DESCRIPTION my-github-helmrepo/my-app-chart 0.1.0 1.0 A Helm chart for Kubernetes ```<file_sep># Setting up Firewall + Private Link AKS Every now and then we get the question on how to build an AKS cluster that is not exposing or using any public IPs. Up until recently that was not possible because the AKS hosted control plane was using a public ip (that is no longer required if you leverage privatelink https://docs.microsoft.com/en-us/azure/aks/private-clusters) or the fact that your worker nodes still needed to have public IP attached to their standard load balancer (which is required to get ensure internet egress for container registries and such https://docs.microsoft.com/en-us/azure/aks/egress). One option that can be set up relativly easy but is not documented in detail is using the Azure Firewall (https://azure.microsoft.com/en-us/services/azure-firewall/). The end result will look like this and requires some steps to configure the vnet, subnets, routetable, firewall rules and azure kubernetes services which are described below: ![](/img/fullyprivateaks.png) ## setting up the vnet First we will setup the vnet - I prefer using azure cli over powershell but you can easy achieve the same using terraform or arm. If you have preferences on the naming conventions please adjust the variables below. In most companies the vnet is provided by the networking team so we should assume that the network configuration will not be done by the teams which is maintaining the aks cluster. 0. Variables ``` SUBSCRIPTION_ID="" # here enter your subscription id KUBE_GROUP="nopublicipaks" # here enter the resources group name of your aks cluster KUBE_NAME="dzprivatekube" # here enter the name of your kubernetes resource LOCATION="australiaeast" # here enter the datacenter location VNET_GROUP="networks" # here the name of the resource group for the vnet and hub resources KUBE_VNET_NAME="spoke1-kubevnet" # here enter the name of your vnet KUBE_ING_SUBNET_NAME="ing-1-subnet" # here enter the name of your ingress subnet KUBE_AGENT_SUBNET_NAME="aks-2-subnet" # here enter the name of your aks subnet HUB_VNET_NAME="hub1-firewalvnet" HUB_FW_SUBNET_NAME="AzureFirewallSubnet" # this you cannot change HUB_JUMP_SUBNET_NAME="jumpbox-subnet" FW_NAME="dzkubenetfw" # here enter the name of your azure firewall resource FW_IP_NAME="azureFirewalls-ip" # here enter the name of your public ip resource for the firewall KUBE_VERSION="1.15.7" # here enter the kubernetes version of your aks SERVICE_PRINCIPAL_ID= # here enter the service principal of your aks SERVICE_PRINCIPAL_SECRET= # here enter the service principal secret ``` 1. Select subscription, create the resource group and the vnets ``` az account set --subscription $SUBSCRIPTION_ID az group create -n $KUBE_GROUP -l $LOCATION az group create -n $VNET_GROUP -l $LOCATION az network vnet create -g $VNET_GROUP -n $HUB_VNET_NAME --address-prefixes 10.0.0.0/22 az network vnet create -g $VNET_GROUP -n $KUBE_VNET_NAME --address-prefixes 10.0.4.0/22 ``` 2. Assign permissions on vnet for your service principal - usually "virtual machine contributor is enough" ``` az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $VNET_GROUP az role assignment create --role "Virtual Machine Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $VNET_GROUP ``` 3. Create subnets for the firewall, jumpbox, ingress and aks ``` az network vnet subnet create -g $VNET_GROUP --vnet-name $HUB_VNET_NAME -n $KUBE_FW_SUBNET_NAME --address-prefix 10.0.0.0/24 az network vnet subnet create -g $VNET_GROUP --vnet-name $HUB_VNET_NAME -n $HUB_JUMP_SUBNET_NAME --address-prefix 10.0.1.0/24 az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 --service-endpoints Microsoft.KeyVault Microsoft.Storage ``` 4. Create vnet peering between hub vnet and spoke vnet ``` az network vnet peering create -g $VNET_GROUP -n HubToSpoke1 --vnet-name $HUB_VNET_NAME --remote-vnet $KUBE_VNET_NAME --allow-vnet-access az network vnet peering create -g $VNET_GROUP -n Spoke1ToHub --vnet-name $KUBE_VNET_NAME --remote-vnet $HUB_VNET_NAME --allow-vnet-access ``` ## setting up the cluster As you might know there are two different options on how networking can be set up in aks called "Basic networking" and "Advanced Networking". I am not going into detail how they differ - you can look it up here: https://docs.microsoft.com/en-us/azure/aks/concepts-network . For the usage of azure firewall in this scenario it does not matter since both options work but need to be configured differently, which is why I am documenting both options. ## setting up cluster with azure cni Advanced networking is a bit simpler but requires you to create the routetable first, create the route and then again associate it with the aks subnet. 5. Create azure firewall ``` FW_PRIVATE_IP="10.0.0.4" az network public-ip create -g $VNET_GROUP -n $FW_IP_NAME --sku Standard az extension add --name azure-firewall az network firewall create --name $FW_NAME --resource-group $VNET_GROUP --location $LOCATION az network firewall ip-config create --firewall-name $FW_NAME --name $FW_NAME --public-ip-address $FW_IP_NAME --resource-group $VNET_GROUP --private-ip-address $FW_PRIVATE_IP --vnet-name $HUB_VNET_NAME ``` 6. Create UDR and force traffic from the kubernetes subnet to the azure firewall ``` FW_ROUTE_NAME="${FW_NAME}_fw_r" FW_ROUTE_TABLE_NAME="${FW_NAME}_fw_rt" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az network route-table create -g $VNET_GROUP --name $FW_ROUTE_TABLE_NAME az network vnet subnet update --resource-group $VNET_GROUP --route-table $FW_ROUTE_TABLE_NAME --ids $KUBE_AGENT_SUBNET_ID az network route-table route create --resource-group $VNET_GROUP --name $FW_ROUTE_NAME --route-table-name $FW_ROUTE_TABLE_NAME --address-prefix 0.0.0.0/0 --next-hop-type VirtualAppliance --next-hop-ip-address $FW_PRIVATE_IP --subscription $SUBSCRIPTION_ID az network route-table route list --resource-group $VNET_GROUP --route-table-name $FW_ROUTE_TABLE_NAME ``` 7. Deploy cluster ``` az group deployment create \ --name privatecluster \ --resource-group $KUBE_GROUP \ --template-file "arm/fullyprivate.json" \ --parameters "arm/zones_parameters.json" \ --parameters "resourceName=$KUBE_NAME" \ "location=$LOCATION" \ "dnsPrefix=$KUBE_NAME" \ "kubernetesVersion=$KUBE_VERSION" \ "servicePrincipalClientId=$SERVICE_PRINCIPAL_ID" \ "servicePrincipalClientSecret=$SERVICE_PRINCIPAL_SECRET" \ "vnetSubnetID=$KUBE_AGENT_SUBNET_ID" --no-wait ``` Deploy cluster using cli ``` az aks create -g MyResourceGroup -n MyManagedCluster az aks create \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --node-resource-group $NODE_GROUP \ --load-balancer-sku standard \ --enable-private-cluster \ --network-plugin azure \ --vnet-subnet-id $KUBE_AGENT_SUBNET_ID \ --docker-bridge-address 172.17.0.1/16 \ --dns-service-ip 10.2.0.10 \ --service-cidr 10.2.0.0/24 \ --enable-managed-identity ``` ## Configure azure firewall Setup the azure firewall diagnostics and create a dashboard by importing this file: https://docs.microsoft.com/en-us/azure/firewall/tutorial-diagnostics https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-firewall/AzureFirewall.omsview Create Log Analytics workspace ``` az monitor log-analytics workspace create --resource-group $VNET_GROUP --workspace-name privateaksfwlogs --location $LOCATION ``` Add network rule for 123 (time sync) and 53 (dns) for the worker nodes - this is optional for ubuntu patches ``` az network firewall network-rule create --firewall-name $FW_NAME --collection-name "aksnetwork" --destination-addresses "*" --destination-ports 9000 --name "allow network" --protocols "TCP" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "aks network rule" --priority 100 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "time" --destination-addresses "*" --destination-ports 123 --name "allow time" --protocols "UDP" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "aks node time sync rule" --priority 101 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "dns" --destination-addresses "*" --destination-ports 53 --name "allow dns" --protocols "UDP" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "aks node dns rule" --priority 102 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "kubesvc" --destination-addresses "*" --destination-ports 443 --name "allow network" --protocols "TCP" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "aks kube svc rule" --priority 103 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "ssh" --destination-addresses "*" --destination-ports 22 --name "allow network" --protocols "TCP" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "aks ssh access rule" --priority 104 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "servicetags" --destination-addresses "AzureContainerRegistry" "MicrosoftContainerRegistry" "AzureActiveDirectory" --destination-ports "*" --name "allow service tags" --protocols "Any" --resource-group $VNET_GROUP --source-addresses "*" --action "Allow" --description "allow service tags" --priority 110 az network firewall network-rule list --firewall-name $FW_NAME --resource-group $VNET_GROUP ``` See complete list of external dependencies: https://docs.microsoft.com/en-us/azure/aks/limit-egress-traffic Required application rule for: - `*<region>.azmk8s.io` (eg. `*westeurope.azmk8s.io`) – this is the dns that is running your masters - `*cloudflare.docker.io` – docker hub cdn - `*registry-1.docker.io` – docker hub - `*azurecr.io` – storing your images in azure container registry - `*blob.core.windows.net` – the storage behind acr - `k8s.gcr.io` - images stored in gcr - `storage.googleapis.com` - storage behind google gcr Optional: - `*.ubuntu.com, download.opensuse.org` – This is needed for security patches and updates - if the customer wants them to be applied automatically - `snapcraft.io, api.snapcraft.io` - used by ubuntu for packages - `packages.microsoft.com`- packages from microsoft - `login.microsoftonline.com` - for azure aad login - `dc.services.visualstudio.com` - application insights - `*.opinsights.azure.com` - azure monitor - `*.monitoring.azure.com` - azure monitor - `*.management.azure.com` - azure tooling ### create the application rules ![](/img/hcp-new.png) ``` az network firewall application-rule create --firewall-name $FW_NAME --collection-name "aksbasics" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $VNET_GROUP --action "Allow" --target-fqdns "*.azmk8s.io" "aksrepos.azurecr.io" "*.blob.core.windows.net" "mcr.microsoft.com" "*.cdn.mscr.io" "acs-mirror.azureedge.net" "management.azure.com" "login.microsoftonline.com" "api.snapcraft.io" "*auth.docker.io" "*cloudflare.docker.io" "*cloudflare.docker.com" "*registry-1.docker.io" --priority 100 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "akstools" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $VNET_GROUP --action "Allow" --target-fqdns "download.opensuse.org" "packages.microsoft.com" "dc.services.visualstudio.com" "*.opinsights.azure.com" "*.monitoring.azure.com" "gov-prod-policy-data.trafficmanager.net" "apt.dockerproject.org" "nvidia.github.io" --priority 101 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "osupdates" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $VNET_GROUP --action "Allow" --target-fqdns "download.opensuse.org" "*.ubuntu.com" "packages.microsoft.com" "snapcraft.io" "api.snapcraft.io" --priority 102 ``` test the outgoing traffic ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF ``` ``` kubectl exec -ti centos -- /bin/bash curl bad.org curl superbad.org curl ubuntu.com kubectl get endpoints -o=jsonpath='{.items[?(@.metadata.name == "kubernetes")].subsets[].addresses[].ip}' -o wide --all-namespaces ``` ### public ip NET rules * THIS IS ONLY REQUIRED IF YOU HAVE PUBLIC IP LOADBALANCERS IN AKS* create a pod ``` kubectl run nginx --image=nginx --port=80 ``` expose it via internal lb ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: name: nginx-internal annotations: service.beta.kubernetes.io/azure-load-balancer-internal: "true" service.beta.kubernetes.io/azure-load-balancer-internal-subnet: "ing-1-subnet" spec: type: LoadBalancer loadBalancerIP: 10.0.4.25 ports: - port: 80 selector: name: nginx EOF ``` get the internal ip adress ``` SERVICE_IP=$(kubectl get svc nginx-internal --template="{{range .status.loadBalancer.ingress}}{{.ip}}{{end}}") ``` create an azure firewall nat rule for that internal service ``` FW_PUBLIC_IP=$(az network public-ip show -g $VNET_GROUP -n $FW_IP_NAME --query ipAddress) az network firewall nat-rule create --firewall-name $FW_NAME --collection-name "inboundlbrules" --name "allow inbound load balancers" --protocols "TCP" --source-addresses "*" --resource-group $VNET_GROUP --action "Dnat" --destination-addresses $FW_PUBLIC_IP --destination-ports 80 --translated-address 10.0.4.25 --translated-port "80" --priority 101 open http://$FW_PUBLIC_IP:80 ``` now you can acces the internal service by going to the $FW_PUBLIC_IP on port 80 <file_sep># Install prometheus https://itnext.io/using-prometheus-in-azure-kubernetes-service-aks-ae22cada8dd9 https://docs.microsoft.com/en-us/azure/aks/aks-ssh add --authentication-token-webhook to /etc/default/kubelet sudo systemctl restart kubelet ``` helm repo add coreos https://s3-eu-west-1.amazonaws.com/coreos-charts/stable/ helm install coreos/prometheus-operator --name prometheus-operator --namespace monitoring --set rbacEnable=false helm install coreos/kube-prometheus --name kube-prometheus --set global.rbacEnable=false --namespace monitoring kubectl -n kube-system create sa tiller kubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller helm init --service-account tiller APP_NAME=monitoring helm install coreos/prometheus-operator --name prometheus-operator --namespace $APP_NAME helm install coreos/kube-prometheus --name kube-prometheus --namespace $APP_NAME # if it fails with "Error: watch closed before Until timeout" kubectl delete job prometheus-operator-create-sm-job -n $APP_NAME kubectl delete job prometheus-operator-get-crd -n $APP_NAME helm upgrade prometheus-operator coreos/prometheus-operator --namespace $APP_NAME --force kubectl --namespace monitoring port-forward $(kubectl get pod --namespace monitoring -l prometheus=kube-prometheus -l app=prometheus -o template --template "{{(index .items 0).metadata.name}}") 9090:9090 echo username:$(kubectl get secret --namespace monitoring kube-prometheus-grafana -o jsonpath="{.data.user}"|base64 --decode;echo) echo password:$(kubectl get secret --namespace monitoring kube-prometheus-grafana -o jsonpath="{.data.password}"|base64 --decode;echo) kubectl --namespace monitoring port-forward $(kubectl get pod --namespace monitoring -l app=kube-prometheus-grafana -o template --template "{{(index .items 0).metadata.name}}") 3000:3000 helm delete prometheus-operator --purge helm delete kube-prometheus --purge<file_sep># Deploy the OMS (AKS) https://docs.microsoft.com/en-us/azure/aks/tutorial-kubernetes-monitor https://docs.microsoft.com/en-us/azure/log-analytics/log-analytics-containers https://docs.microsoft.com/en-gb/azure/monitoring/media/monitoring-container-insights-overview/azmon-containers-views.png https://github.com/helm/charts/tree/master/incubator/azuremonitor-containers ## Deploy the secrets 0. Define variables ``` WORKSPACE_NAME= WORKSPACE_ID= WORKSPACE_KEY= az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $WORKSPACE_NAME --location $LOCATION az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $WORKSPACE_NAME WORKSPACE_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $WORKSPACE_NAME -o json | jq '.id' -r) az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons monitoring --workspace-resource-id $WORKSPACE_ID az aks disable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons monitoring ``` 1. Deploy the oms daemons get the latest yaml file from here https://github.com/Microsoft/OMS-docker/blob/master/Kubernetes/omsagent.yaml https://github.com/Microsoft/OMS-docker/blob/ci_feature_prod/Kubernetes/omsagent.yaml ``` kubectl create -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/omsdaemonset.yaml kubectl get daemonset ``` Deploy cluster role for live log streaming ``` cat <<EOF | kubectl apply -f - kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: containerHealth-log-reader rules: - apiGroups: [""] resources: ["pods/log"] verbs: ["get"] --- kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: containerHealth-read-logs-global subjects: - kind: User name: clusterUser apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: containerHealth-log-reader apiGroup: rbac.authorization.k8s.io EOF ``` Deploy bindings for deployments ``` cat <<EOF | kubectl apply -f - apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: containerHealth-log-reader rules: - apiGroups: ["", "metrics.k8s.io", "extensions", "apps"] resources: - "pods/log" - "events" - "nodes" - "pods" - "deployments" - "replicasets" verbs: ["get", "list"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: containerHealth-read-logs-global roleRef: kind: ClusterRole name: containerHealth-log-reader apiGroup: rbac.authorization.k8s.io subjects: - kind: User name: clusterUser apiGroup: rbac.authorization.k8s.io EOF ``` get oms agent version ``` kubectl get pods -l component=oms-agent -o yaml -n kube-system | grep image: ``` ## Create custom logs via dummy logger 1. Create host to log from dummy logger ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: dummy-logger labels: app: dummy-logger spec: containers: - name: dummy-logger image: denniszielke/dummy-logger:latest ports: - containerPort: 80 name: http protocol: TCP imagePullPolicy: Always resources: requests: memory: "128Mi" cpu: "100m" limits: memory: "256Mi" cpu: "200m" --- apiVersion: v1 kind: Service metadata: name: dummy-logger namespace: default #annotations: # service.beta.kubernetes.io/azure-load-balancer-internal: "true" # service.beta.kubernetes.io/azure-load-balancer-internal-subnet: "ing-4-subnet" spec: ports: - port: 80 targetPort: 80 selector: app: dummy-logger type: LoadBalancer EOF ``` 2. Figure out ip and log something ``` kubectl get svc,pod dummy-logger LOGGER_IP= kubectl get svc dummy-logger -o template --template "{{(index .items 0).status.loadBalancer.ingress }}" curl -H "message: hallo" -X POST http://$LOGGER_IP/api/log ``` See the response ``` kubectl logs dummy-logger {"timestamp":"2018-09-21 06:39:44","value":37,"host":"dummy-logger","source":"::ffff:10.0.4.97","message":"hi"}% ``` 3. Search for the log message in log analytics by this query https://docs.microsoft.com/en-us/azure/monitoring/monitoring-container-insights-analyze?toc=%2fazure%2fmonitoring%2ftoc.json#example-log-search-queries ``` let startTimestamp = ago(1h); KubePodInventory | where TimeGenerated > startTimestamp | where ClusterName =~ "dzkubeaks" | distinct ContainerID | join ( ContainerLog | where TimeGenerated > startTimestamp ) on ContainerID | project LogEntrySource, LogEntry, TimeGenerated, Computer, Image, Name, ContainerID | order by TimeGenerated desc | where LogEntrySource == "stdout" | where Image == "dummy-logger" | render table ``` ``` let startDateTime = datetime('2018-10-22T06:15:00.000Z'); let endDateTime = datetime('2019-10-22T12:26:21.322Z'); let ContainerIdList = KubePodInventory | where TimeGenerated >= startDateTime and TimeGenerated < endDateTime | where ContainerName startswith 'crashing-app' | where ClusterName =~ "mesh44" | distinct ContainerID; ContainerLog | where TimeGenerated >= startDateTime and TimeGenerated < endDateTime | where ContainerID in (ContainerIdList) | project LogEntrySource, LogEntry, TimeGenerated, Computer, Image, Name, ContainerID | order by TimeGenerated desc | render table ``` ``` let startTimestamp = ago(1d); KubePodInventory | where TimeGenerated > startTimestamp | where ClusterName =~ "dkubaci" | distinct ContainerID | join ( ContainerLog | where TimeGenerated > startTimestamp ) on ContainerID | project LogEntrySource, LogEntry, TimeGenerated, Computer, Image, Name, ContainerID | order by TimeGenerated desc | render table Perf | where ObjectName == "Container" and CounterName == "Memory Usage MB" | where InstanceName contains "buggy-app" | summarize AvgUsedMemory = avg(CounterValue) by bin(TimeGenerated, 30m), InstanceName Perf | where ObjectName == "Container" and CounterName == "% Processor Time" | where InstanceName contains "buggy-app" | summarize AvgCPUPercent = avg(CounterValue) by bin(TimeGenerated, 30m), InstanceName ``` You will see raw data from your log output 4. Create a custom log format https://docs.microsoft.com/en-us/azure/log-analytics/log-analytics-data-sources-custom-logs Goto Log Analytics -> Data -> Custom Logs Cleanup ``` kubectl delete pod,svc dummy-logger ``` ## Install via helm https://github.com/Helm/charts/tree/master/incubator/azuremonitor-containers ``` WORKSPACE_ID= WORKSPACE_KEY= KUBE_NAME=logginghealth-apps helm repo add incubator https://kubernetes-charts-incubator.storage.googleapis.com/ helm install ./azuremonitor-containers --name oms-secondary --set omsagent.secret.wsid=$WORKSPACE_ID,omsagent.secret.key=$WORKSPACE_KEY,omsagent.env.clusterName=$KUBE_NAME ``` ## Logging on pod crashes ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: buggy-app labels: app: buggy-app spec: containers: - name: buggy-app image: denniszielke/buggy-app:latest livenessProbe: httpGet: path: /ping port: 80 scheme: HTTP initialDelaySeconds: 20 timeoutSeconds: 5 ports: - containerPort: 80 name: http protocol: TCP imagePullPolicy: Always resources: requests: memory: "128Mi" cpu: "500m" limits: memory: "256Mi" cpu: "1000m" --- apiVersion: v1 kind: Service metadata: name: buggy-app namespace: default spec: ports: - port: 80 targetPort: 80 selector: app: buggy-app type: LoadBalancer EOF ``` ``` cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Deployment metadata: name: buggy-app spec: replicas: 1 minReadySeconds: 5 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 1 template: metadata: labels: name: buggy-app demo: logging app: buggy-app spec: containers: - name: buggy-app image: denniszielke/buggy-app:latest livenessProbe: httpGet: path: /ping port: 80 scheme: HTTP initialDelaySeconds: 20 timeoutSeconds: 5 ports: - containerPort: 80 name: http protocol: TCP imagePullPolicy: Always resources: requests: memory: "128Mi" cpu: "500m" limits: memory: "256Mi" cpu: "1000m" --- apiVersion: v1 kind: Service metadata: name: buggy-app namespace: default spec: ports: - port: 80 targetPort: 80 selector: app: buggy-app type: LoadBalancer EOF ``` deploy crashing app ``` cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Deployment metadata: name: crashing-app spec: replicas: 1 minReadySeconds: 5 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 1 template: metadata: labels: name: crashing-app demo: logging app: crashing-app spec: containers: - name: crashing-app image: denniszielke/crashing-app:latest livenessProbe: httpGet: path: /ping port: 80 scheme: HTTP initialDelaySeconds: 20 timeoutSeconds: 5 ports: - containerPort: 80 name: http protocol: TCP imagePullPolicy: Always resources: requests: memory: "128Mi" cpu: "500m" limits: memory: "256Mi" cpu: "1000m" --- apiVersion: v1 kind: Service metadata: name: crashing-app namespace: default spec: ports: - port: 80 targetPort: 80 selector: app: crashing-app type: LoadBalancer EOF ``` ``` cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Deployment metadata: name: dummy-logger spec: replicas: 1 minReadySeconds: 5 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 1 template: metadata: labels: name: dummy-logger demo: logging app: dummy-logger spec: containers: - name: dummy-logger image: denniszielke/dummy-logger:latest livenessProbe: httpGet: path: /ping port: 80 scheme: HTTP initialDelaySeconds: 20 timeoutSeconds: 5 ports: - containerPort: 80 name: http protocol: TCP imagePullPolicy: Always resources: requests: memory: "128Mi" cpu: "500m" limits: memory: "256Mi" cpu: "1000m" --- apiVersion: v1 kind: Service metadata: name: dummy-logger namespace: default spec: ports: - port: 80 targetPort: 80 selector: app: dummy-logger type: ClusterIP EOF ``` ## Create an alert based on container fail Log query ``` ContainerInventory | where Image contains "buggy-app" and TimeGenerated > ago(10m) and ContainerState == "Failed" | summarize AggregatedValue = dcount(ContainerID) by Computer, Image, ContainerState ``` ``` ContainerInventory | where Image contains "buggy-app" and TimeGenerated > ago(10m) and ContainerState == "Failed" ``` ## Crash or leak app cat <<EOF | kubectl apply -f - apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: containerHealth-log-reader rules: - apiGroups: [""] resources: ["pods/log", "events"] verbs: ["get", "list"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: containerHealth-read-logs-global roleRef: kind: ClusterRole name: containerHealth-log-reader apiGroup: rbac.authorization.k8s.io subjects: - kind: User name: clusterUser apiGroup: rbac.authorization.k8s.io EOF the app has a route called crash - it you call it the app will crash /crash the app has a route called leak - if you call it it will leak memory /leak ``` LOGGER_IP=172.16.31.10 LOGGER_IP=10.0.147.7 LEAKER_IP=172.16.31.10 CRASHER_IP=172.16.58.3 curl -H "message: hi" -X POST http://$LOGGER_IP/api/log curl -X GET http://$CRASHER_IP/crash curl -X GET http://$LOGGER_IP/leak ``` ## Log nginx http errors ``` cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: hello-world-ingress annotations: kubernetes.io/ingress.class: nginx cert-manager.io/issuer: "letsencrypt-prod" nginx.ingress.kubernetes.io/rewrite-target: / nginx.ingress.kubernetes.io/ssl-redirect: "true" spec: tls: - hosts: - 192.168.3.11.xip.io secretName: dummy-tls rules: - host: 192.168.3.11.xip.io http: paths: - path: / backend: serviceName: dummy-logger servicePort: 80 EOF ``` curl -k -v -XGET -H "User-Agent: kubectl/v1.12.2 (darwin/amd64) kubernetes/17c77c7" -H "Accept: application/json;as=Table;v=v1beta1;g=meta.k8s.io, application/json" -H "Authorization: Bearer xxxxx" 'https://acnie-34961d1e.hcp.westeurope.azmk8s.io:443/api/v1/componentstatuses?limit=500' ## Logging from ACI ``` LOCATION=westeurope ACI_GROUP=aci-group az container create --image denniszielke/dummy-logger --resource-group $ACI_GROUP --location $LOCATION --name dummy-logger --os-type Linux --cpu 1 --memory 3.5 --dns-name-label dummy-logger --ip-address public --ports 80 --verbose LOGGER_IP=192.168.3.11 LOGGER_IP=172.16.58.3 LEAKER_IP=192.168.3.11 CRASHER_IP=192.168.3.11 curl -H "message: hi" -X POST http://$LOGGER_IP/api/log curl -X GET http://$CRASHER_IP/crash curl -X GET http://$CRASHER_IP/leak for i in `seq 1 20`; do time curl -s $LEAKER_IP/leak > /dev/null; done ``` ## Get prm metrics http://192.168.3.11.xip.io/dummy-logger/ping kubectl delete pod -n kube-system --selector="dsName=omsagent-ds" ``` InsightsMetrics | where Namespace contains "prometheus" | where TimeGenerated > ago(1h) | where Name startswith "http_requests_" | summarize max(Val) by Name, bin(TimeGenerated, 1m) | render timechart ``` ``` https://gist.github.com/vyta/d13151c7031054f998a7efc99ae706d0<file_sep># Create container cluster (AKS) 0. Variables ``` SUBSCRIPTION_ID="" KUBE_GROUP="kubesaks" KUBE_NAME="dzkubes" LOCATION="eastus" REGISTRY_NAME="" ``` # Create and configure container registry 1. Create container registr ``` az acr create --resource-group "$KUBE_GROUP" --name "$REGISTRY_NAME" --sku Basic --admin-enabled true ``` 2. Login to ACR ``` az acr login --name $REGISTRY_NAME --expose-token az acr update --name $REGISTRY_NAME --admin-enabled true ``` 3. Read login servier ``` export REGISTRY_URL=$(az acr show -g $KUBE_GROUP -n $REGISTRY_NAME --query "loginServer") export REGISTRY_URL=("${REGISTRY_URL[@]//\"/}") export REGISTRY_PW= ``` 4. import images ``` az acr import -n $REGISTRY_NAME --source docker.io/denniszielke/aci-helloworld:latest -t aci-helloworld:latest docker tag denniszielke/aci-helloworld $REGISTRY_NAME.azurecr.io/aci-helloworld docker push $REGISTRY_NAME.azurecr.io/aci-helloworld az container create --name "acidemohello" --image "$REGISTRY_NAME.azurecr.io/aci-helloworld" --resource-group "byokdemo" --ip-address public --registry-password $REGISTRY_PW --registry-username "dzdemoky23" --ports 80 --os-type Linux ``` # Schedule container deployment If the container registry is in the same resource group then no additional configration is needed otherwise you can assign the kubernetes service prinicpal to the reader role of the container registry ``` az role assignment create --scope /subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.ContainerRegistry/registries/$REGISTRY_NAME --role Reader --assignee $SERVICE_PRINCIPAL_ID ``` trigger a deployment with a customer image to validate ``` kubectl run helloworld --image $REGISTRY_NAME.azurecr.io/aci-helloworld-ci:latest ``` # Run builds in ACR https://docs.microsoft.com/en-us/azure/container-registry/container-registry-tutorial-build-task ``` ACR_NAME=dzkubereg RES_GROUP=kuberegistry LOCATION=northeurope USER=denniszielke GIT_PAT= az group create --resource-group $RES_GROUP --location $LOCATION az acr create --resource-group $RES_GROUP --name $ACR_NAME --sku Standard --location $LOCATION az acr build --registry $ACR_NAME --image helloacr:v1 . az acr task list -o table az acr task create --registry $ACR_NAME --name go-calc-backend-acr --image go-calc-backend:{{.Run.ID}} --context https://github.com/$USER/container_demos.git --branch master --file apps/go-calc-backend/ACR.Dockerfile --git-access-token $GIT_PAT --no-cache true --set appfolder="apps/go-calc-backend/app" --arg appfolder="apps/go-calc-backend/app" az acr task create --registry $ACR_NAME --name js-calc-backend-acr --image js-calc-backend:{{.Run.ID}} --context https://github.com/$USER/container_demos.git --branch master --file apps/js-calc-backend/ACR.Dockerfile --git-access-token $GIT_PAT --no-cache true --set appfolder="apps/js-calc-backend/app" --arg appfolder="apps/js-calc-backend/app" az acr task create --registry $ACR_NAME --name js-calc-frontend-acr --image js-calc-frontend:{{.Run.ID}} --context https://github.com/$USER/container_demos.git --branch master --file apps/js-calc-frontend/ACR.Dockerfile --git-access-token $GIT_PAT --no-cache true --set appfolder="apps/js-calc-frontend/app" --arg appfolder="apps/js-calc-frontend/app" az acr task run --registry $ACR_NAME --name go-calc-backend-acr az acr task run --registry $ACR_NAME --name js-calc-backend-acr az acr task run --registry $ACR_NAME --name js-calc-frontend-acr ``` ## Helm repositories https://docs.microsoft.com/en-gb/azure/container-registry/container-registry-helm-repos set default registry ``` ACR_NAME= az configure --defaults acr=$ACR_NAME az acr helm repo add $ACR_NAME ``` List helm charts ``` az acr helm list --name $ACR_NAME az acr repository show --name $ACR_NAME --repository multicalculatorv3 az acr helm search -l $ACR_NAME/multicalculatorv3 helm search repo -l $ACR_NAME/multicalculatorv3 ``` Delete charts ``` az acr helm delete $ACR_NAME/multicalculator az acr helm delete -n $ACR_NAME multicalculatorv3 --version 0.1.0 ``` ## Security Scanning ``` ACR_NAME= docker pull docker.io/vulnerables/web-dvwa docker tag docker.io/vulnerables/web-dvwa $ACR_NAME.azurecr.io/vulnerables/web-dvwa docker push $ACR_NAME.azurecr.io/vulnerables/web-dvwa docker pull mcr.microsoft.com/dotnet/core/sdk:2.2.105 docker tag mcr.microsoft.com/dotnet/core/sdk:2.2.105 $ACR_NAME.azurecr.io/vulnerables/core/sdk:2.2.105 docker push $ACR_NAME.azurecr.io/vulnerables/core/sdk:2.2.105 ``` ## Teleport <file_sep>quarkus.rest-client.invoke.url=http://localhost:8080<file_sep>#!/bin/sh # # wget https://raw.githubusercontent.com/denniszielke/container_demos/master/scripts/aks_des_byo_vnet.sh # chmod +x ./aks_des_byo_vnet.sh # bash ./aks_des_byo_vnet.sh # set -e # sudo nano /etc/environment # http_proxy=http://192.168.43.100:3128/\nhttps_proxy=https://192.168.43.100:3128/ # sudo nano /etc/ntp.conf SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id DEPLOYMENT_NAME="dzciti38" # here enter unique deployment name (ideally short and with letters for global uniqueness) LOCATION="westeurope" # here enter the datacenter location KUBE_VNET_GROUP="networks" # here enter the vnet resource group KUBE_VNET_NAME="hub1-firewalvnet" # here enter the name of your AKS vnet KUBE_AGENT_SUBNET_NAME="jumpbox-subnet" # here enter the name of your AKS subnet IGNORE_FORCE_ROUTE="true" # only set to true if you have a routetable on the AKS subnet but that routetable does not contain a route for '0.0.0.0/0' with target VirtualAppliance or VirtualNetworkGateway USE_PRIVATE_LINK="false" # use to deploy private master endpoint AAD_GROUP_ID="9329d38c-5296-4ecb-afa5-3e74f9abe09f" # here the AAD group that will be used to lock down AKS authentication KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" # here enter the kubernetes version of your AKS or leave this and it will select the latest stable version TENANT_ID=$(az account show --query tenantId -o tsv) # azure tenant id KUBE_GROUP=$DEPLOYMENT_NAME # here enter the resources group name of your AKS cluster KUBE_NAME=$DEPLOYMENT_NAME # here enter the name of your kubernetes resource NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group MY_OWN_OBJECT_ID=$(az ad signed-in-user show --query objectId --output tsv) # this will be your own aad object id OUTBOUNDTYPE="" az account set --subscription $SUBSCRIPTION_ID az extension add --name aks-preview az extension update --name aks-preview if [ $(az group exists --name $KUBE_GROUP) = false ]; then echo "creating resource group $KUBE_GROUP..." az group create -n $KUBE_GROUP -l $LOCATION -o none echo "resource group $KUBE_GROUP created" else echo "resource group $KUBE_GROUP already exists" fi KUBE_AGENT_SUBNET_ID=$(az network vnet subnet show -g $KUBE_VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --query id -o tsv) if [ "$KUBE_AGENT_SUBNET_ID" == "" ]; then echo "could not find subnet $KUBE_AGENT_SUBNET_NAME in vnet $KUBE_VNET_NAME in $KUBE_VNET_GROUP" exit else echo "using subnet $KUBE_AGENT_SUBNET_ID" fi ROUTE_TABLE_ID=$(az network vnet subnet show -g $KUBE_VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --query routeTable.id -o tsv) if [ "$ROUTE_TABLE_ID" == "" ]; then echo "could not find routetable on AKS subnet $KUBE_AGENT_SUBNET_ID" else echo "using routetable $ROUTE_TABLE_ID with the following entries" ROUTE_TABLE_GROUP=$(az network route-table show --ids $ROUTE_TABLE_ID --query "[resourceGroup]" -o tsv) ROUTE_TABLE_NAME=$(az network route-table show --ids $ROUTE_TABLE_ID --query "[name]" -o tsv) echo "if this routetable does not contain a route for '0.0.0.0/0' with target VirtualAppliance or VirtualNetworkGateway then we will not need the outbound type parameter" az network route-table route list --resource-group $ROUTE_TABLE_GROUP --route-table-name $ROUTE_TABLE_NAME -o table echo "if it does not contain a '0.0.0.0/0' route then you should set the parameter IGNORE_FORCE_ROUTE=true" echo "adding routes for microsoft container registry" az network route-table route create --resource-group $ROUTE_TABLE_GROUP --name "mcr" --route-table-name $ROUTE_TABLE_NAME --address-prefix MicrosoftContainerRegistry --next-hop-type Internet echo "adding routes for active directory" az network route-table route create --resource-group $ROUTE_TABLE_GROUP --name "aad" --route-table-name $ROUTE_TABLE_NAME --address-prefix AzureActiveDirectory --next-hop-type Internet echo "adding routes for azure monitor" az network route-table route create --resource-group $ROUTE_TABLE_GROUP --name "monitor" --route-table-name $ROUTE_TABLE_NAME --address-prefix AzureMonitor --next-hop-type Internet echo "adding routes for azure region $LOCATION" az network route-table route create --resource-group $ROUTE_TABLE_GROUP --name "azure" --route-table-name $ROUTE_TABLE_NAME --address-prefix AzureCloud.$LOCATION --next-hop-type Internet if [ "$IGNORE_FORCE_ROUTE" == "true" ]; then echo "ignoring forced tunneling route information" OUTBOUNDTYPE="" else echo "using forced tunneling route information" OUTBOUNDTYPE=" --outbound-type userDefinedRouting " fi fi echo "setting up keyvault" KEYVAULT_ID=$(az keyvault list --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$KEYVAULT_ID" == "" ]; then echo "creating keyvault $KUBE_NAME in resource group $KUBE_GROUP..." az keyvault create -n $KUBE_NAME -g $KUBE_GROUP -l $LOCATION --enable-purge-protection true --enable-soft-delete true -o none KEYVAULT_ID=$(az keyvault show --name $KUBE_NAME --query "[id]" -o tsv) echo "created keyvault $KEYVAULT_ID" else echo "keyvault $KEYVAULT_ID already exists" fi KEYVAULT_URL=$(az keyvault key list --vault-name $KUBE_NAME --query "[?contains(name, 'des')].kid" -o tsv) if [ "$KEYVAULT_URL" == "" ]; then echo "creating key des in $KUBE_NAME in resource group $KUBE_GROUP..." az keyvault key create -n des --vault-name $KUBE_NAME --kty RSA --ops encrypt decrypt wrapKey unwrapKey sign verify --size 2048 -o none KEYVAULT_URL=$(az keyvault key show --vault-name $KUBE_NAME --name des --query "[key.kid]" -o tsv) echo "created keyvault kes $KEYVAULT_URL" else KEYVAULT_URL=$(az keyvault key show --vault-name $KUBE_NAME --name des --query "[key.kid]" -o tsv) echo "key des in keyvault $KEYVAULT_URL already exists" fi echo "setting up disk encryption set" DES_ID=$(az disk-encryption-set list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$DES_ID" == "" ]; then echo "creating disk encryption set $KUBE_NAME" az disk-encryption-set create -n $KUBE_NAME -l $LOCATION -g $KUBE_GROUP --source-vault $KEYVAULT_ID --key-url $KEYVAULT_URL -o none sleep 5 DES_IDENTITY=$(az disk-encryption-set show -n $KUBE_NAME -g $KUBE_GROUP --query "[identity.principalId]" -o tsv) az keyvault set-policy -n $KUBE_NAME -g $KUBE_GROUP --object-id $DES_IDENTITY --key-permissions wrapkey unwrapkey get -o none DES_ID=$(az disk-encryption-set show -n $KUBE_NAME -g $KUBE_GROUP --query "[id]" -o tsv) DES_IDENTITY=$(az disk-encryption-set show -n $KUBE_NAME -g $KUBE_GROUP --query "[identity.principalId]" -o tsv) echo "created disk encryption set $DES_ID" else echo "disk encryption set $DES_ID already exists" fi echo "setting up controller identity" AKS_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-id')].id" -o tsv)" if [ "$AKS_CLIENT_ID" == "" ]; then echo "creating controller identity $KUBE_NAME-id in $KUBE_GROUP" az identity create --name $KUBE_NAME-id --resource-group $KUBE_GROUP -o none sleep 5 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" sleep 5 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 5 # wait for replication az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none if [ "$ROUTE_TABLE_ID" == "" ]; then echo "no route table used" else echo "assigning permissions on routetable $ROUTE_TABLE_ID" az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $ROUTE_TABLE_ID -o none fi else echo "controller identity $AKS_CONTROLLER_RESOURCE_ID already exists" echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none if [ "$ROUTE_TABLE_ID" == "" ]; then echo "no route table used" else echo "assigning permissions on routetable $ROUTE_TABLE_ID" az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $ROUTE_TABLE_ID -o none fi fi echo "setting up azure container registry" ACR_ID="$(az acr list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv)" if [ "$ACR_ID" == "" ]; then echo "creating ACR $KUBE_NAME in $KUBE_GROUP" az acr create --resource-group $KUBE_GROUP --name $KUBE_NAME --sku Standard --location $LOCATION -o none ACR_ID="$(az acr show -g $KUBE_GROUP -n $KUBE_NAME --query id -o tsv)" echo "created ACR $ACR_ID" else echo "ACR $ACR_ID already exists" fi echo "setting up aks" AKS_ID=$(az aks list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$USE_PRIVATE_LINK" == "true" ]; then ACTIVATE_PRIVATE_LINK=" --enable-private-cluster " else ACTIVATE_PRIVATE_LINK="" fi if [ "$AKS_ID" == "" ]; then echo "creating AKS $KUBE_NAME in $KUBE_GROUP" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --ssh-key-value ~/.ssh/id_rsa.pub --node-count 3 --min-count 3 --max-count 5 --enable-cluster-autoscaler --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin kubenet --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --no-ssh-key --assign-identity $AKS_CONTROLLER_RESOURCE_ID --node-osdisk-size 300 --node-osdisk-diskencryptionset-id $DES_ID --enable-managed-identity --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $TENANT_ID --uptime-sla --attach-acr $ACR_ID $OUTBOUNDTYPE $ACTIVATE_PRIVATE_LINK -o none AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query id -o tsv) echo "created AKS $AKS_ID" else echo "AKS $AKS_ID already exists" fi echo "setting up azure monitor" WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace list --resource-group $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$WORKSPACE_RESOURCE_ID" == "" ]; then echo "creating workspace $KUBE_NAME in $KUBE_GROUP" az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --location $LOCATION -o none WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME -o json | jq '.id' -r) az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons monitoring --workspace-resource-id $WORKSPACE_RESOURCE_ID OMS_CLIENT_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query addonProfiles.omsagent.identity.clientId -o tsv) az role assignment create --assignee $OMS_CLIENT_ID --scope $AKS_ID --role "Monitoring Metrics Publisher" fi az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME <file_sep># Using Helm https://github.com/kubernetes/charts/tree/master/incubator/kafka ## Install Helm for rbac ``` APP_NAME=kafka APP_INSTANCE=mykafka kubectl create ns $APP_NAME helm repo add incubator http://storage.googleapis.com/kubernetes-charts-incubator helm repo update kubectl create namespace kafka helm install dapr-kafka --namespace kafka incubator/kafka --set replicas=1 ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: testclient namespace: kafka spec: containers: - name: kafka image: confluentinc/cp-kafka:5.0.1 command: - sh - -c - "exec tail -f /dev/null" EOF find / -type f -name kafka-topics.sh Once you have the testclient pod above running, you can list all kafka topics with: kubectl -n kafka exec testclient -- /opt/kafka/bin/kafka-topics.sh --zookeeper my-kafka-zookeeper:2181 --list To create a new topic: kubectl -n kafka exec testclient -- /opt/kafka/bin/kafka-topics.sh --zookeeper my-kafka-zookeeper:2181 --topic test1 --create --partitions 1 --replication-factor 1 To listen for messages on a topic: kubectl -n kafka exec -ti testclient -- /opt/kafka/bin/kafka-console-consumer.sh --bootstrap-server my-kafka:9092 --topic test1 --from-beginning To stop the listener session above press: Ctrl+C To start an interactive message producer session: kubectl -n kafka exec -ti testclient -- /opt/kafka/bin/kafka-console-producer.sh --broker-list my-kafka-headless:9092 --topic test1 To create a message in the above session, simply type the message and press "enter" To end the producer session try: Ctrl+C<file_sep>APPGW_NAME="dzappgw5" APPGW_GROUP="kub_ter_a_m_appgw5" # here enter the appgw resource group name APPGW_SUBNET_NAME="gw-1-subnet" # name of AppGW subnet VNET="appgw5-vnet" APPGW_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$APPGW_GROUP/providers/Microsoft.Network/virtualNetworks/$VNET/subnets/$APPGW_SUBNET_NAME" az network public-ip create --resource-group $APPGW_GROUP --name $APPGW_NAME-pip --allocation-method Static --sku Standard APPGW_PUBLIC_IP=$(az network public-ip show -g $APPGW_GROUP -n $APPGW_NAME-pip --query ipAddress -o tsv) az network application-gateway create --name $APPGW_NAME --resource-group $APPGW_GROUP --location $LOCATION --http2 Enabled --min-capacity 0 --max-capacity 10 --sku WAF_v2 --vnet-name $VNET --subnet $APPGW_SUBNET_ID --http-settings-cookie-based-affinity Disabled --frontend-port 80 --http-settings-port 80 --http-settings-protocol Http --public-ip-address $APPGW_NAME-pip --private-ip-address "10.0.1.100" APPGW_NAME=$(az network application-gateway list --resource-group=$APPGW_GROUP -o json | jq -r ".[0].name") APPGW_RESOURCE_ID=$(az network application-gateway list --resource-group=$APPGW_GROUP -o json | jq -r ".[0].id") APPGW_SUBNET_ID=$(az network application-gateway list --resource-group=$APPGW_GROUP -o json | jq -r ".[0].gatewayIpConfigurations[0].subnet.id") KUBELET_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identityProfile.kubeletidentity.clientId -o tsv) CONTROLLER_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identity.principalId -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az role assignment create --role "Managed Identity Operator" --assignee $KUBELET_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Managed Identity Operator" --assignee $CONTROLLER_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Virtual Machine Contributor" --assignee $KUBELET_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Reader" --assignee $KUBELET_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$KUBE_GROUP az identity create -g $NODE_GROUP -n $APPGW_NAME-id sleep 5 # wait for replication AGIC_ID_CLIENT_ID="$(az identity show -g $NODE_GROUP -n $APPGW_NAME-id --query clientId -o tsv)" AGIC_ID_RESOURCE_ID="$(az identity show -g $NODE_GROUP -n $APPGW_NAME-id --query id -o tsv)" NODES_RESOURCE_ID=$(az group show -n $NODE_GROUP -o tsv --query "id") KUBE_GROUP_RESOURCE_ID=$(az group show -n $KUBE_GROUP -o tsv --query "id") sleep 15 # wait for replication echo "assigning permissions for AGIC client $AGIC_ID_CLIENT_ID" az role assignment create --role "Contributor" --assignee $AGIC_ID_CLIENT_ID --scope $APPGW_RESOURCE_ID az role assignment create --role "Reader" --assignee $AGIC_ID_CLIENT_ID --scope $KUBE_GROUP_RESOURCE_ID # might not be needed az role assignment create --role "Reader" --assignee $AGIC_ID_CLIENT_ID --scope $NODES_RESOURCE_ID # might not be needed az role assignment create --role "Reader" --assignee $AGIC_ID_CLIENT_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$APPGW_GROUP helm repo add application-gateway-kubernetes-ingress https://appgwingress.blob.core.windows.net/ingress-azure-helm-package/ helm repo update helm pull application-gateway-kubernetes-ingress/ingress-azure helm upgrade ingress-azure application-gateway-kubernetes-ingress/ingress-azure \ --namespace kube-system \ --install \ --set appgw.name=$APPGW_NAME \ --set appgw.resourceGroup=$APPGW_GROUP \ --set appgw.subscriptionId=$SUBSCRIPTION_ID \ --set appgw.usePrivateIP=false \ --set appgw.shared=false \ --set armAuth.type=aadPodIdentity \ --set armAuth.identityClientID=$AGIC_ID_CLIENT_ID \ --set armAuth.identityResourceID=$AGIC_ID_RESOURCE_ID \ --set rbac.enabled=true \ --set verbosityLevel=3 # --set kubernetes.watchNamespace=default cat <<EOF | kubectl apply -f - apiVersion: cert-manager.io/v1alpha2 kind: ClusterIssuer metadata: name: letsencrypt namespace: kube-system spec: acme: server: https://acme-v02.api.letsencrypt.org/directory email: $MY_USER_ID privateKeySecretRef: name: letsencrypt-secret solvers: - http01: ingress: class: azure/application-gateway EOF az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME -a ingress-appgw --appgw-id $APPGW_RESOURCE_ID kubectl apply -f https://raw.githubusercontent.com/Azure/application-gateway-kubernetes-ingress/master/docs/examples/aspnetapp.yaml <file_sep>#!/bin/sh set -euqq sudo apt update sudo apt --assume-yes install python-pip wget https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/python-ip/requirements.txt wget https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/python-ip/echo.py pip install -r requirements.txt chmod +x echo.py python echo.py #nohup python /home/azureuser/echo.py & <file_sep>package qdapr.acme; import org.eclipse.microprofile.rest.client.RestClientBuilder; import org.eclipse.microprofile.rest.client.inject.RestClient; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @Path("/hello") public class GreetingResource { @RestClient InvokeService invokeService; @GET @Produces(MediaType.TEXT_PLAIN) public String hello() { return "Hello from RESTEasy Reactive"; } @POST @Path("/invoke/{id}") public String post(S id) { return "invoked " + Integer.toString(id); } @DELETE public String delete(int id) { return "deleted " + Integer.toString(id); } } <file_sep>#!/bin/bash sudo mkdir /opt/music sudo cp /etc/kubernetes/azure.json /opt/music<file_sep># Grafana install ``` GRAFANA_IN=my-grafana GRAFANA_NS=monitoring kubectl create ns $GRAFANA_NS helm upgrade --install $GRAFANA_IN stable/grafana --set plugins={grafana-azure-monitor-datasource} --namespace $GRAFANA_NS ``` get secret ``` kubectl get secret -n $GRAFANA_NS $GRAFANA_IN -o jsonpath="{.data.admin-password}" | base64 --decode ``` create port forwarding ``` kubectl port-forward --namespace $GRAFANA_NS service/$GRAFANA_IN 3000:80 & ``` ## Configure azure monitor plugin https://grafana.com/grafana/plugins/grafana-azure-monitor-datasource https://docs.microsoft.com/en-gb/azure/azure-monitor/platform/grafana-plugin https://www.stefanroth.net/2019/10/18/azure-monitor-helm-install-aks-monitoring-grafana-dashboard-with-azure-ad-integration/ ``` SUBSCRIPTION_ID="" TENANT_ID="" SERVICE_PRINCIPAL_ID="" SERVICE_PRINCIPAL_SECRET="" ``` KUBE_NAME=monitoring71 SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) echo $AZURE_TENANT_ID SERVICE_PRINCIPAL_ID=$(az ad sp show --id $KUBE_NAME -o json | jq -r '.[0].appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --append --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo -e "\n\n Remember these outputs:" echo -e "Your Kubernetes service_principal_id should be \e[7m$SERVICE_PRINCIPAL_ID\e[0m" echo -e "Your Kubernetes service_principal_secret should be \e[7m$SERVICE_PRINCIPAL_SECRET\e[0m" echo -e "Your Azure tenant_id should be \e[7m$AZURE_TENANT_ID\e[0m" echo -e "Your Azure subscription_id should be \e[7m$SUBSCRIPTION_ID\e[0m" echo -e "\n\n" DashboardId 10956 ## Loki install ``` LOKI_IN=my-loki LOKI_NS=loki helm repo add loki https://grafana.github.io/loki/charts helm repo update kubectl create ns $LOKI_NS helm upgrade --install $LOKI_IN -n=$LOKI_NS loki/loki-stack --set grafana.enabled=true,prometheus.enabled=true,prometheus.alertmanager.persistentVolume.enabled=true,prometheus.server.persistentVolume.enabled=true helm -n loki-stack ls ``` connect ``` kubectl get secret --namespace $LOKI_NS $LOKI_IN-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo kubectl port-forward --namespace $LOKI_NS service/$LOKI_IN-grafana 3000:80 ``` <file_sep> # Consul new ui https://www.hashicorp.com/blog/service-mesh-visualization-in-hashicorp-consul-1-9 ## Install brew tap hashicorp/tap brew install hashicorp/tap/consul brew upgrade hashicorp/tap/consul ## Helm kubectl create namespace consul helm upgrade consul -f consul-helm/values.yaml --install --namespace consul ./consul-helm \ --set connectInject.enabled=true --set connectInject.nodeSelector="beta.kubernetes.io/os: linux" \ --set client.enabled=true --set client.grpc=true --set client.nodeSelector="beta.kubernetes.io/os: linux" \ --set server.nodeSelector="beta.kubernetes.io/os: linux" \ --set syncCatalog.enabled=true --set syncCatalog.nodeSelector="beta.kubernetes.io/os: linux" kubectl get svc --namespace consul --output wide kubectl get pod --namespace consul --output wide https://github.com/hashicorp/demo-consul-101/tree/master/k8s kubectl port-forward -n consul service/consul-consul-server 8500:8500 kubectl apply -f consul/counting-minimal-pod.yaml kubectl port-forward pod/dashboard 9001:9001 kubectl apply -f consul/counting-minimal-svc.yaml kubectl exec -it counting-minimal-pod /bin/sh ## Consul Helm helm repo add hashicorp https://helm.releases.hashicorp.com helm search repo hashicorp/consul helm repo update helm search repo hashicorp/consul kubectl create namespace consul helm upgrade consul hashicorp/consul --install --set global.name=consul --set connectInject.enabled=true \ --set client.enabled=true --set client.grpc=true --namespace consul helm upgrade consul hashicorp/consul --install -f consul/consul-values.yaml --namespace consul kubectl get secrets/consul-bootstrap-acl-token --template={{.data.token}} | base64 -D kubectl port-forward service/consul-server 8500:8500 -n consul ## Consul Helm 1.9 helm repo add hashicorp https://helm.releases.hashicorp.com helm search repo hashicorp/consul helm repo update helm search repo hashicorp/consul kubectl create namespace consul helm upgrade consul hashicorp/consul --install --set global.name=consul --set connectInject.enabled=true \ --set client.enabled=true --set client.grpc=true --namespace consul helm upgrade consul hashicorp/consul --install -f consul/consul-values.yaml --set global.image=consul:1.9.0-beta1 --set controller.enabled=true --namespace consul kubectl get secrets/consul-bootstrap-acl-token --template={{.data.token}} | base64 -D kubectl port-forward service/consul-server 8500:8500 -n consul kubectl port-forward pods/ambassador-65586b5bc6-94jn9 8877:8877 http://localhost:8877/ambassador/v0/diag/ ## Consul helm TLS consul tls ca create consul tls cert create -server kubectl create secret generic consul-ca-cert --from-file='tls.crt=./consul-agent-ca.pem' kubectl create secret generic consul-ca-key --from-file='tls.key=./consul-agent-ca-key.pem' helm repo add hashicorp https://helm.releases.hashicorp.com helm repo update helm search repo hashicorp/consul kubectl create namespace consul helm upgrade consul hashicorp/consul --install -f consul/consul-values.yaml --namespace consul kubectl get secrets/consul-bootstrap-acl-token --template={{.data.token}} | base64 -D kubectl port-forward service/consul-ui 8500:443 -n consul ## Consul agent https://learn.hashicorp.com/tutorials/consul/get-started-agent consul agent -dev consul members consul intentions https://learn.hashicorp.com/tutorials/consul/kubernetes-custom-resource-definitions ## Consul DNS https://www.consul.io/docs/platform/k8s/dns.html 10.2.0.250 kubectl edit configmap coredns -n kube-system consul { errors cache 30 forward . 10.2.0.250 } kubectl get configmap coredns -n kube-system -o yaml kubectl get pods --show-all | grep dns ## KV consul kv put redis/config/minconns 1 consul kv put redis/config/maxconns 25 consul kv put -flags=42 redis/config/users/admin abcd1234 consul kv get redis/config/minconns consul kv get -detailed redis/config/users/admin consul kv delete -recurse redis cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: consul-example spec: containers: - name: example image: 'consul:latest' env: - name: HOST_IP valueFrom: fieldRef: fieldPath: status.hostIP command: - '/bin/sh' - '-ec' - | export CONSUL_HTTP_ADDR="${HOST_IP}:8500" consul kv put hello world restartPolicy: Never EOF ## Metrics https://learn.hashicorp.com/tutorials/consul/kubernetes-layer7-observability?in=consul/interactive Grafana dashboard https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/grafana/hashicups-dashboard.json kubectl get secret --namespace $LOKI_NS $LOKI_IN-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo kubectl port-forward --namespace $LOKI_NS service/$LOKI_IN-grafana 3000:80 kubectl apply -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/app/frontend.yaml kubectl apply -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/app/products-api.yaml kubectl apply -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/app/products-db.yaml kubectl apply -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/app/public-api.yaml kubectl port-forward deploy/frontend 8080:80 kubectl port-forward deploy/frontend 19000:19000 open http://localhost:19000/config_dump kubectl port-forward deploy/my-loki-prometheus-server 9090:9090 -n loki sum by(__name__)({app="products-api"}) kubectl apply -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/traffic.yaml kubectl delete -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/app/frontend.yaml kubectl delete -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/app/products-api.yaml kubectl delete -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/app/products-db.yaml kubectl delete -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/app/public-api.yaml kubectl delete -f https://raw.githubusercontent.com/hashicorp/consul-k8s-prometheus-grafana-hashicups-demoapp/master/traffic.yaml ## demo counting kubectl apply -f https://raw.githubusercontent.com/hashicorp/demo-consul-101/master/k8s/04-yaml-connect-envoy/counting-service.yaml kubectl apply -f https://raw.githubusercontent.com/hashicorp/demo-consul-101/master/k8s/04-yaml-connect-envoy/dashboard-service.yaml kubectl delete -f https://raw.githubusercontent.com/hashicorp/demo-consul-101/master/k8s/04-yaml-connect-envoy/counting-service.yaml kubectl delete -f https://raw.githubusercontent.com/hashicorp/demo-consul-101/master/k8s/04-yaml-connect-envoy/dashboard-service.yaml ## demo simple client server kubectl apply -f consul/demo-api.yaml kubectl apply -f consul/demo-web.yaml kubectl port-forward service/web 9090:9090 --address 0.0.0.0<file_sep>#!/bin/sh # # wget https://raw.githubusercontent.com/denniszielke/container_demos/master/scripts/aks_vnet.sh # chmod +x ./aks_vnet.sh # bash ./aks_vnet.sh # set -e DEPLOYMENT_NAME="dzobsnat1" # here enter unique deployment name (ideally short and with letters for global uniqueness) USE_PRIVATE_API="false" # use to deploy private master endpoint USE_POD_SUBNET="false" USE_OVERLAY="true" USE_CILIUM="" #--enable-cilium-dataplane" VNET_PREFIX="0" AAD_GROUP_ID="0644b510-7b35-41aa-a9c6-4bfc3f644c58 --enable-azure-rbac" # here the AAD group that will be used to lock down AKS authentication LOCATION="northeurope" # "northcentralus" "northeurope" #"southcentralus" #"eastus2euap" #"westeurope" # here enter the datacenter location can be eastus or westeurope KUBE_GROUP=$DEPLOYMENT_NAME # here enter the resources group name of your AKS cluster KUBE_NAME=$DEPLOYMENT_NAME # here enter the name of your kubernetes resource NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group KUBE_VNET_NAME="$DEPLOYMENT_NAME-vnet" KUBE_FW_SUBNET_NAME="AzureFirewallSubnet" # this you cannot change BASTION_SUBNET_NAME="AzureBastionSubnet" # this you cannot change APPGW_SUBNET_NAME="gw-1-subnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" # here enter the name of your ingress subnet KUBE_API_SUBNET_NAME="api-0-subnet" KUBE_AGENT_SUBNET_NAME="aks-5-subnet" # here enter the name of your AKS subnet POD_AGENT_SUBNET_NAME="pod-8-subnet" ACI_AGENT_SUBNET_NAME="aci-7-subnet" VAULT_NAME=dzkv$KUBE_NAME SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id TENANT_ID=$(az account show --query tenantId -o tsv) KUBE_VERSION=$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv) # here enter the kubernetes version of your AKS KUBE_VERSION="1.26.3" KUBE_CNI_PLUGIN="azure" # azure # kubenet MY_OWN_OBJECT_ID=$(az ad signed-in-user show --query objectId --output tsv) # this will be your own aad object id #DNS_ID=$(az network dns zone list -g appconfig -o tsv --query "[].id") OUTBOUNDTYPE="" #az account set --subscription $SUBSCRIPTION_ID echo "deploying version $KUBE_VERSION" PROM_RESOURCE_ID="/subscriptions/$SUBSCRIPTION_ID/resourcegroups/observability/providers/microsoft.monitor/accounts/observability" GF_WORKSPACE="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/observability/providers/Microsoft.Dashboard/grafana/gfdashboards" az extension add --name aks-preview az extension update --name aks-preview echo "deploying into subscription $SUBSCRIPTION_ID" if [ $(az group exists --name $KUBE_GROUP) = false ]; then echo "creating resource group $KUBE_GROUP..." az group create -n $KUBE_GROUP -l $LOCATION -o none echo "resource group $KUBE_GROUP created" else echo "resource group $KUBE_GROUP already exists" fi SECRET_NAME="mySecret" VAULT_ID=$(az keyvault list -g $KUBE_GROUP --query "[?contains(name, '$VAULT_NAME')].id" -o tsv) if [ "$VAULT_ID" == "" ]; then echo "creating keyvault $VAULT_NAME" az keyvault create -g $KUBE_GROUP -n $VAULT_NAME -l $LOCATION -o none az keyvault secret set -n $SECRET_NAME --vault-name $VAULT_NAME --value MySuperSecretThatIDontWantToShareWithYou! -o none VAULT_ID=$(az keyvault show -g $KUBE_GROUP -n $VAULT_NAME -o tsv --query id) echo "created keyvault $VAULT_ID" else echo "keyvault $VAULT_ID already exists" VAULT_ID=$(az keyvault show -g $KUBE_GROUP -n $VAULT_NAME -o tsv --query name) fi echo "setting up vnet" VNET_RESOURCE_ID=$(az network vnet list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_VNET_NAME')].id" -o tsv) if [ "$VNET_RESOURCE_ID" == "" ]; then echo "creating vnet $KUBE_VNET_NAME..." az network vnet create --address-prefixes "10.$VNET_PREFIX.0.0/19" -g $KUBE_GROUP -n $KUBE_VNET_NAME -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $BASTION_SUBNET_NAME --address-prefix 10.$VNET_PREFIX.0.0/24 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_API_SUBNET_NAME --address-prefix 10.$VNET_PREFIX.1.0/24 --delegations Microsoft.ContainerService/managedClusters -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_FW_SUBNET_NAME --address-prefix 10.$VNET_PREFIX.3.0/24 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $APPGW_SUBNET_NAME --address-prefix 10.$VNET_PREFIX.2.0/24 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.$VNET_PREFIX.4.0/23 --delegations Microsoft.ServiceNetworking/trafficControllers -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.$VNET_PREFIX.6.0/23 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $POD_AGENT_SUBNET_NAME --address-prefix 10.$VNET_PREFIX.8.0/22 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $ACI_AGENT_SUBNET_NAME --address-prefix 10.$VNET_PREFIX.16.0/20 -o none VNET_RESOURCE_ID=$(az network vnet show -g $KUBE_GROUP -n $KUBE_VNET_NAME --query id -o tsv) echo "created $VNET_RESOURCE_ID" else echo "vnet $VNET_RESOURCE_ID already exists" fi NSG_RESOURCE_ID=$(az network nsg list -g $KUBE_GROUP --query "[?contains(name, '$POD_AGENT_SUBNET_NSG')].id" -o tsv) if [ "$NSG_RESOURCE_ID" == "" ]; then echo "creating nsgs..." az network nsg create --name $APPGW_SUBNET_NAME --resource-group $KUBE_GROUP --location $LOCATION APPGW_SUBNET_NSG=$(az network nsg show -g $KUBE_GROUP -n $APPGW_SUBNET_NAME --query id -o tsv) APPGW_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $APPGW_SUBNET_NAME --query id -o tsv) az network nsg rule create --name appgwrule --nsg-name $APPGW_SUBNET_NAME --resource-group $KUBE_GROUP --priority 110 \ --source-address-prefixes '*' --source-port-ranges '*' \ --destination-address-prefixes '*' --destination-port-ranges '*' --access Allow --direction Inbound \ --protocol "*" --description "Required allow rule for AppGW." az network vnet subnet update --resource-group $KUBE_GROUP --network-security-group $APPGW_SUBNET_NSG --ids $APPGW_SUBNET_ID #az lock create --name $APPGW_SUBNET_NAME --lock-type ReadOnly --resource-group $KUBE_GROUP --resource-name $APPGW_SUBNET_NAME --resource-type Microsoft.Network/networkSecurityGroups az network nsg create --name $KUBE_ING_SUBNET_NAME --resource-group $KUBE_GROUP --location $LOCATION az network nsg rule create --name appgwrule --nsg-name $KUBE_ING_SUBNET_NAME --resource-group $KUBE_GROUP --priority 110 \ --source-address-prefixes '*' --source-port-ranges '*' \ --destination-address-prefixes '*' --destination-port-ranges 80 443 3443 6390 --access Allow --direction Inbound \ --protocol "*" --description "Required allow rule for APIM." KUBE_ING_SUBNET_NSG=$(az network nsg show -g $KUBE_GROUP -n $KUBE_ING_SUBNET_NAME --query id -o tsv) KUBE_ING_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --query id -o tsv) #az network vnet subnet update --resource-group $KUBE_GROUP --network-security-group $KUBE_ING_SUBNET_NSG --ids $KUBE_ING_SUBNET_ID #az lock create --name $KUBE_ING_SUBNET_NAME --lock-type ReadOnly --resource-group $KUBE_GROUP --resource-name $KUBE_ING_SUBNET_NAME --resource-type Microsoft.Network/networkSecurityGroups az network nsg create --name $KUBE_AGENT_SUBNET_NAME --resource-group $KUBE_GROUP --location $LOCATION az network nsg rule create --name ingress --nsg-name $KUBE_AGENT_SUBNET_NAME --resource-group $KUBE_GROUP --priority 110 \ --source-address-prefixes '*' --source-port-ranges '*' \ --destination-address-prefixes '*' --destination-port-ranges 80 443 --access Allow --direction Inbound \ --protocol "*" --description "Required to allow ingress." KUBE_AGENT_SUBNET_NSG=$(az network nsg show -g $KUBE_GROUP -n $KUBE_AGENT_SUBNET_NAME --query id -o tsv) KUBE_AGENT_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --query id -o tsv) az network vnet subnet update --resource-group $KUBE_GROUP --network-security-group $KUBE_AGENT_SUBNET_NSG --ids $KUBE_AGENT_SUBNET_ID #az lock create --name $KUBE_AGENT_SUBNET_NAME --lock-type ReadOnly --resource-group $KUBE_GROUP --resource-name $KUBE_AGENT_SUBNET_NAME --resource-type Microsoft.Network/networkSecurityGroups az network nsg create --name $POD_AGENT_SUBNET_NAME --resource-group $KUBE_GROUP --location $LOCATION POD_AGENT_SUBNET_NSG=$(az network nsg show -g $KUBE_GROUP -n $POD_AGENT_SUBNET_NAME --query id -o tsv) POD_AGENT_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $POD_AGENT_SUBNET_NAME --query id -o tsv) az network vnet subnet update --resource-group $KUBE_GROUP --network-security-group $POD_AGENT_SUBNET_NSG --ids $POD_AGENT_SUBNET_ID #az lock create --name $POD_AGENT_SUBNET_NAME --lock-type ReadOnly --resource-group $KUBE_GROUP --resource-name $POD_AGENT_SUBNET_NAME --resource-type Microsoft.Network/networkSecurityGroups echo "cread and locked nsgs " else echo "nsg $NSG_RESOURCE_ID already exists" fi ROUTE_TABLE_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --query routeTable.id -o tsv) KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" KUBE_POD_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$POD_AGENT_SUBNET_NAME" KUBE_API_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_API_SUBNET_NAME" KUBE_ING_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --query id -o tsv) if [ "$ROUTE_TABLE_ID" == "" ]; then echo "could not find routetable on AKS subnet $KUBE_AGENT_SUBNET_ID" else echo "using routetable $ROUTE_TABLE_ID with the following entries" ROUTE_TABLE_GROUP=$(az network route-table show --ids $ROUTE_TABLE_ID --query "[resourceGroup]" -o tsv) ROUTE_TABLE_NAME=$(az network route-table show --ids $ROUTE_TABLE_ID --query "[name]" -o tsv) echo "if this routetable does not contain a route for '0.0.0.0/0' with target VirtualAppliance or VirtualNetworkGateway then we will not need the outbound type parameter" az network route-table route list --resource-group $ROUTE_TABLE_GROUP --route-table-name $ROUTE_TABLE_NAME -o table echo "if it does not contain a '0.0.0.0/0' route then you should set the parameter IGNORE_FORCE_ROUTE=true" if [ "$IGNORE_FORCE_ROUTE" == "true" ]; then echo "ignoring forced tunneling route information" OUTBOUNDTYPE="" else echo "using forced tunneling route information" OUTBOUNDTYPE=" --outbound-type userDefinedRouting " fi fi echo "setting up controller identity" AKS_CONTROLLER_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-ctl-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-clt-id')].id" -o tsv)" if [ "$AKS_CONTROLLER_RESOURCE_ID" == "" ]; then echo "creating controller identity $KUBE_NAME-ctl-id in $KUBE_GROUP" az identity create --name $KUBE_NAME-ctl-id --resource-group $KUBE_GROUP -o none sleep 10 # wait for replication AKS_CONTROLLER_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-ctl-id --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-ctl-id --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 20 # wait for replication AKS_CONTROLLER_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-ctl-id --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-ctl-id --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 20 # wait for replication az role assignment create --role "Network Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none az role assignment create --role "Network Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_API_SUBNET_ID -o none az role assignment create --role "Network Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_ING_SUBNET_ID -o none if [ "$ROUTE_TABLE_ID" == "" ]; then echo "no route table used" else echo "assigning permissions on routetable $ROUTE_TABLE_ID" az role assignment create --role "Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $ROUTE_TABLE_ID -o none fi else echo "controller identity $AKS_CONTROLLER_RESOURCE_ID already exists" echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" az role assignment create --role "Network Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none az role assignment create --role "Network Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_API_SUBNET_ID -o none az role assignment create --role "Network Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_ING_SUBNET_ID -o none if [ "$ROUTE_TABLE_ID" == "" ]; then echo "no route table used" else echo "assigning permissions on routetable $ROUTE_TABLE_ID" az role assignment create --role "Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $ROUTE_TABLE_ID -o none fi fi echo "setting up kubelet identity" AKS_KUBELET_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-kbl-id')].clientId" -o tsv)" AKS_KUBELET_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-kbl-id')].id" -o tsv)" if [ "$AKS_KUBELET_CLIENT_ID" == "" ]; then echo "creating kubelet identity $KUBE_NAME-kbl-id in $KUBE_GROUP" az identity create --name $KUBE_NAME-kbl-id --resource-group $KUBE_GROUP -o none sleep 5 # wait for replication AKS_KUBELET_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-kbl-id --query clientId -o tsv)" AKS_KUBELET_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-kbl-id --query id -o tsv)" echo "created kubelet identity $AKS_KUBELET_RESOURCE_ID " sleep 25 # wait for replication AKS_KUBELET_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-kbl-id --query clientId -o tsv)" AKS_KUBELET_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-kbl-id --query id -o tsv)" echo "created kubelet identity $AKS_KUBELET_RESOURCE_ID " echo "assigning permissions on keyvault $VAULT_ID" az keyvault set-policy -n $VAULT_NAME --object-id $AKS_KUBELET_CLIENT_ID --key-permissions get --certificate-permissions get --secret-permissions get -o none else echo "kubelet identity $AKS_KUBELET_RESOURCE_ID already exists" echo "assigning permissions on keyvault $VAULT_ID" az keyvault set-policy -n $VAULT_NAME --object-id $AKS_KUBELET_CLIENT_ID --key-permissions get --certificate-permissions get --secret-permissions get -o none fi echo "setting up aks" AKS_ID=$(az aks list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$USE_PRIVATE_API" == "true" ]; then ACTIVATE_PRIVATE_LINK=" --enable-private-cluster --enable-apiserver-vnet-integration --apiserver-subnet-id $KUBE_API_SUBNET_ID " else ACTIVATE_PRIVATE_LINK="" fi # enable-overlay-mode", "true echo "setting up aks" AKS_ID=$(az aks list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$AKS_ID" == "" ]; then echo "creating AKS $KUBE_NAME in $KUBE_GROUP" echo "using host subnet $KUBE_AGENT_SUBNET_ID" if [ "$USE_OVERLAY" == "true" ]; then echo "using overlay subnet $KUBE_POD_SUBNET_ID" az aks create --enable-network-observability --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --ssh-key-value ~/.ssh/id_rsa.pub --node-count 2 --min-count 2 --max-count 5 --enable-cluster-autoscaler --node-resource-group $NODE_GROUP --load-balancer-sku standard --vm-set-type VirtualMachineScaleSets --network-plugin azure --network-plugin-mode overlay --pod-cidr 172.16.31.10/10 --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --assign-identity $AKS_CONTROLLER_RESOURCE_ID --enable-managed-identity --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --node-vm-size "standard_d4s_v5" --aad-tenant-id $TENANT_ID $USE_CILIUM -o none else if [ "$USE_POD_SUBNET" == "true" ]; then echo "using pod subnet $KUBE_POD_SUBNET_ID" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --ssh-key-value ~/.ssh/id_rsa.pub --node-count 2 --min-count 2 --max-count 5 --enable-cluster-autoscaler --node-resource-group $NODE_GROUP --load-balancer-sku standard --vm-set-type VirtualMachineScaleSets --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --assign-identity $AKS_CONTROLLER_RESOURCE_ID --node-osdisk-size 300 --enable-managed-identity --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $TENANT_ID --pod-subnet-id $KUBE_POD_SUBNET_ID $ACTIVATE_PRIVATE_LINK $USE_CILIUM --node-vm-size "Standard_D4s_v3" -o none else az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --ssh-key-value ~/.ssh/id_rsa.pub --node-count 2 --min-count 2 --max-count 3 --enable-cluster-autoscaler --node-resource-group $NODE_GROUP --load-balancer-sku standard --vm-set-type VirtualMachineScaleSets --network-plugin $KUBE_CNI_PLUGIN --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.3.0.10 --service-cidr 10.3.0.0/24 --kubernetes-version $KUBE_VERSION --assign-identity $AKS_CONTROLLER_RESOURCE_ID --node-osdisk-size 300 --enable-managed-identity --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $TENANT_ID $ACTIVATE_PRIVATE_LINK --node-osdisk-size 300 --node-vm-size "Standard_B2ms" -o none fi fi sleep 10 # az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --ssh-key-value ~/.ssh/id_rsa.pub --zones 1 2 3 --node-count 3 --node-vm-size "Standard_D2s_v3" --min-count 3 --max-count 5 --enable-cluster-autoscaler --auto-upgrade-channel patch --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --assign-identity $AKS_CONTROLLER_RESOURCE_ID --assign-kubelet-identity $AKS_KUBELET_RESOURCE_ID --node-osdisk-size 300 --enable-managed-identity --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $TENANT_ID $ACTIVATE_PRIVATE_LINK -o none AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query id -o tsv) echo "created AKS $AKS_ID" az aks update -n $KUBE_NAME -g $KUBE_GROUP --enable-oidc-issuer --enable-workload-identity --yes else echo "AKS $AKS_ID already exists" az aks mesh enable --resource-group ${KUBE_GROUP} --name ${KUBE_NAME} az aks mesh enable-ingress-gateway --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --ingress-gateway-type external #az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="azure-keyvault-secrets-provider" #az aks update --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --enable-secret-rotation --yes #az aks update --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --syncSecret.enabled --yes #az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="open-service-mesh" #az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="web_application_routing" --dns-zone-resource-id $DNS_ID #az aks update --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --enable-keda --yes az aks update -n $KUBE_NAME -g $KUBE_GROUP --enable-oidc-issuer --enable-workload-identity --yes #az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="virtual-node" --subnet-name $ACI_AGENT_SUBNET_NAME #az aks nodepool add --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --name mywasipool --node-count 1 --workload-runtime WasmWasi #az aks nodepool add --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --name ociwasmpool --node-count 1 --workload-runtime ocicontainer #az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="azure-keyvault-secrets-provider" #az aks update --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --enable-secret-rotation --yes #az aks update --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --syncSecret.enabled --yes #az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="open-service-mesh" #az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="web_application_routing" --dns-zone-resource-id $DNS_ID #az aks update --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --enable-keda --yes #az aks update --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --enable-image-cleaner --yes #az aks upgrade -n $KUBE_NAME -g $KUBE_GROUP --aks-custom-headers EnableCloudControllerManager=True #az aks nodepool add --scale-down-mode Deallocate --node-count 2 --name marinerpool2 --cluster-name $KUBE_NAME --resource-group $KUBE_GROUP --os-sku CBLMariner # az aks maintenanceconfiguration add -g $KUBE_GROUP --cluster-name $KUBE_NAME --name tuesday --weekday Tuesday --start-hour 13 # az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME --name strpool1 --node-count 3 --mode user --node-vm-size standard_d4s_v5 # az aks nodepool update --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --name strpool1 --labels acstor.azure.com/io-engine=acstor #az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME --name armpool --node-count 2 --mode system --node-vm-size Standard_D4ps_v5 --pod-subnet-id $KUBE_POD_SUBNET_ID #az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME --name one --node-count 1 --mode system --node-vm-size Standard_B2ms --pod-subnet-id $KUBE_POD_SUBNET_ID #az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME --name mariner22 --node-count 2 --mode system --node-vm-size Standard_D2s_v3 --pod-subnet-id $KUBE_POD_SUBNET_ID --os-sku CBLMariner #az aks update -g $KUBE_GROUP --name $KUBE_NAME --enable-apiserver-vnet-integration --apiserver-subnet-id $KUBE_API_SUBNET_ID #az aks update --resource-group $KUBE_GROUP --name $KUBE_NAME --auto-upgrade-channel rapid --yes #az aks nodepool update --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --name nodepool1 --labels acstor.azure.com/io-engine=acstor #az k8s-extension create --cluster-type managedClusters --cluster-name $KUBE_NAME --resource-group $KUBE_GROUP --name azurecontainerstorage --extension-type microsoft.azurecontainerstorage --scope cluster --release-train prod --release-namespace acstor fi echo "setting up azure monitor" az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME --admin --overwrite-existing export AZURE_CORE_USE_COMMAND_INDEX=False WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace list --resource-group $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$WORKSPACE_RESOURCE_ID" == "" ]; then echo "creating workspace $KUBE_NAME in $KUBE_GROUP" az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --location $LOCATION -o none WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME -o json | jq '.id' -r) az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --enable-msi-auth-for-monitoring --addons monitoring --workspace-resource-id $WORKSPACE_RESOURCE_ID az aks update --enable-azure-monitor-metrics --resource-group $KUBE_GROUP --name $KUBE_NAME --azure-monitor-workspace-resource-id $PROM_RESOURCE_ID --grafana-resource-id $GF_WORKSPACE #OMS_CLIENT_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query addonProfiles.omsagent.identity.clientId -o tsv) #az role assignment create --assignee $OMS_CLIENT_ID --scope $AKS_ID --role "Monitoring Metrics Publisher" az monitor app-insights component create --app $KUBE_NAME-ai --location $LOCATION --resource-group $KUBE_GROUP --application-type web --kind web --workspace $WORKSPACE_RESOURCE_ID az monitor log-analytics workspace table update --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --name ContainerLogV2 --plan Basic kubectl apply -f logging/container-azm-ms-agentconfig-v2.yaml fi # az aks nodepool add --node-count 1 --scale-down-mode Deallocate --node-osdisk-type Managed --max-pods 30 --mode System --name nodepool2 --cluster-name $KUBE_NAME --resource-group $KUBE_GROUP az aks update --disable-defender --resource-group $KUBE_GROUP --name $KUBE_NAME echo "created this AKS cluster:" # az aks update -n $KUBE_NAME -g $KUBE_GROUP --nrg-lockdown-restriction-level ReadOnly az aks show --resource-group=$KUBE_GROUP --name=$KUBE_NAME <file_sep># Install istio https://istio.io/latest/docs/setup/getting-started/#download ``` curl -L https://git.io/getLatestIstio | sh - export PATH="$PATH:/Users/dennis/lib/istio-1.8.0/bin" https://istio.io/docs/setup/kubernetes/helm-install/ helm template install/kubernetes/helm/istio --name istio --namespace istio-system > $HOME/istio.yaml helm template install/kubernetes/helm/istio --name istio --namespace istio-system --set sidecarInjectorWebhook.enabled=false > $HOME/istio.yaml kubectl -n istio-system port-forward $(kubectl -n istio-system get pod -l app=grafana -o jsonpath='{.items[0].metadata.name}') 3000:3000 & kubectl label namespace default istio-injection=enabled kubectl label namespace calculator istio-injection=disabled kubernetes.azure.com/mode=system kubectl patch deployment istio-egressgateway -n istio-system -p \ '{"spec":{"template":{"spec":{"nodeSelector":[{"kubernetes.azure.com/mode":"system"}]}}}}' ``` ## Install grafana dashboard https://istio.io/docs/tasks/telemetry/using-istio-dashboard/ ``` kubectl -n default port-forward $(kubectl -n default get pod -l app=vistio-api -o jsonpath='{.items[0].metadata.name}') 9091:9091 & http://localhost:9091/graph kubectl -n default port-forward $(kubectl -n default get pod -l app=vistio-web -o jsonpath='{.items[0].metadata.name}') 8080:8080 & http://localhost:8080 kubectl -n istio-system port-forward $(kubectl -n istio-system get \ pod -l app=grafana -o jsonpath='{.items[0].metadata.name}') 3000:3000 & kubectl apply --record -f <(istioctl kube-inject -f ./full-deply.yaml) cat <<EOF | istioctl create -f - apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: front-virtual-service spec: hosts: - "*" gateways: - front-gateway http: - match: - uri: prefix: /app/front route: - destination: host: calc-frontend-svc EOF cat <<EOF | istioctl create -f - apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: reviews spec: hosts: - reviews http: - route: - destination: host: reviews subset: v1 weight: 75 - destination: host: reviews subset: v2 weight: 25 EOF cat <<EOF | istioctl create -f - apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: front-gateway spec: selector: istio: ingressgateway # use istio default controller servers: - port: number: 80 name: http protocol: HTTP hosts: - "*" EOF cat <<EOF | istioctl create -f - apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: delay-calc spec: hosts: - calc-backend-svc http: - fault: delay: fixedDelay: 7s percent: 100 match: - headers: number: regex: ^(.*?)?(.*7.*)(.*)?$ route: - destination: host: calc-backend-svc - route: - destination: host: calc-backend-svc EOF kubectl apply -f https://raw.githubusercontent.com/CSA-OCP-GER/unicorn/master/hints/yaml/challenge-istio/base-sample-app.yaml helm install install/kubernetes/helm/istio --name istio --namespace istio-system --values install/kubernetes/helm/istio/values.yaml kubectl get po -n istio-system kubectl port-forward grafana-749c78bcc5-mrw8f 3000:3000 -n istio-system KIALI_USERNAME=$(read '?Kiali Username: ' uval && echo -n $uval | base64) KIALI_PASSPHRASE=$(read -s "?Kiali Passphrase: " pval && echo -n $pval | base64) NAMESPACE=istio-system cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Secret metadata: name: kiali namespace: $NAMESPACE labels: app: kiali type: Opaque data: username: $KIALI_USERNAME passphrase: <PASSWORD> EOF kubectl port-forward kiali-68677d47d7-hdpfq 20001:20001 -n istio-system kubectl --namespace istio-system port-forward $(kubectl get pod --namespace istio-system -l app=kiali -o template --template "{{(index .items 0).metadata.name}}") 20001:20001 kubectl apply -f https://raw.githubusercontent.com/CSA-OCP-GER/unicorn/master/hints/yaml/challenge-istio/request-routing/c2-ingress-rr.yaml kubectl delete -f https://raw.githubusercontent.com/CSA-OCP-GER/unicorn/master/hints/yaml/challenge-istio/faultinjection/c2-ingress-rr-faulty-delay.yaml kubectl apply -f https://raw.githubusercontent.com/CSA-OCP-GER/unicorn/master/hints/yaml/challenge-istio/faultinjection/c2-error-frontend.yaml kubectl apply -f https://raw.githubusercontent.com/CSA-OCP-GER/unicorn/master/hints/yaml/challenge-istio/faultinjection/c2-ingress-rr-faulty-error.yaml kubectl delete -f https://raw.githubusercontent.com/CSA-OCP-GER/unicorn/master/hints/yaml/challenge-istio/faultinjection/c2-ingress-rr-faulty-error.yaml ``` ## Istio 1.4.3 ``` mkdir istio-1.4.3 ISTIO_VERSION=1.4.3 cd istio-1.4.3 curl -sL "https://github.com/istio/istio/releases/download/$ISTIO_VERSION/istio-$ISTIO_VERSION-osx.tar.gz" | tar xz\n GRAFANA_USERNAME=$(echo -n "grafana" | base64) GRAFANA_PASSPHRASE=$(echo -n "REPLACE_WITH_YOUR_SECURE_PASSWORD" | base64) cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Secret metadata: name: grafana namespace: istio-system labels: app: grafana type: Opaque data: username: $GRAFANA_USERNAME passphrase: <PASSWORD> EOF KIALI_USERNAME=$(echo -n "kiali" | base64) KIALI_PASSPHRASE=$(echo -n "REPLACE_WITH_YOUR_SECURE_PASSWORD" | base64) cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Secret metadata: name: kiali namespace: istio-system labels: app: kiali type: Opaque data: username: $KIALI_USERNAME passphrase: $<PASSWORD> EOF cd istio-$ISTIO_VERSION\nsudo cp ./bin/istioctl /usr/local/bin/istioctl\nsudo chmod +x /usr/local/bin/istioctl helm repo add istio.io https://storage.googleapis.com/istio-release/releases/$ISTIO_VERSION/charts/\nhelm repo update install crds helm upgrade istio-init istio.io/istio-init --install --namespace istio-system check for crds kubectl get crds | grep 'istio.io' | wc -l install istio helm upgrade istio istio.io/istio --install --namespace istio-system --version $ISTIO_VERSION \ --set global.controlPlaneSecurityEnabled=true \ --set global.mtls.enabled=true \ --set grafana.enabled=true --set grafana.security.enabled=true \ --set tracing.enabled=true \ --set kiali.enabled=true \ --set global.defaultNodeSelector."beta\.kubernetes\.io/os"=linux add injection kubectl label namespace default istio-injection=enabled check kubectl get namespace -L istio-injection kubectl get svc --namespace istio-system --output wide https://jimmysong.io/en/posts/understanding-how-envoy-sidecar-intercept-and-route-traffic-in-istio-service-mesh/ https://istio.io/docs/examples/bookinfo/ deploy sample app kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml curl productpage kubectl exec -it $(kubectl get pod -l app=ratings -o jsonpath='{.items[0].metadata.name}') -c ratings -- curl productpage:9080/productpage | grep -o "<title>.*</title>" <title>Simple Bookstore App</title> kubectl apply -f samples/bookinfo/networking/bookinfo-gateway.yaml kubectl get svc istio-ingressgateway -n istio-system export INGRESS_HOST=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') export INGRESS_PORT=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="http2")].port}') export SECURE_INGRESS_PORT=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="https")].port}') export GATEWAY_URL=$INGRESS_HOST:$INGRESS_PORT curl -s http://${GATEWAY_URL}/productpage | grep -o "<title>.*</title>" set destination rules kubectl apply -f samples/bookinfo/networking/destination-rule-all.yaml ``` ## Egress gateway ``` meshConfig.outboundTrafficPolicy.mode istioctl install <flags-you-used-to-install-Istio> \ --set meshConfig.outboundTrafficPolicy.mode=REGISTRY_ONLY cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF [root@centos /]# curl app.azuredns.com:8080/ip {"realip":"172.16.0.180","remoteaddr":"172.16.0.180","remoteip":"172.16.0.180"} app.azuredns.com:8080/ip kubectl delete serviceentry azuredns kubectl delete gateway istio-egressgateway kubectl delete virtualservice direct-cnn-through-egress-gateway kubectl delete destinationrule egressgateway-for-cnn kubectl apply -f - <<EOF apiVersion: networking.istio.io/v1alpha3 kind: ServiceEntry metadata: name: azuredns spec: hosts: - app.azuredns.com ports: - number: 80 name: http protocol: HTTP resolution: DNS EOF kubectl apply -f - <<EOF apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: istio-egressgateway spec: selector: istio: egressgateway servers: - port: number: 8080 name: http protocol: HTTP hosts: - app.azuredns.com --- apiVersion: networking.istio.io/v1alpha3 kind: DestinationRule metadata: name: egressgateway-for-cnn spec: host: istio-egressgateway.istio-system.svc.cluster.local subsets: - name: azuredns --- apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: direct-cnn-through-egress-gateway spec: hosts: - app.azuredns.com gateways: - mesh - istio-egressgateway http: - match: - gateways: - mesh route: - destination: host: istio-egressgateway.istio-system.svc.cluster.local subset: azuredns port: number: 8080 - match: - gateways: - istio-egressgateway route: - destination: host: app.azuredns.com port: number: 8080 weight: 100 EOF kubectl apply -f - <<EOF kind: Service apiVersion: v1 metadata: name: my-httpbin spec: type: ExternalName externalName: httpbin.org ports: - name: http protocol: TCP port: 80 EOF kubectl apply -f - <<EOF apiVersion: networking.istio.io/v1alpha3 kind: DestinationRule metadata: name: my-httpbin spec: host: my-httpbin.default.svc.cluster.local trafficPolicy: tls: mode: DISABLE EOF kubectl apply -f - <<EOF apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: istio-egressgateway spec: selector: istio: egressgateway servers: - port: number: 80 name: http protocol: HTTP hosts: - app.azuredns.com --- apiVersion: networking.istio.io/v1alpha3 kind: DestinationRule metadata: name: egressgateway-for-cnn spec: host: istio-egressgateway.istio-system.svc.cluster.local subsets: - name: azuredns EOF kubectl apply -f - <<EOF apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: direct-cnn-through-egress-gateway spec: hosts: - app.azuredns.com gateways: - istio-egressgateway - mesh http: - match: - gateways: - mesh port: 80 route: - destination: host: istio-egressgateway.istio-system.svc.cluster.local subset: azuredns port: number: 80 weight: 100 - match: - gateways: - istio-egressgateway port: 80 route: - destination: host: app.azuredns.com port: number: 80 weight: 100 EOF kubectl logs -l istio=egressgateway -c istio-proxy -n istio-system | tail ``` ➜ ~ (⎈ |dzvnets:default) kubectl exec -ti centos -- /bin/bash Defaulting container name to centos. Use 'kubectl describe pod/centos -n default' to see all of the containers in this pod. [root@centos /]# curl app.azuredns.com/ip {"realip":"10.0.5.35","remoteaddr":"10.0.5.35","remoteip":"10.0.5.35"} [root@centos /]# exit exit ➜ ~ (⎈ |dzvnets:default) kubectl logs -l istio=egressgateway -c istio-proxy -n istio-system | tail 2020-11-23T17:15:54.429430Z info sds Skipping waiting for gateway secret 2020-11-23T17:15:54.429461Z info cache Loaded root cert from certificate ROOTCA 2020-11-23T17:15:54.429698Z info sds resource:ROOTCA pushed root cert to proxy 2020-11-23T17:15:56.021434Z info Envoy proxy is ready [2020-11-23T17:42:48.178Z] "- - -" 0 - "-" "-" 906 1302575 56 - "-" "-" "-" "-" "172.16.58.3:443" outbound|443||edition.cnn.com 10.0.5.36:43256 10.0.5.36:8443 172.16.0.173:33606 edition.cnn.com - 2020-11-23T17:48:34.633000Z warning envoy config StreamAggregatedResources gRPC config stream closed: 13, 2020-11-23T18:19:01.780475Z warning envoy config StreamAggregatedResources gRPC config stream closed: 13, 2020-11-23T18:49:28.622501Z warning envoy config StreamAggregatedResources gRPC config stream closed: 13, 2020-11-23T19:19:35.472602Z warning envoy config StreamAggregatedResources gRPC config stream closed: 13, [2020-11-23T19:28:26.170Z] "GET /ip HTTP/2" 200 - "-" "-" 0 71 6 6 "172.16.0.173" "curl/7.61.1" "789cbf9c-cb21-9fd8-b9c8-44acc00232e3" "app.azuredns.com" "10.240.0.4:80" outbound|80||app.azuredns.com 10.0.5.36:60168 10.0.5.36:8080 172.16.0.173:36988 - - ➜ ~ (⎈ |dzvnets:default) kubectl get pod -n istio-system -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES istio-egressgateway-5dd8975cb-h262m 1/1 Running 0 133m 10.0.5.36 aks-nodepool1-38665453-vmss000001 <none> <none> istio-ingressgateway-76447f8f85-6kgg9 1/1 Running 0 143m 172.16.0.138 aks-router-38665453-vmss000001 <none> <none> istiod-75c5776d98-hwdxx 1/1 Running 0 159m 172.16.0.182 aks-router-38665453-vmss000002 <none> <none> https://preliminary.istio.io/latest/blog/2018/egress-mongo/ https://github.com/istio/istio/issues/26772 <file_sep># Common issues ## New version of azure cli does not work with az aks browse or aks get credentials 'ManagedCluster' object has no attribute 'properties' Downgrade azure cli to working version ``` WORKING_VERSION=2.0.23-1 sudo apt-get install azure-cli=$WORKING_VERSION ``` ## Get latest supported version ``` LOCATION='westeurope' az aks get-versions -l $LOCATION --query "orchestrators[?default == `true` && isPreview == `null`].orchestratorVersion" --output tsv az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv ``` ## Edit using NANO ``` KUBE_EDITOR="nano" kubectl edit svc/nginxpod-service KUBE_EDITOR="nano" kubectl -n kube-system edit cm kube-proxy export KUBE_EDITOR='code --wait' kubectl edit deployment dummy -n dnamespace ``` ## NIC in failed state reset nic via cli ``` az network nic update -g MC_* -n aks-nodepool1-*-nic-0 ``` ## Check if your cluster has RBAC ``` kubectl cluster-info dump --namespace kube-system | grep authorization-mode ``` ## Get Image Version of nodes ``` az aks nodepool get-upgrades --nodepool-name default --cluster-name $KUBE_NAME --resource-group $KUBE_GROUP -o table az aks get-upgrades --resource-group $KUBE_GROUP --name $KUBE_NAME --output table kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.metadata.labels.kubernetes\.azure\.com\/node-image-version}{"\n"}{end}' az aks upgrade --resource-group $KUBE_GROUP --name $KUBE_NAME --node-image-only ``` ## Find out source ip ``` curl ipinfo.io/ip kubectl run azure-function-on-kubernetes --image=denniszielke/az-functions --port=80 --requests=cpu=100m kubectl expose deployment azure-function-on-kubernetes --type=LoadBalancer kubectl autoscale deploy azure-function-on-kubernetes --cpu-percent=20 --max=10 --min=1 apk add --update curl export num=0 && while true; do curl -s -w "$num = %{time_namelookup}" "time nslookup google.com"; echo ""; num=$((num+1)); done kubectl run alp --image=alpine:3.6 kubectl run alp --image=quay.io/collectai/alpine-curl docker run --rm jess/curl -sSL ipinfo.io/ip while true; do kubectl get pod -A -o wide ; done ``` ## Steps how to attach public IP to a worker node find out the resource group that AKS created for the node VMs az group list -o table list resources in the group and find the VM you want to access az resource list -g MC_kubernetes_kubernetes-cluster_ukwest -o table show parameters of that VM, see for example: "adminUsername": "azureuser" az vm show -g aks-default-10832236-0 -n aks-default-10832236-0 create the public IP az network public-ip create -g MC_kub_ter_k_m_iuasdf_iuasdf_westeurope -n test-ip find out correct NIC where to add the public IP az network nic list -g MC_kub_ter_k_m_iuasdf_iuasdf_westeurope -o table find out the name of the ipconfig within that NIC az network nic ip-config list --nic-name aks-default-10832236-nic-0 -g MC_kub_ter_k_m_iuasdf_iuasdf_westeurope modify the ipconfig by adding the public IP address az network nic ip-config update -g MC_kub_ter_k_m_iuasdf_iuasdf_westeurope --nic-name aks-default-10832236-nic-0 --name ipconfig1 --public-ip-address test-ip find out what the allocated public IP address is az network public-ip show -g MC_kubernetes_kubernetes-cluster_ukwest -n test-ip then finally connect with SSH ssh azureuser@<public ip address> delete containers kubectl delete pod -n kube-system --selector "component=kube-proxy" enumerate all service principals for all clusters az aks list --query '[].{Name:name, ClientId:servicePrincipalProfile.clientId, MsiId:identity.principalId}' -o table kubectl patch deployment myapp-deployment -p \ '{"spec":{"template":{"spec":{"containers":[{"name":"myapp","image":"172.20.34.206:5000/myapp:img:3.0"}]}}}}' kubectl patch deployment myapp-deployment -p \ '{"spec":{"template":{"spec":{"tolerations":[{"key":"expensive","operator":"Equal","value":"true","effect":"NoSchedule"}]}}}}' ``` cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: curl spec: containers: - name: curl image: jess/curl args: ["-sSL", "ipinfo.io/ip"] EOF kubectl logs curl ``` kubectl exec runclient -- bash -c "date && \ echo 1 && \ echo 2" kubectl exec alpclient -- bash -c "var=1 && \ while true ; do && \ res=$( { curl -o /dev/null -s -w %{time_namelookup}\\\\n http://www.google.com; } 2>&1 ) && \ var=$((var+1)) && \ if [[ $res =~ ^[1-9] ]]; then && \ now=$(date +'%T') && \ echo '$var slow: $res $now' && \ break && \ fi && \ done" kubectl get pods |grep runclient|cut -f1 -d\ |\ while read pod; \ do echo "$pod writing:";\ kubectl exec -t $pod -- bash -c \ var=1 \ while true ; do \ res=$( { curl -o /dev/null -s -w %{time_namelookup}\\n http://www.google.com; } 2>&1 ) \ var=$((var+1)) \ if [[ $res =~ ^[1-9] ]]; then \ now=$(date +"%T") \ echo "$var slow: $res $now" \ break \ fi \ done \ done var=1; while true ; do res=$( { curl -o /dev/null -s -w %{time_namelookup}\\n http://nginx; } 2>&1 ) var=$((var+1)) now=$(date +"%T") echo "$var slow: $res $now" if [[ $res =~ ^[1-9] ]]; then now=$(date +"%T") echo "$var slow: $res $now" break fi done var=1; while true ; do res=$( { curl -o /dev/null -s -w %{time_namelookup}\\n http://www.google.com; } 2>&1 ) var=$((var+1)) now=$(date +"%T") echo "$var slow: $res $now" done for i in `seq 1 1000`; do time curl -s google.com > /dev/null; done kubectl run -i --tty busybox --image=busybox --restart=Never -- sh scp /path/to/file username@a:/path/to/destination scp username@b:/path/to/file /path/to/destination scp dennis@172.16.31.10:/var/log/azure/cluster-provision.log cluster-provision.log scp dennis@172.16.31.10:/var/log/cloud-init-output.log cloud-init-output.log scp ~/.ssh/id_rsa <EMAIL>:/.ssh chmod 400 ~/.ssh/id_rsa ssh dennis@10.240.0.4 -i ~/.ssh/id_rsa CLUSTER_RESOURCE_GROUP=$(az aks show --resource-group security --name slbrouter --query nodeResourceGroup -o tsv) az vmss extension set \ --resource-group $CLUSTER_RESOURCE_GROUP \ --vmss-name $SCALE_SET_NAME \ --name VMAccessForLinux \ --publisher Microsoft.OSTCExtensions \ --version 1.4 \ --protected-settings "{\"username\":\"dennis\", \"ssh_key\":\"$(cat ~/.ssh/id_rsa.pub)\"}" cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: debian spec: containers: - name: debian image: debian ports: - containerPort: 80 command: - sleep - "3600" EOF kubectl get events --sort-by='{.lastTimestamp}'<file_sep># WASM ``` az aks nodepool add \ --resource-group $KUBE_GROUP \ --cluster-name $KUBE_NAME \ --name mywasipool \ --node-count 1 \ --workload-runtime wasmwasi az aks nodepool show -g $KUBE_GROUP --cluster-name $KUBE_GROUP -n mywasipool cat <<EOF | kubectl apply -f - apiVersion: node.k8s.io/v1 kind: RuntimeClass metadata: name: "wasmtime-slight-v1" handler: "slight" scheduling: nodeSelector: "kubernetes.azure.com/wasmtime-slight-v1": "true" --- apiVersion: node.k8s.io/v1 kind: RuntimeClass metadata: name: "wasmtime-spin-v1" handler: "spin" scheduling: nodeSelector: "kubernetes.azure.com/wasmtime-spin-v1": "true" EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: wasm-slight spec: replicas: 1 selector: matchLabels: app: wasm-slight template: metadata: labels: app: wasm-slight spec: runtimeClassName: wasmtime-slight-v1 containers: - name: hello-slight image: ghcr.io/deislabs/containerd-wasm-shims/examples/slight-rust-hello:v0.3.3 command: ["/"] resources: requests: cpu: 10m memory: 10Mi limits: cpu: 500m memory: 128Mi --- apiVersion: v1 kind: Service metadata: name: wasm-slight spec: type: LoadBalancer ports: - protocol: TCP port: 80 targetPort: 80 selector: app: wasm-slight EOF ``` ## Deploy demo app ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: krustlet-wagi-demo labels: app: krustlet-wagi-demo annotations: alpha.wagi.krustlet.dev/default-host: "0.0.0.0:3001" alpha.wagi.krustlet.dev/modules: | { "krustlet-wagi-demo-http-example": {"route": "/http-example", "allowed_hosts": ["https://api.brigade.sh"]}, "krustlet-wagi-demo-hello": {"route": "/hello/..."}, "krustlet-wagi-demo-error": {"route": "/error"}, "krustlet-wagi-demo-log": {"route": "/log"}, "krustlet-wagi-demo-index": {"route": "/"} } spec: hostNetwork: true nodeSelector: kubernetes.io/arch: wasm32-wagi containers: - image: webassembly.azurecr.io/krustlet-wagi-demo-http-example:v1.0.0 imagePullPolicy: Always name: krustlet-wagi-demo-http-example - image: webassembly.azurecr.io/krustlet-wagi-demo-hello:v1.0.0 imagePullPolicy: Always name: krustlet-wagi-demo-hello - image: webassembly.azurecr.io/krustlet-wagi-demo-index:v1.0.0 imagePullPolicy: Always name: krustlet-wagi-demo-index - image: webassembly.azurecr.io/krustlet-wagi-demo-error:v1.0.0 imagePullPolicy: Always name: krustlet-wagi-demo-error - image: webassembly.azurecr.io/krustlet-wagi-demo-log:v1.0.0 imagePullPolicy: Always name: krustlet-wagi-demo-log tolerations: - key: "node.kubernetes.io/network-unavailable" operator: "Exists" effect: "NoSchedule" - key: "kubernetes.io/arch" operator: "Equal" value: "wasm32-wagi" effect: "NoExecute" - key: "kubernetes.io/arch" operator: "Equal" value: "wasm32-wagi" effect: "NoSchedule" EOF ``` <file_sep>// package org.acme.rest.client; // import io.quarkus.test.junit.NativeImageTest; // @NativeImageTest // public class CalculationResourceIT extends CalculationResourceTest { // // Run the same tests // }<file_sep>https://nordicapis.com/how-to-create-an-api-using-grpc-and-node-js/<file_sep># Kubernetes Role based acccess control 0. Variables ``` KUBE_GROUP=kuberbac KUBE_NAME=dzkuberbac LOCATION="eastus" SUBSCRIPTION_ID= AAD_APP_ID= AAD_APP_SECRET= AAD_CLIENT_ID= TENANT_ID= YOUR_SSH_KEY=$(cat ~/.ssh/id_rsa.pub) SERVICE_PRINCIPAL_ID= SERVICE_PRINCIPAL_SECRET= ADMIN_GROUP_ID= MY_OBJECT_ID= KUBE_ADMIN_ID= READER_USER_ID= ``` ## Create RBAC with AKs ``` az group create --name $KUBE_GROUP --location $LOCATION az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --ssh-key-value ~/.ssh/id_rsa.pub --enable-rbac --aad-server-app-id $AAD_APP_ID --aad-server-app-secret $AAD_APP_SECRET --aad-client-app-id $AAD_CLIENT_ID --aad-tenant-id $TENANT_ID --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --enable-addons http_application_routing az aks get-credentials --resource-group $KUBE_GROUP --name $KUBE_NAME --admin az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query enableRbac kubectl api-versions ``` set cluster role binding ``` cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: kube-cluster-admins roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - apiGroup: rbac.authorization.k8s.io kind: User name: "<EMAIL>" EOF ``` create admin user binding ``` cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: cluster-kube-admins roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - apiGroup: rbac.authorization.k8s.io kind: User name: "$MY_OBJECT_ID" - apiGroup: rbac.authorization.k8s.io kind: User name: "$MY_USER_ID" EOF az aks get-credentials --resource-group $KUBE_GROUP --name $KUBE_NAME az aks browse --resource-group $KUBE_GROUP --name $KUBE_NAME ``` if you see the following error message error: unable to forward port because pod is not running. Current status=Pending create a binding for the dashboard account ``` kubectl create clusterrolebinding kubernetes-dashboard --clusterrole=cluster-admin --serviceaccount=kube-system:kubernetes-dashboard ``` or yaml ``` cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: kubernetes-dashboard labels: k8s-app: kubernetes-dashboard roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - kind: ServiceAccount name: kubernetes-dashboard namespace: kube-system EOF cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: kubernetes-default labels: k8s-app: kubernetes-default roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - kind: ServiceAccount name: default namespace: kube-system EOF ``` check if RBAC is active ``` kubectl cluster-info dump --namespace kube-system | grep authorization-mode ``` ## Create namespaces and trimmed roles ``` kubectl create ns small kubectl create ns big cat <<EOF | kubectl create -f - kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: namespace: small name: pod-and-pod-logs-reader rules: - apiGroups: [""] resources: ["pods", "pods/log"] verbs: ["get", "list"] EOF cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: namespace: small name: small-pod-reader roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: pod-and-pod-logs-reader subjects: - apiGroup: rbac.authorization.k8s.io kind: User name: "$READER_USER_ID" EOF kubectl create rolebinding small-pod-reader --role=pod-and-pod-logs-reader --user=$READER_USER_ID --namespace=small kubectl auth can-i create deployments --namespace=small --as=$READER_USER_ID kubectl auth can-i list pods --namespace=small --as=$READER_USER_ID ``` ## Prepare acs-engine ``` sed -e "s/AAD_APP_ID/$AAD_APP_ID/ ; s/AAD_CLIENT_ID/$AAD_CLIENT_ID/ ; s/SERVICE_PRINCIPAL_ID/$SERVICE_PRINCIPAL_ID/ ; s/SERVICE_PRINCIPAL_SECRET/$SERVICE_PRINCIPAL_SECRET/ ; s/TENANT_ID/$TENANT_ID/" acsengrbac.json > acsengkubernetes.json docker pull ams0/acs-engine-light-autobuild mkdir deployment docker run -it --rm -v deployment:/acs -w /acs ams0/acs-engine-light-autobuild:latest /acs-engine generate acsengkubernetes.json ``` ## Deploy cluster ``` az login az group create -n $KUBE_GROUP -l $LOCATION az group deployment create \ --name dz-aad-k8s-18 \ --resource-group $KUBE_GROUP \ --template-file "_output/dz-aad-k8s-18/azuredeploy.json" \ --parameters "_output/dz-aad-k8s-18/azuredeploy.parameters.json" ``` ## Create cluster role binding ``` export KUBECONFIG=`pwd`/_output/dz-aad-k8s-18/kubeconfig/kubeconfig.northeurope.json ssh -i ~/.ssh/id_rsa dennis@dz-aad-k8s-18.northeurope.cloudapp.azure.com \ kubectl create clusterrolebinding aad-default-cluster-admin-binding \ --clusterrole=cluster-admin \ --user 'https://sts.windows.net/<tenant-id>/#<user-id>' kubectl create clusterrolebinding aad-default-cluster-admin-binding --clusterrole=cluster-admin --user=https://sts.windows.net/$TENANT_ID/#$MY_OBJECT_ID ``` ## Verify with can-i ``` kubectl auth can-i create deployments ``` ## Azure RBAC ``` KUBE_NAME=dzuserauth AKS_ID=$(az aks show -g MyResourceGroup -n MyManagedCluster --query id -o tsv) az aks get-credentials -g MyResourceGroup -n MyManagedCluster --admin az role assignment create --role "Azure Kubernetes Service RBAC Viewer" --assignee $MY_USER_ID --scope $AKS_ID/namespaces/<namespace-name> SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET ```<file_sep>package org.acme.rest.client; import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; import org.jboss.resteasy.annotations.jaxrs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import java.util.concurrent.CompletionStage; @Path("/api") @RegisterRestClient(configKey="calculation-api") public interface CalculationService { @POST @Path("/calculation") CalculationResponse Calculate(@HeaderParam String number, @HeaderParam Boolean victim); @POST @Path("/calculation") CompletionStage<CalculationResponse> CalculateAsync(@HeaderParam String number, @HeaderParam Boolean victim); }<file_sep># Fix DNS issue by deploying networkmonitor as a daemonset in cluster 1. Take networkmonitor image from https://hub.docker.com/r/containernetworking/networkmonitor/ Latest value should be ``` containernetworking/networkmonitor:v0.0.4 ``` 2. Take latest version and replace <azureCNINetworkMonitorImage> with it. Deploy as a daemonset using the template from here https://github.com/Azure/acs-engine/blob/master/parts/k8s/addons/azure-cni-networkmonitor.yaml 3. Alternative deploy directly ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/bestpractices/azure-cni-networkmonitor.yaml ```<file_sep># Create container cluster (AKS) https://docs.microsoft.com/en-us/azure/aks/kubernetes-walkthrough 0. Variables ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id KUBE_GROUP="dzaksaadv2" KUBE_NAME="aksaad" KUBE_VERSION="1.18.10" # here enter the kubernetes version of your aks KUBE_VNET_NAME="spoke1-kubevnet" KUBE_ING_SUBNET_NAME="ing-1-subnet" # here enter the name of your ingress subnet KUBE_AGENT_SUBNET_NAME="aks-2-subnet" # here enter the name of your aks subnet NAT_EGR_SUBNET_NAME="egr-3-subnet" # here enter the name of your egress subnet LOCATION="australiaeast" KUBE_VERSION="1.16.7" AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) AAD_GROUP_ID="" ``` Select subscription ``` az account set --subscription $SUBSCRIPTION_ID az group create -n $KUBE_GROUP -l $LOCATION az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME --address-prefixes 10.0.4.0/22 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $NAT_EGR_SUBNET_NAME --address-prefix 10.0.6.0/24 KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" EGRESS_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$NAT_EGR_SUBNET_NAME" NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group ``` get available version ``` az aks get-versions -l $LOCATION -o table ``` 2. Create the aks cluster ``` az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin kubenet --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --enable-managed-identity --kubernetes-version $KUBE_VERSION --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $AZURE_TENANT_ID --uptime-sla ``` az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n gpu2pool -c 1 --node-vm-size Standard_D2_v2 --mode user --vnet-subnet-id $EGRESS_AGENT_SUBNET_ID with existing keys and latest version ``` SMSI_SERVICE_PRINCIPAL_ID=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query "identity.principalId" -o tsv ) az role assignment create --role "Contributor" --assignee $SMSI_SERVICE_PRINCIPAL_ID -g $VNET_GROUP ``` with existing service principal ``` az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 3 --ssh-key-value ~/.ssh/id_rsa.pub --kubernetes-version $KUBE_VERSION --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --enable-addons http_application_routing ``` with rbac (is now default) ``` az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 3 --ssh-key-value ~/.ssh/id_rsa.pub --kubernetes-version $KUBE_VERSION --enable-rbac --aad-server-app-id $AAD_APP_ID --aad-server-app-secret $AAD_APP_SECRET --aad-client-app-id $AAD_CLIENT_ID --aad-tenant-id $TENANT_ID --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --node-vm-size "Standard_B1ms" --enable-addons http_application_routing monitoring az aks create \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --enable-vmss \ --node-count 1 \ --ssh-key-value ~/.ssh/id_rsa.pub \ --kubernetes-version $KUBE_VERSION \ --enable-rbac \ --enable-addons monitoring ``` without rbac () ``` --disable-rbac ``` show deployment ``` az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME ``` deactivate routing addon ``` az aks disable-addons --addons http_application_routing --resource-group $KUBE_GROUP --name $KUBE_NAME ``` az aks enable-addons \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --addons virtual-node \ --subnet-name aci-2-subnet # deploy zones, msi, slb via arm ``` az group create -n $KUBE_GROUP -l $LOCATION az group deployment create \ --name spot \ --resource-group $KUBE_GROUP \ --template-file "arm/spot_template.json" \ --parameters "arm/spot_parameters.json" \ --parameters "resourceName=$KUBE_NAME" \ "location=$LOCATION" \ "dnsPrefix=$KUBE_NAME" \ "kubernetesVersion=$KUBE_VERSION" \ "servicePrincipalClientId=$SERVICE_PRINCIPAL_ID" \ "servicePrincipalClientSecret=$SERVICE_PRINCIPAL_SECRET" ``` 3. Export the kubectrl credentials files ``` az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME ``` or If you are not using the Azure Cloud Shell and don’t have the Kubernetes client kubectl, run ``` az aks install-cli ``` or download the file manually ``` scp azureuser@($KUBE_NAME)mgmt.westeurope.cloudapp.azure.com:.kube/config $HOME/.kube/config ``` 4. Check that everything is running ok ``` kubectl version kubectl config current-contex ``` Use flag to use context ``` kubectl --kube-context ``` 5. Activate the kubernetes dashboard ``` az aks browse --resource-group=$KUBE_GROUP --name=$KUBE_NAME http://localhost:8001/api/v1/namespaces/kube-system/services/kubernetes-dashboard/proxy/#!/login ``` 6. Get all upgrade versions ``` az aks get-upgrades --resource-group=$KUBE_GROUP --name=$KUBE_NAME --output table ``` 7. Perform upgrade ``` az aks upgrade --resource-group=$KUBE_GROUP --name=$KUBE_NAME --kubernetes-version 1.10.6 ``` # Add agent pool ``` az aks enable-addons \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --addons virtual-node \ --subnet-name aci-2-subnet az aks disable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons virtual-node cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: aci-helloworld spec: replicas: 1 selector: matchLabels: app: aci-helloworld template: metadata: labels: app: aci-helloworld spec: containers: - name: aci-helloworld image: microsoft/aci-helloworld ports: - containerPort: 80 nodeSelector: kubernetes.io/role: agent beta.kubernetes.io/os: linux type: virtual-kubelet tolerations: - key: virtual-kubelet.io/provider operator: Exists - key: azure.com/aci effect: NoSchedule EOF az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n linuxpool2 -c 1 az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME --os-type Windows -n winpoo -c 1 --node-vm-size Standard_D2_v2 az aks nodepool list -g $KUBE_GROUP --cluster-name $KUBE_NAME -o table az aks nodepool scale -g $KUBE_GROUP --cluster-name $KUBE_NAME -n cheap -c 1 az aks nodepool scale -g $KUBE_GROUP --cluster-name $KUBE_NAME -n agentpool -c 1 ``` # autoscaler https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md#im-running-cluster-with-nodes-in-multiple-zones-for-ha-purposes-is-that-supported-by-cluster-autoscaler ``` az aks nodepool scale -g $KUBE_GROUP --cluster-name $KUBE_NAME -n agentpool1 -c 1 az aks nodepool update --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --name agentpool1 --enable-cluster-autoscaler --min-count 1 --max-count 3 ``` ``` kubectl -n kube-system describe configmap cluster-autoscaler-status ``` # Create SSH access https://docs.microsoft.com/en-us/azure/aks/ssh ``` NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) SCALE_SET_NAME=$(az vmss list --resource-group $NODE_GROUP --query [0].name -o tsv) az vmss list-instances --resource-group kub_ter_a_m_dapr5_nodes_northeurope --name aks-default-33188643-vmss --query '[].[name, storageProfile.dataDisks[]]' | less az vmss extension set \ --resource-group $NODE_GROUP \ --vmss-name $SCALE_SET_NAME \ --name VMAccessForLinux \ --publisher Microsoft.OSTCExtensions \ --version 1.4 \ --protected-settings "{\"username\":\"dennis\", \"ssh_key\":\"$(cat ~/.ssh/id_rsa.pub)\"}" az vmss update-instances --instance-ids '*' \ --resource-group $NODE_GROUP \ --name $SCALE_SET_NAME kubectl run -it --rm aks-ssh --image=debian kubectl -n test exec -it $(kubectl -n test get pod -l run=aks-ssh -o jsonpath='{.items[0].metadata.name}') -- /bin/sh kubectl cp ~/.ssh/id_rsa $(kubectl get pod -l run=aks-ssh -o jsonpath='{.items[0].metadata.name}'):/id_rsa ``` # Delete everything ``` az group delete -n $KUBE_GROUP echo "retrieving login credentials" export TENANT_ID=$(cat /host/azure.json | jq -r ".[0].tenantId" ) export SUBSCRIPTION_ID=$(cat /host/azure.json | jq -r ".[0].subscriptionId" ) export CLIENT_ID=$(cat /host/azure.json | jq -r ".[0].aadClientId" ) export CLIENT_SECRET=$(cat /host/azure.json | jq -r ".[0].aadClientSecret" ) az login --service-principal --username $CLIENT_ID --password $CLIENT_SECRET --tenant $TENANT_ID az role assignment list --assignee CLIENT_ID ``` ## Kubernetes AAD RBAC https://docs.microsoft.com/en-us/azure/aks/manage-azure-rbac ``` KUBE_GROUP="dzaksaadv2" KUBE_NAME="aksaad" LOCATION="westus2" AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) AAD_GROUP_ID="" az group create -n $KUBE_GROUP -l $LOCATION az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --vm-set-type VirtualMachineScaleSets \ --load-balancer-sku standard \ --node-count 1 --enable-managed-identity \ --enable-aad --enable-azure-rbac az aks update --resource-group $KUBE_GROUP --name $KUBE_NAME --enable-azure-rbac az aks update --resource-group $KUBE_GROUP --name $KUBE_NAME --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $TENANT_ID AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query id -o tsv) az aks get-credentials -g $KUBE_GROUP -n $KUBE_NAME --admin kubectl create ns aadsecured kubectl run --image=k8s.gcr.io/echoserver:1.10 echoserver --port=80 -n aadsecured kubectl run --image=nginx nginx --port=80 -n aadsecured kubectl create secret generic azure-secret --from-literal accountname=dzpremium1 --from-literal accountkey="<KEY> --type=Opaque -n aadsecured az role assignment create --role "Azure Kubernetes Service RBAC Admin" --assignee $MY_USER_ID --scope $AKS_ID az role assignment create --role "Azure Kubernetes Service RBAC Reader" --assignee $MY_USER_ID --scope $AKS_ID/namespaces/default az role assignment create --role "Azure Kubernetes Service RBAC Reader" --assignee $MY_USER_ID --scope $AKS_ID/namespaces/aadsecured az aks update --resource-group $KUBE_GROUP --name $KUBE_NAME --aad-admin-group-object-ids $AAD_GROUP_ID kubectl get pod -n aadsecured KUBE_NAME=dzuserauth AKS_ID=$(az aks show -g MyResourceGroup -n MyManagedCluster --query id -o tsv) az aks get-credentials -g MyResourceGroup -n MyManagedCluster --admin az role assignment create --role "Azure Kubernetes Service RBAC Viewer" --assignee $MY_USER_ID --scope $AKS_ID/namespaces/aadsecured az role assignment create --role "Azure Kubernetes Service RBAC Reader" --assignee $MY_USER_ID --scope $AKS_ID/namespaces/aadsecured az aks update --enable-pod-identity --resource-group $KUBE_GROUP --name $KUBE_NAME SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET KUBE_NAME=MyManagedCluster KUBE_GROUP=myResourceGroup az aks get-credentials -g dzallincl -n dzallincl SERVICE_PRINCIPAL_ID= SERVICE_PRINCIPAL_SECRET= AZURE_TENANT_ID=$(az account show -o json | jq '.tenantId' -r) echo $AZURE_TENANT_ID az login --identity az login --service-principal -u $SERVICE_PRINCIPAL_ID -p $SERVICE_PRINCIPAL_SECRET --tenant $AZURE_TENANT_ID az role assignment create --role "Azure Kubernetes Service RBAC Reader" --assignee "$SERVICE_PRINCIPAL_ID" --scope $AKS_ID/namespaces/aadsecured az role assignment create --role "Azure Kubernetes Service RBAC Writer" --assignee $SERVICE_PRINCIPAL_ID --scope $AKS_ID/namespaces/aadsecured wget https://github.com/Azure/kubelogin/releases/download/v0.0.10/kubelogin-linux-amd64.zip unzip kubelogin-linux-amd64.zip -d kubetools export KUBECONFIG=/home/dennis/.kube/config az aks get-credentials -g $KUBE_GROUP -n $KUBE_NAME rm /home/dennis/.kube/config touch /home/dennis/.kube/config kubelogin convert-kubeconfig -l ropc export AAD_USER_PRINCIPAL_NAME= export AAD_SERVICE_PRINCIPAL_CLIENT_ID= export AAD_SERVICE_PRINCIPAL_CLIENT_SECRET= export AAD_USER_PRINCIPAL_PASSWORD= kubectl get no SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id KUBE_GROUP="kub_ter_a_m_dzarc1" KUBE_NAME="dzarc1" LOCATION="westeurope" KUBE_VERSION="1.16.13" KUBE_VNET_NAME="dzarc1-vnet" KUBE_AGENT_SUBNET_NAME="aks-5-subnet" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin azure --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --enable-managed-identity --kubernetes-version $KUBE_VERSION --uptime-sla --enable-aad --enable-azure-rbac --vnet-subnet-id $KUBE_AGENT_SUBNET_ID AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query id -o tsv) az role assignment create --role "Azure Kubernetes Service RBAC Admin" --assignee $MY_USER_ID --scope $AKS_ID ``` ## No Pod Identity ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF kubectl exec -it centos -- /bin/bash yum install jq -y curl --silent -H Metadata:True --noproxy "*" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" curl --silent -H Metadata:True --noproxy "*" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/&client_id=6d579b6d-f7ec-4b82-b78a-11efbb22a829" | jq ``` ## AAD Pod Identity ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) IDENTITY_NAME=podidentity1 POD_IDENTITY_NAME="my-pod-identity" POD_IDENTITY_NAMESPACE="my-app" NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az identity create --resource-group ${NODE_GROUP} --name ${IDENTITY_NAME} IDENTITY_CLIENT_ID="$(az identity show -g ${NODE_GROUP} -n ${IDENTITY_NAME} --query clientId -o tsv)" IDENTITY_RESOURCE_ID="$(az identity show -g ${NODE_GROUP} -n ${IDENTITY_NAME} --query id -o tsv)" az aks update --resource-group $KUBE_GROUP --name $KUBE_NAME --enable-pod-identity kubectl create namespace $POD_IDENTITY_NAMESPACE az aks pod-identity add --resource-group ${KUBE_GROUP} --cluster-name ${KUBE_NAME} --namespace ${POD_IDENTITY_NAMESPACE} --name ${POD_IDENTITY_NAME} --identity-resource-id ${IDENTITY_RESOURCE_ID} az role assignment create --role "Reader" --assignee "cd74751b-ed09-421a-9001-807cddbb29de" --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Reader" --assignee "$IDENTITY_CLIENT_ID" --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP https://azure.github.io/aad-pod-identity/docs/configure/pod_identity_in_managed_mode/ cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: demo labels: aadpodidbinding: $POD_IDENTITY_NAME namespace: $POD_IDENTITY_NAMESPACE spec: containers: - name: demo image: mcr.microsoft.com/oss/azure/aad-pod-identity/demo:v1.6.3 args: - --subscriptionid=$SUBSCRIPTION_ID - --clientid=$IDENTITY_CLIENT_ID - --resourcegroup=$NODE_GROUP env: - name: MY_POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: MY_POD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: MY_POD_IP valueFrom: fieldRef: fieldPath: status.podIP nodeSelector: kubernetes.io/os: linux EOF kubectl logs demo --follow --namespace my-app ``` # Service Process https://appscode.com/products/guard/v0.6.1/guides/authenticator/azure/ ``` KUBE_NAME=dzaadauth LOCATION=westeurope KUBE_GROUP=dzaadauth KUBE_VERSION=1.20.7 NODE_GROUP=dzaadauth_dzaadauth_nodes_westeurope SERVICE_PRINCIPAL_ID=msi SERVICE_PRINCIPAL_ID=msi KUBE_NAME=dzaad8 KUBE_GROUP="dzaad8" APP_NAME=$KUBE_NAME-runner AKS_ID= SERVICE_PRINCIPAL_ID= SERVICE_PRINCIPAL_SECRET= SUBSCRIPTION_ID= TENANT_ID= USER_NAME=<EMAIL> USER_PASSWORD=<PASSWORD> USER_PASSWORD=<PASSWORD> CI_NAME=$KUBE_NAME-github CI_PRINCIPAL_ID= CI_K8S_AKS CI_AKS_NAME=dzaadauth CI_AKS_GROUP=dzaadauth SUBSCRIPTION_ID=$(az account show --query id -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv) az aks update -g $KUBE_GROUP -n $KUBE_NAME --disable-local-accounts AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query id -o tsv) APP_NAME=$KUBE_NAME-runner CI_NAME=$KUBE_NAME-github az ad sp create-for-rbac --name $CI_NAME --sdk-auth --role "Azure Kubernetes Service Cluster User Role" --scopes $AKS_ID --disable-local-accounts --enable-local-accounts SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $APP_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET az role assignment create --assignee $SERVICE_PRINCIPAL_ID --scope $AKS_ID --role "Azure Kubernetes Service Cluster User Role" az role assignment create --assignee $MY_USER_ID --scope $AKS_ID --role "Azure Kubernetes Service Cluster User Role" az role assignment create --assignee $SERVICE_PRINCIPAL_ID --scope /subscriptions/$SUBSCRIPTION_ID --role "Azure Kubernetes Service Cluster User Role" az role assignment create --role "Azure Kubernetes Service RBAC Reader" --assignee $SERVICE_PRINCIPAL_ID --scope /subscriptions/$SUBSCRIPTION_ID APPDEV_ID=$(az ad group create --display-name appdev --mail-nickname appdev --query objectId -o tsv) az role assignment create --assignee $APPDEV_ID --scope /subscriptions/$SUBSCRIPTION_ID --role "Azure Kubernetes Service Cluster User Role" az role assignment create --role "Azure Kubernetes Service RBAC Reader" --assignee $APPDEV_ID --scope /subscriptions/$SUBSCRIPTION_ID kubectl create ns application1 # full kubectl run --image=nginx nginx --port=80 -n application1 kubectl create secret generic azure-secret --from-literal accountname=dzpremium1 --from-literal accountkey="<KEY> --type=Opaque -n application1 az role assignment create --role "Azure Kubernetes Service RBAC Writer" --assignee $SERVICE_PRINCIPAL_ID --scope $AKS_ID/namespaces/application1 az role assignment create --role "Azure Kubernetes Service RBAC Writer" --assignee $CI_PRINCIPAL_ID --scope $AKS_ID/namespaces/application1 kubectl create ns application2 # read kubectl run --image=nginx nginx --port=80 -n application2 kubectl create secret generic azure-secret --from-literal accountname=dzpremium1 --from-literal accountkey="<KEY> --type=Opaque -n application2 az role assignment create --role "Azure Kubernetes Service RBAC Reader" --assignee $SERVICE_PRINCIPAL_ID --scope $AKS_ID/namespaces/application2 az role assignment create --role "Azure Kubernetes Service RBAC Reader" --assignee $CI_PRINCIPAL_ID --scope $AKS_ID/namespaces/application2 kubectl create ns aadsecured kubectl get pod -n aadsecured az login --service-principal -u $SERVICE_PRINCIPAL_ID -p $SERVICE_PRINCIPAL_SECRET --tenant $TENANT_ID https://github.com/azure/kubelogin wget https://github.com/Azure/kubelogin/releases/download/v0.0.12/kubelogin-linux-amd64.zip unzip kubelogin-linux-amd64.zip -d kubetools export KUBECONFIG=`pwd`/kubeconfig az aks get-credentials -g $KUBE_GROUP -n $KUBE_NAME --file `pwd`/kubeconfig --overwrite-existing export AAD_SERVICE_PRINCIPAL_CLIENT_ID=$SERVICE_PRINCIPAL_ID export AAD_SERVICE_PRINCIPAL_CLIENT_SECRET=$SERVICE_PRINCIPAL_SECRET echo "using spn flow" ./kubetools/bin/linux_amd64/kubelogin convert-kubeconfig -l spn echo "using msi flow" ./kubetools/bin/linux_amd64/kubelogin convert-kubeconfig -l msi ./kubetools/bin/linux_amd64/kubelogin convert-kubeconfig -l msi --client-id msi-client-id echo "using azure cli login" ./kubetools/bin/linux_amd64/kubelogin convert-kubeconfig -l azurecli #./kubetools/bin/linux_amd64/kubelogin remove-tokens kubectl get pod -n application1 kubectl get secret -n application1 kubectl get pod -n application2 kubectl get secret -n application2 kubectl get pod -n aadsecured yum install jq -y curl --silent -H Metadata:True --noproxy "*" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" | jq curl --silent -H Metadata:True --noproxy "*" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/&client_id=6d579b6d-f7ec-4b82-b78a-11efbb22a829" | jq curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' -H Metadata:true -s curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F&client_id=4329deb8-c65b-497a-b528-8e07082b8115' -H Metadata:true -s ``` https://docs.microsoft.com/en-us/azure/developer/java/sdk/identity-azure-hosted-auth ## Pod Identity V2 ``` KUBE_GROUP="dzallincluded" KUBE_NAME="dzallincluded" KEYVAULT_NAME="<KEY>" SECRET_NAME=mySecret SERVICE_PRINCIPAL_ID= AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) az aks update -g $KUBE_GROUP --name $KUBE_NAME --enable-oidc-issuer helm repo add azure-workload-identity https://azure.github.io/azure-workload-identity/charts helm repo update helm install workload-identity-webhook azure-workload-identity/workload-identity-webhook \ --namespace azure-workload-identity-system \ --create-namespace \ --set azureTenantID="${AZURE_TENANT_ID}" kubectl get pods -n azure-workload-identity-system SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET SERVICE_PRINCIPAL_OBJECT_ID="$(az ad app show --id ${SERVICE_PRINCIPAL_ID} --query objectId -o tsv)" echo $SERVICE_PRINCIPAL_OBJECT_ID az keyvault set-policy -n ${KEYVAULT_NAME} --secret-permissions get --spn ${SERVICE_PRINCIPAL_ID} ISSUER_URL=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query "oidcIssuerProfile.issuerUrl" -o tsv) echo $ISSUER_URL az rest --method POST --uri "https://graph.microsoft.com/beta/applications/$SERVICE_PRINCIPAL_OBJECT_ID/federatedIdentityCredentials" --body "{'name':'aks-kv','issuer':'$ISSUER_URL','subject':'system:serviceaccount:default:pod-identity-sa','description':'aks kv access','audiences':['api://AzureADTokenExchange']}" kubectl create secret generic secrets-store-creds --from-literal clientid=$SERVICE_PRINCIPAL_ID --from-literal clientsecret=$SERVICE_PRINCIPAL_SECRET kubectl label secret secrets-store-creds secrets-store.csi.k8s.io/used=true cat <<EOF | kubectl apply -f - apiVersion: v1 data: AZURE_ENVIRONMENT: "AzurePublicCloud" AZURE_TENANT_ID: "$AZURE_TENANT_ID" kind: ConfigMap metadata: name: aad-pi-webhook-config namespace: aad-pi-webhook-system EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: ServiceAccount metadata: annotations: azure.workload.identity/client-id: ${SERVICE_PRINCIPAL_ID} azure.workload.identity/tenant-id: "$AZURE_TENANT_ID" labels: azure.workload.identity/use: "true" name: pod-identity-sa EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: demo spec: serviceAccountName: pod-identity-sa containers: - image: denniszielke/akvdotnet:latest imagePullPolicy: IfNotPresent name: oidc env: - name: KEYVAULT_NAME value: ${KEYVAULT_NAME} - name: SECRET_NAME value: ${SECRET_NAME} nodeSelector: kubernetes.io/os: linux EOF cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1 kind: SecretProviderClass metadata: name: azure-kvname-workload-id namespace: default spec: provider: azure parameters: usePodIdentity: "false" clientID: ${SERVICE_PRINCIPAL_ID} keyvaultName: "$KEYVAULT_NAME" cloudName: "" # [OPTIONAL for Azure] if not provided, azure environment will default to AzurePublicCloud objects: | array: - | objectName: ${SECRET_NAME} objectType: secret # object types: secret, key or cert objectVersion: "" # [OPTIONAL] object versions, default to latest if empty tenantId: "$AZURE_TENANT_ID" # the tenant ID of the KeyVault EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: demo-csi spec: serviceAccountName: pod-identity-sa containers: - name: busybox image: k8s.gcr.io/e2e-test-images/busybox:1.29 command: - "/bin/sleep" - "10000" volumeMounts: - name: secrets-store01-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store01-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: "azure-kvname-workload-id" nodePublishSecretRef: name: secrets-store-creds EOF cat /var/run/secrets/tokens/azure-identity-token ``` ## Managed Identity ``` KUBE_NAME= KUBE_GROUP= SERVICE_ACCOUNT_NAMESPACE=app1ns SERVICE_ACCOUNT_NAME=app1 kubectl create ns $SERVICE_ACCOUNT_NAMESPACE az identity create --name $SERVICE_ACCOUNT_NAME --resource-group $KUBE_GROUP -o none export USER_ASSIGNED_CLIENT_ID="$(az identity show --resource-group "${KUBE_GROUP}" --name "$SERVICE_ACCOUNT_NAME" --query 'clientId' -o tsv)" AKS_OIDC_ISSUER="$(az aks show -n $KUBE_NAME -g $KUBE_GROUP --query "oidcIssuerProfile.issuerUrl" -o tsv)" cat <<EOF | kubectl apply -f - apiVersion: v1 kind: ServiceAccount metadata: annotations: azure.workload.identity/client-id: ${USER_ASSIGNED_CLIENT_ID} labels: azure.workload.identity/use: "true" name: ${SERVICE_ACCOUNT_NAME} namespace: ${SERVICE_ACCOUNT_NAMESPACE} EOF az identity federated-credential create --name ${SERVICE_ACCOUNT_NAME} --identity-name "${SERVICE_ACCOUNT_NAME}" --resource-group $KUBE_GROUP --issuer ${AKS_OIDC_ISSUER} --subject system:serviceaccount:${SERVICE_ACCOUNT_NAMESPACE}:${SERVICE_ACCOUNT_NAME} cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: idstart namespace: ${SERVICE_ACCOUNT_NAMESPACE} labels: azure.workload.identity/use: "true" annotations: azure.workload.identity/inject-proxy-sidecar: "true" azure.workload.identity/proxy-sidecar-port: "8080" spec: serviceAccountName: ${SERVICE_ACCOUNT_NAME} containers: - image: centos name: centos command: - sleep - "3600" nodeSelector: kubernetes.io/os: linux EOF kubectl exec -it idstart -- /bin/bash cat /var/run/secrets/azure/tokens/azure-identity-token curl --silent -H Metadata:True --noproxy "*" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" ```<file_sep>KUBE_NAME=$1 KUBE_GROUP=$2 USE_ADDON=$3 SUBSCRIPTION_ID=$(az account show --query id -o tsv) #subscriptionid LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) AKS_SUBNET_ID=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query "agentPoolProfiles[0].vnetSubnetId" -o tsv) AKS_SUBNET_NAME="aks-5-subnet" OSM_ADDON_ENABLED=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query "addonProfiles.openServiceMesh.enabled" -o tsv) if [ "$OSM_ADDON_ENABLED" == "true" ]; then echo "osm addon is already active" else echo "enabling osm addon..." az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="open-service-mesh" fi https://release-v0-11.docs.openservicemesh.io/docs/demos/ingress_k8s_nginx/ echo "cluster is running osm version:" kubectl get deployment -n kube-system osm-controller -o=jsonpath='{$.spec.template.spec.containers[:1].image}' echo "cluster is running osm config:" kubectl get meshconfig osm-mesh-config -n kube-system -o yaml #kubectl patch meshconfig osm-mesh-config -n kube-system -p '{"spec":{"traffic":{"enablePermissiveTrafficPolicyMode":true}}}' --type=merge kubectl edit meshconfig osm-mesh-config -n kube-system kubectl patch meshconfig osm-mesh-config -n kube-system -p '{"spec":{"certificate:":{"ingressGateway": {"secret": {"name": "osm-nginx-client-cert","namespace": "kube-system"},"subjectAltNames": ["nginx-ingress-ingress-nginx-controller.ingress.cluster.local"],"validityDuration": "24h"}}}}' --type=merge kubectl get meshconfig osm-mesh-config -n kube-system certificate: ingressGateway: secret: name: osm-nginx-client-cert namespace: kube-system subjectAltNames: - nginx-ingress-ingress-nginx.ingress.cluster.local validityDuration: 24h osm namespace add dummy-logger osm_namespace=kube-system # replace <osm-namespace> with the namespace where OSM is installed osm_mesh_name=osm # replace <osm-mesh-name> with the mesh name (use `osm mesh list` command) nginx_ingress_namespace=ingress # replace <nginx-namespace> with the namespace where Nginx is installed nginx_ingress_service=nginx-ingress-ingress-nginx-controller # replace <nginx-ingress-controller-service> with the name of the nginx ingress controller service nginx_ingress_host="$(kubectl -n "$nginx_ingress_namespace" get service "$nginx_ingress_service" -o jsonpath='{.status.loadBalancer.ingress[0].ip}')" nginx_ingress_port="$(kubectl -n "$nginx_ingress_namespace" get service "$nginx_ingress_service" -o jsonpath='{.spec.ports[?(@.name=="http")].port}')" kubectl label ns "$nginx_ingress_namespace" openservicemesh.io/monitored-by="$osm_mesh_name" kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-$APP_NAMESPACE namespace: $APP_NAMESPACE annotations: cert-manager.io/cluster-issuer: letsencrypt nginx.ingress.kubernetes.io/rewrite-target: / nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" nginx.ingress.kubernetes.io/configuration-snippet: | proxy_ssl_name "default.dummy-logger.cluster.local"; nginx.ingress.kubernetes.io/proxy-ssl-secret: "kube-system/osm-nginx-client-cert" nginx.ingress.kubernetes.io/proxy-ssl-verify: "on" spec: tls: - hosts: - $DNS secretName: $SECRET_NAME ingressClassName: nginx rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 --- apiVersion: policy.openservicemesh.io/v1alpha1 kind: IngressBackend metadata: name: dummy-logger namespace: $APP_NAMESPACE spec: backends: - name: dummy-logger port: number: 80 protocol: https tls: skipClientCertValidation: false sources: - kind: Service name: "$nginx_ingress_service" namespace: "$nginx_ingress_namespace" - kind: AuthenticatedPrincipal name: nginx-ingress-ingress-nginx.ingress.cluster.local EOF kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: http-dummy-logger namespace: dummy-logger spec: ingressClassName: nginx rules: - http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 --- kind: IngressBackend apiVersion: policy.openservicemesh.io/v1alpha1 metadata: name: http-dummy-logger namespace: dummy-logger spec: backends: - name: dummy-logger port: number: 80 protocol: http sources: - kind: Service namespace: "$nginx_ingress_namespace" name: "$nginx_ingress_service" EOF curl -sI $DNS kubectl label namespace ingress-basic cert-manager.io/disable-validation=true helm repo add jetstack https://charts.jetstack.io helm repo update CERT_MANAGER_REGISTRY=quay.io CERT_MANAGER_TAG=v1.3.1 CERT_MANAGER_IMAGE_CONTROLLER=jetstack/cert-manager-controller CERT_MANAGER_IMAGE_WEBHOOK=jetstack/cert-manager-webhook CERT_MANAGER_IMAGE_CAINJECTOR=jetstack/cert-manager-cainjector # Install the cert-manager Helm chart helm upgrade cert-manager jetstack/cert-manager \ --namespace ingress --install \ --version $CERT_MANAGER_TAG \ --set installCRDs=true \ --set image.repository=$CERT_MANAGER_REGISTRY/$CERT_MANAGER_IMAGE_CONTROLLER \ --set image.tag=$CERT_MANAGER_TAG \ --set webhook.image.repository=$CERT_MANAGER_REGISTRY/$CERT_MANAGER_IMAGE_WEBHOOK \ --set webhook.image.tag=$CERT_MANAGER_TAG \ --set cainjector.image.repository=$CERT_MANAGER_REGISTRY/$CERT_MANAGER_IMAGE_CAINJECTOR \ --set cainjector.image.tag=$CERT_MANAGER_TAG kubectl apply -f - <<EOF apiVersion: cert-manager.io/v1 kind: ClusterIssuer metadata: name: letsencrypt spec: acme: server: https://acme-v02.api.letsencrypt.org/directory email: <EMAIL> privateKeySecretRef: name: letsencrypt solvers: - http01: ingress: class: nginx EOF kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-dummy-logger namespace: dummy-logger annotations: cert-manager.io/cluster-issuer: letsencrypt spec: tls: - hosts: - $DNS secretName: dummy-cert-secret ingressClassName: nginx rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 EOF kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-dummy-logger namespace: dummy-logger annotations: cert-manager.io/cluster-issuer: letsencrypt nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" # proxy_ssl_name for a service is of the form <service-account>.<namespace>.cluster.local nginx.ingress.kubernetes.io/configuration-snippet: | proxy_ssl_name "httpbin.httpbin.cluster.local"; nginx.ingress.kubernetes.io/proxy-ssl-secret: "osm-system/osm-nginx-client-cert" nginx.ingress.kubernetes.io/proxy-ssl-verify: "on" spec: ingressClassName: nginx rules: - http: paths: - path: / pathType: Prefix backend: service: name: httpbin port: number: 14001 --- apiVersion: policy.openservicemesh.io/v1alpha1 kind: IngressBackend metadata: name: httpbin namespace: httpbin spec: backends: - name: httpbin port: number: 14001 protocol: https tls: skipClientCertValidation: false sources: - kind: Service name: "$nginx_ingress_service" namespace: "$nginx_ingress_namespace" - kind: AuthenticatedPrincipal name: ingress-nginx.ingress.cluster.local EOF curl -sI http://"$DNS"/get kubectl get secret dummy-cert-secret -n dummy-logger -o json | jq '.data | map_values(@base64d)' openssl pkcs12 -export -in ingress-tls.crt -inkey ingress-tls.key -out $CERT_NAME.pfx # skip Password prompt az keyvault certificate import --vault-name ${KEYVAULT_NAME} -n $CERT_NAME -f $CERT_NAME.pfx cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1alpha1 kind: SecretProviderClass metadata: name: ingress-tls namespace: ingress spec: provider: azure parameters: usePodIdentity: "false" useVMManagedIdentity: "true" userAssignedIdentityID: "$AKS_KUBELET_CLIENT_ID" keyvaultName: "$VAULT_NAME" cloudName: "" # [OPTIONAL for Azure] if not provided, azure environment will default to AzurePublicCloud objects: | array: - | objectName: mySecret objectType: secret # object types: secret, key or cert objectVersion: "" # [OPTIONAL] object versions, default to latest if empty tenantId: "$TENANT_ID" # the tenant ID of the KeyVault EOF cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: busybox-secrets-store-inline-user-msi namespace: ingress spec: containers: - name: busybox image: k8s.gcr.io/e2e-test-images/busybox:1.29 command: - "/bin/sleep" - "10000" volumeMounts: - name: secrets-store01-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store01-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: "ingress-tls" EOF AD_APP_NAME="$DEPLOYMENT_NAME-msal-proxy" APP_HOSTNAME="$DNS" HOMEPAGE=https://$APP_HOSTNAME IDENTIFIER_URIS=$HOMEPAGE REPLY_URLS=https://$APP_HOSTNAME/msal/signin-oidc CLIENT_ID="" OBJECT_ID="" CLIENT_ID=$(az ad app create --display-name $AD_APP_NAME --homepage $HOMEPAGE --reply-urls $REPLY_URLS --required-resource-accesses @manifest.json -o json | jq -r '.appId') echo $CLIENT_ID OBJECT_ID=$(az ad app show --id $CLIENT_ID -o json | jq '.objectId' -r) echo $OBJECT_ID az ad app update --id $OBJECT_ID --set "oauth2Permissions=[]" # The newly registered app does not have a password. Use "az ad app credential reset" to add password and save to a variable. CLIENT_SECRET=$(az ad app credential reset --id $CLIENT_ID -o json | jq '.password' -r) echo $CLIENT_SECRET # Get your Azure AD tenant ID and save to variable AZURE_TENANT_ID=$(az account show -o json | jq '.tenantId' -r) echo $AZURE_TENANT_ID<file_sep> # Install traefik https://github.com/thomseddon/traefik-forward-auth https://github.com/helm/charts/tree/master/stable/traefik ``` kubectl apply -f https://raw.githubusercontent.com/containous/traefik/v1.7/examples/k8s/traefik-rbac.yaml ``` ## create public ip ``` KUBE_GROUP=security KUBE_NAME=pspcluster DNS_NAME=dztraefik1 IP_NAME=traefik-ingress-pip NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az network public-ip create \ --resource-group $NODE_GROUP \ --name $IP_NAME \ --dns-name $DNS_NAME \ --allocation-method static DNS=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query dnsSettings.fqdn --output tsv) IP=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query ipAddress --output tsv) helm repo add traefik https://helm.traefik.io/traefik helm repo update kubectl create namespace traefik helm install stable/traefik --name traefikingress --namespace traefik --set dashboard.enabled=true,dashboard.domain=dashboard.localhost,rbac.enabled=true,loadBalancerIP=$IP,externalTrafficPolicy=Local,replicas=2,ssl.enabled=true,ssl.permanentRedirect=true,ssl.insecureSkipVerify=true,acme.enabled=true,acme.challengeType=http-01,acme.email=$MY_ID,acme.staging=false helm upgrade traefikingress traefik/traefik --install --namespace traefik --set dashboard.enabled=true,dashboard.domain=dashboard.localhost,rbac.enabled=true,loadBalancerIP=$IP,externalIP=$IP,externalTrafficPolicy=Local,replicas=2,ssl.enabled=true,ssl.permanentRedirect=true,ssl.insecureSkipVerify=true,acme.enabled=true,acme.challengeType=http-01,acme.email=$MY_ID,acme.staging=false helm upgrade traefikingress traefik/traefik --install --namespace traefik kubectl port-forward $(kubectl get pods --selector "app.kubernetes.io/name=traefik" --output=name --namespace traefik) 9000:9000 --namespace traefik annotations: https://docs.traefik.io/configuration/backends/kubernetes/#general-annotations kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/pod-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/yaml/calc-min-depl.yaml kubectl get -n default deploy -o yaml \ | linkerd inject - \ | kubectl apply -f - DNS=192.168.3.11.xip.io cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: dummy-logger annotations: kubernetes.io/ingress.class: traefik ingress.kubernetes.io/whitelist-x-forwarded-for: "true" traefik.ingress.kubernetes.io/redirect-permanent: "true" traefik.ingress.kubernetes.io/preserve-host: "true" traefik.ingress.kubernetes.io/rewrite-target: /logger traefik.ingress.kubernetes.io/rate-limit: | extractorfunc: client.ip rateset: rateset1: period: 3s average: 3 burst: 5 spec: rules: - host: $DNS http: paths: - path: /logger backend: serviceName: dummy-logger-cluster servicePort: 80 EOF cat <<EOF | kubectl apply -f - apiVersion: traefik.containo.us/v1alpha1 kind: Middleware metadata: name: l5d-header-middleware namespace: traefik spec: headers: customRequestHeaders: l5d-dst-override: "web-svc.emojivoto.svc.cluster.local:80" --- apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: annotations: kubernetes.io/ingress.class: traefik creationTimestamp: null name: emojivoto-web-ingress-route namespace: emojivoto spec: entryPoints: [] routes: - kind: Rule match: PathPrefix(`/`) priority: 0 middlewares: - name: l5d-header-middleware services: - kind: Service name: web-svc port: 80 EOF for i in `seq 1 10000`; do time curl -s http://$DNS > /dev/null; done for i in `seq 1 10000`; do time curl -s http://172.16.58.3.xip.io/color; done DNS=172.16.58.3.xip.io/color cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: kubernetes.io/ingress.class: traefik traefik.ingress.kubernetes.io/rewrite-target: / traefik.ingress.kubernetes.io/service-weights: | color-blue-svc: 90% color-green-svc: 10% name: colors namespace: colors spec: rules: - host: $DNS http: paths: - backend: serviceName: color-blue-svc servicePort: 80 path: /color - backend: serviceName: color-green-svc servicePort: 80 path: /color EOF ``` cat <<EOF | kubectl apply -f - apiVersion: traefik.containo.us/v1alpha1 kind: Middleware metadata: name: test-ratelimit spec: rateLimit: average: 1 burst: 2 EOF ## Traefik Oauth2Proxy https://geek-cookbook.funkypenguin.co.nz/reference/oauth_proxy/ configure app for azure https://pusher.github.io/oauth2_proxy/auth-configuration#azure-auth-provider use the following sign-on url https://dzapis.westeurope.cloudapp.azure.com https://dzapis.westeurope.cloudapp.azure.com/oauth2/callback github ``` generate cookie secret: python -c 'import os,base64; print base64.b64encode(os.urandom(16))' API_CLIENT_ID= API_CLIENT_SECRET= API_COOKIE_SECRET= ``` ``` helm install --name authproxy \ --namespace=kube-system \ --set config.clientID=$API_CLIENT_ID \ --set config.clientSecret=$API_CLIENT_SECRET \ --set config.cookieSecret=$API_COOKIE_SECRET \ --set extraArgs.provider=github \ --set resources.limits.cpu=200m \ stable/oauth2-proxy cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: kubernetes.io/ingress.class: traefik traefik.ingress.kubernetes.io/rewrite-target: / name: auth2 namespace: kube-system spec: rules: - host: dzapis.westeurope.cloudapp.azure.com http: paths: - backend: serviceName: authproxy-oauth2-proxy servicePort: 80 path: /oauth2 EOF ``` http://authproxy-oauth2-proxy.kube-system.svc.cluster.local:80/auth http://authproxy-oauth2-proxy.kube-system.svc.cluster.local:80/start configure forward authentication https://docs.traefik.io/configuration/entrypoints/#forward-authentication https://raw.githubusercontent.com/helm/charts/master/stable/traefik/values.yaml ``` helm upgrade mytraefik stable/traefik --values yaml/traefik.yaml --namespace kube-system --set dashboard.enabled=true,dashboard.domain=dashboard.localhost,rbac.enabled=true,loadBalancerIP=$IP,externalTrafficPolicy=Local,replicas=2,ssl.enabled=true,ssl.permanentRedirect=true,ssl.insecureSkipVerify=true,acme.enabled=true,acme.challengeType=http-01,acme.email=$MY_ID,acme.staging=false,forwardAuth.address=http://authproxy-oauth2-proxy.kube-system.svc.cluster.local:80 ```<file_sep># Kubernetes on Windows Version compatibility in container engine: https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/version-compatibility Windows walkthrough: https://github.com/Azure/acs-engine/blob/master/docs/kubernetes/windows.md#supported-windows-versions customizing windows deployments: https://github.com/Azure/acs-engine/blob/master/docs/kubernetes/windows-details.md#customizing-windows-deployments ## Get acs-engine Download latest release from https://github.com/Azure/acs-engine/releases/tag/v0.26.2 ``` wget https://github.com/Azure/acs-engine/releases/download/v0.26.2/acs-engine-v0.26.2-darwin-amd64.tar.gz tar -zxvf acs-engine-v0.26.2-darwin-amd64.tar.gz cd acs-engine-v0.26.2-darwin-amd64 ``` ## create mixed cluster set variables ``` KUBE_GROUP="dz-win-1709-L" KUBE_NAME="dz-win-1709-L" LOCATION="westeurope" ``` create resource group ``` az group create -n $KUBE_GROUP -l $LOCATION ``` get one of the sample templates from https://github.com/Azure/acs-engine/tree/master/examples/windows or use these ones https://github.com/denniszielke/container_demos/blob/master/aks-engine/acsengvnet-win-1809.json https://github.com/denniszielke/container_demos/blob/master/aks-engine/acsengvnet-win-1803.json make sure to set the variables for `SERVICE_PRINCIPAL_ID`, `SERVICE_PRINCIPAL_SECRET` and `YOUR_SSH_KEY` with your own values create arm template by using the acs-engine json ``` ./acs-engine generate acseng-1709-L.json ``` deploy arm template ``` az group deployment create \ --name $KUBE_NAME \ --resource-group $KUBE_GROUP \ --template-file "_output/$KUBE_NAME/azuredeploy.json" \ --parameters "_output/$KUBE_NAME/azuredeploy.parameters.json" ``` set the kubeconfig ``` export KUBECONFIG=`pwd`/_output/$KUBE_NAME/kubeconfig/kubeconfig.westeurope.json ``` check nodes ``` kubectl get node -l beta.kubernetes.io/os=windows -o wide kubectl get node -l beta.kubernetes.io/os=linux -o wide ``` open the dashboard by opening http://localhost:8081/ui ``` kubectl proxy ``` if you see the following error message error: unable to forward port because pod is not running. Current status=Pending create a binding for the dashboard account ``` kubectl create clusterrolebinding kubernetes-dashboard --clusterrole=cluster-admin --serviceaccount=kube-system:kubernetes-dashboard ``` create container registry authentication secret ``` REGISTRY_URL= REGISTRY_NAME= REGISTRY_PASSWORD= kubectl create secret docker-registry mobileregistry --docker-server $REGISTRY_URL --docker-username $REGISTRY_NAME --docker-password $REGISTRY_PASSWORD --docker-email '<EMAIL>' ``` ## Creating storage for the file share https://github.com/andyzhangx/demo/tree/master/windows ``` AKS_STORAGE_ACCOUNT_NAME= AKS_STORAGE_RESOURCE_GROUP= AKS_STORAGE_KEY= LOCATION=westeurope ```` create storage account ``` az storage account create --resource-group $AKS_STORAGE_RESOURCE_GROUP --name $AKS_STORAGE_ACCOUNT_NAME --location $LOCATION --sku Standard_LRS AKS_STORAGE_KEY=$(az storage account keys list --account-name $AKS_STORAGE_ACCOUNT_NAME --resource-group $AKS_STORAGE_RESOURCE_GROUP --query "[0].value") az storage share create -n www-content --quota 10 --account-name $AKS_STORAGE_ACCOUNT_NAME --account-key $AKS_STORAGE_KEY az storage share create -n www-configuration --quota 10 --account-name $AKS_STORAGE_ACCOUNT_NAME --account-key $AKS_STORAGE_KEY az storage share create -n publicweb-content --quota 10 --account-name $AKS_STORAGE_ACCOUNT_NAME --account-key $AKS_STORAGE_KEY kubectl create secret generic azure-secret --from-literal=azurestorageaccountname=$AKS_STORAGE_ACCOUNT_NAME --from-literal=azurestorageaccountkey=$AKS_STORAGE_KEY ``` ## Setting up ingress in a mixed cluster https://github.com/Azure/acs-engine/blob/master/docs/kubernetes/mixed-cluster-ingress.md init helm only on linux boxes ``` helm init --upgrade --node-selectors "beta.kubernetes.io/os=linux" helm install --name nginx-ingress \ --set controller.nodeSelector."beta\.kubernetes\.io\/os"=linux \ --set defaultBackend.nodeSelector."beta\.kubernetes\.io\/os"=linux \ --set rbac.create=true \ stable/nginx-ingress ``` create hello world app ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/aci-helloworld/iis-win-1803.yaml ``` create ingress ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/aci-helloworld/ingress-win-1803.yaml ``` ## Additional getting logs from windows agents: https://github.com/andyzhangx/Demo/tree/master/debug#q-how-to-get-k8s-kubelet-logs-on-windows-agent using storage in windows agents: https://github.com/andyzhangx/demo/tree/master/windows ## Issues - AHS VHD https://github.com/Azure/aks-engine/tree/master/vhd/release-notes/aks-windows - Windows Containers (Pods) does not respect CPU Resources Limits in AKS v 1.17.X https://github.com/kubernetes/kubernetes/pull/86101 - Host Aliases do not work in Windows Container RUN Add-Content -Path C:\Windows\System32\drivers\etc\hosts -Value https://github.com/kubernetes/kubernetes/issues/91132 - Timezone https://github.com/microsoft/Windows-Containers/issues/15 - AHAB https://docs.microsoft.com/en-us/azure/aks/windows-faq#can-i-use-azure-hybrid-benefit-with-windows-nodes - Keine Hyper-V Isolated Container - ContainerD (with Hyper-V) Windows Containers (Pods) does not respect CPU Resources Limits in AKS v 1.17.X Setting CPU resource Limits in Windows Container (Pod) yaml files are neglected causing the PODs to starve the node resources, which in turn makes it very hard to roll deployment updates, as there is no room for max surge pods to be deployed. The issue is fixed in this GitHub pull request and rolled out starting version k8s 1.18. Host Aliases does not work in Windows Containers. Unexpectedly setting Host Aliases in Windows Pod yaml files will be neglected, according to the following issue raised in GitHub, it is a known issue in Kubernetes, we ended up adding the following command in the docker file to overcome this: RUN Add-Content -Path C:\Windows\System32\drivers\etc\hosts -Value "<IP>`<Domain>" -Force The need of increased Worker Processes to Increase performance. We noticed a slowness and a waste of CPU resources, due the fact that each Windows Pod is only running one worker process, we managed to overcome this issue by adding the following line to docker file: RUN C:\windows\system32\inetsrv\appcmd.exe set apppool "DefaultAppPool" /processModel.maxProcesses:5 Which in turn increased worker processes to 5 wps, and also helped in mitigating the risk of SQL Server backend reaching the limit of 32767 max concurrent connections. Linux nodes taking over the responsibility of In/Out Bandwidth. Environment Variables are not automatically favored over Application configuration files. Lack of official SMB drivers for mounting PVT based on Caching Servers. <file_sep> # Linkerd Basics https://linkerd.io/2/getting-started/ export KUBECONFIG=~/kubecon-workshop-20-kubeconfig export PATH=$PATH:$HOME/.linkerd2/bin ## setup books app curl -sL https://run.linkerd.io/booksapp.yml \ | kubectl apply -f - curl -sL https://run.linkerd.io/emojivoto.yml \ | kubectl apply -f - kubectl apply -f booksapp.yml kubectl delete -f booksapp.yml linkerd install | kubectl apply -f - see yaml kubectl get deploy -o yaml | linkerd inject - inject yaml kubectl get deploy -o yaml | linkerd inject - | kubectl apply -f - kubectl get deploy -o yaml -n $APP_NS | linkerd inject - | kubectl apply -f - kubectl get -n emojivoto deploy -o yaml \ | linkerd inject - \ | kubectl apply -f - kubectl get deploy -o yaml \ | linkerd inject - \ | kubectl apply -f - ## get swagger and create service profile curl https://run.linkerd.io/booksapp/authors.swagger create service profile curl https://run.linkerd.io/booksapp/authors.swagger | linkerd profile --open-api - authors apply service profile curl https://run.linkerd.io/booksapp/authors.swagger | linkerd profile --open-api - authors | kubectl apply -f - cat apps/js-calc-backend/app/swagger.json | linkerd profile --open-api - $APP_IN-calc-backend-svc | kubectl apply -f - check routes linkerd routes svc/authors linkerd routes svc/$APP_IN-calc-backend-svc -n $APP_NS ## create ingress kubectl apply -f ingress-mandatory.yml kubectl apply -f nginx-ingress-svc.yml inject linkerd into ingress controller kubectl -n ingress-nginx get deployment -o yaml | linkerd inject - | kubectl apply -f - configure books app ingress kubectl apply -f books-ingress.yml Uncomment in books-ingress.yml to remove host header lookup # nginx.ingress.kubernetes.io/configuration-snippet: | # proxy_set_header l5d-dst-override $service_name.$namespace.svc.cluster.local:7000; # proxy_hide_header l5d-remote-ip; # proxy_hide_header l5d-server-id; curl -v http://34.90.58.35 linkerd routes svc/authors ## insert retries https://linkerd.io/2/tasks/configuring-retries/ https://linkerd.io/2/tasks/books/#retries linkerd routes deploy/books --to svc/authors linkerd routes deployment/multicalchart-backend --namespace $APP_NS --to svc/$APP_IN-calc-backend-svc --to-namespace $APP_NS linkerd routes deployment/multicalchart-frontend --namespace $APP_NS --to deployment/multicalchart-backend --to-namespace $APP_NS -o wide KUBE_EDITOR="nano" KUBE_EDITOR="nano" kubectl edit sp/authors.default.svc.cluster.local add isRetryable: true - condition: method: HEAD pathRegex: /authors/[^/]*\.json name: HEAD /authors/{id}.json isRetryable: true kubectl edit sp/$APP_IN-calc-backend-svc.default.svc.cluster.local -n $APP_NS kubectl edit sp/calc1-calc-backend-svc.default.svc.cluster.local check for effective succeess linkerd routes deploy/books --to svc/authors -o wide linkerd routes deploy/books --to svc/authors -o wide ROUTE SERVICE EFFECTIVE_SUCCESS EFFECTIVE_RPS ACTUAL_SUCCESS ACTUAL_RPS LATENCY_P50 LATENCY_P95 LATENCY_P99 DELETE /authors/{id}.json authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms GET /authors.json authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms GET /authors/{id}.json authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms HEAD /authors/{id}.json authors 88.54% 2.6rps 57.44% 4.0rps 4ms 10ms 18ms POST /authors.json authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms [DEFAULT] authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms ## insert timeout https://linkerd.io/2/tasks/configuring-timeouts/ kubectl edit sp/authors.default.svc.cluster.local insert timeout into spec - condition: method: HEAD pathRegex: /authors/[^/]*\.json isRetryable: true timeout: 10ms name: HEAD /authors/{id}.json linkerd routes deploy/books --to svc/authors -o wide ROUTE SERVICE EFFECTIVE_SUCCESS EFFECTIVE_RPS ACTUAL_SUCCESS ACTUAL_RPS LATENCY_P50 LATENCY_P95 LATENCY_P99 DELETE /authors/{id}.json authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms GET /authors.json authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms GET /authors/{id}.json authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms HEAD /authors/{id}.json authors 88.54% 2.6rps 57.44% 4.0rps 4ms 10ms 18ms POST /authors.json authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms [DEFAULT] authors 0.00% 0.0rps 0.00% 0.0rps 0ms 0ms 0ms linkerd routes deployment/multicalchart-frontend -n $APP_NS --to svc/calc1-calc-backend-svc -n $APP_NS -o wide # Linkerd Security check linkerd issuer secret kubectl get secret linkerd-identity-issuer -n linkerd -o yaml check trust root kubectl get configmap linkerd-config -n linkerd -o yaml https://medium.com/solo-io/linkerd-or-istio-6fcd2aad6e42 cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: netshoot spec: containers: - name: netshoot image: nicolaka/netshoot ports: - containerPort: 80 command: - sleep - "3600" EOF http_proxy=$HOST_IP:$(kubectl get svc l5d -o 'jsonpath={.spec.ports[0].nodePort}') curl -s http://hello http_proxy=$INGRESS_LB:4140 curl -s http://hello curl -skH 'l5d-dtab: /svc=>/#/io.l5d.k8s/default/admin/l5d;' https://$INGRESS_LB:4141/admin/ping # Linkerd Debugging linkerd tap deploy/webapp -o wide | grep req linkerd tap deploy/webapp -o wide --path=/authors linkerd tap deployment/books --namespace default --to deployment/authors --to-namespace default show all failed requests linkerd tap deployment/authors | grep :status=503 linkerd tap deployment/authors | grep :status=503 -C 1 linkerd tap deploy/authors --to ns/default -o wide | grep rt_route="GET /authors" invert all that do not send to any route linkerd tap deploy/authors --to ns/default -o wide | grep -v rt_route kubectl -n booksapp port-forward svc/webapp 7000 curl -sL https://run.linkerd.io/booksapp/webapp.swagger \ | linkerd -n booksapp profile --open-api - webapp \ | kubectl -n booksapp apply -f - kubectl get ServiceProfile kubectl -n booksapp edit sp/authors.booksapp.svc.cluster.local linkerd -n booksapp routes deploy/books --to svc/authors -o wide ## Linkerd multi cluster linkerd multicluster uninstall | kubectl delete -f - linkerd multicluster unlink --cluster-name=dzdublin | kubectl delete -f - linkerd viz uninstall | kubectl delete -f - kubectl config rename-context dzparis-admin dzparis kubectl config rename-context dzdublin-admin dzdublin kubectl config use-context dzdublin kubectl config use-context dzparis west=dzparis east=dzdublin step certificate create root.linkerd.cluster.local root.crt root.key \ --profile root-ca --no-password --insecure step certificate create identity.linkerd.cluster.local issuer.crt issuer.key \ --profile intermediate-ca --not-after 8760h --no-password --insecure \ --ca root.crt --ca-key root.key linkerd install \ --identity-trust-anchors-file root.crt \ --identity-issuer-certificate-file issuer.crt \ --identity-issuer-key-file issuer.key \ | tee \ >(kubectl --context=dzparis apply -f -) \ >(kubectl --context=dzdublin apply -f -) for ctx in dzparis dzdublin; do linkerd --context=${ctx} viz install | \ kubectl --context=${ctx} apply -f - || break done for ctx in dzparis dzdublin; do echo "Checking cluster: ${ctx} ........." linkerd --context=${ctx} check || break echo "-------------" done for ctx in dzparis dzdublin; do echo "Installing on cluster: ${ctx} ........." linkerd --context=${ctx} multicluster install | \ kubectl --context=${ctx} apply -f - || break echo "-------------" done for ctx in dzparis dzdublin; do echo "Checking gateway on cluster: ${ctx} ........." kubectl --context=${ctx} -n linkerd-multicluster \ rollout status deploy/linkerd-gateway || break echo "-------------" done for ctx in dzparis dzdublin; do printf "Checking cluster: ${ctx} ........." while [ "$(kubectl --context=${ctx} -n linkerd-multicluster get service -o 'custom-columns=:.status.loadBalancer.ingress[0].ip' --no-headers)" = "<none>" ]; do printf '.' sleep 1 done printf "\n" done linkerd --context=dzdublin multicluster link --cluster-name dzdublin | kubectl --context=dzparis apply -f - linkerd --context=dzparis multicluster check linkerd --context=dzdublin multicluster check kubectl label namespace dummy-logger "linkerd.io/inject=enabled" kubectl apply -f logging/dummy-logger/depl-logger.yaml -n dummy-logger kubectl apply -f logging/dummy-logger/depl-explorer.yaml -n dummy-logger kubectl apply -f logging/dummy-logger/svc-cluster-logger.yaml -n dummy-logger kubectl apply -f logging/dummy-logger/svc-cluster-explorer.yaml -n dummy-logger kubectl get deploy -o yaml -n dummy-logger | linkerd inject - | kubectl apply -f - kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-$APP_NAMESPACE namespace: $APP_NAMESPACE annotations: cert-manager.io/cluster-issuer: letsencrypt nginx.ingress.kubernetes.io/service-upstream: "true" nginx.ingress.kubernetes.io/rewrite-target: / spec: tls: - hosts: - $DNS secretName: $SECRET_NAME ingressClassName: nginx rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: explorer port: number: 80 - path: /dummy-logger pathType: Prefix backend: service: name: dummy-logger port: number: 80 - path: /explorer pathType: Prefix backend: service: name: explorer port: number: 80 EOF linkerd --context=dzdublin-admin multicluster link --cluster-name dzdublin | kubectl --context=dzparis-admin apply -f - linkerd --context=dzparis multicluster check linkerd --context=dzdublin multicluster check linkerd --context=dzparis-admin multicluster gateways <file_sep># Managed OpenShift https://github.com/Azure/OpenShift https://docs.microsoft.com/en-us/azure/aks/aad-integration create app id and create permissions the same as for aks ``` az ad app create --display-name $OSA_CLUSTER_NAME --key-type Password --password $OSA_AAD_SECRET --identifier-uris $OSA_AAD_REPLY_URL --reply-urls $OSA_AAD_REPLY_URL ``` Define variables ``` OSA_RG_NAME=dzopenshdemo OSA_CLUSTER_NAME=dzosa123 LOCATION=westeurope OSA_AAD_SECRET=supersecret OSA_AAD_ID=herebeaadclientid OSA_AAD_TENANT=herebeaadtenant OSA_AAD_REPLY_URL=https://$OSA_CLUSTER_NAME.$LOCATION.cloudapp.azure.com/oauth2callback/Azure%20AD OSA_FQDN=$OSA_CLUSTER_NAME.$LOCATION.cloudapp.azure.com OSA_ADMIN_GROUP_ID=herebeadmingroupobjectid ``` ## create cluster via cli ``` az group create --name $OSA_RG_NAME --location $LOCATION az openshift create --resource-group $OSA_RG_NAME --name $OSA_CLUSTER_NAME -l $LOCATION --fqdn $OSA_FQDN --aad-client-app-id $OSA_AAD_ID --aad-client-app-secret $OSA_AAD_SECRET --aad-tenant-id $OSA_AAD_TENANT open https://dzosa123.westeurope.cloudapp.azure.com oc new-app openshift/ruby:25~https://github.com/denniszielke/ruby-ex https://dzosa123.westeurope.cloudapp.azure.com/oauth2callback/Azure%20AD https://openshift.454daa57a4544cc88ceb.westeurope.azmosa.io/oauth2callback/Azure%20AD https://openshift.xxxxxxx.westeurope.azmosa.io/oauth2callback/Azure%20AD ``` ## create via arm ``` az group create -n $OSA_RG_NAME -l $LOCATION az group deployment create \ --name openshiftmanaged \ --resource-group $OSA_RG_NAME \ --template-file "arm/openshift_template.json" \ --parameters "arm/openshift_parameters.json" \ --parameters "resourceName=$OSA_CLUSTER_NAME" \ "location=$LOCATION" \ "fqdn=$OSA_FQDN" \ "servicePrincipalClientId=$OSA_AAD_ID" \ "servicePrincipalClientSecret=$OSA_AAD_SECRET" \ "tenantId=$OSA_AAD_TENANT" \ "customerAdminGroupId=$OSA_ADMIN_GROUP_ID" ``` ## cluster operations ``` az openshift scale --resource-group $OSA_RG_NAME --name $OSA_CLUSTER_NAME --compute-count 5 az openshift delete --resource-group $OSA_RG_NAME --name $OSA_CLUSTER_NAME ``` ## delete via arm https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/delete ## ARO 4.3 https://github.com/Azure/ARO-RP/blob/master/docs/using-az-aro.md <file_sep># Kubernetes ingress controller Easy way via helm https://docs.microsoft.com/en-us/azure/aks/ingress https://github.com/helm/charts/tree/master/stable/nginx-ingress ## Internal Ip Configur ingress variables to use internal assigned ip adress from a different subnet ``` INTERNALINGRESSIP="10.0.2.10" INGRESSSUBNETNAME="InternalIngressSubnet" ``` "annotations": { "service.beta.kubernetes.io/azure-load-balancer-internal": "true" } helm install stable/nginx-ingress --name ingress-controller --namespace kube-system --set controller.service.enableHttps=false -f ingres-values.yaml helm delete ingress-controller --purge cat <<EOF | kubectl create -n nginx-demo -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: nginx-ingress annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - http: paths: - path: / backend: serviceName: nginx servicePort: 80 EOF ## External Ip, DNS and Certificate https://docs.microsoft.com/en-us/azure/aks/ingress#install-an-ingress-controller Create a public ip adress ``` IP_NAME=myAKSPublicIP az network public-ip create --resource-group $NODE_GROUP --name $IP_NAME --allocation-method static IP=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query ipAddress --output tsv) ``` Use the assigned ip address in the helm chart ``` helm upgrade stable/nginx-ingress --install ingress-controller --namespace kube-system --set rbac.create=true --set controller.service.loadBalancerIP="$IP" --set controller.stats.enabled=true --set controller.replicaCount=2 --set controller.service.externalTrafficPolicy=Local helm upgrade ingress-controller stable/nginx-ingress --install --namespace kube-system --set controller.stats.enabled=true --set controller.replicaCount=2 --set controller.service.externalTrafficPolicy=Local helm install stable/nginx-ingress --name ingress-controller --namespace kube-system --set controller.service.externalTrafficPolicy=Local helm upgrade quiet-echidna stable/nginx-ingress --set controller.service.externalTrafficPolicy=Local # dedicate dip helm upgrade nginx-ingress stable/nginx-ingress --set controller.service.externalTrafficPolicy=Local --set controller.replicaCount=2 --set controller.service.loadBalancerIP=172.16.31.10 --set rbac.create=true --namespace kube-system # internal helm upgrade nginx-ingress stable/nginx-ingress --set controller.service.externalTrafficPolicy=Local --set controller.replicaCount=2 --set rbac.create=true --set controller.service.annotations="{service.beta.kubernetes.io/azure-load-balancer-internal:\\"true"} --namespace kube-system helm upgrade --install nginx-ingress stable/nginx-ingress --set controller.service.externalTrafficPolicy=Local --set controller.replicaCount=2 --set controller.metrics.enabled=true --set controller.stats.enabled=true --namespace ingress helm upgrade --install nginx-ingress stable/nginx-ingress --set controller.service.externalTrafficPolicy=Local --set controller.replicaCount=2 --namespace ingress KUBE_EDITOR="nano" kubectl edit svc/nginx-ingress-controller -n kube-system service.beta.kubernetes.io/azure-load-balancer-internal: "true" controller: service: loadBalancerIP: 10.240.0.42 annotations: service.beta.kubernetes.io/azure-load-balancer-internal: "true" --set ingress.annotations={kubernetes.io/ingress.class:\\n\\nginx} config-service --set alertmanager.ingress.annotations."alb\.ingress\.kubernetes\.io/scheme"=internet-facing ``` ## DNSName to associate with public IP address https://docs.microsoft.com/en-us/azure/aks/ingress#configure-a-dns-name ``` DNSNAME="dzapis" PUBLICIPID=$(az network public-ip list --query "[?ipAddress!=null]|[?contains(ipAddress, '$IP')].[id]" --output tsv) DNS=$DNSNAME.westeurope.cloudapp.azure.com az network public-ip update --ids $PUBLICIPID --dns-name $DNSNAME ``` ## Create dummy ingress for challenge dzapis.westeurope.cloudapp.azure.com ``` kubectl run nginx --image nginx --port=80 kubectl expose deployment nginx --type=ClusterIP cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: nginx-ingress annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - host: $DNS http: paths: - path: / backend: serviceName: nginx servicePort: 80 EOF cat <<EOF | kubectl create -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: nginx-ingress annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/rewrite-target: / spec: tls: - hosts: - $DNS secretName: hello-tls-secret rules: - host: $DNS http: paths: - path: / backend: serviceName: nginx servicePort: 80 EOF ``` launch dns ``` open http://$DNS ``` install demo app ``` helm repo add azure-samples https://azure-samples.github.io/helm-charts/ helm install azure-samples/aks-helloworld helm install azure-samples/aks-helloworld --set title="AKS Ingress Demo" --set serviceName="ingress-demo" ``` ## Install certmanager for letsencrypt suppot https://docs.microsoft.com/en-us/azure/aks/ingress#install-cert-manager install cert manager ``` helm install stable/cert-manager --name cert-issuer-manager --namespace kube-system --set ingressShim.defaultIssuerName=letsencrypt-prod --set ingressShim.defaultIssuerKind=ClusterIssuer ``` create cert manager cluster issuer for stage or prod ``` cat <<EOF | kubectl apply -f - apiVersion: certmanager.k8s.io/v1alpha1 kind: ClusterIssuer metadata: name: letsencrypt-prod namespace: ingress-basic spec: acme: server: https://acme-v02.api.letsencrypt.org/directory email: $MY_USER_ID privateKeySecretRef: name: letsencrypt-prod http01: {} EOF ``` staging ``` cat <<EOF | kubectl apply -f - apiVersion: certmanager.k8s.io/v1alpha1 kind: ClusterIssuer metadata: name: letsencrypt-prod spec: acme: server: https://acme-staging-v02.api.letsencrypt.org/directory email: $MY_USER_ID privateKeySecretRef: name: letsencrypt-prod http01: {} EOF ``` create certificate ``` cat <<EOF | kubectl apply -f - apiVersion: certmanager.k8s.io/v1alpha1 kind: Certificate metadata: name: hello-tls-secret spec: secretName: hello-tls-secret dnsNames: - $DNS acme: config: - http01: ingressClass: nginx domains: - $DNS issuerRef: name: letsencrypt-prod kind: ClusterIssuer EOF ``` you can now create the nginx-ingress ``` kubectl delete ingress nginx-ingress ``` create ingress ``` cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: hello-world-ingress namespace: ingress-basic annotations: kubernetes.io/ingress.class: nginx certmanager.k8s.io/cluster-issuer: letsencrypt-staging nginx.ingress.kubernetes.io/rewrite-target: /$1 spec: tls: - hosts: - dzapis.westeurope.cloudapp.azure.com secretName: tls-secret rules: - host: dzapis.westeurope.cloudapp.azure.com http: paths: - backend: serviceName: aks-helloworld servicePort: 80 path: /(.*) EOF ``` Cleanup ``` kubectl delete ingress hello-world-ingress kubectl delete certificate hello-tls-secret kubectl delete clusterissuer letsencrypt-staging helm delete cert-issuer-manager --purge ``` ## Ingress controller manually 1. Provision default backend ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/services/default-backend.yaml ``` 2. Create ingress service ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/services/default-svc.yaml ``` 3. Create ingress service ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/services/ingress-svc.yaml ``` 4. Get ingress public ip adress to that service ``` kubectl get svc ``` 5. Create ingress controller ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/services/ingress-ctl.yaml ``` 6. Deploy ingress ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/services/color-ingress.yaml ``` Test it ``` curl -H 'Host:mysite.com' [ALB_IP] ``` ## Ingress & SSL Termination https://kubernetes.io/docs/concepts/services-networking/ingress/ https://dgkanatsios.com/2017/07/07/using-ssl-for-a-service-hosted-on-a-kubernetes-cluster/ https://blogs.technet.microsoft.com/livedevopsinjapan/2017/02/28/configure-nginx-ingress-controller-for-tls-termination-on-kubernetes-on-azure-2/ https://daemonza.github.io/2017/02/13/kubernetes-nginx-ingress-controller/ ``` git clone https://github.com/kubernetes/ingress.git cd ingress/examples/deployment/nginx kubectl apply -f default-backend.yaml kubectl -n kube-system get po kubectl apply -f nginx-ingress-controller.yaml kubectl -n kube-system get po openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout tls.key -out tls.crt -subj "/CN=nginxsvc/O=nginxsvc" kubectl create secret tls tls-secret --key tls.key --cert tls.crt kubectl create -f http-svc.yaml nano http-svc.yaml kubectl create -f http-svc.yaml kubectl get service nano nginx-tls-ingress.yaml kubectl create -f nginx-tls-ingress.yaml rm nginx-tls-ingress.yaml nano nginx-tls-ingress.yaml kubectl create -f nginx-tls-ingress.yaml kubectl get rs --namespace kube-system kubectl expose rs nginx-ingress-controller-2781903634 --port=443 --target-port=443 --name=nginx-ingress-ssl --type=LoadBalancer --namespace kube-system kubectl get services --namespace kube-system -w ``` ## App Routing-Addon ``` kubectl patch svc nginx -n app-routing-system -p '{"metadata": {"annotations":{"service.beta.kubernetes.io/azure-load-balancer-internal":"true"}} }' ```<file_sep>#!/bin/bash set -e # infrastructure deployment properties PROJECT_NAME="$1" LOCATION="$2" CONTROLLER_IDENTITY_NAME="$3" if [ "$PROJECT_NAME" == "" ]; then echo "No project name provided - aborting" exit 0; fi if [ "$LOCATION" == "" ]; then echo "No location provided - aborting" exit 0; fi if [[ $PROJECT_NAME =~ ^[a-z0-9]{5,9}$ ]]; then echo "project name $PROJECT_NAME is valid" else echo "project name $PROJECT_NAME is invalid - only numbers and lower case min 5 and max 8 characters allowed - aborting" exit 0; fi RESOURCE_GROUP="$PROJECT_NAME" AZURE_CORE_ONLY_SHOW_ERRORS="True" if [ $(az group exists --name $RESOURCE_GROUP) = false ]; then echo "creating resource group $RESOURCE_GROUP..." az group create -n $RESOURCE_GROUP -l $LOCATION -o none echo "resource group $RESOURCE_GROUP created" else echo "resource group $RESOURCE_GROUP already exists" LOCATION=$(az group show -n $RESOURCE_GROUP --query location -o tsv) fi echo "setting up vnet" KUBE_VNET_NAME="$PROJECT_NAME-vnet" KUBE_ING_SUBNET_NAME="$PROJECT_NAME-ingress" AKS_SUBNET_NAME="$PROJECT_NAME-aks" VNET_RESOURCE_ID=$(az network vnet list -g $RESOURCE_GROUP --query "[?contains(name, '$KUBE_VNET_NAME')].id" -o tsv) if [ "$VNET_RESOURCE_ID" == "" ]; then echo "creating vnet $KUBE_VNET_NAME..." az network vnet create --address-prefixes "10.0.0.0/24" -g $RESOURCE_GROUP -n $KUBE_VNET_NAME -o none az network vnet subnet create -g $RESOURCE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.0.0/28 -o none az network vnet subnet create -g $RESOURCE_GROUP --vnet-name $KUBE_VNET_NAME -n $AKS_SUBNET_NAME --address-prefix 10.0.0.32/27 -o none VNET_RESOURCE_ID=$(az network vnet show -g $RESOURCE_GROUP -n $KUBE_VNET_NAME --query id -o tsv) echo "created $VNET_RESOURCE_ID" else echo "vnet $VNET_RESOURCE_ID already exists" fi NSG_RESOURCE_ID=$(az network nsg list -g $RESOURCE_GROUP --query "[?contains(name, '$AKS_SUBNET_NAME')].id" -o tsv) if [ "$NSG_RESOURCE_ID" == "" ]; then echo "creating nsgs..." az network nsg create --name $KUBE_ING_SUBNET_NAME --resource-group $RESOURCE_GROUP --location $LOCATION az network nsg rule create --name appgwrule --nsg-name $KUBE_ING_SUBNET_NAME --resource-group $RESOURCE_GROUP --priority 110 \ --source-address-prefixes '*' --source-port-ranges '*' \ --destination-address-prefixes '*' --destination-port-ranges 80 443 --access Allow --direction Inbound \ --protocol "*" --description "Required allow rule for Ingress." KUBE_ING_SUBNET_NSG=$(az network nsg show -g $RESOURCE_GROUP -n $KUBE_ING_SUBNET_NAME --query id -o tsv) KUBE_ING_SUBNET_ID=$(az network vnet subnet show -g $RESOURCE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --query id -o tsv) az network vnet subnet update --resource-group $RESOURCE_GROUP --network-security-group $KUBE_ING_SUBNET_NSG --ids $KUBE_ING_SUBNET_ID echo "attached nsg to subnet $KUBE_ING_SUBNET_ID" az network nsg create --name $AKS_SUBNET_NAME --resource-group $RESOURCE_GROUP --location $LOCATION az network nsg rule create --name ingress --nsg-name $AKS_SUBNET_NAME --resource-group $RESOURCE_GROUP --priority 110 \ --source-address-prefixes '*' --source-port-ranges '*' \ --destination-address-prefixes '*' --destination-port-ranges 80 443 --access Allow --direction Inbound \ --protocol "*" --description "Required to allow ingress." KUBE_AGENT_SUBNET_NSG=$(az network nsg show -g $RESOURCE_GROUP -n $AKS_SUBNET_NAME --query id -o tsv) KUBE_AGENT_SUBNET_ID=$(az network vnet subnet show -g $RESOURCE_GROUP --vnet-name $KUBE_VNET_NAME -n $AKS_SUBNET_NAME --query id -o tsv) az network vnet subnet update --resource-group $RESOURCE_GROUP --network-security-group $KUBE_AGENT_SUBNET_NSG --ids $KUBE_AGENT_SUBNET_ID echo "attached nsg to subnet $KUBE_AGENT_SUBNET_ID" echo "cread nsgs " else echo "nsg $NSG_RESOURCE_ID already exists" fi KUBE_ING_SUBNET_ID=$(az network vnet subnet show -g $RESOURCE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --query id -o tsv) KUBE_AGENT_SUBNET_ID=$(az network vnet subnet show -g $RESOURCE_GROUP --vnet-name $KUBE_VNET_NAME -n $AKS_SUBNET_NAME --query id -o tsv) AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $RESOURCE_GROUP --query "[?contains(name, '$CONTROLLER_IDENTITY_NAME')].id" -o tsv)" if [ "$AKS_CONTROLLER_RESOURCE_ID" == "" ]; then echo "controller identity $CONTROLLER_IDENTITY_NAME does not exist in resource group $RESOURCE_GROUP - creating..." az identity create --name $CONTROLLER_IDENTITY_NAME --resource-group $RESOURCE_GROUP -o none sleep 10 # wait for replication AKS_CONTROLLER_CLIENT_ID="$(az identity show -g $RESOURCE_GROUP -n $CONTROLLER_IDENTITY_NAME --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $RESOURCE_GROUP -n $CONTROLLER_IDENTITY_NAME --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 20 # wait for replication AKS_CONTROLLER_CLIENT_ID="$(az identity show -g $RESOURCE_GROUP -n $CONTROLLER_IDENTITY_NAME --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $RESOURCE_GROUP -n $CONTROLLER_IDENTITY_NAME --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 20 # wait for replication az role assignment create --role "Network Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none az role assignment create --role "Network Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_ING_SUBNET_ID -o none else echo "controller identity $AKS_CONTROLLER_RESOURCE_ID already exists" fi <file_sep># Setting up Firewall + AKS Every now and then we get the question on how to lock down ingoing to and outgoing traffic from the kubernetes cluster in azure. One option that can be set up relativly easy but is not documented in detail is using the Azure Firewall (https://azure.microsoft.com/en-us/services/azure-firewall/). The end result will look like this and requires some steps to configure the vnet, subnets, routetable, firewall rules and azure kubernetes services which are described below: ![](/img/aks-firewall.png) My personal recommendation on this scenario is to use the firewall to diagnose the network dependencies of your applications - which is why I am also documenting the services that are currently needed for aks to run. If you turn on the rules to block outgoing traffic, you risk that your cluster breaks if the engineering team brings in additional required network dependencies. ## setting up the vnet First we will setup the vnet - I prefer using azure cli over powershell but you can easy achieve the same using terraform or arm. If you have preferences on the naming conventions please adjust the variables below. In most companies the vnet is provided by the networking team so we should assume that the network configuration will not be done by the teams which is maintaining the aks cluster. 0. Variables ``` SUBSCRIPTION_ID="" # here enter your subscription id KUBE_GROUP="kubes_fw_knet" # here enter the resources group name of your aks cluster KUBE_NAME="dzkubekube" # here enter the name of your kubernetes resource LOCATION="westeurope" # here enter the datacenter location KUBE_VNET_NAME="knets" # here enter the name of your vnet KUBE_FW_SUBNET_NAME="AzureFirewallSubnet" # this you cannot change KUBE_ING_SUBNET_NAME="ing-4-subnet" # here enter the name of your ingress subnet KUBE_AGENT_SUBNET_NAME="aks-5-subnet" # here enter the name of your aks subnet FW_NAME="dzkubenetfw" # here enter the name of your azure firewall resource FW_IP_NAME="azureFirewalls-ip" # here enter the name of your public ip resource for the firewall KUBE_VERSION="1.11.5" # here enter the kubernetes version of your aks SERVICE_PRINCIPAL_ID= # here enter the service principal of your aks SERVICE_PRINCIPAL_SECRET= # here enter the service principal secret ``` 1. Select subscription, create the resource group and the vnet ``` az feature register --name APIServerSecurityPreview --namespace Microsoft.ContainerService az feature list -o table --query "[?contains(name, 'Microsoft.Container‐Service/APIServerSecurityPreview')].{Name:name,State:properties.state}" az provider register --namespace Microsoft.ContainerService az account set --subscription $SUBSCRIPTION_ID az group create -n $KUBE_GROUP -l $LOCATION az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME ``` 2. Assign permissions on vnet for your service principal - usually "virtual machine contributor is enough" ``` az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP az role assignment create --role "Virtual Machine Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP ``` 3. Create subnets for the firewall, ingress and aks ``` az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_FW_SUBNET_NAME --address-prefix 10.0.3.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage ``` ## setting up the cluster As you might know there are two different options on how networking can be set up in aks called "Basic networking" and "Advanced Networking". I am not going into detail how they differ - you can look it up here: https://docs.microsoft.com/en-us/azure/aks/concepts-network . For the usage of azure firewall in this scenario it does not matter since both options work but need to be configured differently, which is why I am documenting both options. ### setting up aks cluster with basic networking Basic networking requires to modify the routetable that will be created by the aks deployment, add another route and point it towards the internal ip of the azure firewall. If you want to use advanced networking skip this section and continue below. 4. Create the aks cluster ``` KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --network-plugin kubenet --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --enable-rbac --node-vm-size "Standard_D2s_v3" --vm-set-type VirtualMachineScaleSets --load-balancer-sku standard ``` 5. Create azure firewall * this is currently not possible via cli - the creation of the azure firewall in that vnet is only possible with the azure portal * ``` az extension add --name azure-firewall az network public-ip create -g $KUBE_GROUP -n $FW_NAME-ip --sku Standard az network firewall create --name $FW_NAME --resource-group $KUBE_GROUP --location $LOCATION az network firewall ip-config create --firewall-name $FW_NAME --name $FW_NAME --public-ip-address $FW_NAME-ip --resource-group $KUBE_GROUP --vnet-name $KUBE_VNET_NAME FW_PRIVATE_IP=$(az network firewall show -g $KUBE_GROUP -n $FW_NAME --query "ipConfigurations[0].privateIpAddress" -o tsv) az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $FW_NAME-lgw --location $LOCATION KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az network route-table create -g $KUBE_GROUP --name $FW_NAME-rt az network route-table route create --resource-group $KUBE_GROUP --name $FW_NAME --route-table-name $FW_NAME-rt --address-prefix 0.0.0.0/0 --next-hop-type VirtualAppliance --next-hop-ip-address $FW_PRIVATE_IP az network vnet subnet update --route-table $FW_NAME-rt --ids $KUBE_AGENT_SUBNET_ID az network route-table route list --resource-group $KUBE_GROUP --route-table-name $FW_NAME-rt az network firewall network-rule create --firewall-name $FW_NAME --collection-name "time" --destination-addresses "*" --destination-ports 123 --name "allow network" --protocols "UDP" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "aks node time sync rule" --priority 101 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "dns" --destination-addresses "*" --destination-ports 53 --name "allow network" --protocols "UDP" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "aks node dns rule" --priority 102 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "servicetags" --destination-addresses "AzureContainerRegistry" "MicrosoftContainerRegistry" "AzureActiveDirectory" "AzureMonitor" --destination-ports "*" --name "allow service tags" --protocols "Any" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "allow service tags" --priority 110 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "hcp" --destination-addresses "*" --destination-ports "1194" --name "allow master tags" --protocols "Any" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "allow tunnel access" --priority 120 az network firewall application-rule create --firewall-name $FW_NAME --resource-group $KUBE_GROUP --collection-name 'aksfwar' -n 'fqdn' --source-addresses '*' --protocols 'http=80' 'https=443' --fqdn-tags "AzureKubernetesService" --action allow --priority 101 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "osupdates" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $KUBE_GROUP --action "Allow" --target-fqdns "download.opensuse.org" "security.ubuntu.com" "packages.microsoft.com" "azure.archive.ubuntu.com" "changelogs.ubuntu.com" "snapcraft.io" "api.snapcraft.io" "motd.ubuntu.com" --priority 102 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "dockerhub" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $KUBE_GROUP --action "Allow" --target-fqdns "*auth.docker.io" "*cloudflare.docker.io" "*cloudflare.docker.com" "*registry-1.docker.io" --priority 200 ``` 6. Create UDR After the deployment we create another route in the routetable and associate the route table to the subnet - which is required due to the known bug that is currently in aks (https://github.com/Azure/AKS/issues/718) ``` FW_ROUTE_NAME="${FW_NAME}_fw_r" FW_PUBLIC_IP=$(az network public-ip show -g $KUBE_GROUP -n $FW_IP_NAME --query ipAddress) FW_PRIVATE_IP="10.0.3.4" AKS_MC_RG=$(az group list --query "[?starts_with(name, 'MC_${KUBE_GROUP}')].name | [0]" --output tsv) ROUTE_TABLE_ID=$(az network route-table list -g ${AKS_MC_RG} --query "[].id | [0]" -o tsv) ROUTE_TABLE_NAME=$(az network route-table list -g ${AKS_MC_RG} --query "[].name | [0]" -o tsv) AKS_NODE_NSG=$(az network nsg list -g ${AKS_MC_RG} --query "[].id | [0]" -o tsv) az network vnet subnet update --resource-group $KUBE_GROUP --route-table $ROUTE_TABLE_ID --network-security-group $AKS_NODE_NSG --ids $KUBE_AGENT_SUBNET_ID az network route-table route create --resource-group $AKS_MC_RG --name $FW_ROUTE_NAME --route-table-name $ROUTE_TABLE_NAME --address-prefix 0.0.0.0/0 --next-hop-type VirtualAppliance --next-hop-ip-address $FW_PRIVATE_IP --subscription $SUBSCRIPTION_ID az network route-table route list --resource-group $AKS_MC_RG --route-table-name $ROUTE_TABLE_NAME ``` ## setting up cluster with azure cni Advanced networking is a bit simpler but requires you to create the routetable first, create the route and then again associate it with the aks subnet. 4. Create the aks cluster ``` KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --enable-rbac --node-vm-size "Standard_D2s_v3" --max-pods 15 ``` 5. Create azure firewall * this is currently not possible via cli - the creation of the azure firewall in that vnet is only possible with the azure portal * ``` az extension add --name azure-firewall az network firewall create --name $FW_NAME --resource-group $KUBE_GROUP --location $LOCATION ``` 6. Create UDR ``` FW_ROUTE_NAME="${FW_NAME}_fw_r" FW_ROUTE_TABLE_NAME="${FW_NAME}_fw_rt" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" FW_PUBLIC_IP=$(az network public-ip show -g $KUBE_GROUP -n $FW_IP_NAME --query ipAddress) FW_PRIVATE_IP="10.0.3.4" az network route-table create -g $KUBE_GROUP --name $FW_ROUTE_TABLE_NAME az network vnet subnet update --resource-group $KUBE_GROUP --route-table $FW_ROUTE_TABLE_NAME --ids $KUBE_AGENT_SUBNET_ID az network route-table route create --resource-group $KUBE_GROUP --name $FW_ROUTE_NAME --route-table-name $FW_ROUTE_TABLE_NAME --address-prefix 0.0.0.0/0 --next-hop-type VirtualAppliance --next-hop-ip-address $FW_PRIVATE_IP --subscription $SUBSCRIPTION_ID az network route-table route list --resource-group $KUBE_GROUP --route-table-name $FW_ROUTE_TABLE_NAME ``` ## Configure azure firewall Setup the azure firewall diagnostics and create a dashboard by importing this file: https://docs.microsoft.com/en-us/azure/firewall/tutorial-diagnostics https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-firewall/AzureFirewall.omsview get hcp ip (if the feature is active you can resolve your dedicated api server ip) ``` HCP_IP=$(kubectl get endpoints -o=jsonpath='{.items[?(@.metadata.name == "kubernetes")].subsets[].addresses[].ip}') ``` Add firewall rules Add network rule for 9000 (tunnel), and 443 (api server) for aks to work - this is needed for aks Add network rule for 123 (time sync) and 53 (dns) for the worker nodes - this is optional for ubuntu patches ``` az network firewall network-rule create --firewall-name $FW_NAME --collection-name "aksnetwork" --destination-addresses $HCP_IP --destination-ports 9000 --name "allow network" --protocols "TCP" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "aks network rule" --priority 100 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "time" --destination-addresses "*" --destination-ports 123 --name "allow network" --protocols "UDP" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "aks node time sync rule" --priority 101 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "dns" --destination-addresses "*" --destination-ports 53 --name "allow network" --protocols "UDP" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "aks node dns rule" --priority 102 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "kubesvc" --destination-addresses "*" --destination-ports 443 --name "allow network" --protocols "TCP" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "aks kube svc rule" --priority 103 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "ssh" --destination-addresses "*" --destination-ports 22 --name "allow network" --protocols "TCP" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "aks ssh access rule" --priority 104 ``` See complete list of external dependencies: https://docs.microsoft.com/en-us/azure/aks/limit-egress-traffic Required application rule for: - `*<region>.azmk8s.io` (eg. `*westeurope.azmk8s.io`) – this is the dns that is running your masters - `*cloudflare.docker.io` – docker hub cdn - `*registry-1.docker.io` – docker hub - `*azurecr.io` – storing your images in azure container registry - `*blob.core.windows.net` – the storage behind acr - `k8s.gcr.io` - images stored in gcr - `storage.googleapis.com` - storage behind google gcr Optional: - `*.ubuntu.com, download.opensuse.org` – This is needed for security patches and updates - if the customer wants them to be applied automatically - `snapcraft.io, api.snapcraft.io` - used by ubuntu for packages - `packages.microsoft.com`- packages from microsoft - `login.microsoftonline.com` - for azure aad login - `dc.services.visualstudio.com` - application insights - `*.opinsights.azure.com` - azure monitor - `*.monitoring.azure.com` - azure monitor - `*.management.azure.com` - azure tooling ### create the application rules ![](/img/hcp-new.png) ``` az network firewall application-rule create --firewall-name $FW_NAME --collection-name "aksbasics" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $KUBE_GROUP --action "Allow" --target-fqdns "*.azmk8s.io" "aksrepos.azurecr.io" "*.blob.core.windows.net" "mcr.microsoft.com" "*.cdn.mscr.io" "management.azure.com" "login.microsoftonline.com" "packages.microsoft.com" "acs-mirror.azureedge.net" "security.ubuntu.com" "api.snapcraft.io" "*auth.docker.io" "*cloudflare.docker.io" "*cloudflare.docker.com" "*registry-1.docker.io" --priority 100 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "monitoring" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $KUBE_GROUP --action "Allow" --target-fqdns "dc.services.visualstudio.com" "*.ods.opinsights.azure.com " "*.oms.opinsights.azure.com" "*.microsoftonline.com" "*.monitoring.azure.com" --priority 101 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "osupdates" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $KUBE_GROUP --action "Allow" --target-fqdns "security.ubuntu.com" "azure.archive.ubuntu.com" "changelogs.ubuntu.com" --priority 102 ``` test the outgoing traffic ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF ``` ``` kubectl exec -ti centos -- /bin/bash curl bad.org curl ubuntu.com kubectl get endpoints -o=jsonpath='{.items[?(@.metadata.name == "kubernetes")].subsets[].addresses[].ip}' -o wide --all-namespaces ``` ### public ip NET rules * THIS IS ONLY REQUIRED IF YOU HAVE PUBLIC IP LOADBALANCERS IN AKS* create a pod ``` kubectl run nginx --image=nginx --port=80 ``` expose it via internal lb ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: name: nginx-internal annotations: service.beta.kubernetes.io/azure-load-balancer-internal: "true" service.beta.kubernetes.io/azure-load-balancer-internal-subnet: "ing-4-subnet" spec: type: LoadBalancer loadBalancerIP: 10.0.4.25 ports: - port: 80 selector: name: nginx EOF ``` get the internal ip adress ``` SERVICE_IP=$(kubectl get svc nginx-internal --template="{{range .status.loadBalancer.ingress}}{{.ip}}{{end}}") ``` create an azure firewall nat rule for that internal service ``` az network firewall nat-rule create --firewall-name $FW_NAME --collection-name "inboundlbrules" --name "allow inbound load balancers" --protocols "TCP" --source-addresses "*" --resource-group $KUBE_GROUP --action "Dnat" --destination-addresses $FW_PUBLIC_IP --destination-ports 80 --translated-address $SERVICE_IP --translated-port "80" --priority 101 open http://$FW_PUBLIC_IP:80 ``` now you can acces the internal service by going to the $FW_PUBLIC_IP on port 80 <file_sep>echo "getting clusters" az aks list -o table #echo $clusterlist #echo $clusterlist export cluster_id="$1" if [ "$cluster_id" == "" ]; then echo "which cluster id to get?" read -n 1 cluster_id echo fi az aks list -o json > table.json #az aks list -o tsv | awk 'NR==$(cluster_id)' | cut -f 5 | tr -d " " # name export KUBE_NAME=$(cat table.json | jq -r ".[$cluster_id].name" ) # resource id export KUBE_ID=$(cat table.json | jq -r ".[$cluster_id].id" ) # version export KUBE_VERSION=$(cat table.json | jq -r ".[$cluster_id].kubernetesVersion" ) # location export LOCATION=$(cat table.json | jq -r ".[$cluster_id].location" ) # version export NODE_GROUP=$(cat table.json | jq -r ".[$cluster_id].nodeResourceGroup" ) # location export KUBE_GROUP=$(cat table.json | jq -r ".[$cluster_id].resourceGroup" ) # service principal id export SERVICE_PRINCIPAL_ID=$(cat table.json | jq -r ".[$cluster_id].servicePrincipalProfile.clientId" ) # service principal id for MSI export SERVICE_MSI_ID=$(cat table.json | jq -r ".[$cluster_id].identity.principalId" ) echo "KUBE_NAME=$KUBE_NAME" echo "LOCATION=$LOCATION" echo "KUBE_GROUP=$KUBE_GROUP" echo "KUBE_VERSION=$KUBE_VERSION" echo "NODE_GROUP=$NODE_GROUP" echo "SERVICE_PRINCIPAL_ID=$SERVICE_PRINCIPAL_ID" if [ "$SERVICE_MSI_ID" != "null" ]; then echo "SERVICE_PRINCIPAL_ID=$SERVICE_MSI_ID" fi rm table.json az aks get-credentials -n $KUBE_NAME -g $KUBE_GROUP #az aks list -o table | awk 'NR==3{print $2}' #export KUBE_VERSION=$(az aks list -o tsv | awk 'NR==2' | cut -f 5 | tr -d " ")<file_sep>## redis https://github.com/dapr/docs/blob/master/concepts/components/redis.md#creating-a-redis-store https://github.com/dapr/docs/blob/master/concepts/components/redis.md#creating-a-redis-cache-in-your-kubernetes-cluster-using-helm kubectl create namespace redis helm upgrade redis stable/redis --install --set password=<PASSWORD> --namespace redis helm delete redis kubectl get secret --namespace default redis -o jsonpath="{.data.redis-password}" | base64 --decode cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: redispubsub spec: type: pubsub.redis metadata: - name: redisHost value: redis-master:6379 - name: redisPassword value: <PASSWORD> EOF cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: statestore spec: type: state.redis metadata: - name: redisHost value: redis-master:6379 - name: redisPassword value: <PASSWORD> EOF REDIS_HOST=.redis.cache.windows.net:6379 REDIS_PASSWORD= cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: statestore spec: type: state.redis metadata: - name: redisHost value: $REDIS_HOST - name: redisPassword value: $REDIS_PASSWORD EOF<file_sep>#!/bin/sh set -e KUBE_NAME=$1 KUBE_GROUP=$2 USE_ADDON=$3 SUBSCRIPTION_ID=$(az account show --query id -o tsv) #subscriptionid LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) AKS_SUBNET_ID=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query "agentPoolProfiles[0].vnetSubnetId" -o tsv) AKS_SUBNET_NAME="aks-5-subnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" APP_NAMESPACE="dummy-logger" SECRET_NAME="nginx-cert-secret" VAULT_NAME=dzkv$KUBE_NAME AKS_CONTROLLER_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-ctl-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-clt-id')].id" -o tsv)" IP_ID=$(az network public-ip list -g $KUBE_GROUP --query "[?contains(name, 'nginxingress')].id" -o tsv) if [ "$IP_ID" == "" ]; then echo "creating ingress ip nginxingress" az network public-ip create -g $KUBE_GROUP -n nginxingress --sku STANDARD --dns-name n$KUBE_NAME -o none IP_ID=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query id) IP=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query dnsSettings.fqdn) echo "created ip $IP_ID with $IP on $DNS" az role assignment create --role "Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $IP_ID -o none else IP=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query dnsSettings.fqdn) echo "AKS $AKS_ID already exists with $IP on $DNS" fi if kubectl get namespace ingress; then echo -e "Namespace ingress found." else kubectl create namespace ingress echo -e "Namespace ingress created." fi if kubectl get namespace $APP_NAMESPACE; then echo -e "Namespace $APP_NAMESPACE found." else kubectl create namespace $APP_NAMESPACE echo -e "Namespace $APP_NAMESPACE created." fi sleep 2 kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml -n $APP_NAMESPACE #kubectl apply -f logging/dummy-logger/svc-cluster-logger.yaml -n dummy-logger kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml -n $APP_NAMESPACE # Add the ingress-nginx repository helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx helm repo add jetstack https://charts.jetstack.io # Update the helm repo(s) helm repo update helm upgrade cert-manager jetstack/cert-manager \ --namespace ingress --install \ --set installCRDs=true --wait helm upgrade nginx-ingress ingress-nginx/ingress-nginx --install \ --namespace ingress \ --set controller.replicaCount=2 \ --set controller.metrics.enabled=true \ --set controller.service.loadBalancerIP="$IP" \ --set defaultBackend.enabled=true \ --set controller.service.annotations."service\.beta\.kubernetes\.io/azure-load-balancer-health-probe-request-path"=/healthz \ --set-string controller.service.annotations.'service\.beta\.kubernetes\.io/azure-load-balancer-resource-group'="$KUBE_GROUP" \ --set-string controller.service.annotations.'service\.beta\.kubernetes\.io/azure-pip-name'="nginxingress" \ --set controller.service.externalTrafficPolicy=Local #\ #--set-string controller.podAnnotations.'linkerd\.io/inject'="enabled" --wait sleep 5 kubectl apply -f - <<EOF apiVersion: cert-manager.io/v1 kind: ClusterIssuer metadata: name: letsencrypt namespace: cert-manager spec: acme: server: https://acme-v02.api.letsencrypt.org/directory email: <EMAIL> privateKeySecretRef: name: letsencrypt solvers: - http01: ingress: class: nginx EOF sleep 5 kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-$APP_NAMESPACE namespace: $APP_NAMESPACE annotations: cert-manager.io/cluster-issuer: letsencrypt nginx.ingress.kubernetes.io/service-upstream: "true" nginx.ingress.kubernetes.io/rewrite-target: / spec: tls: - hosts: - $DNS secretName: $SECRET_NAME ingressClassName: nginx rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 EOF echo $DNS<file_sep># AKS features lists Get AKS features ``` az feature list --namespace Microsoft.ContainerService -o table az feature list --namespace Microsoft.ContainerRegistry -o table az feature list --namespace Microsoft.PolicyInsights -o table az feature list --namespace Microsoft.DocumentDB -o table az feature list --namespace Microsoft.Network -o table az feature list --namespace Microsoft.Storage -o table az feature list --namespace Microsoft.RedHatOpenShift -o table az feature list --namespace Microsoft.Web -o table az feature list --namespace Microsoft.Compute -o table az feature list --namespace Microsoft.Kubernetes -o table az feature list --namespace Microsoft.KubernetesConfiguration -o table az feature list --namespace Microsoft.EventGrid -o table az feature list --namespace Microsoft.OperationalInsights -o table az feature list --namespace Microsoft.Dashboard -o table az feature list --namespace Microsoft.ServiceNetworking -o table ``` Register a feature and reregister the provider ``` az feature register --name CustomNodeConfigPreview --namespace Microsoft.ContainerService az feature register --name PodSubnetPreview --namespace Microsoft.ContainerService az feature register --name EnableACRTeleport --namespace Microsoft.ContainerService az feature register --name AutoUpgradePreview --namespace Microsoft.ContainerService az feature register --name MobyImage --namespace Microsoft.ContainerService az feature register --name AKSAuditLog --namespace Microsoft.ContainerService az feature register --name EnableSingleIPPerCCP --namespace Microsoft.ContainerService az feature register --name APIServerSecurityPreview --namespace Microsoft.ContainerService az feature register --name PodSecurityPolicyPreview --namespace Microsoft.ContainerService az feature register --name EnableNetworkPolicy --namespace Microsoft.ContainerService az feature register --name MultiAgentpoolPreview --namespace Microsoft.ContainerService az feature register --name AKS-RegionEarlyAccess --namespace Microsoft.ContainerService az feature register --name V20180331API --namespace Microsoft.ContainerService az feature register --name AksBypassServiceGate --namespace Microsoft.ContainerService az feature register --name AvailabilityZonePreview --namespace Microsoft.ContainerService az feature register --name WindowsPreview --namespace Microsoft.ContainerService az feature register --name AKSLockingDownEgressPreview --namespace Microsoft.ContainerService az feature register --name AKS-AzurePolicyAutoApprove --namespace Microsoft.ContainerService az feature register --namespace Microsoft.PolicyInsights --name AKS-DataplaneAutoApprove az feature register --namespace Microsoft.ContainerService/AROGA --name AKS-DataplaneAutoApprove az feature register --namespace "Microsoft.ContainerService" --name "AKSAzureStandardLoadBalancer" az feature register --namespace "Microsoft.ContainerService" --name "MSIPreview" az feature register --namespace "Microsoft.ContainerService" --name "NodePublicIPPreview" az feature register --namespace "Microsoft.ContainerService" --name "LowPriorityPoolPreview" az feature register --namespace "Microsoft.ContainerService" --name "OpenVPN" az feature register --namespace "Microsoft.ContainerService" --name "SpotPoolPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-AzurePolicyV2" az feature register --namespace "Microsoft.ContainerService" --name "AKS-IngressApplicationGatewayAddon" az feature register --namespace "Microsoft.ContainerService" --name "UseCustomizedContainerRuntime" az feature register --namespace "Microsoft.ContainerService" --name "UserAssignedIdentityPreview" az feature register --namespace "Microsoft.ContainerService" --name "useContainerd" az feature register --namespace "Microsoft.ContainerService" --name "EnableAzureDiskFileCSIDriver" az feature register --namespace "Microsoft.ContainerService" --name "EnableUltraSSD" az feature register --namespace "Microsoft.ContainerService" --name "ProximityPlacementGroupPreview" az feature register --namespace "Microsoft.ContainerService" --name "NodeImageUpgradePreview" az feature register --namespace "Microsoft.ContainerService" --name "MaxSurgePreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-GitOps" az feature register --namespace "Microsoft.ContainerService" --name "AKSNetworkModePreview" az feature register --namespace "Microsoft.ContainerService" --name "GPUDedicatedVHDPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKSHTTPCustomFeatures" az feature register --namespace "Microsoft.ContainerService" --name "EnableEphemeralOSDiskPreview" az feature register --namespace "Microsoft.ContainerService" --name "StartStopPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-OpenServiceMesh" az feature register --namespace "Microsoft.ContainerService" --name "EnablePodIdentityPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-OMSAppMonitoring" az feature register --namespace "Microsoft.ContainerService" --name "MigrateToMSIClusterPreview" az feature register --namespace "Microsoft.ContainerService" --name "EnableAzureKeyvaultSecretsProvider" az feature register --namespace "Microsoft.ContainerService" --name "RunCommandPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-AzureDefender" az feature register --namespace "Microsoft.ContainerService" --name "EventgridPreview" az feature register --namespace "Microsoft.ContainerService" --name "EnablePrivateClusterPublicFQDN" az feature register --namespace "Microsoft.ContainerService" --name "HTTPProxyConfigPreview" az feature register --namespace "Microsoft.ContainerService" --name "DisableLocalAccountsPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-ScaleDownModePreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-NATGatewayPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-Dapr" az feature register --namespace "Microsoft.ContainerService" --name "PreviewStartStopAgentPool" az feature register --namespace "Microsoft.ContainerService" --name "EnableMultipleStandardLoadBalancers" az feature register --namespace "Microsoft.ContainerService" --name "EnablePodIdentityPreview" az feature register --namespace "Microsoft.ContainerService" --name "EnableOIDCIssuerPreview" az feature register --namespace "Microsoft.ContainerService" --name "PreviewGuardRails" az feature register --namespace "Microsoft.ContainerService" --name "EnableNamespaceResourcesPreview" az feature register --namespace "Microsoft.ContainerService" --name "FleetResourcePreview" az feature register --namespace "Microsoft.ContainerService" --name "SnapshotPreview" az feature register --namespace "Microsoft.ContainerService" --name "HTTP-Application-Routing" az feature register --namespace "Microsoft.ContainerService" --name "AKS-KedaPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKSARM64Preview" az feature register --namespace "Microsoft.ContainerService" --name "EnableBlobCSIDriver" az feature register --namespace "Microsoft.ContainerService" --name "EnableImageCleanerPreview" az feature register --namespace "Microsoft.ContainerService" --name "FleetResourcePreview" az feature register --namespace "Microsoft.ContainerService" --name "KubeProxyConfigurationPreview" az feature register --namespace "Microsoft.ContainerService" --name "CiliumDataplanePreview" az feature register --namespace "Microsoft.ContainerService" --name "WasmNodePoolPreview" az feature register --namespace "Microsoft.ContainerService" --name "EnablePrivateClusterSubZone" az feature register --namespace "Microsoft.ContainerService" --name "EnableWorkloadIdentityPreview" az feature register --namespace "Microsoft.ContainerService" --name "EnableAzureDiskCSIDriverV2" az feature register --namespace "Microsoft.ContainerService" --name "AzureOverlayPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-PrometheusAddonPreview" az feature register --namespace "Microsoft.ContainerService" --name "KataVMIsolationPreview" az feature register --namespace "Microsoft.ContainerService" --name "AutoUpgradePreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-ExtensionManager" az feature register --namespace "Microsoft.ContainerService" --name "AKSNodelessPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKS-ExtensionManager" az feature register --namespace "Microsoft.ContainerService" --name "CiliumDataplanePreview" az feature register --namespace "Microsoft.ContainerService" --name "EnableAPIServerVnetIntegrationPreview" az feature register --namespace "Microsoft.ContainerService" --name "NRGLockdownPreview" az feature register --namespace "Microsoft.ContainerService" --name "AzureServiceMeshPreview" az feature register --namespace "Microsoft.ContainerService" --name "NodeOsUpgradeChannelPreview" az feature register --namespace "Microsoft.ContainerService" --name "NetworkObservabilityPreview" az feature register --namespace "Microsoft.ContainerService" --name "AKSLockingDownEgressPreview" az feature register --namespace "Microsoft.ContainerService" --name "GuardrailsPreview" az feature list --namespace Microsoft.ContainerService -o table az feature register --name PrivatePreview --namespace Microsoft.Dashboard az feature list --namespace Microsoft.Network -o table az feature register --namespace "Microsoft.Network" --name "AllowPrivateEndpoints" az feature register --namespace "Microsoft.Network" --name "AllowAppGwPublicAndPrivateIpOnSamePort" az feature register --namespace "Microsoft.Network" --name "AllowApplicationGatewayV2UrlRewrite" az feature register --namespace "Microsoft.Network" --name "AllowApplicationGatewayPrivateLink" az feature register --namespace "Microsoft.Network" --name "AllowApplicationGatewayRelaxedOutboundRestrictions" az feature register --namespace "Microsoft.Network" --name "AllowApplicationGatewayLoadDistributionPolicy" az feature list --namespace Microsoft.App -o table az feature register --namespace "microsoft.app" --name "ServerlessCompute" az feature register --namespace "microsoft.app" --name "PrereleaseApiVersionAllowed" az feature register --namespace "microsoft.app" --name "WorkloadProfiles" az feature register --namespace "microsoft.storage" --name "AllowNFSV3" az feature register --namespace "microsoft.storage" --name "PremiumHns" az feature register --namespace "Microsoft.RedHatOpenShift" --name "preview" az feature register --namespace "Microsoft.RedHatOpenShift" --name "PrivateClusters" az feature register --namespace "Microsoft.RedHatOpenShift" --name "INT-APROVED" az feature register --namespace "Microsoft.RedHatOpenShift" --name "INT-APPROVED" az provider register -n "Microsoft.RedHatOpenShift" --wait az feature register --namespace "Microsoft.Compute" --name "SharedDisksForPremium" az feature list --namespace Microsoft.ServiceNetworking -o table az feature register --namespace "Microsoft.ServiceNetworking" --name "AllowTrafficController" ``` Check if the feature is active ``` az feature list -o table --query "[?contains(name, 'Microsoft.ContainerService/EnablePrivateClusterPublicFQDNh')].{Name:name,State:properties.state}" ``` Re-register the provider ``` az provider register --namespace Microsoft.ContainerService az provider register --namespace Microsoft.Network az provider register --namespace Microsoft.storage az provider register --namespace Microsoft.PolicyInsights az provider register --namespace Microsoft.Insights az provider register --namespace Microsoft.AlertsManagement az provider register --namespace Microsoft.OperationsManagement az provider register --namespace Microsoft.ServiceNetworking az provider show -n Microsoft.ServiceNetworking az provider unregister --namespace Microsoft.ContainerService az provider unregister --namespace Microsoft.Network az provider unregister --namespace Microsoft.storage az provider unregister --namespace Microsoft.PolicyInsights ``` Install the preview cli ``` az extension add -n aks-preview ``` Unregister a feature https://github.com/yangl900/armclient-go ``` curl -sL https://github.com/yangl900/armclient-go/releases/download/v0.2.3/armclient-go_linux_64-bit.tar.gz | tar xz ./armclient post /subscriptions/$SUBSCRIPTION_ID/providers/Microsoft.Features/providers/Microsoft.ContainerService/features/EnableSingleIPPerCCP/unregister?api-version=2015-12-01 ./armclient post /subscriptions/$SUBSCRIPTION_ID/providers/Microsoft.Features/providers/Microsoft.ContainerService/features/APIServerSecurityPreview/unregister?api-version=2015-12-01 ./armclient post /subscriptions/$SUBSCRIPTION_ID/providers/Microsoft.Features/providers/Microsoft.ContainerService/features/MultiAgentpoolPreview/unregister?api-version=2015-12-01 ./armclient post /subscriptions/$SUBSCRIPTION_ID/providers/Microsoft.Features/providers/Microsoft.ContainerService/features/AKS-RegionEarlyAccess/unregister?api-version=2015-12-01 ```<file_sep>#!/usr/bin/env bash set -o pipefail # ./deploy.sh number1 . 1231546131 westeurope subscriptionid 1.17.7 export deploymentname="$1" # deployment name REQUIRED export terra_path="$2" # path to terraform executable REQUIRED export aadadmin_group_id="$3" # you need to be part of this group during deployment REQUIRED export location="$4" # azure region OPTIONAL export subscriptionid="$5" # subscription id OPTIONAL export kubernetes_version="$6" # kubernetes version OPTIONAL echo "deploymentname: $deploymentname" echo "terra_path: $terra_path" echo "aadadmin_group_id: $aadadmin_group_id" echo "location: $location" echo "subscriptionid: $subscriptionid" echo "kubernetes_version: $kubernetes_version" if [ "$deploymentname" == "" ]; then echo "no deploymentname provided" exit 0; fi if [ "$terra_path" == "" ]; then echo "no terraform path provided" exit 0; fi if [ "$aadadmin_group_id" == "" ]; then echo "no aad admin group id provided" echo $aadadmin_group_id exit 0; fi if [ "$location" == "" ]; then location="westeurope" echo "No location provided - defaulting to $location" fi if [ "$subscriptionid" == "" ]; then subscriptionid=$(az account show --query id -o tsv) echo "No subscriptionid provided defaulting to $subscriptionid" else az account set --subscription $subscriptionid fi tenantid=$(az account show --query tenantId -o tsv) echo "This script will create an environment for $deploymentname in $location" TERRAFORM_STORAGE_NAME="t$deploymentname$location" TERRAFORM_STATE_RESOURCE_GROUP_NAME="state$deploymentname$location" echo "creating terraform state storage..." TFGROUPEXISTS=$(az group show --name $TERRAFORM_STATE_RESOURCE_GROUP_NAME --query name -o tsv --only-show-errors) if [ "$TFGROUPEXISTS" == $TERRAFORM_STATE_RESOURCE_GROUP_NAME ]; then echo "terraform storage resource group $TERRAFORM_STATE_RESOURCE_GROUP_NAME exists" else echo "creating terraform storage resource group $TERRAFORM_STATE_RESOURCE_GROUP_NAME..." az group create -n $TERRAFORM_STATE_RESOURCE_GROUP_NAME -l $location --output none fi TFSTORAGEEXISTS=$(az storage account show -g $TERRAFORM_STATE_RESOURCE_GROUP_NAME -n $TERRAFORM_STORAGE_NAME --query name -o tsv) if [ "$TFSTORAGEEXISTS" == $TERRAFORM_STORAGE_NAME ]; then echo "terraform storage account $TERRAFORM_STORAGE_NAME exists" TERRAFORM_STORAGE_KEY=$(az storage account keys list --account-name $TERRAFORM_STORAGE_NAME --resource-group $TERRAFORM_STATE_RESOURCE_GROUP_NAME --query "[0].value" -o tsv) else echo "creating terraform storage account $TERRAFORM_STORAGE_NAME..." az storage account create --resource-group $TERRAFORM_STATE_RESOURCE_GROUP_NAME --name $TERRAFORM_STORAGE_NAME --location $location --sku Standard_LRS --output none TERRAFORM_STORAGE_KEY=$(az storage account keys list --account-name $TERRAFORM_STORAGE_NAME --resource-group $TERRAFORM_STATE_RESOURCE_GROUP_NAME --query "[0].value" -o tsv) az storage container create -n tfstate --account-name $TERRAFORM_STORAGE_NAME --account-key $TERRAFORM_STORAGE_KEY --output none fi if [ "$kubernetes_version" == "" ]; then echo "getting latest aks supporte version" KUBERNETES_VERSION=$(az aks get-versions -l $location --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv) echo "found AKS version $KUBERNETES_VERSION" fi echo "initialzing terraform state storage..." $terra_path init -backend-config="storage_account_name=$TERRAFORM_STORAGE_NAME" -backend-config="container_name=tfstate" -backend-config="access_key=$TERRAFORM_STORAGE_KEY" -backend-config="key=codelab.microsoft.tfstate" ./ echo "planning terraform..." $terra_path plan -out $deploymentname-out.plan -var="ad_admin_group_id=$aadadmin_group_id" -var="kubernetes_version=$KUBERNETES_VERSION" -var="resource_group_name=$deploymentname" -var="deployment_name=$deploymentname" -var="location=$location" -var="tenant_id=$tenantid" -var="subscription_id=$subscriptionid" ./ if [ -f $deploymentname-out.plan ]; then echo "running terraform apply..." $terra_path apply $deploymentname-out.plan else echo "skipping terraform apply." fi <file_sep># Security Center scanning https://docs.microsoft.com/en-us/azure/security-center/defender-for-container-registries-cicd <file_sep>cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: helloworld labels: app: helloworld run: nginx spec: containers: - name: aci-helloworld image: denniszielke/aci-helloworld ports: - containerPort: 80 name: http protocol: TCP livenessProbe: httpGet: path: / port: 80 readinessProbe: httpGet: path: / port: 80 initialDelaySeconds: 10 periodSeconds: 5 resources: requests: memory: "128Mi" cpu: "500m" limits: memory: "256Mi" cpu: "1000m" EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: labels: app: helloworld name: helloworld namespace: default spec: ports: - port: 80 protocol: TCP targetPort: 80 selector: app: helloworld clusterIP: None EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: labels: app: helloworld name: helloworld namespace: default spec: ports: - port: 80 protocol: TCP targetPort: 80 selector: app: helloworld type: LoadBalancer EOF cat <<EOF | kubectl create -f - apiVersion: v1 kind: Service metadata: annotations: service.beta.kubernetes.io/azure-load-balancer-resource-group: kub_ter_a_m_gitops2 name: dummy-logger spec: loadBalancerIP: 172.16.17.32 type: LoadBalancer ports: - port: 80 selector: app: dummy-logger EOF cat <<EOF | kubectl create -f - kind: Pod apiVersion: v1 metadata: name: runclient labels: run: pdemo spec: containers: - name: ubuntu image: tutum/curl command: ["tail"] args: ["-f", "/dev/null"] EOF kubectl exec -ti runclient -- sh az network lb outbound-rule create \ --resource-group myresourcegroupoutbound \ --lb-name lb \ --name outboundrule NODE_GROUP=kub_ter_a_m_dapr6_nodes_westeurope az network lb outbound-rule list --lb-name kubernetes -g $NODE_GROUP az network lb outbound-rule update -g $NODE_GROUP --lb-name kubernetes -n aksOutboundRule<file_sep># Installing virtual kubelet https://github.com/virtual-kubelet/virtual-kubelet https://github.com/virtual-kubelet/azure-aci/blob/master/README.md https://github.com/virtual-kubelet/azure-aci/blob/master/README.md#manual-set-up 0. Variables ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) KUBE_GROUP=kubes-aci KUBE_NAME=dzkubaci LOCATION=westeurope KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" ``` 1. create aci resource group ``` az group create --name $KUBE_GROUP --location $LOCATION az network vnet create -g $KUBE_GROUP -n $KUBE_NAME-vnet az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_NAME-vnet -n gw-subnet --address-prefix 10.0.1.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_NAME-vnet -n aci-subnet --address-prefix 10.0.2.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_NAME-vnet -n aks-subnet --address-prefix 10.0.5.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage ``` 2. install connector ``` KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_NAME-vnet/subnets/aks-subnet" KUBE_VNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_NAME-vnet SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --vm-set-type VirtualMachineScaleSets --load-balancer-sku standard --kubernetes-version $KUBE_VERSION \ --node-count 3 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --enable-rbac --enable-addons monitoring --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --service-cidr 10.2.0.0/24 --dns-service-ip 10.2.0.10 az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --vm-set-type VirtualMachineScaleSets --load-balancer-sku standard --kubernetes-version $KUBE_VERSION \ --node-count 3 --enable-managed-identity --enable-rbac --enable-addons monitoring --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --service-cidr 10.2.0.0/24 --dns-service-ip 10.2.0.10 KUBELET_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identityProfile.kubeletidentity.clientId -o tsv) CONTROLLER_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identity.principalId -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Contributor" --assignee $CONTROLLER_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Contributor" --assignee $CONTROLLER_ID --scope $KUBE_VNET_ID az aks install-connector --resource-group $KUBE_GROUP --name $KUBE_NAME --aci-resource-group $ACI_GROUP az aks enable-addons \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --addons virtual-node \ --subnet-name aci-subnet az aks disable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons virtual-node ``` Install open source virtual kubelet ``` SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET TENANT_ID=$(az account show --query tenantId -o tsv) SUBSCRIPTION_ID=$(az account show --query id -o tsv) az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP export VK_RELEASE=virtual-kubelet-latest export MASTER_URI=https://dzkubaci-kubes-aci-5abd81-6d74b9ff.hcp.westeurope.azmk8s.io:443 export RELEASE_NAME=virtual-kubelet export VK_RELEASE=virtual-kubelet-latest export NODE_NAME=virtual-kubelet export CHART_URL=https://github.com/virtual-kubelet/azure-aci/raw/master/charts/$VK_RELEASE.tgz helm install "$RELEASE_NAME" "$CHART_URL" \ --set provider=azure \ --set providers.azure.targetAKS=false \ --set providers.azure.masterUri=$MASTER_URI \ --set providers.azure.vnet.enabled=false \ --set providers.azure.clientId=$SERVICE_PRINCIPAL_ID \ --set providers.azure.clientKey=$SERVICE_PRINCIPAL_SECRET \ --set providers.azure.tenantId=$TENANT_ID \ --set providers.azure.subscriptionId=$SUBSCRIPTION_ID \ --set providers.azure.aciResourceGroup=$KUBE_GROUP \ --set providers.azure.aciRegion=$LOCATION ``` 3. schedule pod on virtual node ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: helloworld1 spec: containers: - image: microsoft/aci-helloworld imagePullPolicy: Always name: helloworld resources: requests: memory: 1G cpu: 1 ports: - containerPort: 80 name: http protocol: TCP - containerPort: 443 name: https dnsPolicy: ClusterFirst nodeSelector: kubernetes.io/role: agent beta.kubernetes.io/os: linux type: virtual-kubelet tolerations: - key: virtual-kubelet.io/provider operator: Exists - key: azure.com/aci effect: NoSchedule EOF ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: job-claim spec: accessModes: - ReadWriteMany resources: requests: storage: 100Gi storageClassName: azurefile EOF ``` cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: aci-helloworld spec: replicas: 1 selector: matchLabels: app: aci-helloworld template: metadata: labels: app: aci-helloworld spec: containers: - name: aci-helloworld image: microsoft/aci-helloworld ports: - containerPort: 80 resources: limits: nvidia.com/gpu: 1 nodeSelector: kubernetes.io/hostname: virtual-node-aci-linux tolerations: - key: virtual-kubelet.io/provider operator: Equal value: azure effect: NoSchedule EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: aci-helloworldnode spec: replicas: 1 selector: matchLabels: app: aci-helloworldnode template: metadata: labels: app: aci-helloworldnode spec: containers: - name: aci-helloworldnode image: microsoft/aci-helloworld ports: - containerPort: 80 volumeMounts: - name: files mountPath: /mnt/azure volumes: - name: files azureFile: shareName: "job" readOnly: false secretName: azurefile-secret EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: aci-helloworld spec: replicas: 1 selector: matchLabels: app: aci-helloworld template: metadata: labels: app: aci-helloworld spec: containers: - name: aci-helloworld image: microsoft/aci-helloworld ports: - containerPort: 80 volumeMounts: - name: files mountPath: /mnt/azure nodeSelector: kubernetes.io/hostname: virtual-node-aci-linux tolerations: - key: virtual-kubelet.io/provider operator: Equal value: azure effect: NoSchedule volumes: - name: files azureFile: shareName: "job" readOnly: false secretName: azurefile-secret EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: aci-helloworldv1 spec: replicas: 1 selector: matchLabels: app: aci-helloworldv1 template: metadata: labels: app: aci-helloworldv1 spec: containers: - name: aci-helloworldv1 image: microsoft/aci-helloworld ports: - containerPort: 80 volumeMounts: - name: files mountPath: /mnt/azure nodeSelector: kubernetes.io/hostname: virtual-node-aci-linux tolerations: - key: virtual-kubelet.io/provider operator: Equal value: azure effect: NoSchedule volumes: - name: files azureFile: shareName: "job" readOnly: false secretName: azurefilev1-secret EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: aci-helloworldnodev1 spec: replicas: 1 selector: matchLabels: app: aci-helloworldnodev1 template: metadata: labels: app: aci-helloworldnodev1 spec: containers: - name: aci-helloworldnodev1 image: microsoft/aci-helloworld ports: - containerPort: 80 volumeMounts: - name: files mountPath: /mnt/azure volumes: - name: files azureFile: shareName: "job" readOnly: false secretName: azurefilev1-secret EOF ``` 4. clean up ``` kubectl delete pods,services -l app=hello-app kubectl delete pods,services -l pod-template-hash=916745872 ``` ## Storage ``` STORAGE_ACCOUNT=$KUBE_NAME NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az storage account create --resource-group $NODE_GROUP --name $STORAGE_ACCOUNT --location $LOCATION --sku Standard_LRS --kind StorageV2 --access-tier hot --https-only false STORAGE_KEY=$(az storage account keys list --account-name $STORAGE_ACCOUNT --resource-group $NODE_GROUP --query "[0].value") az storage share create -n job --quota 10 --account-name $STORAGE_ACCOUNT --account-key $STORAGE_KEY kubectl create secret generic azurefile-secret --from-literal=azurestorageaccountname=$STORAGE_ACCOUNT --from-literal=azurestorageaccountkey=$STORAGE_KEY STORAGE_ACCOUNT=dzstorv1 NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az storage account create --resource-group $NODE_GROUP --name $STORAGE_ACCOUNT --location $LOCATION --sku Standard_LRS --kind Storage --https-only false STORAGE_KEY=$(az storage account keys list --account-name $STORAGE_ACCOUNT --resource-group $NODE_GROUP --query "[0].value") az storage share create -n job --quota 10 --account-name $STORAGE_ACCOUNT --account-key $STORAGE_KEY kubectl create secret generic azurefilev1-secret --from-literal=azurestorageaccountname=$STORAGE_ACCOUNT --from-literal=azurestorageaccountkey=$STORAGE_KEY ``` ## AGIC ``` cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: aci-helloworld-blue spec: replicas: 1 selector: matchLabels: app: aci-helloworld template: metadata: labels: app: aci-helloworld spec: containers: - name: aci-helloworld image: denniszielke/blue ports: - containerPort: 80 nodeSelector: kubernetes.io/role: agent beta.kubernetes.io/os: linux type: virtual-kubelet tolerations: - key: virtual-kubelet.io/provider operator: Exists EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: aci-helloworld-green spec: replicas: 1 selector: matchLabels: app: aci-helloworld template: metadata: labels: app: aci-helloworld spec: containers: - name: aci-helloworld image: denniszielke/green ports: - containerPort: 80 nodeSelector: kubernetes.io/role: agent beta.kubernetes.io/os: linux type: virtual-kubelet tolerations: - key: virtual-kubelet.io/provider operator: Exists EOF kubectl expose deployment aci-helloworld-green --type=LoadBalancer --port=80 cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: aci-helloworld-green annotations: kubernetes.io/ingress.class: azure/application-gateway spec: rules: - http: paths: - backend: serviceName: aci-helloworld-green servicePort: 80 EOF ``` <file_sep>#!/bin/sh # # wget https://raw.githubusercontent.com/denniszielke/container_demos/master/scripts/aks_lima_v2.sh # chmod +x ./aks_lima_v2.sh # bash ./aks_lima_v2.sh # set -e DEPLOYMENT_NAME="dzlima9" # here enter unique deployment name (ideally short and with letters for global uniqueness) AAD_GROUP_ID="9329d38c-5296-4ecb-afa5-3e74f9abe09f" # here the AAD group that will be used to lock down AKS authentication LOCATION="eastus" # here enter the datacenter location can be eastus or westeurope KUBE_GROUP=$DEPLOYMENT_NAME # here enter the resources group name of your AKS cluster KUBE_NAME=$DEPLOYMENT_NAME # here enter the name of your kubernetes resource NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group KUBE_VNET_NAME="limavnet" KUBE_AGENT_SUBNET_NAME="aks-5-subnet" # here enter the name of your AKS subnet SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id TENANT_ID=$(az account show --query tenantId -o tsv) KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" # here enter the kubernetes version of your AKS KUBE_CNI_PLUGIN="azure" MY_OWN_OBJECT_ID=$(az ad signed-in-user show --query objectId --output tsv) # this will be your own aad object id OUTBOUNDTYPE="" IGNORE_FORCE_ROUTE="true" # only set to true if you have a routetable on the AKS subnet but that routetable does not contain a route for '0.0.0.0/0' with target VirtualAppliance or VirtualNetworkGateway USE_PRIVATE_LINK="false" # use to deploy private master endpoint ARC_CLUSTER_NAME="${KUBE_NAME}-cluster" ARC_CLUSTER_GROUP="${KUBE_GROUP}-arc" extensionName="${KUBE_NAME}-appsvc-ext" customLocationName="${KUBE_NAME}-loc" kubeEnvironmentName="${KUBE_NAME}-kubeenv" ASELOCATION="northcentralusstage" # or "centraluseuap" echo 'registering providers... (only once)' # az feature register --namespace Microsoft.Resources --name EUAPParticipation # az provider register -n Microsoft.Resources --wait # az feature register --namespace Microsoft.Kubernetes # az provider register --namespace Microsoft.Kubernetes --wait # az feature register --namespace Microsoft.KubernetesConfiguration # az provider register --namespace Microsoft.KubernetesConfiguration --wait # az feature register --namespace Microsoft.ExtendedLocation # az provider register --namespace Microsoft.ExtendedLocation --wait # az provider register --namespace Microsoft.Web --wait #az provider register --namespace Microsoft.OperationalInsights --wait # az provider show -n Microsoft.Web --query "resourceTypes[?resourceType=='kubeEnvironments'].locations" #echo "this should include 'North Central US (Stage)'" # echo 'installing extensions...' # az extension add --upgrade -n connectedk8s # az extension add --upgrade -n k8s-extension # az extension add --upgrade -n customlocation # az extension add --yes --source "https://aka.ms/appsvc/appservice_kube-latest-py2.py3-none-any.whl" az account set --subscription $SUBSCRIPTION_ID if [ $(az group exists --name $KUBE_GROUP) = false ]; then echo "creating resource group $KUBE_GROUP..." az group create -n $KUBE_GROUP -l $LOCATION -o none echo "resource group $KUBE_GROUP created" else echo "resource group $KUBE_GROUP already exists" fi echo "setting up vnet" VNET_RESOURCE_ID=$(az network vnet list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_VNET_NAME')].id" -o tsv) if [ "$VNET_RESOURCE_ID" == "" ]; then echo "creating vnet $KUBE_VNET_NAME..." az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n "AzureFirewallSubnet" --address-prefix 10.0.3.0/24 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n "gw-1-subnet" --address-prefix 10.0.2.0/24 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n "ing-4-subnet" --address-prefix 10.0.4.0/24 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 -o none VNET_RESOURCE_ID=$(az network vnet show -g $KUBE_GROUP -n $KUBE_VNET_NAME --query id -o tsv) echo "created $VNET_RESOURCE_ID" else echo "vnet $VNET_RESOURCE_ID already exists" fi ROUTE_TABLE_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --query routeTable.id -o tsv) KUBE_AGENT_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --query id -o tsv) if [ "$ROUTE_TABLE_ID" == "" ]; then echo "could not find routetable on AKS subnet $KUBE_AGENT_SUBNET_ID" else echo "using routetable $ROUTE_TABLE_ID with the following entries" ROUTE_TABLE_GROUP=$(az network route-table show --ids $ROUTE_TABLE_ID --query "[resourceGroup]" -o tsv) ROUTE_TABLE_NAME=$(az network route-table show --ids $ROUTE_TABLE_ID --query "[name]" -o tsv) echo "if this routetable does not contain a route for '0.0.0.0/0' with target VirtualAppliance or VirtualNetworkGateway then we will not need the outbound type parameter" az network route-table route list --resource-group $ROUTE_TABLE_GROUP --route-table-name $ROUTE_TABLE_NAME -o table echo "if it does not contain a '0.0.0.0/0' route then you should set the parameter IGNORE_FORCE_ROUTE=true" if [ "$IGNORE_FORCE_ROUTE" == "true" ]; then echo "ignoring forced tunneling route information" OUTBOUNDTYPE="" else echo "using forced tunneling route information" OUTBOUNDTYPE=" --outbound-type userDefinedRouting " fi fi echo "setting up controller identity" AKS_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-id')].id" -o tsv)" if [ "$AKS_CLIENT_ID" == "" ]; then echo "creating controller identity $KUBE_NAME-id in $KUBE_GROUP" az identity create --name $KUBE_NAME-id --resource-group $KUBE_GROUP -o none sleep 5 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" sleep 5 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 25 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" sleep 5 # wait for replication AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query id -o tsv)" sleep 10 echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 5 # wait for replication az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none if [ "$ROUTE_TABLE_ID" == "" ]; then echo "no route table used" else echo "assigning permissions on routetable $ROUTE_TABLE_ID" az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $ROUTE_TABLE_ID -o none fi else echo "controller identity $AKS_CONTROLLER_RESOURCE_ID already exists" echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none if [ "$ROUTE_TABLE_ID" == "" ]; then echo "no route table used" else echo "assigning permissions on routetable $ROUTE_TABLE_ID" az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $ROUTE_TABLE_ID -o none fi fi echo "setting up aks" AKS_ID=$(az aks list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$USE_PRIVATE_LINK" == "true" ]; then ACTIVATE_PRIVATE_LINK=" --enable-private-cluster " else ACTIVATE_PRIVATE_LINK="" fi if [ "$AKS_ID" == "" ]; then echo "creating AKS $KUBE_NAME in $KUBE_GROUP" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --ssh-key-value ~/.ssh/id_rsa.pub --node-count 3 --min-count 3 --max-count 5 --enable-cluster-autoscaler --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --no-ssh-key --assign-identity $AKS_CONTROLLER_RESOURCE_ID --node-osdisk-size 300 --enable-managed-identity --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $TENANT_ID --uptime-sla $OUTBOUNDTYPE $ACTIVATE_PRIVATE_LINK -o none az aks update --resource-group $KUBE_GROUP --name $KUBE_NAME --auto-upgrade-channel rapid AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query id -o tsv) echo "created AKS $AKS_ID" else echo "AKS $AKS_ID already exists" fi echo "setting up azure monitor" WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace list --resource-group $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$WORKSPACE_RESOURCE_ID" == "" ]; then echo "creating workspace $KUBE_NAME in $KUBE_GROUP" az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --location $LOCATION -o none WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --query id -o tsv) # az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons monitoring --workspace-resource-id $WORKSPACE_RESOURCE_ID fi IP_ID=$(az network public-ip list -g $NODE_GROUP --query "[?contains(name, 'limaingress')].id" -o tsv) if [ "$IP_ID" == "" ]; then echo "creating ingress ip limaingress" az network public-ip create -g $NODE_GROUP -n limaingress --sku STANDARD IP_ID=$(az network public-ip show -g $NODE_GROUP -n limaingress -o tsv) echo "created ip $IP_ID" IP=$(az network public-ip show -g $NODE_GROUP -n limaingress -o tsv --query ipAddress) else echo "IP $IP_ID already exists" IP=$(az network public-ip show -g $NODE_GROUP -n limaingress -o tsv --query ipAddress) fi az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME --admin --overwrite-existing if [ $(az group exists --name $ARC_CLUSTER_GROUP) = false ]; then echo "creating resource group $ARC_CLUSTER_GROUP..." az group create -n $ARC_CLUSTER_GROUP -l $LOCATION -o none echo "resource group $ARC_CLUSTER_GROUP created" else echo "resource group $ARC_CLUSTER_GROUP already exists" fi ARC_CLUSTER_ID=$(az connectedk8s list --resource-group $ARC_CLUSTER_GROUP --query "[?contains(name, '$ARC_CLUSTER_NAME')].id" -o tsv) if [ "$ARC_CLUSTER_ID" == "" ]; then echo "creating arc cluster object for $ARC_CLUSTER_NAME" az connectedk8s connect --name $ARC_CLUSTER_NAME --resource-group $ARC_CLUSTER_GROUP --distribution aks --infrastructure azure sleep 5 ARC_CLUSTER_ID=$(az connectedk8s show --resource-group $ARC_CLUSTER_GROUP --name $ARC_CLUSTER_NAME --query id -o tsv) echo "created arc cluster $ARC_CLUSTER_ID" else echo "arc cluster $ARC_CLUSTER_ID already exists" fi az resource wait --ids $ARC_CLUSTER_ID --custom "properties.connectivityStatus!='Connecting'" --api-version "2021-04-01-preview" az k8s-configuration flux create \ -g $ARC_CLUSTER_GROUP -c $ARC_CLUSTER_NAME -t connectedClusters \ -n gitops-demo --namespace gitops-demo --scope cluster \ -u https://github.com/denniszielke/arc-k8s-demo --branch master --kustomization name=kustomization1 prune=true sleep 5 WORKSPACE_CUSTOMER_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --query customerId -o tsv) WORKSPACE_SHARED_KEY=$(az monitor log-analytics workspace get-shared-keys --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --query primarySharedKey -o tsv) logAnalyticsCustomerIdEnc=$(echo $WORKSPACE_CUSTOMER_ID | base64) logAnalyticsKeyEnc=$(echo $WORKSPACE_SHARED_KEY | base64) sleep 10 extensionId=$(az k8s-extension list -g $ARC_CLUSTER_GROUP --cluster-name $ARC_CLUSTER_NAME --cluster-type connectedClusters --query "[?contains(name, '$extensionName')].id" -o tsv) if [ "$extensionId" == "" ]; then echo "creating arc k8s extension $extensionName" az k8s-extension create -g $ARC_CLUSTER_GROUP --name $extensionName \ --cluster-type connectedClusters -c $ARC_CLUSTER_NAME \ --extension-type 'Microsoft.Web.Appservice' --release-train stable --auto-upgrade-minor-version true \ --scope cluster --release-namespace $customLocationName \ --configuration-settings "Microsoft.CustomLocation.ServiceAccount=default" \ --configuration-settings "appsNamespace=$customLocationName" \ --configuration-settings "clusterName=$ARC_CLUSTER_NAME" \ --configuration-settings "loadBalancerIp=$IP" \ --configuration-settings "keda.enabled=true" \ --configuration-settings "buildService.storageClassName=default" \ --configuration-settings "buildService.storageAccessMode=ReadWriteOnce" \ --configuration-settings "customConfigMap=$customLocationName/kube-environment-config" \ --configuration-settings "envoy.annotations.service.beta.kubernetes.io/azure-load-balancer-resource-group=$NODE_GROUP" \ --configuration-settings "logProcessor.appLogs.destination=log-analytics" \ --configuration-protected-settings "logProcessor.appLogs.logAnalyticsConfig.customerId=$logAnalyticsCustomerIdEnc" \ --configuration-protected-settings "logProcessor.appLogs.logAnalyticsConfig.sharedKey=$logAnalyticsKeyEnc" sleep 5 extensionId=$(az k8s-extension show -g $ARC_CLUSTER_GROUP --cluster-name $ARC_CLUSTER_NAME --cluster-type connectedClusters --name $extensionName --query id -o tsv) sleep 5 echo "created arc k8s extension $extensionId" else echo "arc cluster $extensionId already exists" fi az resource wait --ids $extensionId --custom "properties.installState!='Pending'" --api-version "2020-07-01-preview" sleep 5 customLocationId=$(az customlocation list -g $ARC_CLUSTER_GROUP --query "[?contains(name, '$customLocationName')].id" -o tsv) if [ "$customLocationId" == "" ]; then echo "creating custom location $customLocationName" az customlocation create -g $ARC_CLUSTER_GROUP -n $customLocationName --host-resource-id $ARC_CLUSTER_ID --namespace $customLocationName -c $extensionId -l $LOCATION sleep 5 customLocationId=$(az customlocation show -g $ARC_CLUSTER_GROUP --name $customLocationName --query id -o tsv) sleep 5 echo "created custom location $customLocationId" else echo "custom location $customLocationId already exists" fi kubeEnvironmentId=$(az appservice kube list -g $ARC_CLUSTER_GROUP --query "[?contains(name, '$extensionName')].id" -o tsv) if [ "$kubeEnvironmentId" == "" ]; then echo "creating kube environment $customLocationName" az appservice kube create -g $ARC_CLUSTER_GROUP -n $extensionName --custom-location $customLocationId --static-ip $IP -l $LOCATION sleep 5 kubeEnvironmentId=$(az appservice kube show -g $ARC_CLUSTER_GROUP --name $extensionName --query id -o tsv) echo "created kube environment $kubeEnvironmentId" else echo "kube environment $kubeEnvironmentId already exists" fi az resource wait --ids $kubeEnvironmentId --custom "properties.provisioningState=='Succeeded'" --api-version "2021-02-01" sleep 5 appserviceplanId=$(az appservice plan list -g $ARC_CLUSTER_GROUP --query "[?contains(name, 'kubeappsplan')].id" -o tsv) if [ "$appserviceplanId" == "" ]; then echo "creating app service plan kubeappsplan" az appservice plan create -g $ARC_CLUSTER_GROUP -n kubeappsplan --custom-location $customLocationId --sku K1 --per-site-scaling --is-linux az appservice plan show -g $ARC_CLUSTER_GROUP --name kubeappsplan sleep 5 appserviceplanId=$(az appservice plan show -g $ARC_CLUSTER_GROUP --name kubeappsplan --query id -o tsv) echo "created app service plan kubeappsplan" else echo "app service plan kubeappsplan already exists" fi az resource wait --ids $appserviceplanId --custom "properties.provisioningState=='Succeeded'" --api-version "2021-02-01" sleep 5 dummyappId=$(az webapp list -g $ARC_CLUSTER_GROUP --query "[?contains(name, 'dzdummylogger')].id" -o tsv) if [ "$dummyappId" == "" ]; then echo "creating app dzdummylogger" az webapp create -g $ARC_CLUSTER_GROUP -p kubeappsplan -n dzdummylogger --deployment-container-image-name denniszielke/dummy-logger:latest az webapp show -g $ARC_CLUSTER_GROUP --name dzdummylogger sleep 5 dummyappId=$(az webapp show -g $ARC_CLUSTER_GROUP --name dzdummylogger --query id -o tsv) dummyappUrl=$(az webapp show -g $ARC_CLUSTER_GROUP --name dzdummylogger --query defaultHostName -o tsv) echo "created app service $dummyappId with url $dummyappUrl" else dummyappUrl=$(az webapp show -g $ARC_CLUSTER_GROUP --name dzdummylogger --query defaultHostName -o tsv) echo "app service $dummyappId already exists with url $dummyappUrl" fi <file_sep>#!/bin/sh set -e # https://azure.github.io/secrets-store-csi-driver-provider-azure/configurations/ingress-tls/ KUBE_NAME=$1 KUBE_GROUP=$2 USE_ADDON=$3 SUBSCRIPTION_ID=$(az account show --query id -o tsv) #subscriptionid TENANT_ID=$(az account show --query tenantId -o tsv) LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) AKS_SUBNET_ID=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query "agentPoolProfiles[0].vnetSubnetId" -o tsv) AKS_SUBNET_NAME="aks-5-subnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" APP_NAMESPACE="dummy-logger" SECRET_NAME="mytls-cert-secret" VAULT_NAME=dzkv$KUBE_NAME AKS_CONTROLLER_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-ctl-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-clt-id')].id" -o tsv)" AKS_KUBELET_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-kbl-id')].clientId" -o tsv)" AKS_KUBELET_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-kbl-id')].id" -o tsv)" IP_ID=$(az network public-ip list -g $KUBE_GROUP --query "[?contains(name, 'nginxingress')].id" -o tsv) if [ "$IP_ID" == "" ]; then echo "creating ingress ip nginxingress" az network public-ip create -g $KUBE_GROUP -n nginxingress --sku STANDARD --dns-name $KUBE_NAME -o none IP_ID=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query id) IP=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query dnsSettings.fqdn) echo "created ip $IP_ID with $IP on $DNS" az role assignment create --role "Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $IP_ID -o none else IP=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n nginxingress -o tsv --query dnsSettings.fqdn) echo "AKS $AKS_ID already exists with $IP on $DNS" fi if kubectl get namespace ingress; then echo -e "Namespace ingress found." else kubectl create namespace ingress echo -e "Namespace ingress created." fi if kubectl get namespace $APP_NAMESPACE; then echo -e "Namespace $APP_NAMESPACE found." else kubectl create namespace $APP_NAMESPACE echo -e "Namespace $APP_NAMESPACE created." fi kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml -n $APP_NAMESPACE #kubectl apply -f logging/dummy-logger/svc-cluster-logger.yaml -n dummy-logger kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml -n $APP_NAMESPACE cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1 kind: SecretProviderClass metadata: name: ingress-csi-tls name: ingress spec: provider: azure secretObjects: - secretName: ingress-tls-csi-cert #name of the secret that gets created - this is the value we provide to nginx type: kubernetes.io/tls data: - objectName: $SECRET_NAME key: tls.key - objectName: $SECRET_NAME key: tls.crt parameters: usePodIdentity: "false" useVMManagedIdentity: "true" userAssignedIdentityID: "$AKS_KUBELET_CLIENT_ID" keyvaultName: "$VAULT_NAME" objects: | array: - | objectName: $SECRET_NAME objectType: secret # object types: secret, key or cert tenantId: "$TENANT_ID" # the tenant ID of the KeyVault EOF kubectl logs -l app=secrets-store-csi-driver -n kube-system sleep 5 # Add the ingress-nginx repository helm repo add nginx-stable https://helm.nginx.com/stable # Update the helm repo(s) helm repo update --validating-webhook-certificate=/usr/local/certificates/cert --validating-webhook-key=/usr/local/certificates/key helm upgrade nginx-ingress nginx-stable/nginx-ingress --install \ --namespace ingress \ --set controller.replicaCount=1 \ --set controller.metrics.enabled=true \ --set controller.service.loadBalancerIP="$IP" \ --set defaultBackend.enabled=true \ --set-string controller.service.annotations.'service\.beta\.kubernetes\.io/azure-load-balancer-resource-group'="$KUBE_GROUP" \ --set-string controller.service.annotations.'service\.beta\.kubernetes\.io/azure-pip-name'="nginxingress" \ --set controller.service.externalTrafficPolicy=Local --wait --timeout 60s \ -f - <<EOF controller: extraVolumes: - name: secrets-store-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: "ingress-csi-tls" #name of the SecretProviderClass we created above extraVolumeMounts: - name: secrets-store-inline mountPath: "/mnt/secrets-store" readOnly: true EOF #/etc/ssl/certs # /mnt/secrets-store/mytls-cert-secret #ln -s /mnt/secrets-store/mytls-cert-secret /etc/ingress-controller/ssl/dummy-logger/ingress-tls-csi-cert sleep 5 cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1 kind: SecretProviderClass metadata: name: ingress-csi-tls-cert namespace: $APP_NAMESPACE spec: provider: azure secretObjects: - secretName: ingress-tls-csi-cert #name of the secret that gets created - this is the value we provide to nginx type: kubernetes.io/tls data: - objectName: $SECRET_NAME key: tls.key - objectName: $SECRET_NAME key: tls.crt parameters: usePodIdentity: "false" useVMManagedIdentity: "true" userAssignedIdentityID: "$AKS_KUBELET_CLIENT_ID" keyvaultName: "$VAULT_NAME" objects: | array: - | objectName: $SECRET_NAME objectType: cert # object types: secret, key or cert objectVersion: "" # [OPTIONAL] object versions, default to latest if empty tenantId: "$TENANT_ID" # the tenant ID of the KeyVault EOF # ssl on; # ssl_certificate /etc/ingress-controller/ssl/dzmtls.westeurope.cloudapp.azure.com.pem; # ssl_certificate_key /etc/ingress-controller/ssl/dzmtls.westeurope.cloudapp.azure.com.key; kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-$APP_NAMESPACE namespace: $APP_NAMESPACE annotations: nginx.ingress.kubernetes.io/rewrite-target: /$1 spec: tls: - hosts: - $DNS secretName: ingress-tls-csi-cert ingressClassName: nginx rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 EOF kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-$APP_NAMESPACE namespace: ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: tls: - hosts: - $DNS secretName: ingress-tls-csi-cert ingressClassName: nginx rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 EOF echo $DNS curl -v -k --resolve $DNS:443:$IP https://$DNS exit OUTPUT=${1:-"$HOME/certificates"} DOMAIN=$(kubectl get secret -n $APP_NAMESPACE $SECRET_NAME -o json | jq -r '.data."tls.crt"' | base64 -d | openssl x509 -noout -text | grep "Subject: CN=" | sed -E 's/\s+Subject: CN=([^ ]*)/\1/g') echo -n " ${DOMAIN}" mkdir -p "${OUTPUT}/${DOMAIN}" kubectl get secret -n ${APP_NAMESPACE} ${SECRET_NAME} -o json | jq -r '.data."tls.key"' | base64 -d > "${OUTPUT}/${DOMAIN}/privkey.pem" kubectl get secret -n ${APP_NAMESPACE} ${SECRET_NAME} -o json | jq -r '.data."tls.crt"' | base64 -d > "${OUTPUT}/${DOMAIN}/fullchain.pem" #kubectl get secret -n dummy-logger dummy-cert-secret -o json | jq -r '.data."tls.crt"' | base64 -d openssl pkcs12 -export -in "${OUTPUT}/${DOMAIN}/fullchain.pem" -inkey "${OUTPUT}/${DOMAIN}/privkey.pem" -out "${OUTPUT}/${DOMAIN}/$SECRET_NAME.pfx" az keyvault certificate import --vault-name ${VAULT_NAME} -n $SECRET_NAME -f "${OUTPUT}/${DOMAIN}/$SECRET_NAME.pfx" exit export CERT_NAME=ingresscert openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ -out ingress-tls.crt \ -keyout ingress-tls.key \ -subj "/CN=demo.test.com/O=ingress-tls" openssl pkcs12 -export -in ingress-tls.crt -inkey ingress-tls.key -out $CERT_NAME.pfx az keyvault certificate import --vault-name ${VAULT_NAME} -n $SECRET_NAME -f "$CERT_NAME.pfx" cat <<EOF | kubectl apply -n $NAMESPACE -f - apiVersion: secrets-store.csi.x-k8s.io/v1 kind: SecretProviderClass metadata: name: azure-tls spec: provider: azure secretObjects: # secretObjects defines the desired state of synced K8s secret objects - secretName: ingress-tls-csi type: kubernetes.io/tls data: - objectName: $CERT_NAME key: tls.key - objectName: $CERT_NAME key: tls.crt parameters: usePodIdentity: "false" useVMManagedIdentity: "true" userAssignedIdentityID: "$AKS_KUBELET_CLIENT_ID" keyvaultName: $AKV_NAME # the name of the KeyVault objects: | array: - | objectName: $CERT_NAME objectType: secret tenantId: $TENANT_ID # the tenant ID of the KeyVault EOF helm install ingress-nginx/ingress-nginx --generate-name \ --namespace $NAMESPACE \ --set controller.replicaCount=2 \ --set controller.nodeSelector."beta\.kubernetes\.io/os"=linux \ --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux \ -f - <<EOF controller: extraVolumes: - name: secrets-store-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: "azure-tls" extraVolumeMounts: - name: secrets-store-inline mountPath: "/mnt/secrets-store" readOnly: true EOF cat <<EOF | kubectl apply -n $NAMESPACE -f - apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-tls annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/rewrite-target: / spec: tls: - hosts: - demo.test.com secretName: ingress-tls-csi rules: - host: demo.test.com http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 EOF curl -v -k --resolve demo.test.com:443:172.16.17.32 https://demo.test.com az k8s-configuration flux create \ --name cluster-config \ --cluster-name arc-cicd-cluster \ --namespace cluster-config \ --resource-group myResourceGroup \ -u https://dev.azure.com/<Your organization>/<Your project>/arc-cicd-demo-gitops \ --https-user <Azure Repos username> \ --https-key <Azure Repos PAT token> \ --scope cluster \ --cluster-type managedClusters \ --branch master \ --kustomization name=cluster-config prune=true path=arc-cicd-cluster/manifests<file_sep># Hello world https://github.com/dapr/samples/tree/master/2.hello-kubernetes <file_sep>package org.acme.rest.client; import org.eclipse.microprofile.rest.client.inject.RestClient; import org.jboss.resteasy.annotations.jaxrs.PathParam; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ThreadLocalRandom; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import java.util.Random; import java.util.HashMap; import java.util.Map; import org.jboss.logging.Logger; @Path("/api") public class CalculationResource { @Inject @RestClient CalculationService calculationService; // // @AutoWired // // TelemetryClient telemetryClient; // static final TelemetryClient telemetryClient = new TelemetryClient(); @Inject Logger log; @GET @Path("/ping") public Boolean ping() { return true; } @GET @Path("/trigger/{count}") public Boolean trigger(@PathParam Integer count) { Random rand = new Random(); log.info("received trigger for " + count + " requests."); for (int i = 0; i < count; i++) { Integer randInt = rand.nextInt(1000); String randString = randInt.toString(); CalculationResponse response = calculationService.Calculate(randString, false); log.info("received trigger response for " + response.toString() + "."); } // Map<String, String> properties = new HashMap<>(); // properties.put("properties", "PROPERTIES OF PROPERTIES"); // Map<String, Double> metrics = new HashMap<>(); // metrics.put("metrics", 10.0); // telemetryClient.trackEvent("telemetryClient trackEvent test", properties, metrics); // Boolean isdisabled = telemetryClient.isDisabled(); // telemetryClient.flush(); return true; } @GET @Path("/triggerasync/{count}") public CompletionStage<CalculationResponse> triggerAsync(@PathParam Integer count) { Random rand = new Random(); Integer randInt = rand.nextInt(1000); String randString = randInt.toString(); log.info("received trigger async for " + count + " requests."); for (int i = 0; i < count; i++) { CompletionStage<CalculationResponse> response = calculationService.CalculateAsync(randString, false); log.info("received trigger async response for " + response.toString() + "."); randInt = rand.nextInt(1000); randString = randInt.toString(); } CompletionStage<CalculationResponse> response = calculationService.CalculateAsync(randString, false); System.out.println(response.toString()); return response; } }<file_sep># Setting up Service Broker https://docs.microsoft.com/en-us/azure/aks/integrate-azure 0. Define variables ``` SUBSCRIPTION_ID="" KUBE_GROUP="kubesaks" KUBE_NAME="dzkubes" LOCATION="westeurope" REGISTRY_NAME="" APPINSIGHTS_KEY="" OSBA_CLIENT_ID= OSBA_CLIENT_SECRET= OSBA_TENANT_ID= OSBA_SUBSCRIPTION_ID=$SUBSCRIPTION_ID ``` az ad sp create-for-rbac --name "osba_sp" 1. Install service catalog ``` helm repo add svc-cat https://svc-catalog-charts.storage.googleapis.com helm install svc-cat/catalog --name catalog --namespace catalog --set controllerManager.healthcheck.enabled=false kubectl get apiservice ``` 2. OSBA for Azure ``` helm repo add azure https://kubernetescharts.blob.core.windows.net/azure az ad sp create-for-rbac --name "osba_sp" helm install azure/open-service-broker-azure --name osba --namespace osba \ --set azure.subscriptionId=$OSBA_SUBSCRIPTION_ID \ --set azure.tenantId=$OSBA_TENANT_ID \ --set azure.clientId=$OSBA_CLIENT_ID \ --set azure.clientSecret=$OSBA_CLIENT_SECRET helm upgrade osba azure/open-service-broker-azure --set logLevel=DEBUG --namespace osba \ --set azure.subscriptionId=$OSBA_SUBSCRIPTION_ID \ --set azure.tenantId=$OSBA_TENANT_ID \ --set azure.clientId=$OSBA_CLIENT_ID \ --set azure.clientSecret=$OSBA_CLIENT_SECRET ``` 3. Install cli https://github.com/Azure/service-catalog-cli ``` curl -sLO https://servicecatalogcli.blob.core.windows.net/cli/latest/$(uname -s)/$(uname -m)/svcat chmod +x ./svcat ``` 4. install instance and create binding https://github.com/Azure/open-service-broker-azure ``` kubectl delete servicebinding my-postgresqldb-binding ```<file_sep># AKS Maintenance Get all upgrade versions ``` az aks get-upgrades --resource-group=$KUBE_GROUP --name=$KUBE_NAME --output table az aks nodepool get-upgrades --nodepool-name nodepool2 --resource-group=$KUBE_GROUP --cluster-name=$KUBE_NAME ``` Perform upgrade ``` az aks nodepool show --resource-group=$KUBE_GROUP --cluster-name=$KUBE_NAME --name nodepool1 --query nodeImageVersion az aks upgrade --resource-group=$KUBE_GROUP --name=$KUBE_NAME --kubernetes-version 1.22.6 az aks nodepool upgrade --name nodepool2 --resource-group=$KUBE_GROUP --cluster-name=$KUBE_NAME --kubernetes-version 1.22.6 az aks upgrade --resource-group=$KUBE_GROUP --name=$KUBE_NAME --node-image-only az aks update -g $KUBE_GROUP -n $KUBE_NAME --auto-upgrade-channel stable # patch stable rapid node-image az aks update -g $KUBE_GROUP -n $KUBE_NAME --auto-upgrade-channel node-image ``` ## Maintenance window ``` az aks maintenanceconfiguration add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n default --weekday Tuesday --start-hour 12 ``` <file_sep># AKS Engine https://github.com/Azure/aks-engine/blob/master/docs/topics/clusterdefinitions.md 0. Variables ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv) KUBE_GROUP="akse118" VNET_GROUP="akse118" KUBE_NAME="dz-aksemsi" LOCATION="westeurope" SERVICE_PRINCIPAL_ID="" SERVICE_PRINCIPAL_SECRET="" KUBE_VNET_NAME=aksvnet VM_VNET_NAME=vmnet KUBE_MASTER_SUBNET_NAME="m-1-subnet" KUBE_WORKER_SUBNET_NAME="w-2-subnet" KUBE_POD_SUBNET_NAME="p-3-subnet" YOUR_SSH_KEY=$(cat ~/.ssh/id_rsa.pub) ``` # Get aks-engine tools Download latest release from https://github.com/Azure/aks-engine/releases ``` wget https://github.com/Azure/aks-engine/releases/download/v0.43.2/aks-engine-v0.43.2-darwin-amd64.tar.gz tar -zxvf aks-engine-v0.43.2-darwin-amd64.tar.gz cd aks-engine-v0.43.2-darwin-amd64 ``` # Create Identity ``` SP_NAME="$KUBE_NAME-sp" SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $SP_NAME -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET ``` # Prepare variables 1. Download config file from https://github.com/denniszielke/container_demos/blob/master/aks-engine/acseng.json Check config https://github.com/Azure/aks-engine/blob/master/docs/topics/clusterdefinitions.md Replace `SERVICE_PRINCIPAL_ID`, `SERVICE_PRINCIPAL_SECRET` and `YOUR_SSH_KEY` with your own values ``` sed -e "s/SERVICE_PRINCIPAL_ID/$SERVICE_PRINCIPAL_ID/ ; s/SERVICE_PRINCIPAL_SECRET/$SERVICE_PRINCIPAL_SECRET/ ; s/SUBSCRIPTION_ID/$SUBSCRIPTION_ID/ ; s/KUBE_GROUP/$KUBE_GROUP/ ; s/GROUP_ID/$GROUP_ID/" acseng.json > acseng_out.json ``` 2. Replace YOUR_SSH_KEY with your ssh key # Create VNET ``` az group create -n $VNET_GROUP -l $LOCATION az network vnet create -g $VNET_GROUP -n $KUBE_VNET_NAME --address-prefixes 172.16.0.0/16 10.240.0.0/16 az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_MASTER_SUBNET_NAME --address-prefix 172.16.1.0/24 az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_WORKER_SUBNET_NAME --address-prefix 172.16.2.0/24 az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_POD_SUBNET_NAME --address-prefix 10.240.0.0/16 az network vnet create -g $VNET_GROUP -n $VM_VNET_NAME --address-prefixes 10.241.0.0/16 --subnet-name $VM_VNET_NAME --subnet-prefix 10.241.0.0/24 az network vnet peering create -g $VNET_GROUP -n KubeToVMPeer --vnet-name $KUBE_VNET_NAME --remote-vnet $VM_VNET_NAME --allow-vnet-access az network vnet peering create -g $VNET_GROUP -n VMToKubePeer --vnet-name $VM_VNET_NAME --remote-vnet $KUBE_VNET_NAME --allow-vnet-access ``` # Generate aks-engine ``` ./aks-engine generate akseng.json ``` # Deploy cluster 1. Create the resource group and role assignment ``` az group create -n $KUBE_GROUP -l $LOCATION az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP az identity create -g $KUBE_GROUP -n dzaksemsi MSI_CLIENT_ID=$(az identity show -n dzaksemsi -g $KUBE_GROUP --query clientId -o tsv) az role assignment create --role "Network Contributor" --assignee $MSI_CLIENT_ID -g $VNET_GROUP az role assignment create --role "Contributor" --assignee $MSI_CLIENT_ID -g $KUBE_GROUP # will be done by aks-engine ``` 2. Create cluster ``` az group deployment create \ --name $KUBE_NAME \ --resource-group $KUBE_GROUP \ --template-file "_output/$KUBE_NAME/azuredeploy.json" \ --parameters "_output/$KUBE_NAME/azuredeploy.parameters.json" --no-wait ``` # assign permissions for smsi ``` SCALE_SET_NAME=$(az vmss list --resource-group $KUBE_GROUP --query '[].{Name:name}' -o tsv) MSI_CLIENT_ID=$(az vmss identity show --name $SCALE_SET_NAME -g $KUBE_GROUP --query principalId -o tsv) az role assignment create --role "Network Contributor" --assignee $MSI_CLIENT_ID -g $VNET_GROUP az role assignment create --role "Contributor" --assignee $MSI_CLIENT_ID -g $VNET_GROUP VNET_RESOURCE_ID=$(az network vnet show -g $VNET_GROUP -n $KUBE_VNET_NAME --query id -o tsv) az role assignment create --role "Network Contributor" --assignee $MSI_CLIENT_ID --scope $VNET_RESOURCE_ID ``` # Fix routetable ``` ROUTETABLE_ID=$(az resource list --resource-group $KUBE_GROUP --resource-type Microsoft.Network/routeTables --query '[].{ID:id}' -o tsv) az network vnet subnet update -n $KUBE_WORKER_SUBNET_NAME -g $VNET_GROUP --vnet-name $KUBE_VNET_NAME --route-table $ROUTETABLE_ID ``` # Load kube config ``` export KUBECONFIG=`pwd`/_output/$KUBE_NAME/kubeconfig/kubeconfig.$LOCATION.json ``` # Delete everything ``` az group delete -n $KUBE_GROUP ``` ``` ./aks-engine get-versions ``` # Upgrade The kubeadm configuration is also accessible by standard kubectl ConfigMap interrogation and is, by convention, named the cluster-info ConfigMap in the kube-public namespace. ``` ./aks-engine get-versions --version 1.11.5 EXPECTED_ORCHESTRATOR_VERSION=1.11.10 ./aks-engine upgrade --debug \ --subscription-id $SUBSCRIPTION_ID \ --deployment-dir ../_output/$KUBE_NAME \ --api-model ../_output/$KUBE_NAME/apimodel.json \ --location $LOCATION \ --resource-group $KUBE_GROUP \ --upgrade-version $EXPECTED_ORCHESTRATOR_VERSION \ --auth-method client_secret \ --client-id $SERVICE_PRINCIPAL_ID \ --client-secret $SERVICE_PRINCIPAL_SECRET ./aks-engine scale --subscription-id $SUBSCRIPTION_ID \ --resource-group $KUBE_GROUP --location $LOCATION \ --client-id $SERVICE_PRINCIPAL_ID \ --client-secret $SERVICE_PRINCIPAL_SECRET \ --api-model _output/$KUBE_NAME/apimodel.json --new-node-count 4 \ --node-pool agentpool2 --master-FQDN $KUBE_NAME.$LOCATION.cloudapp.azure.com ./aks-engine upgrade --debug \ --subscription-id $SUBSCRIPTION_ID \ --deployment-dir ../acs-engine-v0.18.8-darwin-amd64/_output/$KUBE_NAME/ \ --location $LOCATION \ --resource-group $KUBE_GROUP \ --upgrade-version $EXPECTED_ORCHESTRATOR_VERSION \ --auth-method client_secret \ --client-id $SERVICE_PRINCIPAL_ID \ --client-secret $SERVICE_PRINCIPAL_SECRET ``` # Upgrade credentials https://github.com/Azure/aks-engine/issues/724#issuecomment-403183388 ``` CLUSTER_RESOURCE_GROUP=acsaksupgrade SCALE_SET_NAME=aks-default-47461129-vmss az vmss extension list --resource-group $CLUSTER_RESOURCE_GROUP --vmss-name $SCALE_SET_NAME az vmss extension show --name vmssCSE --resource-group $CLUSTER_RESOURCE_GROUP --vmss-name $SCALE_SET_NAME --output json az vm get-instance-view \ --resource-group $CLUSTER_RESOURCE_GROUP \ --name k8s-agentpool1-86714434-vmss_0 \ --query "instanceView.extensions" az vmss extension set --name customScript \ --resource-group $CLUSTER_RESOURCE_GROUP \ --vmss-name $SCALE_SET_NAME \ --provision-after-extensions "vmssCSE" \ --publisher Microsoft.Azure.Extensions --version 2.0 \ --protected-settings '{"fileUris": ["https://raw.githubusercontent.com/denniszielke/container_demos/master/arm/cse.sh"],"commandToExecute": "./cse.sh"}' az vmss extension set --vmss-name my-vmss --name customScript --resource-group my-group \ --version 2.0 --publisher Microsoft.AKS \ --settings '{"commandToExecute": "echo testing"}' az vmss extension set --name customScript \ --resource-group $CLUSTER_RESOURCE_GROUP \ --vmss-name $SCALE_SET_NAME \ --publisher Microsoft.AKS --version 1.0 \ --protected-settings '{"fileUris": ["https://raw.githubusercontent.com/denniszielke/container_demos/master/arm/cse.sh"],"commandToExecute": "./cse.sh"}' az vmss extension set --name CustomScriptForLinux \ --resource-group $CLUSTER_RESOURCE_GROUP \ --provisionAfterExtensions "vmssCSE" \ --vmss-name $SCALE_SET_NAME \ --publisher Microsoft.OSTCExtensions \ --settings '{"fileUris": ["https://raw.githubusercontent.com/denniszielke/container_demos/master/arm/cse.sh"],"commandToExecute": "./cse.sh"}' ``` # Troubleshooting https://github.com/Azure/aks-engine/blob/master/docs/howto/troubleshooting.md # Restarting as part of extension mkdir ~/msifix echo $(date +"%T") >> ~/msifix/out.log sleep 100 echo $(date +"%T") >> ~/msifix/out.log kubectl get pod -n kube-system >> ~/msifix/out.log echo $(date +"%T") >> ~/msifix/out.log PODNAME=$(kubectl -n kube-system get pod -l "component=kube-controller-manager" -o jsonpath='{.items[0].metadata.name}') kubectl -n kube-system delete pod $PODNAME >> ~/msifix/out.log kubectl get pod -n kube-system >> ~/msifix/out.log echo $(date +"%T") >> ~/msifix/out.log # Removing LBs az network lb list -g $KUBE_GROUP LB_NAME=$KUBE_GROUP LB_GROUP=$KUBE_GROUP az network lb rule list --lb-name $LB_NAME --resource-group $LB_GROUP az network lb outbound-rule list --lb-name $LB_NAME -g $LB_GROUP az network lb outbound-rule delete --lb-name $LB_NAME -g $LB_GROUP -n $LB_NAME az network lb outbound-rule delete --lb-name $LB_NAME -g $LB_GROUP -n LBOutboundRule az network lb rule list --lb-name $LB_NAME --resource-group $LB_GROUP az network lb delete -g $LB_GROUP -n $LB_NAME az network lb rule list --lb-name $LB_NAME --resource-group $LB_GROUP az network lb probe list --lb-name $LB_NAME --resource-group $LB_GROUP az network lb address-pool list --lb-name $LB_NAME --resource-group $LB_GROUP az network lb address-pool delete --lb-name $LB_NAME --name $LB_NAME --resource-group $LB_GROUP # Add new LB LB_GROUP=aksengine LB_NAME=standardload IP_NAME=newip /etc/kubernetes/azure.json "loadBalancerResourceGroup": "aksengine", "loadBalancerName": "standardload", az network lb address-pool create --resource-group $LB_GROUP --lb-name $LB_NAME --name LBOutboundRule az network lb frontend-ip create --resource-group $LB_GROUP --name LoadBalancerFrontEnd --lb-name $LB_NAME --public-ip-address $IP_NAME az network lb rule create \ --resource-group myresourcegroupoutbound \ --lb-name lb \ --name inboundlbrule \ --protocol tcp \ --frontend-port 80 \ --backend-port 80 \ --probe http \ --frontend-ip-name myfrontendinbound \ --backend-pool-name bepoolinbound \ --disable-outbound-snat az network lb rule update --disable-outbound-snat az network lb outbound-rule create \ --resource-group $LB_GROUP \ --lb-name $LB_NAME \ --name outbound \ --frontend-ip-configs LoadBalancerFrontEnd \ --protocol All \ --idle-timeout 15 \ --outbound-ports 10000 \ --address-pool LBOutboundRule<file_sep>KUBE_NAME=$1 KUBE_GROUP=$2 AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) SUBSCRIPTION_ID=$(az account show --query id -o tsv) #subscriptionid LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) SERVICE_PRINCIPAL_ID=$(az ad sp show --id $KUBE_NAME -o json | jq -r '.[0].appId') if [ "$SERVICE_PRINCIPAL_ID" == "" ]; then SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME -o json | jq -r '.appId') fi SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --append --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo -e "\n\n Remember these outputs:" echo -e "Your Kubernetes service_principal_id should be \e[7m$SERVICE_PRINCIPAL_ID\e[0m" echo -e "Your Kubernetes service_principal_secret should be \e[7m$SERVICE_PRINCIPAL_SECRET\e[0m" echo -e "Your Azure tenant_id should be \e[7m$AZURE_TENANT_ID\e[0m" echo -e "Your Azure subscription_id should be \e[7m$SUBSCRIPTION_ID\e[0m" echo -e "\n\n" az role assignment create --role "Reader" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP -o none #az role assignment create --role "Monitoring Reader" --assignee $SERVICE_PRINCIPAL_ID --scope /subscriptions/$SUBSCRIPTION_ID -o none #az role assignment create --role "Reader" --assignee $SERVICE_PRINCIPAL_ID --scope /subscriptions/$SUBSCRIPTION_ID -o none WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace list --resource-group $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) az role assignment create --role "Log Analytics Reader" --assignee $SERVICE_PRINCIPAL_ID --scope $WORKSPACE_RESOURCE_ID -o none OMS_CLIENT_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query addonProfiles.omsagent.identity.clientId -o tsv) AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query id -o tsv) if [ "$OMS_CLIENT_ID" == "" ]; then az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons monitoring --workspace-resource-id $WORKSPACE_RESOURCE_ID az role assignment create --assignee $OMS_CLIENT_ID --scope $AKS_ID --role "Monitoring Metrics Publisher" else az role assignment create --assignee $OMS_CLIENT_ID --scope $AKS_ID --role "Monitoring Metrics Publisher" fi curl -skSL https://raw.githubusercontent.com/kubernetes-sigs/azurefile-csi-driver/master/deploy/install-driver.sh | bash -s master -- kubectl create -f https://raw.githubusercontent.com/kubernetes-sigs/azurefile-csi-driver/master/deploy/example/storageclass-azurefile-csi.yaml kubectl create -f https://raw.githubusercontent.com/kubernetes-sigs/azurefile-csi-driver/master/deploy/example/storageclass-azurefile-nfs.yaml ## contributor on nodes ## contributor on aks subnet for service endpoint helm repo add grafana https://grafana.github.io/helm-charts helm repo update kubectl create namespace monitoring helm upgrade --install loki grafana/loki-stack -n monitoring --set grafana.enabled=true,grafana.persistence.enabled=true,grafana.persistence.storageClassName=azurefile-csi-nfs,prometheus.enabled=true,prometheus.alertmanager.persistentVolume.enabled=false,prometheus.server.persistentVolume.enabled=false,loki.persistence.enabled=true,loki.persistence.storageClassName=azurefile-csi,loki.persistence.size=5Gi helm repo add prometheus https://prometheus-community.github.io/helm-charts helm repo update helm upgrade --install po \ --namespace monitoring \ prometheus/kube-prometheus-stack --wait helm repo add loki https://grafana.github.io/loki/charts helm repo update helm upgrade --install loki \ --namespace monitoring \ loki/loki --wait #--set grafana.enabled=true,prometheus.enabled=true,prometheus.alertmanager.persistentVolume.enabled=true,prometheus.server.persistentVolume.enabled=true helm upgrade --install promtail \ --namespace monitoring \ --set loki.serviceName=loki \ loki/promtail --wait kubectl port-forward deployment/loki-grafana 3000 3000 -n monitoring # kubectl get secret -n monitoring loki-grafana -o jsonpath="{.data.admin-password}" | base64 --decode #UserName: admin #Password: <PASSWORD> #URL: http://loki:3100 # import https://grafana.com/grafana/dashboards/10956 # import api server https://grafana.com/grafana/dashboards/12006 DNS=dzgrafana1.westeurope.cloudapp.azure.com for i in {1..10000}; do curl -X POST -s -w "%{time_total}\n" -o /dev/null http://$DNS/api/log -H "message: {more: content}"; sleep 0.5; curl -X POST http://$DNS/api/log -H "message: hi" ; done while(true); do sleep 0.5; curl -X POST http://$DNS/api/log -H "message: {more: content}" ; curl -X POST http://$DNS/api/log -H "message: hi" ; done <file_sep>Tigera https://docs.tigera.io/getting-started/kubernetes/aks # StorageClass cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: tigera-elasticsearch parameters: cachingmode: ReadOnly kind: Managed storageaccounttype: Premium_LRS provisioner: kubernetes.io/azure-disk reclaimPolicy: Retain allowVolumeExpansion: true volumeBindingMode: WaitForFirstConsumer EOF kubectl create -f https://docs.tigera.io/manifests/tigera-operator.yaml kubectl create -f https://docs.tigera.io/manifests/tigera-prometheus-operator.yaml kubectl create secret generic tigera-pull-secret \ --type=kubernetes.io/dockerconfigjson -n tigera-operator \ --from-file=.dockerconfigjson=tigera-microsoft-dt-auth.json kubectl create -f license.yaml # Access https://docs.tigera.io/getting-started/cnx/access-the-manager#access-using-port-forwarding cat <<EOF | kubectl apply -f - kind: Service apiVersion: v1 metadata: name: tigera-manager-external namespace: tigera-manager spec: type: LoadBalancer selector: k8s-app: tigera-manager externalTrafficPolicy: Local ports: - port: 9443 targetPort: 9443 protocol: TCP EOF kubectl port-forward -n tigera-manager service/tigera-manager 9443:9443 kubectl create sa jane -n default kubectl create clusterrolebinding jane-access --clusterrole tigera-network-admin --serviceaccount default:jane kubectl get secret $(kubectl get serviceaccount jane -o jsonpath='{range .secrets[*]}{.name}{"\n"}{end}' | grep token) -o go-template='{{.data.token | base64decode}}' && echo # egress gateway kubectl patch felixconfiguration.p default --type='merge' -p \ '{"spec":{"egressIPSupport":"EnabledPerNamespace"}}' kubectl apply -f - <<EOF apiVersion: projectcalico.org/v3 kind: IPPool metadata: name: egress-ippool-1 spec: cidr: 10.0.5.0/27 blockSize: 31 nodeSelector: "!all()" EOF kubectl apply -f - <<EOF apiVersion: apps/v1 kind: Deployment metadata: name: egress-gateway namespace: default labels: egress-code: red spec: replicas: 1 selector: matchLabels: egress-code: red template: metadata: annotations: cni.projectcalico.org/ipv4pools: "[\"egress-ippool-1\"]" labels: egress-code: red spec: imagePullSecrets: - name: tigera-pull-secret nodeSelector: kubernetes.io/os: linux workload: router containers: - name: egress-gateway image: quay.io/tigera/egress-gateway:v3.4.0 env: - name: EGRESS_POD_IP valueFrom: fieldRef: fieldPath: status.podIP securityContext: privileged: true terminationGracePeriodSeconds: 0 EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos annotations: egress.projectcalico.org/selector: egress-code == 'red' egress.projectcalico.org/namespaceSelector: projectcalico.org/name == 'default' spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF<file_sep># Kubernetes using aad-pod-identity to access azure key vault https://github.com/Azure/aad-pod-identity https://blog.jcorioland.io/archives/2018/09/05/azure-aks-active-directory-managed-identities.html 0. Variables ``` KUBE_GROUP=kubesdemo KUBE_NAME=dzkubeaks LOCATION="westeurope" SUBSCRIPTION_ID= AAD_APP_ID= AAD_APP_SECRET= AAD_CLIENT_ID= TENANT_ID= YOUR_SSH_KEY=$(cat ~/.ssh/id_rsa.pub) SERVICE_PRINCIPAL_ID= SERVICE_PRINCIPAL_SECRET= ADMIN_GROUP_ID= MY_OBJECT_ID= KUBE_ADMIN_ID= READER_USER_ID= VAULT_GROUP="dzcsi" VAULT_NAME="dzbyokdemo" MSA_NAME="mykvidentity" MSA_CLIENT_ID="" MSA_PRINCIPAL_ID="" SECRET_NAME="mySecret" SECRET_VERSION="" KEY_NAME="mykey" STORAGE_NAME="dzbyokdemo" az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="azure-keyvault-secrets-provider" ``` 1. create key vault ``` az group create -n $VAULT_GROUP -l $LOCATION az keyvault create -n $VAULT_NAME -g $VAULT_GROUP -l $LOCATION az keyvault create -n $VAULT_NAME -g $VAULT_GROUP -l $LOCATION --enable-soft-delete true --enable-purge-protection true --sku premium az keyvault list -g $VAULT_GROUP -o table --query [].{Name:name,ResourceGroup:resourceGroup,PurgeProtection:properties.enablePurgeProtection,SoftDelete:properties.enableSoftDelete} ``` 2. add dummy secret ``` az keyvault secret set -n $SECRET_NAME --vault-name $VAULT_NAME --value MySuperSecretThatIDontWantToShareWithYou! ``` list secrets ``` az keyvault secret list --vault-name $VAULT_NAME -o table ``` add a key ``` az keyvault key create -n $KEY_NAME --vault-name $VAULT_NAME --kty RSA --ops encrypt decrypt wrapKey unwrapKey sign verify --protection hsm --size 2048 ``` list keys ``` az keyvault key list --vault-name $VAULT_NAME -o table ``` 3. create kubernetes crds ``` kubectl create -f https://raw.githubusercontent.com/Azure/aad-pod-identity/master/deploy/infra/deployment-rbac.yaml ``` 4. create managed identiy for pod ``` az identity create -n $MSA_NAME -g $VAULT_GROUP ``` 5. assign managed identity reader role in keyvault ``` KEYVAULT_PERMISSION="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VAULT_GROUP/providers/Microsoft.KeyVault/vaults/$VAULT_NAME" az role assignment create --role "Reader" --assignee $MSA_PRINCIPAL_ID --scope $KEYVAULT_PERMISSION ``` do this if the identity is not in the same resource groups as the aks nodes ``` az keyvault set-policy -n $VAULT_NAME --secret-permissions get list --spn $MSA_CLIENT_ID KUBE_PERMISSION="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VAULT_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/$MSA_NAME" az role assignment create --role "Managed Identity Operator" --assignee $SERVICE_PRINCIPAL_ID --scope $KUBE_PERMISSION ``` assign permissions on node groups for msi ``` az role assignment create --role "Contributor" --assignee $MSA_PRINCIPAL_ID -g $KUBE_GROUP ``` 6. bind to crds ``` cat <<EOF | kubectl create -f - apiVersion: "aadpodidentity.k8s.io/v1" kind: AzureIdentity metadata: name: $MSA_NAME spec: type: 0 ResourceID: /subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VAULT_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/$MSA_NAME ClientID: $MSA_CLIENT_ID EOF ``` 7. bind pod identity ``` cat <<EOF | kubectl create -f - apiVersion: "aadpodidentity.k8s.io/v1" kind: AzureIdentityBinding metadata: name: sample-binding spec: AzureIdentity: $MSA_NAME Selector: keyvaultsampleidentity EOF ``` 8. deploy sample app ``` cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Deployment metadata: labels: app: demo aadpodidbinding: demo name: demo namespace: default spec: template: metadata: labels: app: keyvaultsampleidentity aadpodidbinding: keyvaultsampleidentity spec: containers: - name: demo image: "mcr.microsoft.com/k8s/aad-pod-identity/demo:1.2" imagePullPolicy: Always args: - "--subscriptionid=$SUBSCRIPTION_ID" - "--clientid=$MSA_CLIENT_ID" - "--resourcegroup=$VAULT_GROUP" - "--aad-resourcename=https://vault.azure.net" # TO SPECIFY NAME OF RESOURCE TO GRANT TOKEN ADD --aad-resourcename # this demo defaults aad-resourcename to https://management.azure.com/ # e.g. - "--aad-resourcename=https://vault.azure.net" env: - name: MY_POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: MY_POD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: MY_POD_IP valueFrom: fieldRef: fieldPath: status.podIP EOF ``` key vault demo ``` VAULT_NAME=dzdevkeyvault AZURE_KEYVAULT_SECRET_NAME=mysupersecret SECRET_VERSION= cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos labels: app: keyvaultsample aadpodidbinding: keyvaultsampleidentity spec: containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF curl http://127.0.0.1:2579/host/token/?resource=https://vault.azure.net -H "podname: centos" -H "podns: default" curl http://127.0.0.1:2579/host/token/?resource=https://vault.azure.net -H "podname: keyvaultsample-65b7d4d4f4-bspd7" -H "podns: default" cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: labels: app: keyvaultsample aadpodidbinding: keyvaultsampleidentity name: keyvaultsample namespace: default spec: replicas: 1 selector: matchLabels: app: keyvaultsample template: metadata: labels: app: keyvaultsample aadpodidbinding: keyvaultsampleidentity name: keyvaultsample spec: containers: - name: keyvaultsample image: jcorioland/keyvault-aad-pod-identity:1.6 env: - name: AZURE_KEYVAULT_NAME value: $VAULT_NAME - name: AZURE_KEYVAULT_SECRET_NAME value: $SECRET_NAME - name: AZURE_KEYVAULT_SECRET_VERSION value: $SECRET_VERSION --- apiVersion: v1 kind: Service metadata: name: keyvaultsample namespace: default spec: ports: - port: 80 targetPort: 8080 selector: app: keyvaultsample type: LoadBalancer EOF ``` Cleanup ``` kubectl delete pods --selector=component=mic PODNAME=`kubectl get pods --namespace=${NAMESPACE} --selector="app=tf-hub" --output=template --template="{{with index .items 0}}{{.metadata.name}}{{end}}"` ``` https://github.com/Azure/azure-libraries-for-java/blob/master/AUTH.md https://github.com/Azure/azure-libraries-for-java/tree/master/azure-mgmt-msi/src ## create storage with byok key 1. create key vault ``` az group create -n $VAULT_GROUP -l $LOCATION az keyvault create -n $VAULT_NAME -g $VAULT_GROUP -l $LOCATION --enable-soft-delete true --enable-purge-protection true --sku premium az keyvault list -g $VAULT_GROUP -o table --query [].{Name:name,ResourceGroup:resourceGroup,PurgeProtection:properties.enablePurgeProtection,SoftDelete:properties.enableSoftDelete} ``` 2. add a key ``` az keyvault key create -n $KEY_NAME --vault-name $VAULT_NAME --kty RSA --ops encrypt decrypt wrapKey unwrapKey sign verify --protection hsm --size 2048 ``` list keys ``` az keyvault key list --vault-name $VAULT_NAME -o table ``` 3. create storage account ``` az storage account create -n $STORAGE_NAME -g $VAULT_GROUP --https-only true --encryption-services table queue blob file --assign-identity ``` 4. get storage account identity ``` az storage account show -g $VAULT_GROUP -n $STORAGE_NAME --query identity.principalId ``` 5. set policy for storage identity to access keyvault ``` az keyvault set-policy -n $VAULT_NAME --object-id cae12840-2557-4469-909e-c29283a82c45 --key-permissions get wrapkey unwrapkey ``` 6. Create or Update your Azure Storage Account to use your new keys from your Key Vault: ``` az storage account update -g $VAULT_GROUP -n $STORAGE_NAME --encryption-key-name $KEY_NAME --encryption-key-source Microsoft.KeyVault --encryption-key-vault https://$VAULT_NAME.vault.azure.net --encryption-key-version 2ce0b736baff47a4b5691edc2c53a597 --encryption-services blob file queue table az acr create -n dzdemoky23 -g $VAULT_GROUP --sku Classic --location $LOCATION --storage-account-name $STORAGE_NAME ``` ## CSI https://github.com/deislabs/secrets-store-csi-driver/tree/master/pkg/providers/azure ``` SERVICE_PRINCIPAL_ID=$AZDO_SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$AKS_SERVICE_PRINCIPAL_SECRET VAULT_GROUP=dztenix-888 AZURE_KEYVAULT_NAME=<KEY> LOCATION=westeurope TENANT_ID=$(az account show --query tenantId -o tsv) SUBSCRIPTION_NAME=$(az account show --query name -o tsv) SUBSCRIPTION_ID=$(az account show --query id -o tsv) kubectl create secret generic secrets-store-creds --from-literal clientid=$SERVICE_PRINCIPAL_ID --from-literal clientsecret=$SERVICE_PRINCIPAL_SECRET az role assignment create --role Reader --assignee $SERVICE_PRINCIPAL_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$VAULT_GROUP/providers/Microsoft.KeyVault/vaults/$AZURE_KEYVAULT_NAME az keyvault set-policy -n $AZURE_KEYVAULT_NAME --key-permissions get --spn $SERVICE_PRINCIPAL_ID az keyvault set-policy -n $AZURE_KEYVAULT_NAME --secret-permissions get --spn $SERVICE_PRINCIPAL_ID az keyvault set-policy -n $AZURE_KEYVAULT_NAME --certificate-permissions get --spn $SERVICE_PRINCIPAL_ID cd /Users/$USER/hack/secrets-store-csi-driver kubectl create ns csi-secrets-store helm upgrade csi-drver charts/secrets-store-csi-driver --namespace csi-secrets-store --install kubectl create ns dummy cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1alpha1 kind: SecretProviderClass metadata: name: azure-kvname1 spec: provider: azure # accepted provider options: azure or vault parameters: usePodIdentity: "false" # [OPTIONAL for Azure] if not provided, will default to "false" keyvaultName: "$AZURE_KEYVAULT_NAME" # the name of the KeyVault objects: | array: - | objectName: acr-name objectType: secret # object types: secret, key or cert - | objectName: aks-group objectType: secret resourceGroup: "$VAULT_GROUP" # [REQUIRED for version < 0.0.4] the resource group of the KeyVault subscriptionId: "$SUBSCRIPTION_ID" # [REQUIRED for version < 0.0.4] the subscription ID of the KeyVault tenantId: "$TENANT_ID" # the tenant ID of the KeyVault EOF cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: nginx-default spec: containers: - image: nginx name: nginx volumeMounts: - name: secrets-store-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: "azure-kvname1" nodePublishSecretRef: name: secrets-store-creds EOF kubectl exec -it nginx-secrets-store-inline -n dummy -- /bin/sh ``` ## df ``` cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: nginx-secrets-store-inline spec: containers: - image: nginx name: nginx volumeMounts: - name: secrets-store-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store-inline csi: driver: secrets-store.csi.k8s.com readOnly: true volumeAttributes: providerName: "azure" usePodIdentity: "false" # [OPTIONAL] if not provided, will default to "false" keyvaultName: "$VAULT_NAME" # the name of the KeyVault objects: | array: - | objectName: mysupersecret objectType: secret # object types: secret, key or cert objectVersion: "" # [OPTIONAL] object versions, default to latest if empty resourceGroup: "$VAULT_GROUP" # the resource group of the KeyVault subscriptionId: "$SUBSCRIPTION_ID" # the subscription ID of the KeyVault tenantId: "$TENANT_ID" # the tenant ID of the KeyVault EOF ``` ``` az identity create -n keyvaultidentity -g $VAULT_GROUP KUBE_PERMISSION="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VAULT_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/keyvaultidentity" az role assignment create --role "Managed Identity Operator" --assignee $SERVICE_PRINCIPAL_ID --scope $KUBE_PERMISSION MSI_ID=$(az identity show -n keyvaultidentity -g $VAULT_GROUP --query clientId --output tsv) az role assignment create --role Reader --assignee $MSI_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$VAULT_GROUP/providers/Microsoft.KeyVault/vaults/$VAULT_NAME # set policy to access keys in your keyvault az keyvault set-policy -n $VAULT_NAME --key-permissions get --spn $MSI_ID # set policy to access secrets in your keyvault az keyvault set-policy -n $VAULT_NAME --secret-permissions get --spn $MSI_ID # set policy to access certs in your keyvault az keyvault set-policy -n $VAULT_NAME --certificate-permissions get --spn $MSI_ID cat <<EOF | kubectl apply -f - apiVersion: "aadpodidentity.k8s.io/v1" kind: AzureIdentity metadata: name: keyvaultidentity spec: type: 0 ResourceID: /subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VAULT_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/keyvaultidentity ClientID: $MSI_ID EOF cat <<EOF | kubectl apply -f - apiVersion: "aadpodidentity.k8s.io/v1" kind: AzureIdentityBinding metadata: name: keyvaultidentity-binding spec: AzureIdentity: keyvaultidentity Selector: keyvaultidentity EOF az keyvault secret set -n mysupersecret --vault-name $VAULT_NAME --value MySuperSecretThatIDontWantToShareWithYou! cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: nginx-secrets-store-inline-pod-identity labels: aadpodidbinding: "keyvaultidentity" spec: containers: - image: nginx name: nginx volumeMounts: - name: secrets-store-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store-inline csi: driver: secrets-store.csi.k8s.com readOnly: true volumeAttributes: providerName: "azure" usePodIdentity: "true" # [OPTIONAL] if not provided, will default to "false" keyvaultName: "$VAULT_NAME" # the name of the KeyVault objects: | array: - | objectName: mysupersecret objectType: secret # object types: secret, key or cert objectVersion: "" # [OPTIONAL] object versions, default to latest if empty resourceGroup: "$VAULT_GROUP" # the resource group of the KeyVault subscriptionId: "$SUBSCRIPTION_ID" # the subscription ID of the KeyVault tenantId: "$TENANT_ID" # the tenant ID of the KeyVault EOF kubectl exec -it nginx-secrets-store-inline-pod-identity cat /kvmnt/testsecret ``` # new CSI ``` helm repo add csi-secrets-store-provider-azure https://raw.githubusercontent.com/Azure/secrets-store-csi-driver-provider-azure/master/charts kubectl create ns csi-secrets-store helm upgrade csi-secret-driver csi-secrets-store-provider-azure/csi-secrets-store-provider-azure --namespace csi-secrets-store --install VAULT_NAME=dzphix1-436-vault az identity create -g $NODE_GROUP -n $VAULT_NAME-id sleep 5 # wait for replication AGIC_ID_CLIENT_ID="$(az identity show -g $NODE_GROUP -n $VAULT_NAME-id --query clientId -o tsv)" AGIC_ID_RESOURCE_ID="$(az identity show -g $NODE_GROUP -n $VAULT_NAME-id --query id -o tsv)" NODES_RESOURCE_ID=$(az group show -n $NODE_GROUP -o tsv --query "id") KUBE_GROUP_RESOURCE_ID=$(az group show -n $KUBE_GROUP -o tsv --query "id") sleep 15 # wait for replication echo "assigning permissions for AGIC client $AGIC_ID_CLIENT_ID" az role assignment create --role "Contributor" --assignee $AGIC_ID_CLIENT_ID --scope $APPGW_RESOURCE_ID az role assignment create --role "Reader" --assignee $AGIC_ID_CLIENT_ID --scope $KUBE_GROUP_RESOURCE_ID # might not be needed az role assignment create --role "Reader" --assignee $AGIC_ID_CLIENT_ID --scope $NODES_RESOURCE_ID # might not be needed az role assignment create --role "Reader" --assignee $AGIC_ID_CLIENT_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$KUBE_GROUP helm repo add aad-pod-identity https://raw.githubusercontent.com/Azure/aad-pod-identity/master/charts helm repo update helm upgrade aad-pod-identity --install --namespace kube-system aad-pod-identity/aad-pod-identity cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1alpha1 kind: SecretProviderClass metadata: name: azure-kvname spec: provider: azure parameters: usePodIdentity: "true" # [REQUIRED] Set to "true" if using managed identities useVMManagedIdentity: "false" # [OPTIONAL] if not provided, will default to "false" userAssignedIdentityID: "$AGIC_ID_CLIENT_ID" # az ad sp show --id http://contosoServicePrincipal --query appId -o tsv # the preceding command will return the client ID of your service principal keyvaultName: "$VAULT_NAME" # [REQUIRED] the name of the key vault # az keyvault show --name contosoKeyVault5 # the preceding command will display the key vault metadata, which includes the subscription ID, resource group name, key vault cloudName: "AzurePublicCloud" # [OPTIONAL for Azure] if not provided, Azure environment will default to AzurePublicCloud objects: | array: - | objectName: dummy objectType: secret objectVersion: "" resourceGroup: "$KUBE_GROUP" # [REQUIRED] the resource group name of the key vault subscriptionId: "$SUBSCRIPTION_ID" # [REQUIRED] the subscription ID of the key vault tenantId: "$TENANT_ID" # [REQUIRED] the tenant ID of the key vault EOF cat <<EOF | kubectl apply -f - apiVersion: aadpodidentity.k8s.io/v1 kind: AzureIdentity metadata: name: "$VAULT_NAME-id" # The name of your Azure identity spec: type: 0 # Set type: 0 for managed service identity resourceID: "$AGIC_ID_RESOURCE_ID" clientID: "$AGIC_ID_CLIENT_ID" # The clientId of the Azure AD identity that you created earlier --- apiVersion: aadpodidentity.k8s.io/v1 kind: AzureIdentityBinding metadata: name: azure-pod-identity-binding spec: azureIdentity: "$VAULT_NAME-id" # The name of your Azure identity selector: azure-pod-identity-binding-selector EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: nginx-secrets-store-inline labels: aadpodidbinding: azure-pod-identity-binding-selector spec: containers: - name: nginx image: nginx volumeMounts: - name: secrets-store-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: azure-kvname EOF ``` ## Managed KV ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv) AZURE_MYOWN_OBJECT_ID=$(az ad signed-in-user show --query objectId --output tsv) KEYVAULT_NAME=dvadzvault KUBE_NAME=dzvault LOCATION=westeurope KUBE_GROUP=dzvault KUBE_VERSION=1.20.7 NODE_GROUP=dzvault_dzvault_nodes_westeurope SERVICE_PRINCIPAL_ID=msi AKV_NS=akv-demo az aks enable-addons --addons azure-keyvault-secrets-provider --enable-secret-rotation --resource-group=$KUBE_GROUP --name=$KUBE_NAME KUBELET_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identityProfile.kubeletidentity.clientId -o tsv) az keyvault set-policy -n $KEYVAULT_NAME --secret-permissions get set list --object-id $AZURE_MYOWN_OBJECT_ID az keyvault set-policy -n $KEYVAULT_NAME --secret-permissions get --spn $KUBELET_ID az keyvault secret set -n supersecret1 --vault-name $KEYVAULT_NAME --value MySuperSecretThatIDontWantToShareWithYou! kubectl create ns $AKV_NS cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1alpha1 kind: SecretProviderClass metadata: name: azure-kvname-user-msi namespace: aadsecured spec: provider: azure parameters: usePodIdentity: "false" useVMManagedIdentity: "true" userAssignedIdentityID: "$KUBELET_ID" keyvaultName: "$KEYVAULT_NAME" cloudName: "" # [OPTIONAL for Azure] if not provided, azure environment will default to AzurePublicCloud objects: | array: - | objectName: mySecret objectType: secret # object types: secret, key or cert objectVersion: "" # [OPTIONAL] object versions, default to latest if empty tenantId: "$TENANT_ID" # the tenant ID of the KeyVault EOF cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1alpha1 kind: SecretProviderClass metadata name: azure-sync namespace: $AKV_NS spec: provider: azure secretObjects: # [OPTIONAL] SecretObject defines the desired state of synced K8s secret objects - secretName: foosecret type: Opaque labels: environment: "test" data: - objectName: secretalias # name of the mounted content to sync. this could be the object name or object alias key: username parameters: usePodIdentity: "false" useVMManagedIdentity: "true" userAssignedIdentityID: "$KUBELET_ID" keyvaultName: "$KEYVAULT_NAME" objects: | array: - | objectName: supersecret1 objectType: secret # object types: secret, key or cert objectAlias: secretalias objectVersion: "" # [OPTIONAL] object versions, default to latest if empty tenantId: "$TENANT_ID" EOF cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: busybox-secrets-store-inline-user-msi namespace: aadsecured spec: containers: - name: busybox image: k8s.gcr.io/e2e-test-images/busybox:1.29 command: - "/bin/sleep" - "10000" volumeMounts: - name: secrets-store01-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store01-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: "azure-kvname-user-msi" EOF kubectl exec -it busybox-secrets-store-inline-user-msi -n akv-demo -- /bin/sh ls -l /mnt/secrets-store/ cat /mnt/secrets-store/supersecret1 ``` <file_sep>## Run a hello world container in Azure Container instances See https://docs.microsoft.com/en-us/azure/container-instances/container-instances-quickstart 1. Login into azure cli ``` az login ``` 2. Create a resource group ``` RESOURCE_GROUP="helloworld" az group create --name "$RESOURCE_GROUP" --location westeurope ``` 3. Create a container instance ``` CONTAINER_NAME="acihelloworld" az container create --name "$CONTAINER_NAME" --image microsoft/aci-helloworld --resource-group "$RESOURCE_GROUP" --ip-address public ``` 4. Confirm creation ``` az container show --name "$CONTAINER_NAME" --resource-group "$RESOURCE_GROUP" ``` 5. Pull container logs ``` az container logs --name "$CONTAINER_NAME" --resource-group "$RESOURCE_GROUP" ``` 6. Cleanup the resource group ``` az group delete --name "$RESOURCE_GROUP" --yes ``` ## Build a container, push it to registry and launch it https://docs.microsoft.com/en-us/azure/container-instances/container-instances-tutorial-deploy-app https://github.com/Azure-Samples/aci-helloworld 1. Set Docker Host (https://docs.docker.com/machine/reference/env/) Check in the Docker Daemon in "General" the setting "Expose daemon on tcp://localhost:2375 without TLS" ``` sudo apt install docker.io export DOCKER_HOST=tcp://127.0.0.1:2375 ``` On Ubuntu make sure that the current user is part of the docker group ``` sudo usermod -aG docker $USER ``` Log in and out to re-evaluate your group membership 2. Create container registry ``` REGISTRY_NAME="hellodemo345" az acr create --resource-group "$RESOURCE_GROUP" --name "$REGISTRY_NAME" --sku Basic --admin-enabled true ``` 3. Get login info (eval used because of the double quotation) Get the registry login server ``` az acr show --name "$REGISTRY_NAME" --query loginServer ``` Get the login password ``` az acr credential show --name "$REGISTRY_NAME" --query passwords[0].value ``` or automate it ``` DOCKER_SERVER=$(az acr show --name "$REGISTRY_NAME" --query loginServer) DOCKER_PASSWORD=$(az acr credential show --name "$REGISTRY_NAME" --query passwords[0].value) eval "docker login --username="$REGISTRY_NAME" --password=$<PASSWORD>_<PASSWORD> $DOCKER_SERVER" ``` or ``` az acr credential show -n myveryownregistry --query "join(' ', ['docker login myveryownregistry-on.azurecr.io', '-u', username, '-p', password])" --output tsv | sh` ``` 4. Pull, tag and push the latest image to the registry ``` docker pull microsoft/aci-helloworld eval "docker tag microsoft/aci-helloworld $DOCKER_SERVER/aci-helloworld:v1" eval "docker push $DOCKER_SERVER/aci-helloworld:v1" ``` or ``` docker tag microsoft/aci-helloworld hellodemo345.azurecr.io/aci-helloworld:v1 docker push "hellodemo345.azurecr.io/aci-helloworld:v1" ``` 5. Clone the source code depot. Build the image and push it to the registry. Run it on a new container instance. ``` git clone https://github.com/Azure-Samples/aci-helloworld.git cd aci-helloworld less Dockerfile docker build -t aci-tut-app . docker images eval "docker tag aci-tut-app $DOCKER_SERVER/aci-tut-app:v1" eval "docker push $DOCKER_SERVER/aci-tut-app:v1" CONTAINER_APP_NAME="acihelloworldapp" az container create -g $RESOURCE_GROUP --name $CONTAINER_APP_NAME --image hellodemo345.azurecr.io/aci-tut-app:v1 --registry-password $DOCKER_PASSWORD ``` cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Deployment metadata: name: hello-app spec: replicas: 1 minReadySeconds: 10 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1 template: metadata: labels: app: hello-app spec: containers: - name: hello-app image: gcr.io/google-samples/hello-app:1.0 #microsoft/aci-helloworld:latest ports: - containerPort: 80 imagePullPolicy: Always EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: hellofromgoogle spec: containers: - name: hellofromgoogle image: gcr.io/google-samples/hello-app:1.0 ports: - containerPort: 80 command: - sleep - "3600" EOF <file_sep># Creation of Service Principal via Azure Shell 1. Open an azure shell in the browser by authenticating with azure corp credentials and navigating to ``` https://shell.azure.com ``` 2. If this is the first time you are opening an azure shell you will be promted to create a storage account to store your bash history. Select a subscription and create the storage. ![](/img/basic-storage.png) 3. Enter the following command to create a service principal (assuming you have the right credentials/permissions) ``` az ad sp create-for-rbac --skip-assignment --name "kubernetes_sp" az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/${SUBSCRIPTION_ID}" --name "kubernetes_sp" KUBE_NAME= az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/${SUBSCRIPTION_ID}" --name $KUBE_NAME --sdk-auth ``` 4. The output will look similar to this ``` { "appId": "7248f250-0000-0000-0000-dbdeb8400d85", "displayName": "azure-cli-2017-10-15-02-20-15", "name": "http://azure-cli-2017-10-15-02-20-15", "password": "<PASSWORD>", "tenant": "72f988bf-0000-0000-0000-2d7cd011db47" } ``` 5. Remember and copy the appId (this is the service principal client id ) and the password (this is the service principal client secret) because you will need them later for kubernetes-to-azure authentication. Creation of an SP with the least amount of priviledges: https://github.com/jsturtevant/aks-examples/tree/master/least-privileged-sp # Creation of Service Principal via Azure Portal 1. Open the azure portal by authenticating with azure corp credentials and navigating to ``` https://portal.azure.com ``` 2. Select Azure Active Directory ![](/img/select-active-directory.png) 3. Select App registrations ![](/img/select-app-registrations.png) 4. Select New application registrations ![](/img/select-add-app.png) 5. Provide a name that will be identifiyable with your kubernetes cluster (keep it short - no special characters) and remember it. Enter a non-existing sign-on url - this url does not have any effect for the kubernetes cluster - but is a mandatory field. ![](/img/create-app.png) 6. From app registrations look up your new created app by name ![](/img/select-app.png) 7. Copy the ApplicationId for later (this is your service principal client id) ![](/img/copy-app-id.png) 8. Now we need to create a key. Go for Settings ![](/img/select-settings.png) 9. To generate an authentication key select Keys ![](/img/select-keys.png) 10. Provide a description of the key, and a duration for the key. When done, select Save. ![](/img/save-key.png) 11. After saving the key, the value of the key is displayed. Copy this value because you are not able to retrieve the key later. You provide the key value with the application ID to log in as the application. Store the key value where your application can retrieve it. ![](/img/copy-key.png) This key is your service principal client secret. ## Minimal permission on AKS 1- attach/detach does not happen on nodes. only controller manager. Volume Controller on the node just performers post attach stuff (wait for attach [by waiting for node object to reflect node.VolumesAttached reflecting whatever it is waiting for], mount, format) all does not need SPN 2- if the node has useInstanceMetadata turned on & no acr secrets then you don't need spn on nodes (iirc acr does not need SPNs only passwords). 3- if the node has useInstanceMetadata == false; then SPN is needed to call ARM 4- You need contribution on NRP, CRP, DRP in RG scope (or other scope depending on the need to provision stuff outside RG). we nevers said otherwise. in fact o remember there was an excel sheet with table trimmed down to exactly what is needed. 5- This is not the first time i raise this to <NAME> we can bootstrap clusters with minimum shit on nodes. 6- please note that OSA can use MSI/explicit identities, it really does not need SPN. 7- as a rule of thumb don't use SPN. We only have it because at some point of time that was the only thing provided, and we still have it because of backcompat <file_sep># Istio ## Install istioctl ``` https://istio.io/latest/docs/setup/getting-started/#download curl -L https://istio.io/downloadIstio | sh - export PATH=$PATH:$HOME/lib/istio-1.7.3 istioctl install --set profile=demo istioctl install --set profile=default istioctl profile dump default az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n istio2 -c 4 --node-vm-size Standard_DS3_v2 --mode system istioctl profile dump --config-path components.ingressGateways istioctl profile dump --config-path values.gateways.istio-ingressgateway istioctl install --set components.telemetry.enabled=true --set addonComponents.grafana.enabled=true istioctl analyze kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.7/samples/addons/kiali.yaml kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.7/samples/addons/prometheus.yaml kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.7/samples/addons/grafana.yaml istioctl x uninstall --purge kubectl delete namespace istio-system ``` ## Example https://istio.io/latest/docs/examples/bookinfo/ ``` kubectl label namespace default istio-injection=enabled kubectl label namespace default istio-injection=disabled kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.7/samples/bookinfo/platform/kube/bookinfo.yaml kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.7/samples/bookinfo/networking/bookinfo-gateway.yaml kubectl get svc istio-ingressgateway -n istio-system export INGRESS_HOST=$(kubectl get po -l istio=ingressgateway -n istio-system -o jsonpath='{.items[0].status.hostIP}') echo $INGRESS_HOST ``` ## ingress https://istio.io/latest/docs/tasks/traffic-management/ingress/ingress-control/ ``` kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.7/samples/httpbin/httpbin.yaml kubectl apply -f - <<EOF apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: httpbin-gateway spec: selector: istio: ingressgateway # use Istio default gateway implementation servers: - port: number: 80 name: http protocol: HTTP hosts: - "httpbin.example.com" EOF kubectl apply -f - <<EOF apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: httpbin spec: hosts: - "httpbin.example.com" gateways: - httpbin-gateway http: - match: - uri: prefix: /status - uri: prefix: /delay route: - destination: port: number: 8000 host: httpbin EOF ``` ## GRPC https://github.com/mhamrah/grpc-example https://github.com/grpc-ecosystem/grpc-gateway ``` kubectl apply -f https://raw.githubusercontent.com/mhamrah/grpc-example/master/k8s/setup/namespace.yaml kubectl label namespace todos istio-injection=enabled kubectl apply -f https://raw.githubusercontent.com/mhamrah/grpc-example/master/k8s/todos-client.yaml kubectl apply -f https://raw.githubusercontent.com/mhamrah/grpc-example/master/k8s/todos-server.yaml kubectl apply -f https://raw.githubusercontent.com/mhamrah/grpc-example/master/k8s/autoscale.yaml cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: todos-client namespace: todos labels: app: todos tier: client spec: replicas: 1 selector: matchLabels: app: todos tier: client template: metadata: labels: app: todos tier: client spec: containers: - name: todos-client image: denniszielke/todos-client env: - name: BACKEND value: "todos-server:50052" EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: todos-server namespace: todos labels: app: todos tier: server spec: replicas: 1 selector: matchLabels: app: todos tier: server template: metadata: labels: app: todos tier: server spec: containers: - name: todos-server image: denniszielke/todos-server ports: - containerPort: 50052 resources: requests: cpu: 100m memory: 128M limits: cpu: 200m memory: 256M EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: name: todos-server namespace: todos spec: selector: app: todos tier: server ports: - name: grpc port: 50052 EOF cat <<EOF | kubectl apply -f - apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: grpc-gateway namespace: todos spec: selector: istio: ingressgateway # use istio default controller servers: - port: number: 50052 name: todos-server protocol: GRPC hosts: - "*" EOF cat <<EOF | kubectl apply -f - apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: grpc-demo namespace: todos spec: hosts: - "*" gateways: - grpc-gateway http: - match: - uri: prefix: / route: - destination: host: todos-server port: number: 50052 EOF cat <<EOF | kubectl apply -f - apiVersion: networking.istio.io/v1alpha3 kind: DestinationRule metadata: name: todos-server spec: host: todos-server trafficPolicy: loadBalancer: simple: ROUND_ROBIN EOF ISTIO_GW=172.16.31.10 grpcurl -plaintext $ISTIO_GW:50052 describe grpcurl -plaintext -d '{ "id": "01E4Q00M7YPD06TX3YW8DMFF8B" }' $ISTIO_GW:50052 todos.Todos/GetTodo curl -X POST http://$ISTIO_GW:51052/todos -H 'Content-Type: application/json' -d '{ "id": "01E4Q00M7YPD06TX3YW8DMFF8B" }' ``` # Authorization ``` kubectl create ns foo kubectl apply -f <(istioctl kube-inject -f https://raw.githubusercontent.com/istio/istio/release-1.7/samples/httpbin/httpbin.yaml) -n foo kubectl apply -f <(istioctl kube-inject -f https://raw.githubusercontent.com/istio/istio/release-1.7/samples/sleep/sleep.yaml) -n foo kubectl exec "$(kubectl get pod -l app=sleep -n foo -o jsonpath={.items..metadata.name})" -c sleep -n foo -- curl http://httpbin.foo:8000/ip -s -o /dev/null -w "%{http_code}\n" cat <<EOF | kubectl apply -f - apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: httpbin namespace: foo spec: selector: matchLabels: app: httpbin version: v1 action: ALLOW rules: - from: - source: principals: ["cluster.local/ns/default/sa/sleep"] - source: namespaces: ["dev"] to: - operation: methods: ["GET"] when: - key: request.auth.claims[iss] values: ["https://accounts.google.com"] EOF cat <<EOF | kubectl apply -f - apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: httpbin-deny namespace: foo spec: selector: matchLabels: app: httpbin version: v1 action: DENY rules: - from: - source: notNamespaces: ["foo"] EOF ``` ## Custom Auth https://istio.io/latest/blog/2021/better-external-authz/ example auth policy ``` cat <<EOF | kubectl apply -f - apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: ext-authz namespace: istio-system spec: # The selector applies to the ingress gateway in the istio-system namespace. selector: matchLabels: app: istio-ingressgateway # The action "CUSTOM" delegates the access control to an external authorizer, this is different from # the ALLOW/DENY action that enforces the access control right inside the proxy. action: CUSTOM # The provider specifies the name of the external authorizer defined in the meshconfig, which tells where and how to # talk to the external auth service. We will cover this more later. provider: name: "my-ext-authz-service" # The rule specifies that the access control is triggered only if the request path has the prefix "/admin/". # This allows you to easily enable or disable the external authorization based on the requests, avoiding the external # check request if it is not needed. rules: - to: - operation: paths: ["/admin/*"] EOF ``` ``` cat > policy.rego <<EOF package envoy.authz import input.attributes.request.http as http_request default allow = false token = {"valid": valid, "payload": payload} { [_, encoded] := split(http_request.headers.authorization, " ") [valid, _, payload] := io.jwt.decode_verify(encoded, {"secret": "secret"}) } allow { is_token_valid action_allowed } is_token_valid { token.valid now := time.now_ns() / 1000000000 token.payload.nbf <= now now < token.payload.exp } action_allowed { startswith(http_request.path, base64url.decode(token.payload.path)) } EOF kubectl create ns opasvc kubectl label ns opademo istio-injection=enabled kubectl label namespace opasvc istio.io/rev=asm-1-17 kubectl create secret generic opa-policy -n opasvc --from-file policy.rego kubectl apply -f - <<EOF apiVersion: v1 kind: Service metadata: name: opa namespace: opasvc labels: app: opa spec: ports: - name: grpc port: 9191 targetPort: 9191 selector: app: opa --- kind: Deployment apiVersion: apps/v1 metadata: name: opa namespace: opasvc labels: app: opa spec: replicas: 1 selector: matchLabels: app: opa template: metadata: labels: app: opa spec: containers: - name: opa image: openpolicyagent/opa:latest-envoy securityContext: runAsUser: 1111 volumeMounts: - readOnly: true mountPath: /policy name: opa-policy args: - "run" - "--server" - "--addr=localhost:8181" - "--diagnostic-addr=0.0.0.0:8282" - "--set=plugins.envoy_ext_authz_grpc.addr=:9191" - "--set=plugins.envoy_ext_authz_grpc.query=data.envoy.authz.allow" - "--set=decision_logs.console=true" - "--ignore=.*" - "/policy/policy.rego" ports: - containerPort: 9191 livenessProbe: httpGet: path: /health?plugins scheme: HTTP port: 8282 initialDelaySeconds: 5 periodSeconds: 5 readinessProbe: httpGet: path: /health?plugins scheme: HTTP port: 8282 initialDelaySeconds: 5 periodSeconds: 5 volumes: - name: proxy-config configMap: name: proxy-config - name: opa-policy secret: secretName: opa-policy EOF kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.17/samples/httpbin/httpbin.yaml -n opasvc ``` define external authorizer ``` kubectl edit configmap istio-asm-1-17 -n aks-istio-system apiVersion: v1 data: mesh: |- defaultConfig: discoveryAddress: istiod-asm-1-17.aks-istio-system.svc:15012 gatewayTopology: numTrustedProxies: 1 image: imageType: distroless tracing: zipkin: address: zipkin.aks-istio-system:9411 enablePrometheusMerge: true rootNamespace: aks-istio-system trustDomain: cluster.local meshNetworks: 'networks: {}' kind: ConfigMap metadata: annotations: meta.helm.sh/release-name: azure-service-mesh-istio-discovery meta.helm.sh/release-namespace: aks-istio-system creationTimestamp: "2023-05-03T14:38:16Z" labels: app.kubernetes.io/managed-by: Helm helm.toolkit.fluxcd.io/name: azure-service-mesh-istio-discovery-helmrelease helm.toolkit.fluxcd.io/namespace: 64523969922c4900013c0af0 install.operator.istio.io/owning-resource: unknown istio.io/rev: asm-1-17 operator.istio.io/component: Pilot release: azure-service-mesh-istio-discovery name: istio-asm-1-17 namespace: aks-istio-system resourceVersion: "57453" uid: 1481ce3d-e8c6-4ff9-90ba-dd2371691ef5 apiVersion: v1 data: mesh: |- # Add the following contents: extensionProviders: - name: "opa.opasvc" envoyExtAuthzGrpc: service: "opa.opasvc.svc.cluster.local" port: "9191" kubectl apply -f - <<EOF apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: httpbin-opa namespace: opasvc spec: selector: matchLabels: app: httpbin action: CUSTOM provider: name: "opa.opasvc" rules: - to: - operation: notPaths: ["/ip"] EOF ``` test the policy ``` kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.17/samples/sleep/sleep.yaml export SLEEP_POD=$(kubectl get pod -l app=sleep -o jsonpath={.items..metadata.name}) export TOKEN_PATH_HEADERS="<KEY> kubectl exec ${SLEEP_POD} -c sleep -- curl http://httpbin-with-opa:8000/headers -s -o /dev/null -w "%{http_code}\n" ```<file_sep># Ambassador https://www.getambassador.io/user-guide/helm/ ``` helm repo add datawire https://www.getambassador.io IP= IP_NAME=ambassador-ingress-pip AMB_NS=ambassador AMB_IN=ambassador-ingress DNS=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query dnsSettings.fqdn --output tsv) IP=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query ipAddress --output tsv) helm upgrade --install $AMB_IN datawire/ambassador --namespace $AMB_NS export SERVICE_IP=$(kubectl get svc --namespace default ambassador -o jsonpath='{.status.loadBalancer.ingress[0].ip}') helm upgrade --install $AMB_IN stable/ambassador --set service.loadBalancerIP=$IP --set service.externalTrafficPolicy=Local --set crds.create=false --namespace $AMB_NS helm upgrade --install $AMB_IN stable/ambassador --set service.externalTrafficPolicy=Local --set crds.create=false --namespace $AMB_NS helm delete $AMB_IN --purge ``` admin ``` export POD_NAME=$(kubectl get pods --namespace $AMB_NS -l "app.kubernetes.io/name=ambassador,app.kubernetes.io/instance=$AMB_IN" -o jsonpath="{.items[0].metadata.name}") kubectl set env deploy -n kong konga NODE_TLS_REJECT_UNAUTHORIZED=0 kubectl port-forward $POD_NAME --namespace $AMB_NS 8080:8877 http://localhost:8080/ambassador/v0/diag/ kubectl apply -f https://getambassador.io/yaml/tour/tour.yaml ``` ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: name: ambassador spec: type: LoadBalancer externalTrafficPolicy: Local ports: - port: 80 selector: service: ambassador EOF ``` ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: name: httpbin annotations: getambassador.io/config: | --- apiVersion: ambassador/v1 kind: Mapping name: httpbin_mapping prefix: /httpbin/ service: httpbin.org:80 host_rewrite: httpbin.org spec: ports: - name: httpbin port: 80 EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: name: dummy-logger annotations: getambassador.io/config: | --- apiVersion: ambassador/v1 kind: Mapping name: dummylogger_mapping prefix: /dummy-logger/ service: dummy-logger spec: ports: - port: 80 targetPort: 80 name: http selector: app: dummy-logger type: ClusterIP EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: annotations: getambassador.io/config: | --- apiVersion: ambassador/v0 kind: Mapping name: httpbin_mapping prefix: /httpbin/ service: httpbin.org:80 host_rewrite: httpbin.org name: httpbin spec: ports: - name: httpbin port: 80 EOF ``` SERVICE_IP=172.16.17.32 export SERVICE_IP=$(kubectl get svc --namespace default ambassador -o jsonpath='{.status.loadBalancer.ingress[0].ip}') curl $SERVICE_IP/httpbin/ip ## Oathkeeper oathkeeper alias oathkeeper='/Users/dennis/lib/oathkeeper/oathkeeper' openssl rand -hex 16 e1ad13cecb1c9b5f436b09264efdb82e3950f4e4e7429e3a11d5996fb4ed7dab CREDENTIALS_ISSUER_ID_TOKEN_HS256_SECRET=101bdaa8ceae00490b86330a2498103d kubectl create secret generic ory-oathkeeper --from-literal=CREDENTIALS_ISSUER_ID_TOKEN_HS256_SECRET=101bdaa8ceae00490b86330a2498103d kubectl apply -f https://raw.githubusercontent.com/ory/k8s/master/yaml/oathkeeper/simple/oathkeeper-api.yaml cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: name: ory-oathkeeper annotations: getambassador.io/config: | --- apiVersion: ambassador/v1 kind: Mapping name: ory-oathkeeper_mapping prefix: /ory-oathkeeper/ service: ory-oathkeeper spec: ports: - name: http-ory-oathkeeper port: 80 targetPort: http-api selector: app: ory-oathkeeper type: ClusterIP EOF curl http://$SERVICE_IP/httpbin/health/alive curl http://$SERVICE_IP/ory-oathkeeper/health/alive curl http://$SERVICE_IP/dummy-logger/ping oathkeeper rules --endpoint http://$SERVICE_IP/ory-oathkeeper list cat <<EOT > access-rule-oathkeeper.json [{ "id": "oathkeeper-access-rule", "match": { "url": "http://$SERVICE_IP/ory-oathkeeper/<.*>", "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"] }, "authenticators": [{ "handler": "anonymous" }], "authorizer": { "handler": "allow" }, "credentials_issuer": { "handler": "noop" } }] EOT ## Quota cat <<EOF | kubectl apply -f - --- apiVersion: v1 kind: Service metadata: name: quote namespace: ambassador spec: ports: - name: http port: 80 targetPort: 8080 selector: app: quote --- apiVersion: apps/v1 kind: Deployment metadata: name: quote namespace: ambassador spec: replicas: 1 selector: matchLabels: app: quote strategy: type: RollingUpdate template: metadata: labels: app: quote spec: containers: - name: backend image: docker.io/datawire/quote:0.4.1 ports: - name: http containerPort: 8080 EOF cat <<EOF | kubectl apply -f - --- apiVersion: getambassador.io/v2 kind: Mapping metadata: name: quote-backend namespace: ambassador spec: prefix: /backend/ service: quote EOF curl -Lk https://${AMBASSADOR_LB_ENDPOINT}/backend/ { "server": "idle-cranberry-8tbb6iks", "quote": "Non-locality is the driver of truth. By summoning, we vibrate.", "time": "2019-12-11T20:10:16.525471212Z" }<file_sep># Limit administrative access https://github.com/kubernetes/dashboard/wiki/Creating-sample-user create user ``` cat <<EOF | kubectl create -f - apiVersion: v1 kind: ServiceAccount metadata: name: metrics-user namespace: kube-system EOF cat <<EOF | kubectl create -f - apiVersion: v1 kind: ServiceAccount metadata: name: dennis namespace: kube-system EOF ``` create cluster role binding ``` cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: admin-user roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: admin subjects: - kind: ServiceAccount name: admin-user namespace: kube-system EOF cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: admin-user roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: admin subjects: - kind: ServiceAccount name: metrics-user namespace: kube-system EOF cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: dennis-nodes-get rules: - apiGroups: [""] resources: ["nodes"] verbs: ["get", "list"] EOF cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: dennis roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: dennis-nodes-get subjects: - kind: ServiceAccount name: dennis namespace: kube-system EOF ``` after 1.8 ``` cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: my-dashboard-sa roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - kind: ServiceAccount name: my-dashboard-sa namespace: kube-system EOF cat <<EOF | kubectl create -f - apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: dennis-binding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - kind: ServiceAccount name: dennis namespace: kube-system EOF ``` create bearer token ``` kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep edit-user | awk '{print $1}') kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep dennis | awk '{print $1}') kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep my-dashboard-sa | awk '{print $1}') ``` Set kubectl context ``` KUBE_MANAGEMENT_ENDPOINT=https://**.azmk8s.io:443 TOKEN= kubectl config set-cluster dennis-user --server=$KUBE_MANAGEMENT_ENDPOINT --insecure-skip-tls-verify=true kubectl config set-credentials dennis --token=$TOKEN kubectl config set-context dennis-context --cluster=dennis-user --user=dennis kubectl config use-context dennis-context AzureDiagnostics | where Category == "kube-apiserver" | project log_s AzureDiagnostics | where Category == "kube-controller-manager" | project log_s AzureDiagnostics | where Category == "kube-scheduler" | project log_s AzureDiagnostics | where Category == "kube-audit" | project log_s AzureDiagnostics | where Category == "guard" | project log_s AzureDiagnostics | where Category == "cluster-autoscaler" | project log_s ``` ## Lock down api server https://github.com/Azure/azure-cli-extensions/tree/master/src/aks-preview#enable-apiserver-authorized-ip-ranges MYIP=$(curl ipinfo.io/ip) KUBE_GROUP="kubvmss" KUBE_NAME="dzkubvmss" az aks update -g $KUBE_GROUP -n $KUBE_NAME --api-server-authorized-ip-ranges "$MYIP" az aks list -g $KUBE_GROUP -n $KUBE_NAME ## Minimum roles https://docs.microsoft.com/en-us/azure/role-based-access-control/built-in-roles ``` First-party SPN Permissions The following permissions are required by the AKS 1st party SPN; The AKS 1st party SPN performs a linked access check on the Cluster creator's role permissions. These permissions are required for CRUD operations on the cluster. The following permissions are required: // Required to configure NSG for the subnet when using custom VNET // AKS property: properties.agentPoolProfiles[*].vnetSubnetID "Microsoft.Network/virtualNetworks/subnets/join/action" // Required to allow create, update Log Analytics workspaces and Azure monitoring for Containers // AKS property: properties.addonProfiles.omsagent.config.logAnalyticsWorkspaceResourceID "Microsoft.OperationalInsights/workspaces/sharedkeys/read" "Microsoft.OperationalInsights/workspaces/read" "Microsoft.OperationsManagement/solutions/write" "Microsoft.OperationsManagement/solutions/read" // Required to configure SLB outbound public IPs // AKS property: properties.networkProfile.loadBalancerProfile.outboundIPs.publicIPs[].ID // properties.networkProfile.loadBalancerProfile.outboundIPPrefixes.publicIPPrefixes[].ID "Microsoft.Network/publicIPAddresses/join/action" "Microsoft.Network/publicIPPrefixes/join/action" User Permissions What permissions does a User need to have in order to deploy or perform CRUD operations to AKS. These should be the linked access check permissions cross-checked from the 1st party RP SPN. See the detailed permissions required in the above section. AKS SPN Permissions Validate what permissions are required to be given to the AKS Service Principal (used by Kubernetes cloud provider, volume drivers as well as addons). Required permissions for AKS SPN // Required to create, delete or update LoadBalancer for LoadBalancer service Microsoft.Network/loadBalancers/delete Microsoft.Network/loadBalancers/read Microsoft.Network/loadBalancers/write // Required to allow query, create or delete public IPs for LoadBalancer service Microsoft.Network/publicIPAddresses/delete Microsoft.Network/publicIPAddresses/read Microsoft.Network/publicIPAddresses/write // Required if public IPs from another resource group are used for LoadBalancer service // This is because of the linked access check when adding the public IP to LB frontendIPConfiguration Microsoft.Network/publicIPAddresses/join/action // Required to create or delete security rules for LoadBalancer service Microsoft.Network/networkSecurityGroups/read Microsoft.Network/networkSecurityGroups/write // Required to create, delete or update AzureDisks Microsoft.Compute/disks/delete Microsoft.Compute/disks/read Microsoft.Compute/disks/write Microsoft.Compute/locations/DiskOperations/read // Required to create, update or delete storage accounts for AzureFile or AzureDisk Microsoft.Storage/storageAccounts/delete Microsoft.Storage/storageAccounts/listKeys/action Microsoft.Storage/storageAccounts/read Microsoft.Storage/storageAccounts/write Microsoft.Storage/operations/read // Required to create, delete or update routeTables and routes for nodes Microsoft.Network/routeTables/read Microsoft.Network/routeTables/routes/delete Microsoft.Network/routeTables/routes/read Microsoft.Network/routeTables/routes/write Microsoft.Network/routeTables/write // Required to query information for VM (e.g. zones, faultdomain, size and data disks) Microsoft.Compute/virtualMachines/read // Required to attach AzureDisks to VM Microsoft.Compute/virtualMachines/write // Required to query information for vmssVM (e.g. zones, faultdomain, size and data disks) Microsoft.Compute/virtualMachineScaleSets/read Microsoft.Compute/virtualMachineScaleSets/virtualMachines/read Microsoft.Compute/virtualMachineScaleSets/virtualmachines/instanceView/read // Requred to add VM to LoadBalancer backendAddressPools Microsoft.Network/networkInterfaces/write // Required to add vmss to LoadBalancer backendAddressPools Microsoft.Compute/virtualMachineScaleSets/write // Required to attach AzureDisks and add vmssVM to LB Microsoft.Compute/virtualMachineScaleSets/virtualmachines/write // Required to upgrade VMSS models to latest for all instances // only needed for Kubernetes 1.11.0-1.11.9, 1.12.0-1.12.8, 1.13.0-1.13.5, 1.14.0-1.14.1 Microsoft.Compute/virtualMachineScaleSets/manualupgrade/action // Required to query internal IPs and loadBalancerBackendAddressPools for VM Microsoft.Network/networkInterfaces/read // Required to query internal IPs and loadBalancerBackendAddressPools for vmssVM microsoft.Compute/virtualMachineScaleSets/virtualMachines/networkInterfaces/read // Required to get public IPs for vmssVM Microsoft.Compute/virtualMachineScaleSets/virtualMachines/networkInterfaces/ipconfigurations/publicipaddresses/read // Required to check whether subnet existing for ILB in another resource group Microsoft.Network/virtualNetworks/read Microsoft.Network/virtualNetworks/subnets/read // Required to create, update or delete snapshots for AzureDisk Microsoft.Compute/snapshots/delete Microsoft.Compute/snapshots/read Microsoft.Compute/snapshots/write // Required to get vm sizes for getting AzureDisk volume limit Microsoft.Compute/locations/vmSizes/read Microsoft.Compute/locations/operations/read Permissions users "might" need When using container insights, the following permissions are required // Required to allow create, update Log Analytics workspaces and Azure monitoring for Containers. // Refer https://docs.microsoft.com/en-us/azure/azure-monitor/insights/container-insights-update-metrics#upgrade-per-cluster-using-azure-cli. "Monitoring Metrics Publisher" or Microsoft.Insights/Metrics/Write When using public IP addresses in another resource group, // Required to allow query or create public IPs for LoadBalancer service Microsoft.Network/publicIPAddresses/read Microsoft.Network/publicIPAddresses/write Microsoft.Network/publicIPAddresses/join/action When using NSG in another resource group, // Required to create or delete security rules for LoadBalancer service Microsoft.Network/networkSecurityGroups/read Microsoft.Network/networkSecurityGroups/write When using subnet in another resource group (e.g. custom VNET), // Required to check whether subnet existing for subnet in another resource group Microsoft.Network/virtualNetworks/subnets/read Microsoft.Network/virtualNetworks/subnets/join/action When using ILB for another resource group, // Required to check whether subnet existing for ILB in another resource group Microsoft.Network/virtualNetworks/subnets/read ``` ## Use dashboard with azure ad https://gist.github.com/digeler/0dbc40141c9ee8a41b42e808a2859f14 turn on the dashboard ``` az aks enable-addons --addons kube-dashboard -g $KUBE_GROUP -n $KUBE_NAME ``` turn off the dashboard ``` az aks disable-addons --addons kube-dashboard -g $KUBE_GROUP -n $KUBE_NAME ``` edit the deployment of the dashboard ``` kubectl edit deployments kubernetes-dashboard -n kube-system ``` containers: - name: kubernetes-dashboard args: - --authentication-mode=token - --enable-insecure-login ## Create SSH Box ``` kubectl run -it aks-ssh --image=debian apt-get update && apt-get install openssh-client -y kubectl cp ~/.ssh/id_rsa $(kubectl get pod -l run=aks-ssh -o jsonpath='{.items[0].metadata.name}'):/id_rsa chmod 400 ~/.ssh/id_rsa ssh -i id_rsa dennis@10.0.5.4 sudo add-apt-repository ppa:wireshark-dev/stable sudo apt-get update sudo apt-get install wireshark sudo apt install tshark sudo dpkg-reconfigure wireshark-common sudo usermod -a -G wireshark dennis tshark -Q -i2 -O http -T json tcp port 7001 | grep http.file_data ``` ## Auditing ``` {"kind":"Event","apiVersion":"audit.k8s.io/v1","level":"Request","auditID":"130ba120-d9b1-4b35-9e91-3366568bfd8d","stage":"ResponseComplete","requestURI":"/api/v1/namespaces/default/pods/nginx","verb":"get","user":{"username":"masterclient","groups":["system:masters","system:authenticated"]},"sourceIPs":["172.16.31.10"],"userAgent":"kubectl/v1.14.0 (linux/amd64) kubernetes/641856d","objectRef":{"resource":"pods","namespace":"default","name":"nginx","apiVersion":"v1"},"responseStatus":{"metadata":{},"status":"Failure","reason":"NotFound","code":404},"requestReceivedTimestamp":"2019-09-20T11:52:19.062985Z","stageTimestamp":"2019-09-20T11:52:19.068391Z","annotations":{"authorization.k8s.io/decision":"allow","authorization.k8s.io/reason":""}} {"kind":"Event","apiVersion":"audit.k8s.io/v1","level":"Request","auditID":"e13ca54f-9b7a-4a47-abb4-930d0b518c49","stage":"ResponseComplete","requestURI":"/api/v1/namespaces/default/pods/nginx/status","verb":"patch","user":{"username":"nodeclient","groups":["system:nodes","system:authenticated"]},"sourceIPs":["192.168.3.11"],"userAgent":"kubelet/v1.14.5 (linux/amd64) kubernetes/0e9fcb4","objectRef":{"resource":"pods","namespace":"default","name":"nginx","apiVersion":"v1","subresource":"status"},"responseStatus":{"metadata":{},"code":200},"requestObject":{"status":{"$setElementOrder/conditions":[{"type":"Initialized"},{"type":"Ready"},{"type":"ContainersReady"},{"type":"PodScheduled"}],"conditions":[{"lastTransitionTime":"2019-09-20T12:56:55Z","message":null,"reason":null,"status":"True","type":"Ready"},{"lastTransitionTime":"2019-09-20T12:56:55Z","message":null,"reason":null,"status":"True","type":"ContainersReady"}],"containerStatuses":[{"containerID":"docker://e4d6babb34b671237490bbf384326c142281bcabe0c74416ea63088146ed1500","image":"nginx:1.15.5","imageID":"docker-pullable://nginx@sha256:b73f527d86e3461fd652f62cf47e7b375196063bbbd503e853af5be16597cb2e","lastState":{},"name":"mypod","ready":true,"restartCount":0,"state":{"running":{"startedAt":"2019-09-20T12:56:55Z"}}}],"phase":"Running","podIP":"10.244.4.11"}},"requestReceivedTimestamp":"2019-09-20T12:56:55.895345Z","stageTimestamp":"2019-09-20T12:56:55.910588Z","annotations":{"authorization.k8s.io/decision":"allow","authorization.k8s.io/reason":"RBAC: allowed by ClusterRoleBinding \"system:aks-client-nodes\" of ClusterRole \"system:node\" to Group \"system:nodes\""}} ``` ## Kubernetes API create service account ``` kubectl create serviceaccount centos cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Namespace metadata: name: demo --- apiVersion: v1 kind: ServiceAccount metadata: name: centos namespace: demo --- apiVersion: v1 kind: Pod metadata: name: centos namespace: demo spec: serviceAccountName: centos containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF ``` ``` kubectl exec -ti centos -n demo -- /bin/bash cat /var/run/secrets/kubernetes.io/serviceaccount/token KUBE_TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) echo $KUBERNETES_SERVICE_HOST 10.96.0.1 echo $KUBERNETES_PORT_443_TCP_PORT 443 echo $HOSTNAME centos curl -sSk -H "Authorization: Bearer $KUBE_TOKEN" https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/demo/pods curl -H "Authorization: Bearer $KUBE_TOKEN" https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1 --insecure curl -H "Authorization: Bearer $KUBE_TOKEN" https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/nodes --insecure kubectl create clusterrolebinding demo-admin --clusterrole cluster-admin --serviceaccount=demo:centos ``` create service account role binding ``` cat <<EOF | kubectl apply -f - kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: pods-list rules: - apiGroups: [""] resources: ["pods"] verbs: ["list"] --- kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: pods-list subjects: - kind: ServiceAccount name: centos namespace: demo roleRef: kind: ClusterRole name: pods-list apiGroup: rbac.authorization.k8s.io EOF ``` cleanup ``` kubectl delete ClusterRoleBinding pods-list kubectl delete ClusterRole pods-list kubectl delete pod centos -n demo kubectl delete serviceaccount centos -n demo kubectl delete ns demo ``` # Security Center List of AKS features for Security Center: https://docs.microsoft.com/en-gb/azure/security-center/security-center-alerts-compute#aks-cluster-level-alerts ``` SUBSCRIPTION_ID= open https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/providers/Microsoft.Security/assessmentMetadata?api-version=2019-01-01-preview ``` # Create service account ``` KUBE_GROUP="dzprivate1" KUBE_NAME="dzprivate1" kubectl create serviceaccount jump-account --namespace kube-system kubectl create clusterrolebinding jump-account-binding --clusterrole=cluster-admin --serviceaccount=kube-system:jump-account --namespace kube-system kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep jump-account | awk '{print $1}') KUBE_MANAGEMENT_ENDPOINT=https://**.azmk8s.io:443 TOKEN= kubectl config set-cluster dennis-user --server=$KUBE_MANAGEMENT_ENDPOINT --insecure-skip-tls-verify=true kubectl config set-credentials dennis --token=$TOKEN kubectl config set-context dennis-context --cluster=dennis-user --user=dennis kubectl config use-context dennis-context az aks command invoke --resource-group $KUBE_GROUP --name $KUBE_NAME --command "kubectl get pods -n kube-system" ```<file_sep># Gatekeeper V2 https://docs.microsoft.com/en-us/azure/governance/policy/concepts/rego-for-aks https://docs.microsoft.com/en-us/azure/governance/policy/concepts/effects#enforceopaconstraint https://docs.microsoft.com/en-us/azure/aks/use-azure-policy#create-and-assign-a-custom-policy-definition-preview AKS-Engine https://github.com/Azure/azure-policy/tree/master/extensions/policy-addon-kubernetes/helm-charts/azure-policy-addon-aks-engine Config https://raw.githubusercontent.com/Azure/azure-policy/master/built-in-references/Kubernetes/gatekeeper-opa-sync.yaml Gatekeeper deploy https://github.com/open-policy-agent/gatekeeper/blob/master/deploy/gatekeeper.yaml https://github.com/open-policy-agent/gatekeeper#replicating-data PSP Library: https://github.com/open-policy-agent/gatekeeper/tree/master/library ## AKS az aks enable-addons --addons azure-policy --name $KUBE_NAME --resource-group $KUBE_GROUP az aks disable-addons --addons azure-policy --name $KUBE_NAME --resource-group $KUBE_GROUP az aks list --query '[].{Name:name, ClientId:servicePrincipalProfile.clientId}' -o table # AKS Engine https://docs.microsoft.com/en-gb/azure/governance/policy/concepts/aks-engine SERVICE_PRINCIPAL_ID=$(az aks show --name $KUBE_NAME --resource-group $KUBE_GROUP --query servicePrincipalProfile -o tsv) SUBSCRIPTION_ID=$(az account show --query id -o tsv) az role assignment create --assignee $SERVICE_PRINCIPAL_ID --scope "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP" --role "Policy Insights Data Writer (Preview)" deploy gatekeeper kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml kubectl label namespaces kube-system control-plane=controller-manager kubectl apply -f https://raw.githubusercontent.com/Azure/azure-policy/master/built-in-references/Kubernetes/gatekeeper-opa-sync.yaml helm github: https://github.com/Azure/azure-policy/tree/master/extensions/policy-addon-kubernetes helm repo add azure-policy https://raw.githubusercontent.com/Azure/azure-policy/master/extensions/policy-addon-kubernetes/helm-charts helm repo update helm upgrade azure-policy-addon azure-policy/azure-policy-addon-aks-engine --namespace=kube-system --install --set azurepolicy.env.resourceid="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP" cleanup policy addon kubectl delete serviceaccount azure-policy -n kube-system kubectl delete clusterrole policy-agent azure policy logs kubectl logs $(kubectl -n kube-system get pods -l app=azure-policy --output=name) -n kube-system gatekeeper logs kubectl logs $(kubectl -n gatekeeper-system get pods -l gatekeeper.sh/system=yes --output=name) -n gatekeeper-system delete gatekeeper kubectl delete -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml helm delete azure-policy-addon --namespace=kube-system kubectl delete serviceaccount azure-policy -n kube-system kubectl delete serviceaccount azure-policy-webhook-account -n kube-system kubectl delete role policy-pod-agent -n kube-system kubectl delete rolebinding policy-pod-agent -n kube-system kubectl delete clusterrole policy-agent kubectl delete clusterrole gatekeeper-manager-role kubectl delete ClusterRoleBinding policy-agent kubectl delete ClusterRoleBinding gatekeeper-manager-rolebinding kubectl delete ns gatekeeper-system kubectl delete crd \ configs.config.gatekeeper.sh \ constraintpodstatuses.status.gatekeeper.sh \ constrainttemplatepodstatuses.status.gatekeeper.sh \ constrainttemplates.templates.gatekeeper.sh SUBSCRIPTION_ID=$(az account show --query id -o tsv) helm install azure-policy-addon azure-policy/azure-policy-addon-aks-engine --set azurepolicy.env.resourceid="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP" helm delete azure-policy-addon kubectl apply -f built-in-references/Kubernetes/container-require-livenessProbe/template.yaml kubectl apply -f built-in-references/Kubernetes/container-require-livenessProbe/constraint.yaml # yaml kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/release-3.1/deploy/gatekeeper.yaml kubectl delete -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml # helm open source kubectl create ns gatekeeper-system helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts helm repo update helm upgrade gatekeeper gatekeeper/gatekeeper -n gatekeeper-system --install # custom policy kubectl logs -l control-plane=controller-manager -n gatekeeper-system kubectl apply -f built-in-references/Kubernetes/container-require-livenessProbe/template.yaml kubectl apply -f built-in-references/Kubernetes/container-require-livenessProbe/constraint.yaml cat <<EOF | kubectl apply -f - apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredProbes metadata: name: must-have-probes spec: match: kinds: - apiGroups: [""] kinds: ["Pod"] excludedNamespaces: - kube-system - gatekeeper-system parameters: probes: ["readinessProbe", "livenessProbe"] probeTypes: ["tcpSocket", "httpGet", "exec"] EOF # policy addon policy evaluation every 15 minutes ``` az aks show --query addonProfiles.azurepolicy -g $KUBE_GROUP -n $KUBE_NAME ``` kubectl get constrainttemplates.templates.gatekeeper.sh kubectl get constrainttemplates.templates.gatekeeper.sh k8sazureloadbalancernopublicips -o yaml https://store.policy.core.windows.net/kubernetes/load-balancer-no-public-ips/v1/template.yaml kubectl get constrainttemplates.templates.gatekeeper.sh k8sazurecontainerallowedimages -o yaml https://store.policy.core.windows.net/kubernetes/container-allowed-images/v1/template.yaml kubectl create namespace special kubectl label namespace special admission.policy.azure.com/ignore=true kubectl label namespace special control-plane=true kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-lb-logger.yaml -n special cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos namespace: special spec: containers: - name: centos image: centos securityContext: privileged: true ports: - containerPort: 80 command: - sleep - "3600" EOF kubectl create namespace ordinary kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-lb-logger.yaml -n ordinary cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos namespace: ordinary spec: containers: - name: centos image: centos securityContext: privileged: true ports: - containerPort: 80 command: - sleep - "3600" EOF kubectl get k8sazurecontainerallowedimages.constraints.gatekeeper.sh -o yaml labels will not deny violations, compliance still available kubectl label namespace control-plane admission.policy.azure.com/ignore see violations kubectl get k8sazurecontainernoprivilege.constraints.gatekeeper.sh -o yaml kubectl describe deployment dummy-logger kubectl describe replicasets.apps dummy-logger ```<file_sep>package org.acme.rest.client; import java.util.List; public class CalculationRequest { public String number; public Boolean randomvictim; }<file_sep>Public Release Notes: https://aka.ms/aks/releasenotes Public Roadmap: http://aka.ms/aks/roadmap Public Previews: https://aka.ms/aks/previewfeatures AKS Release: https://github.com/Azure/AKS/releases https://github.com/Azure/AKS/blob/master/CHANGELOG.md AKS VHD Release Page: https://github.com/Azure/aks-engine/tree/master/vhd/release-notes/aks-ubuntu-1604 Packer script: https://github.com/Azure/aks-engine/blob/master/packer/install-dependencies.sh https://relnotes.k8s.io/ See all aks vhd version ``` az vm image list --publisher microsoft-aks --all -o table ``` AKS CIS Status: https://github.com/Azure/aks-engine/projects/7 Kubernetes azure cloud provider: https://github.com/Azure/container-compute-upstream/projects/1#card-18238708 ACR Roadmap: https://github.com/Azure/acr/blob/master/docs/acr-roadmap.md https://github.com/Azure/acr/projects/1 AKS-Engine Backlog: https://github.com/Azure/aks-engine/projects/2 Upstream backlog: https://github.com/Azure/container-compute-upstream/projects/1 OMS Docker Images: https://github.com/microsoft/OMS-Agent-for-Linux AKS ARM Template: https://docs.microsoft.com/en-us/azure/templates/microsoft.containerservice/2019-02-01/managedclusters https://review.docs.microsoft.com/en-us/azure/templates/microsoft.containerservice/2022-03-02-preview/managedclusters?branch=main&tabs=bicep Review docs: https://github.com/MicrosoftDocs/azure-docs/tree/master/articles/aks https://review.docs.microsoft.com/en-us/azure/aks/?branch=pr-en-us-67074 https://review.docs.microsoft.com/en-us/azure/templates/microsoft.containerservice/2019-02-01/managedclusters?branch=master Preview cli: https://github.com/Azure/azure-cli-extensions/tree/master/src/ https://github.com/Azure/azure-cli-extensions/tree/master/src/aks-preview Preview commands: https://github.com/Azure/azure-cli-extensions/blob/master/src/aks-preview/azext_aks_preview/_help.py Preview CLI release history: https://github.com/Azure/azure-cli-extensions/blob/master/src/aks-preview/HISTORY.md Azure Load Balancer annotations: https://kubernetes-sigs.github.io/cloud-provider-azure/topics/loadbalancer/ Azure troubleshooting: https://github.com/feiskyer/kubernetes-handbook/blob/master/en/troubleshooting/azure.md Azure Disk driver: https://github.com/kubernetes/examples/blob/master/staging/volumes/azure_disk/README.md https://github.com/kubernetes-sigs/azuredisk-csi-driver/blob/master/docs/driver-parameters.md - Azure Dev Spaces -> GA https://azure.microsoft.com/en-us/blog/introducing-dev-spaces-for-aks/ - AKS Authenticated IP for AKS API Server -> Public Preview https://docs.microsoft.com/en-us/azure/aks/api-server-authorized-ip-ranges - AKS Azure Monitor BUILD updates https://azure.microsoft.com/en-us/blog/what-s-new-in-azure-monitor/ - AKS Azure Policy for AKS -> Public Preview https://docs.microsoft.com/en-gb/azure/governance/policy/overview - AKS Functions | KEDA - Kubernetes-based Event-Driven Autoscaling https://github.com/kedacore/keda - AKS Network policy for AKS pods -> GA https://docs.microsoft.com/en-us/azure/aks/use-network-policies - AKS Node Pools + Zones -> Public Preview https://docs.microsoft.com/en-us/azure/aks/use-multiple-node-pools - AKS Autoscaler -> Public Preview https://docs.microsoft.com/en-us/azure/aks/cluster-autoscaler - AKS Pod Security Policies -> Public Preview https://docs.microsoft.com/en-us/azure/aks/use-pod-security-policies - AKS Virtual Nodes -> GA https://docs.microsoft.com/en-us/azure/aks/virtual-nodes-cli - Container Registry | Public Preview - HELM https://azure.microsoft.com/en-us/updates/azure-container-registry-helm-repositories-public-preview/ - Container Registry | Service Endpoints Public Preview https://docs.microsoft.com/en-us/azure/container-registry/container-registry-vnet Keda scaler: https://github.com/kedacore/keda/wiki/Scaler-prioritization Spring cloud: https://github.com/Azure/azure-managed-service-for-spring-cloud-docs ## Addons extras Getting a public ip per node: Using a function : https://github.com/dgkanatsios/AksNodePublicIP Using a daemonset :https://github.com/dgkanatsios/AksNodePublicIPController # Best practices https://learnk8s.io/production-best-practices/ # Dapr https://aka.ms/smartinsights. Grafana: https://github.com/RicardoNiepel/dapr-docs/blob/master/howto/setup-monitoring-tools/setup-prometheus-grafana.md Dapr VSCode: https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-dapr <file_sep>#https://github.com/Azure/application-gateway-kubernetes-ingress/issues/939 #https://github.com/Azure/application-gateway-kubernetes-ingress/issues?page=2&q=is%3Aissue+is%3Aopen #https://github.com/Azure/application-gateway-kubernetes-ingress SUBSCRIPTION_ID=$(az account show --query id -o tsv) #subscriptionid LOCATION="westeurope" # here enter the datacenter location VNET_GROUP="vnets" # here enter the network resource group name HUB_VNET_NAME="hubnet1" # here enter the name of your hub net KUBE_VNET_NAME="k8snet1" # here enter the name of your k8s vnet PREM_VNET_NAME="onpremnet1" # here enter the name of your onprem vnet FW_NAME="dzk8sfw1" # name of your azure firewall resource APPGW_NAME="dzk8sappgw1" APPGW_GROUP="secureappgw1" # here enter the appgw resource group name APPGW_SUBNET_NAME="gw-1-subnet" # name of AppGW subnet KUBE_AGENT_SUBNET_NAME="aks-1-subnet" # name of your AKS subnet KUBE_AGENT2_SUBNET_NAME="aks-2-subnet" # name of your AKS subnet KUBE_GROUP="securek8s1" # here enter the resources group name KUBE_NAME="secureaks1" # here enter the name of your aks resource KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" # here enter the kubernetes version of your AKS KUBE_CNI_PLUGIN="azure" # alternative is "kubenet" #KUBE_CNI_PLUGIN="kubenet" az account set --subscription $SUBSCRIPTION_ID echo "setting up vnet" az group create -n $KUBE_GROUP -l $LOCATION az group create -n $VNET_GROUP -l $LOCATION az group create -n $APPGW_GROUP -l $LOCATION az network vnet create -g $VNET_GROUP -n $HUB_VNET_NAME --address-prefixes 10.0.0.0/22 az network vnet create -g $VNET_GROUP -n $KUBE_VNET_NAME --address-prefixes 10.0.4.0/24 172.16.0.0/18 az network vnet create -g $VNET_GROUP -n $PREM_VNET_NAME --address-prefixes 172.16.17.32/8 az network vnet subnet create -g $VNET_GROUP --vnet-name $HUB_VNET_NAME -n AzureFirewallSubnet --address-prefix 10.0.0.0/24 az network vnet subnet create -g $VNET_GROUP --vnet-name $HUB_VNET_NAME -n $APPGW_SUBNET_NAME --address-prefix 10.0.1.0/24 az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $APPGW_SUBNET_NAME --address-prefix 10.0.4.0/24 az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 172.16.0.0/22 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT2_SUBNET_NAME --address-prefix 172.16.4.0/22 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage az network vnet subnet create -g $VNET_GROUP --vnet-name $PREM_VNET_NAME -n premnet --address-prefix 172.16.17.32/8 az network vnet peering create -g $VNET_GROUP -n HubToSpoke1 --vnet-name $HUB_VNET_NAME --remote-vnet $KUBE_VNET_NAME --allow-vnet-access az network vnet peering create -g $VNET_GROUP -n Spoke1ToHub --vnet-name $KUBE_VNET_NAME --remote-vnet $HUB_VNET_NAME --allow-vnet-access az network vnet peering create -g $VNET_GROUP -n HubToPrem --vnet-name $HUB_VNET_NAME --remote-vnet $PREM_VNET_NAME --allow-vnet-access az network vnet peering create -g $VNET_GROUP -n PremToHub --vnet-name $PREM_VNET_NAME --remote-vnet $HUB_VNET_NAME --allow-vnet-access echo "setting up azure firewall" az extension add --name azure-firewall az network public-ip create -g $VNET_GROUP -n $FW_NAME-ip --sku Standard FW_PUBLIC_IP=$(az network public-ip show -g $VNET_GROUP -n $FW_NAME-ip --query ipAddress) az network firewall create --name $FW_NAME --resource-group $VNET_GROUP --location $LOCATION az network firewall ip-config create --firewall-name $FW_NAME --name $FW_NAME --public-ip-address $FW_NAME-ip --resource-group $VNET_GROUP --vnet-name $HUB_VNET_NAME FW_PRIVATE_IP=$(az network firewall show -g $VNET_GROUP -n $FW_NAME --query "ipConfigurations[0].privateIpAddress" -o tsv) az monitor log-analytics workspace create --resource-group $VNET_GROUP --workspace-name $FW_NAME-lagw1 --location $LOCATION echo "setting up user defined routes" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az network route-table create -g $VNET_GROUP --name $KUBE_NAME-rt az network route-table route create --resource-group $VNET_GROUP --name $FW_NAME --route-table-name $KUBE_NAME-rt --address-prefix 0.0.0.0/0 --next-hop-type VirtualAppliance --next-hop-ip-address $FW_PRIVATE_IP az network vnet subnet update --route-table $KUBE_NAME-rt --ids $KUBE_AGENT_SUBNET_ID az network route-table route list --resource-group $VNET_GROUP --route-table-name $KUBE_NAME-rt echo "setting up network rules" az network firewall network-rule create --firewall-name $FW_NAME --resource-group $VNET_GROUP --collection-name "time" --destination-addresses "*" --destination-ports 123 --name "allow network" --protocols "UDP" --source-addresses "*" --action "Allow" --description "aks node time sync rule" --priority 101 az network firewall network-rule create --firewall-name $FW_NAME --resource-group $VNET_GROUP --collection-name "dns" --destination-addresses "*" --destination-ports 53 --name "allow network" --protocols "Any" --source-addresses "*" --action "Allow" --description "aks node dns rule" --priority 102 az network firewall network-rule create --firewall-name $FW_NAME --resource-group $VNET_GROUP --collection-name "servicetags" --destination-addresses "AzureContainerRegistry" "MicrosoftContainerRegistry" "AzureActiveDirectory" "AzureMonitor" --destination-ports "*" --name "allow service tags" --protocols "Any" --source-addresses "*" --action "Allow" --description "allow service tags" --priority 110 az network firewall network-rule create --firewall-name $FW_NAME --resource-group $VNET_GROUP --collection-name "hcp" --destination-addresses "AzureCloud.$LOCATION" --destination-ports "1194" --name "allow master tags" --protocols "UDP" --source-addresses "*" --action "Allow" --description "allow aks link access to masters" --priority 120 echo "setting up application rules" az network firewall application-rule create --firewall-name $FW_NAME --resource-group $VNET_GROUP --collection-name 'aksfwar' -n 'fqdn' --source-addresses '*' --protocols 'http=80' 'https=443' --fqdn-tags "AzureKubernetesService" --action allow --priority 101 az network firewall application-rule create --firewall-name $FW_NAME --resource-group $VNET_GROUP --collection-name "osupdates" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --action "Allow" --target-fqdns "download.opensuse.org" "security.ubuntu.com" "packages.microsoft.com" "azure.archive.ubuntu.com" "changelogs.ubuntu.com" "snapcraft.io" "api.snapcraft.io" "motd.ubuntu.com" --priority 102 az network firewall application-rule create --firewall-name $FW_NAME --resource-group $VNET_GROUP --collection-name "dockerhub" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --action "Allow" --target-fqdns "*auth.docker.io" "*cloudflare.docker.io" "*cloudflare.docker.com" "*registry-1.docker.io" --priority 200 echo "setting up aks" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" KUBE_VNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME" if [ "$KUBE_CNI_PLUGIN" == "azure" ]; then az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-resource-group $KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION --node-count 2 --network-plugin $KUBE_CNI_PLUGIN --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --no-ssh-key --enable-managed-identity --outbound-type userDefinedRouting CONTROLLER_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identity.principalId -o tsv) az role assignment create --role "Virtual Machine Contributor" --assignee $CONTROLLER_ID --scope $KUBE_VNET_ID fi if [ "$KUBE_CNI_PLUGIN" == "kubenet" ]; then #az feature register --name UserAssignedIdentityPreview --namespace Microsoft.ContainerService #sleep 200 # this might take a while #az feature list -o table --query "[?contains(name, 'Microsoft.ContainerService/UserAssignedIdentityPreview')].{Name:name,State:properties.state}" #sleep 200 # this might take a while #az provider register --namespace Microsoft.ContainerService #az identity create --name $KUBE_NAME-id --resource-group $KUBE_GROUP #AKS_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query clientId -o tsv)" #AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-id --query id -o tsv)" SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET ROUTETABLE_ID=$(az network route-table show -g $VNET_GROUP --name $KUBE_NAME-rt --query id -o tsv) #az role assignment create --role "Contributor" --assignee $AKS_CLIENT_ID --scope $KUBE_VNET_ID az role assignment create --role "Virtual Machine Contributor" --assignee $SERVICE_PRINCIPAL_ID --scope $KUBE_VNET_ID az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID --scope $ROUTETABLE_ID az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-resource-group $KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION --node-count 2 --network-plugin $KUBE_CNI_PLUGIN --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --no-ssh-key --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --outbound-type userDefinedRouting fi az aks get-credentials -g $KUBE_GROUP -n $KUBE_NAME --overwrite-existing echo "setting up azure monitor" az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --location $LOCATION WORKSPACE_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME -o json | jq '.id' -r) az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons monitoring --workspace-resource-id $WORKSPACE_ID echo "creating appgw" APPGW_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$HUB_VNET_NAME/subnets/$APPGW_SUBNET_NAME" az network public-ip create --resource-group $APPGW_GROUP --name $APPGW_NAME-pip --allocation-method Static --sku Standard APPGW_PUBLIC_IP=$(az network public-ip show -g $APPGW_GROUP -n $APPGW_NAME-pip --query ipAddress -o tsv) az network application-gateway create --name $APPGW_NAME --resource-group $APPGW_GROUP --location $LOCATION --http2 Enabled --min-capacity 0 --max-capacity 10 --sku WAF_v2 --vnet-name $KUBE_VNET_NAME --subnet $APPGW_SUBNET_ID --http-settings-cookie-based-affinity Disabled --frontend-port 80 --http-settings-port 80 --http-settings-protocol Http --public-ip-address $APPGW_NAME-pip --private-ip-address "10.0.4.100" APPGW_NAME=$(az network application-gateway list --resource-group=$APPGW_GROUP -o json | jq -r ".[0].name") APPGW_RESOURCE_ID=$(az network application-gateway list --resource-group=$APPGW_GROUP -o json | jq -r ".[0].id") APPGW_SUBNET_ID=$(az network application-gateway list --resource-group=$APPGW_GROUP -o json | jq -r ".[0].gatewayIpConfigurations[0].subnet.id") az aks get-credentials -g $KUBE_GROUP -n $KUBE_NAME echo "install aa pod identity" if [ "$KUBE_CNI_PLUGIN" == "azure" ]; then KUBELET_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identityProfile.kubeletidentity.clientId -o tsv) CONTROLLER_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identity.principalId -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az role assignment create --role "Managed Identity Operator" --assignee $KUBELET_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Managed Identity Operator" --assignee $CONTROLLER_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Virtual Machine Contributor" --assignee $KUBELET_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Reader" --assignee $KUBELET_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$APPGW_GROUP fi helm repo add aad-pod-identity https://raw.githubusercontent.com/Azure/aad-pod-identity/master/charts helm repo update helm upgrade aad-pod-identity --install --namespace kube-system aad-pod-identity/aad-pod-identity #kubectl apply -f https://raw.githubusercontent.com/Azure/aad-pod-identity/v1.6.0/deploy/infra/deployment-rbac.yaml echo "install application gateway ingress controller" az identity create -g $NODE_GROUP -n $APPGW_NAME-id sleep 5 # wait for replication AGIC_ID_CLIENT_ID="$(az identity show -g $NODE_GROUP -n $APPGW_NAME-id --query clientId -o tsv)" AGIC_ID_RESOURCE_ID="$(az identity show -g $NODE_GROUP -n $APPGW_NAME-id --query id -o tsv)" NODES_RESOURCE_ID=$(az group show -n $NODE_GROUP -o tsv --query "id") KUBE_GROUP_RESOURCE_ID=$(az group show -n $KUBE_GROUP -o tsv --query "id") sleep 15 # wait for replication echo "assigning permissions for AGIC client $AGIC_ID_CLIENT_ID" az role assignment create --role "Contributor" --assignee $AGIC_ID_CLIENT_ID --scope $APPGW_RESOURCE_ID az role assignment create --role "Reader" --assignee $AGIC_ID_CLIENT_ID --scope $KUBE_GROUP_RESOURCE_ID # might not be needed az role assignment create --role "Reader" --assignee $AGIC_ID_CLIENT_ID --scope $NODES_RESOURCE_ID # might not be needed az role assignment create --role "Reader" --assignee $AGIC_ID_CLIENT_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$APPGW_GROUP helm repo add application-gateway-kubernetes-ingress https://appgwingress.blob.core.windows.net/ingress-azure-helm-package/ helm repo update helm pull application-gateway-kubernetes-ingress/ingress-azure helm upgrade ingress-azure application-gateway-kubernetes-ingress/ingress-azure \ --namespace kube-system \ --install \ --set appgw.name=$APPGW_NAME \ --set appgw.resourceGroup=$APPGW_GROUP \ --set appgw.subscriptionId=$SUBSCRIPTION_ID \ --set appgw.usePrivateIP=true \ --set appgw.shared=true \ --set armAuth.type=aadPodIdentity \ --set armAuth.identityClientID=$AGIC_ID_CLIENT_ID \ --set armAuth.identityResourceID=$AGIC_ID_RESOURCE_ID \ --set rbac.enabled=true \ --set verbosityLevel=3 # --set kubernetes.watchNamespace=default sleep 120 # this might take a while to configure correctly if [ "$KUBE_CNI_PLUGIN" == "kubenet" ]; then AKS_NODE_NSG=$(az network nsg list -g ${NODE_GROUP} --query "[].id | [0]" -o tsv) az network route-table create -g $APPGW_GROUP --name $APPGW_NAME-rt APPGW_ROUTE_TABLE_ID=$(az network route-table show -g ${APPGW_GROUP} -n $APPGW_NAME-rt --query "id" -o tsv) az network nsg create --name $APPGW_NAME-nsg --resource-group $APPGW_GROUP --location $LOCATION # az network nsg rule create --name appgwrule --nsg-name $APPGW_NAME-nsg --resource-group $APPGW_GROUP --priority 110 \ # --source-address-prefixes '*' --source-port-ranges '*' \ # --destination-address-prefixes '*' --destination-port-ranges '*' --access Allow --direction Inbound \ # --protocol "*" --description "Required allow rule for AppGW." az network nsg rule create --name Allow_GWM --nsg-name $APPGW_NAME-nsg --priority 100 --resource-group $APPGW_GROUP --access Allow --direction Inbound --destination-port-ranges 65200-65535 --source-address-prefixes GatewayManager --description "Required for Gateway Manager." az network nsg rule create --name agic_allow --nsg-name $APPGW_NAME-nsg --resource-group $APPGW_GROUP --priority 120 \ --source-address-prefixes '*' --source-port-ranges '*' \ --destination-address-prefixes "$APPGW_PUBLIC_IP" --destination-port-ranges '80' --access Allow --direction Inbound \ --protocol "*" --description "Required allow rule for Ingress Controller." #az network nsg rule create --name Allow_AzureLoadBalancer --nsg-name $APPGW_NAME-nsg --priority 110 --resource-group $APPGW_GROUP --access Allow --direction Inbound --source-address-prefixes AzureLoadBalancer #az network nsg rule create --name DenyAllInbound_Internet --nsg-name $APPGW_NAME-nsg --priority 200 --resource-group $APPGW_GROUP --access Deny --direction Inbound --source-address-prefixes Internet APPGW_NSG=$(az network nsg list -g ${APPGW_GROUP} --query "[].id | [0]" -o tsv) az network vnet subnet update --route-table $APPGW_ROUTE_TABLE_ID --network-security-group $APPGW_NSG --ids $APPGW_SUBNET_ID AKS_ROUTES=$(az network route-table route list --resource-group $VNET_GROUP --route-table-name $KUBE_NAME-rt) az network route-table route list --resource-group $VNET_GROUP --route-table-name $KUBE_NAME-rt --query "[][name,addressPrefix,nextHopIpAddress]" -o tsv | while read -r name addressPrefix nextHopIpAddress; do echo "checking route $name" echo "creating new hop $name selecting $addressPrefix configuring $nextHopIpAddress as next hop" az network route-table route create --resource-group $APPGW_GROUP --name $name --route-table-name $APPGW_NAME-rt --address-prefix $addressPrefix --next-hop-type VirtualAppliance --next-hop-ip-address $nextHopIpAddress --subscription $SUBSCRIPTION_ID done az network route-table route list --resource-group $APPGW_GROUP --route-table-name $APPGW_NAME-rt fi kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-logger.yaml # cat <<EOF | kubectl apply -f - # apiVersion: extensions/v1beta1 # kind: Ingress # metadata: # name: dummy-logger # annotations: # kubernetes.io/ingress.class: azure/application-gateway # spec: # rules: # - host: $APPGW_PUBLIC_IP.xip.io # http: # paths: # - backend: # serviceName: dummy-logger # servicePort: 80 # EOF open "http://$APPGW_PUBLIC_IP.xip.io/ping" # az aks enable-addons -n $KUBE_NAME -g $KUBE_GROUP -a ingress-appgw --appgw-id $APPGW_RESOURCE_ID cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF sleep 10 kubectl exec -ti centos -- /bin/bash <file_sep># Flux https://www.weave.works/technologies/gitops/ https://github.com/fluxcd/flux https://github.com/fluxcd/flux/blob/master/docs/tutorials/get-started-helm.md https://github.com/denniszielke/flux-get-started https://helm.workshop.flagger.dev/ https://helm.workshop.flagger.dev/gitops-helm-workshop.png helm upgrade -i flux \ --set helmOperator.create=true \ --set helmOperator.createCRD=false \ --set git.url=<EMAIL>:denniszielke/flux-get-started \ --namespace flux \ fluxcd/flux kubectl -n flux logs deployment/flux | grep identity.pub | cut -d '"' -f2 https://github.com/gbaeke/realtimeapp-infra/blob/master/deploy/bases/realtimeapp/kustomization.yaml https://github.com/cyrilbkr/flux2-multicluster-example/blob/main/infrastructure/common/ingress-nginx/nginx-ingress.yaml https://docs.microsoft.com/en-us/azure/azure-arc/kubernetes/tutorial-use-gitops-flux2#work-with-parameters https://docs.microsoft.com/en-us/cli/azure/k8s-configuration/flux?view=azure-cli-latest#az_k8s_configuration_flux_create<file_sep># Redis install helm upgrade redis stable/redis --install --set password=<PASSWORD> --set cluster.enabled=false --namespace=redis REDIS_HOST=redis-master:6379 REDIS_PASSWORD=<PASSWORD> kubectl run --namespace redis redis-client --restart='Never' \ --env REDIS_PASSWORD=$<PASSWORD> \ --image docker.io/bitnami/redis:5.0.7-debian-10-r0 -- bash Connect using the Redis CLI: redis-cli -h redis-master -a $REDIS_PASSWORD <file_sep># IPV6 Guidance https://github.com/leblancd/kube-v6/blob/master/NAT64-DNS64-UBUNTU-INSTALL.md https://thenewstack.io/tayga-bridge-an-ipv6-network-back-to-ipv4-using-nat64/ https://packetpushers.net/nat64-setup-using-tayga/ https://www.internetsociety.org/resources/deploy360/2013/making-content-available-over-ipv6/ ## NAT64 router KUBE_GROUP=kub_a_m_pv6 LOCATION=westeurope az group create \ --name $KUBE_GROUP \ --location $LOCATION # Create the virtual network az network vnet create \ --name vnet \ --resource-group $KUBE_GROUP \ --location $LOCATION \ --address-prefixes "10.0.0.0/16" "fd00:db8:deca::/48" az network nsg create \ --name router-nsg \ --resource-group $KUBE_GROUP \ --location $LOCATION # Create inbound rule for port 80 az network nsg rule create \ --name allowHTTPIn \ --nsg-name router-nsg \ --resource-group $KUBE_GROUP \ --priority 200 \ --description "Allow HTTP In" \ --access Allow \ --protocol "*" \ --direction Inbound \ --source-address-prefixes "*" \ --source-port-ranges 80 \ --destination-address-prefixes "*" \ --destination-port-ranges 80 # Create outbound rule az network nsg rule create \ --name allowAllOut \ --nsg-name router-nsg \ --resource-group $KUBE_GROUP \ --priority 300 \ --description "Allow All Out" \ --access Allow \ --protocol "*" \ --direction Outbound \ --source-address-prefixes "*" \ --source-port-ranges "*" \ --destination-address-prefixes "*" \ --destination-port-ranges "*" # Create a single dual stack subnet az network vnet subnet create \ --name router \ --resource-group $KUBE_GROUP \ --vnet-name vnet \ --address-prefixes "10.0.0.0/24" "fd00:db8:deca:deed::/64" \ --network-security-group router-nsg az network vnet subnet create \ --name aks \ --resource-group $KUBE_GROUP \ --vnet-name vnet \ --address-prefixes "10.0.1.0/24" # create ipv4 az network public-ip create \ --name router-ipv4 \ --resource-group $KUBE_GROUP \ --location $LOCATION \ --sku STANDARD \ --allocation-method static \ --version IPv4 # Create an IPV6 IP address az network public-ip create \ --name router-ipv6 \ --resource-group $KUBE_GROUP \ --location $LOCATION \ --sku STANDARD \ --allocation-method static \ --version IPv6 az network public-ip create \ --name router-remove \ --resource-group $KUBE_GROUP \ --location $LOCATION \ --sku Standard \ --allocation-method static \ --version IPv4 <!-- az network public-ip create \ --name dsVM1_remote_access \ --resource-group $KUBE_GROUP \ --location $LOCATION \ --sku Standard \ --allocation-method static \ --version IPv4 --> # create lb az network lb create \ --name router-lb \ --resource-group $KUBE_GROUP \ --sku Standard \ --location $LOCATION \ --frontend-ip-name frontendv4 \ --public-ip-address router-ipv4 \ --backend-pool-name backendv4 az network lb frontend-ip create \ --lb-name router-lb \ --name frontendv6 \ --resource-group $KUBE_GROUP \ --public-ip-address router-ipv6 az network lb address-pool create \ --lb-name router-lb \ --name backendv6 \ --resource-group $KUBE_GROUP az network lb probe create -g $KUBE_GROUP --lb-name router-lb -n probe80 --protocol tcp --port 80 az network lb rule create \ --lb-name router-lb \ --name lbrulev4 \ --resource-group $KUBE_GROUP \ --frontend-ip-name frontendv4 \ --protocol Tcp \ --frontend-port 80 \ --backend-port 80 \ --probe-name probe80 \ --backend-pool-name backendv4 az network lb rule create \ --lb-name router-lb \ --name lbrulev6 \ --resource-group $KUBE_GROUP \ --frontend-ip-name frontendv6 \ --protocol Tcp \ --frontend-port 80 \ --backend-port 80 \ --probe-name probe80 \ --backend-pool-name backendv6 az vm availability-set create \ --name routeravset \ --resource-group $KUBE_GROUP \ --location $LOCATION \ --platform-fault-domain-count 2 \ --platform-update-domain-count 2 # Create NICs az network nic create \ --name nicv4 \ --resource-group $KUBE_GROUP \ --network-security-group router-nsg \ --vnet-name vnet \ --subnet router \ --private-ip-address-version IPv4 \ --lb-address-pools backendv4 \ --lb-name router-lb \ --public-ip-address dsVM0_remote_access az network nic create \ --name dsNIC1 \ --resource-group $KUBE_GROUP \ --network-security-group dsNSG1 \ --vnet-name vnet \ --subnet gateway \ --private-ip-address-version IPv4 \ --lb-address-pools dsLbBackEndPool_v4 \ --lb-name dsLB \ --public-ip-address dsVM1_remote_access # Create IPV6 configurations for each NIC az network nic ip-config create \ --name dsIp6Config_NIC0 \ --nic-name dsNIC0 \ --resource-group $KUBE_GROUP \ --vnet-name vnet \ --subnet gateway \ --private-ip-address-version IPv6 \ --lb-address-pools dsLbBackEndPool_v6 \ --lb-name dsLB az network nic ip-config create \ --name dsIp6Config_NIC1 \ --nic-name dsNIC1 \ --resource-group $KUBE_GROUP \ --vnet-name vnet \ --subnet gateway \ --private-ip-address-version IPv6 \ --lb-address-pools dsLbBackEndPool_v6 \ --lb-name dsLB az vm create \ --name dsVM0 \ --resource-group $KUBE_GROUP \ --nics dsNIC0 \ --size Standard_A2 \ --availability-set dsAVset \ --image UbuntuLTS \ --authentication-type ssh \ --admin-username azureuser \ --ssh-key-value ~/.ssh/id_rsa.pub az vm create \ --name dsVM1 \ --resource-group $KUBE_GROUP \ --nics dsNIC1 \ --size Standard_A2 \ --availability-set dsAVset \ --image UbuntuLTS \ --authentication-type ssh \ --admin-username azureuser \ --ssh-key-value ~/.ssh/id_rsa.pub<file_sep># Auth https://github.com/mchmarny/dapr-demos/tree/master/hardened ``` TENANT_ID= TENANT_NAME=*.onmicrosoft.com SVC_APP_NAME=node-aad-svc SVC_APP_ID= SVC_APP_SECRET= SVC_APP_SECRET_ENCODED= SVC_APP_URI_ID=https://$TENANT_NAME/node-aad-svc API_APP_NAME=name-aad-api API_APP_ID= API_APP_URI_ID=https://$TENANT_NAME/node-aad-api WB_APP_NAME=Azure Blockchain Workbench Web Client WB_APP_ID= WB_APP_URI_ID=http://$TENANT_NAME.onmicrosoft.com/AzureBlockchainWorkbench/$/WebClient WB_APP_URI_ID=$WB_APP_ID Create azure ad app that will host our custom api az ad app create --display-name node-aad-api --homepage http://localhost --identifier-uris https://$TENANT_NAME/node-aad-api Create azure ad app that will be used to create an authentication token to call our custom api az ad app create --display-name node-aad-svc --homepage http://localhost --identifier-uris https://$TENANT_NAME/node-aad-svc Call azure AD to get bearer token for api curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "client_id=$SVC_APP_ID&resource=$API_APP_URI_ID&client_secret=$SVC_APP_SECRET_ENCODED&grant_type=client_credentials" "https://login.microsoftonline.com/$TENANT_ID/oauth2/token" Call azure AD to get bearer token for workbench curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "client_id=$SVC_APP_ID&resource=$WB_APP_URI_ID&client_secret=$SVC_APP_SECRET_ENCODED&grant_type=client_credentials" "https://login.microsoftonline.com/$TENANT_ID/oauth2/token" Set bearer token to env variable TOKEN= Try out bearer token curl -isS -X GET -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" 'https://$$$-api.azurewebsites.net/api/v1/users' Call our api with the bearer token curl -isS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" http://1172.16.58.3:3000/api ```<file_sep># Network Policy on Kubernetes on Azure Here are a couple of network policy samples: https://github.com/ahmetb/kubernetes-network-policy-recipes The following options exist for AKS: 1. Deploying kube-router to AKS ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/networkpolicies/kube-router-firewall-daemonset-aks.yaml ``` 2. Deploying azure npm to AKS (works only with azure-cni) ``` kubectl apply -f https://github.com/Azure/acs-engine/blob/master/parts/k8s/addons/kubernetesmasteraddons-azure-npm-daemonset.yaml ``` > in order for dns to work you need to allow dns traffic on port 53 to 192.168.127.12 ## Example: Locking down outgoing traffic except for a postgresql database in azure 1. create postgres db ``` PSQL_PASSWORD=$(openssl rand -base64 10) az postgres server create --resource-group $KUBE_GROUP --name $KUBE_NAME --location $LOCATION --admin-user myadmin --admin-password $PSQL_<PASSWORD> --sku-name GP_Gen4_2 --version 9.6 ``` lock up details ``` az postgres server show --resource-group $KUBE_GROUP --name $KUBE_NAME ``` ping server to get ip in this case the ip comes from 192.168.127.12/22 range 2. activate service endpoint to join psql to existing kubernetes vnet ``` KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az postgres server vnet-rule create -g $KUBE_GROUP -s $KUBE_NAME -n psqlvnetrule --subnet $KUBE_AGENT_SUBNET_ID ``` 3. create policy to allow only egress traffic to psql for all containers that have `run:pdemo` label ``` cat <<EOF | kubectl create -f - apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: limit-deny-external-egress spec: podSelector: matchLabels: run: pdemo policyTypes: - Egress egress: - ports: - port: 53 protocol: UDP - port: 53 protocol: TCP - port: 5432 protocol: UDP - port: 5432 protocol: TCP to: - ipBlock: cidr: 192.168.3.11/24 - ipBlock: cidr: 192.168.127.12/22 EOF ``` 4. create pod to test network policy use postgres image to test postgres to verify that the connection works ``` cat <<EOF | kubectl create -f - kind: Pod apiVersion: v1 metadata: name: pclient labels: run: pdemo spec: containers: - name: postgres image: postgres EOF ``` log into the box ``` kubectl exec -ti pclient -- /bin/bash ``` log into psql ``` psql --host=$KUBE_NAME.postgres.database.azure.com --username=myadmin@$KUBE_NAME --dbname=db --port=5432 ``` should work! 5. run a ubuntu image to see that normal internet does not ``` cat <<EOF | kubectl create -f - kind: Pod apiVersion: v1 metadata: name: runclient labels: run: pdemo spec: containers: - name: ubuntu image: tutum/curl command: ["tail"] args: ["-f", "/dev/null"] EOF cat <<EOF | kubectl create -f - kind: Pod apiVersion: v1 metadata: name: runclient labels: run: pdemo spec: containers: - name: debian image: debian command: ["tail"] args: ["-f", "/dev/null"] EOF cat <<EOF | kubectl create -f - apiVersion: v1 kind: Pod metadata: name: helloworld spec: containers: - name: aci-helloworld image: dzkubereg.azurecr.io/aci-helloworld-ci:76 ports: - containerPort: 80 name: http protocol: TCP resources: requests: memory: "128Mi" cpu: "500m" limits: memory: "256Mi" cpu: "1000m" EOF ``` log into the box ``` kubectl exec -ti runclient -- sh kubectl run -it debian --image=debian kubectl attach debian-867c666ddc-fgjdn -c debian -i -t ``` install dependencies for tracing + wget ``` sudo apt-get install --fix-missing sudo apt install traceroute sudo apt install inetutils-traceroute sudo apt install dnsutils sudo apt install wget sudo apt install time sudo apt install curl time nslookup -vc -type=ANY google.com https://jonlabelle.com/snippets/view/shell/nslookup-command kubectl cp ~/.ssh/id_rsa aks-ssh-66cf68f4c7-k5s45:/id_rsa ssh -i id_rsa azureuser@10.0.4.4 ssh -i id_rsa azureuser@10.0.4.66 dig @10.0.4.4 google.com +tcp dig @10.0.4.151 azure.com +tcp traceroute -T -n $KUBE_NAME.postgres.database.azure.com wget --timeout 1 -O- http://www.example.com https://github.com/jamesbrink/docker-postgres ``` should not work!<file_sep># DAPR - Actors https://github.com/dapr/dotnet-sdk/blob/master/docs/get-started-dapr-actor.md dotnet new sln -o dapr-actors dotnet new classlib -o MyActor.Interfaces cd MyActor.Interfaces dotnet add package Dapr.Actors # Setup remote state store https://github.com/dapr/docs/tree/master/howto/setup-state-store helm upgrade redis stable/redis --install --set password=<PASSWORD> --set image.tag=5.0.5-debian-9-r104 helm upgrade redis stable/redis --install --set password=<PASSWORD> --set cluster.enabled=false --namespace=redis REDIS_HOST=redis-master:6379 REDIS_PASSWORD=<PASSWORD> REDIS_HOST=dzactors.redis.cache.windows.net:6379 REDIS_PASSWORD= https://github.com/dapr/dapr/blob/master/docs/decision_records/api/API-008-multi-state-store-api-design.md cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: statestore spec: type: state.redis metadata: - name: redisHost value: "$REDIS_HOST" - name: redisPassword value: "$REDIS_PASSWORD" - name: actorStateStore value: "true" EOF az cosmosdb collection create --collection-name actors --db-name dzactors --partition-key-path '/id' --resource-group $KUBE_GROUP --name $COSMOSDB_NAME az cosmosdb keys list --resource-group $KUBE_GROUP --name $COSMOSDB_NAME COSMOSDB_NAME=dzactors KUBE_GROUP=kub_ter_a_l_dapr2 MASTER_KEY= cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: cosmosdb spec: type: state.azure.cosmosdb metadata: - name: url value: https://$COSMOSDB_NAME.documents.azure.com:443/ - name: masterKey value: $MASTER_KEY - name: database value: dzactors - name: collection value: actors EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos annotations: dapr.io/enabled: "true" dapr.io/id: "curlactor" dapr.io/port: "80" dapr.io/log-level: "debug" spec: containers: - name: centoss image: centos ports: - containerPort: 3500 command: - sleep - "3600" EOF kubectl exec -it centos -- /bin/bash kubectl delete pod centos curl -X GET http://127.0.0.1:3500/dapr/config -H "Content-Type: application/json" curl -X GET http://dapr-api.default.svc.cluster.local:3500/dapr/config -H "Content-Type: application/json" https://github.com/dapr/dapr-docs/blob/master/howto/query-state-store/query-redis-store.md curl -X POST http://127.0.0.1:3005/v1.0/actors/DemoActor/abc/method/GetData curl -X POST http://127.0.0.1:3005/v1.0/actors/DemoActor/abc1 -H "Content-Type: application/json" curl -X POST http://127.0.0.1:3005/v1.0/actors/DemoActor/abc1/method/SaveData -d '{ "PropertyA": "ValueA", "PropertyB": "ValueB" }' curl -X POST http://127.0.0.1:3005/v1.0/actors/DemoActor/abc/method/GetData<file_sep>#!/bin/sh set -e KUBE_NAME=$1 KUBE_GROUP=$2 USE_ADDON=$3 SUBSCRIPTION_ID=$(az account show --query id -o tsv) #subscriptionid LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) AKS_SUBNET_ID=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query "agentPoolProfiles[0].vnetSubnetId" -o tsv) AKS_SUBNET_NAME="aks-5-subnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" CERT_MANAGER_REGISTRY=quay.io CERT_MANAGER_TAG=v1.3.1 CERT_MANAGER_IMAGE_CONTROLLER=jetstack/cert-manager-controller CERT_MANAGER_IMAGE_WEBHOOK=jetstack/cert-manager-webhook CERT_MANAGER_IMAGE_CAINJECTOR=jetstack/cert-manager-cainjector IP_ID=$(az network public-ip list -g $NODE_GROUP --query "[?contains(name, 'nginxingress')].id" -o tsv) if [ "$IP_ID" == "" ]; then echo "creating ingress ip nginxingress" az network public-ip create -g $NODE_GROUP -n nginxingress --sku STANDARD -o none IP_ID=$(az network public-ip show -g $NODE_GROUP -n nginxingress -o tsv) echo "created ip $IP_ID" IP=$(az network public-ip show -g $NODE_GROUP -n nginxingress -o tsv --query ipAddress) else IP=$(az network public-ip show -g $NODE_GROUP -n nginxingress -o tsv --query ipAddress) echo "IP $IP_ID already exists with $IP" fi KUBELET_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identityProfile.kubeletidentity.clientId -o tsv) ACR_ID=$(az acr show -n $REGISTRY_NAME --query id -o tsv) ROLE_ID=$(az role assignment list --scope $ACR_ID --query "[?contains(description, '$KUBELET_ID')].id" -o tsv) if [ "$ROLE_ID" == "" ]; then echo "assigning acrpull for $KUBELET_ID" az role assignment create --role acrpull --assignee $KUBELET_ID --scope $ACR_ID --description "$KUBELET_ID" else echo "role assignment for $KUBELET_ID already present" fi IMAGES_PRESENT=$(az acr repository show -n $REGISTRY_NAME --image $CONTROLLER_IMAGE:$CONTROLLER_TAG --query name -o tsv) if [ "$IMAGES_PRESENT" == "" ]; then echo "importing images into registry $REGISTRY_NAME" az acr import --name $REGISTRY_NAME --source $CONTROLLER_REGISTRY/$CONTROLLER_IMAGE:$CONTROLLER_TAG --image $CONTROLLER_IMAGE:$CONTROLLER_TAG az acr import --name $REGISTRY_NAME --source $PATCH_REGISTRY/$PATCH_IMAGE:$PATCH_TAG --image $PATCH_IMAGE:$PATCH_TAG az acr import --name $REGISTRY_NAME --source $DEFAULTBACKEND_REGISTRY/$DEFAULTBACKEND_IMAGE:$DEFAULTBACKEND_TAG --image $DEFAULTBACKEND_IMAGE:$DEFAULTBACKEND_TAG else echo "images already in registry $REGISTRY_NAME" fi if kubectl get namespace ingress-basic; then echo -e "Namespace ingress-basic found." else kubectl create namespace ingress-basic echo -e "Namespace ingress-basic created." fi helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx ACR_URL=$REGISTRY_NAME.azurecr.io helm upgrade nginx-ingress ingress-nginx/ingress-nginx --install \ --namespace ingress-basic \ --set controller.replicaCount=2 \ --set controller.nodeSelector."kubernetes\.io/os"=linux \ --set controller.image.registry=$ACR_URL \ --set controller.image.image=$CONTROLLER_IMAGE \ --set controller.image.tag=$CONTROLLER_TAG \ --set controller.service.externalTrafficPolicy=Local \ --set controller.service.loadBalancerIP="$IP" \ --set controller.image.digest="" \ --set controller.metrics.enabled=true \ --set controller.autoscaling.enabled=true \ --set controller.admissionWebhooks.patch.nodeSelector."kubernetes\.io/os"=linux \ --set controller.admissionWebhooks.patch.image.registry=$ACR_URL \ --set controller.admissionWebhooks.patch.image.image=$PATCH_IMAGE \ --set controller.admissionWebhooks.patch.image.tag=$PATCH_TAG \ --set controller.admissionWebhooks.patch.image.digest="" # --set defaultBackend.nodeSelector."kubernetes\.io/os"=linux \ # --set defaultBackend.enabled=true \ # --set defaultBackend.image.registry=$ACR_URL \ # --set defaultBackend.image.image=$DEFAULTBACKEND_IMAGE \ # --set defaultBackend.image.tag=$DEFAULTBACKEND_TAG \ # --set defaultBackend.image.digest="" <file_sep>SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id KUBE_GROUP="net_pg_clusters" # here enter the resources group name of your aks cluster KUBE_NAME="cluster" # here enter the name of your kubernetes resource LOCATION="australiaeast" # here enter the datacenter location VNET_GROUP="net_pg_networks" # here the name of the resource group for the vnet and hub resources KUBE1_VNET_NAME="spoke1-kubevnet" # here enter the name of your vnet KUBE2_VNET_NAME="spoke2-kubevnet" # here enter the name of your vnet KUBE3_VNET_NAME="spoke3-kubevnet" # here enter the name of your vnet KUBE4_VNET_NAME="spoke4-kubevnet" # here enter the name of your vnet KUBE_ING_SUBNET_NAME="ing-1-subnet" # here enter the name of your ingress subnet KUBE_AGENT_SUBNET_NAME="aks-2-subnet" # here enter the name of your aks subnet NAT_EGR_SUBNET_NAME="egr-3-subnet" # here enter the name of your egress subnet HUB_VNET_NAME="hub1-firewalvnet" HUB_FW_SUBNET_NAME="AzureFirewallSubnet" # this you cannot change HUB_JUMP_SUBNET_NAME="jumpbox-subnet" KUBE_VERSION="1.16.7" # here enter the kubernetes version of your aks NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group AZURE_MYOWN_OBJECT_ID=$(az ad signed-in-user show --query objectId --output tsv) AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) AAD_GROUP_ID="9329d38c-5296-4ecb-afa5-3e74f9abe09f" az account set --subscription $SUBSCRIPTION_ID echo "creating resource groups" az group create -n $KUBE_GROUP -l $LOCATION -o table az group create -n $VNET_GROUP -l $LOCATION -o table echo "creating vnets" az network vnet create -g $VNET_GROUP -n $HUB_VNET_NAME --address-prefixes 10.0.0.0/22 -o table az network vnet create -g $VNET_GROUP -n $KUBE1_VNET_NAME --address-prefixes 10.0.4.0/22 -o table az network vnet create -g $VNET_GROUP -n $KUBE2_VNET_NAME --address-prefixes 10.0.8.0/22 -o table az network vnet create -g $VNET_GROUP -n $KUBE3_VNET_NAME --address-prefixes 10.0.12.0/22 -o table az network vnet create -g $VNET_GROUP -n $KUBE4_VNET_NAME --address-prefixes 10.0.16.0/22 -o table echo "creating subnets" az network vnet subnet create -g $VNET_GROUP --vnet-name $HUB_VNET_NAME -n $HUB_FW_SUBNET_NAME --address-prefix 10.0.0.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $HUB_VNET_NAME -n $HUB_JUMP_SUBNET_NAME --address-prefix 10.0.1.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE1_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE1_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE1_VNET_NAME -n $NAT_EGR_SUBNET_NAME --address-prefix 10.0.6.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE2_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.8.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE2_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.9.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE2_VNET_NAME -n $NAT_EGR_SUBNET_NAME --address-prefix 10.0.10.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE3_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.12.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE3_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.13.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE3_VNET_NAME -n $NAT_EGR_SUBNET_NAME --address-prefix 10.0.14.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE4_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.16.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE4_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.17.0/24 -o table az network vnet subnet create -g $VNET_GROUP --vnet-name $KUBE4_VNET_NAME -n $NAT_EGR_SUBNET_NAME --address-prefix 10.0.18.0/24 -o table az network vnet peering create -g $VNET_GROUP -n HubToSpoke1 --vnet-name $HUB_VNET_NAME --remote-vnet $KUBE1_VNET_NAME --allow-vnet-access -o table az network vnet peering create -g $VNET_GROUP -n Spoke1ToHub --vnet-name $KUBE1_VNET_NAME --remote-vnet $HUB_VNET_NAME --allow-vnet-access -o table az network vnet peering create -g $VNET_GROUP -n HubToSpoke2 --vnet-name $HUB_VNET_NAME --remote-vnet $KUBE2_VNET_NAME --allow-vnet-access -o table az network vnet peering create -g $VNET_GROUP -n Spoke2ToHub --vnet-name $KUBE2_VNET_NAME --remote-vnet $HUB_VNET_NAME --allow-vnet-access -o table az network vnet peering create -g $VNET_GROUP -n HubToSpoke3 --vnet-name $HUB_VNET_NAME --remote-vnet $KUBE3_VNET_NAME --allow-vnet-access -o table az network vnet peering create -g $VNET_GROUP -n Spoke3ToHub --vnet-name $KUBE3_VNET_NAME --remote-vnet $HUB_VNET_NAME --allow-vnet-access -o table az network vnet peering create -g $VNET_GROUP -n HubToSpoke4 --vnet-name $HUB_VNET_NAME --remote-vnet $KUBE4_VNET_NAME --allow-vnet-access -o table az network vnet peering create -g $VNET_GROUP -n Spoke4ToHub --vnet-name $KUBE4_VNET_NAME --remote-vnet $HUB_VNET_NAME --allow-vnet-access -o table KUBE1_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE1_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" KUBE_NAME=pgcluster1 NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin kubenet --vnet-subnet-id $KUBE1_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --pod-cidr 10.244.0.0/16 --enable-managed-identity --kubernetes-version $KUBE_VERSION --uptime-sla --no-wait KUBE2_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE2_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" KUBE_NAME=pgcluster2 NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin kubenet --vnet-subnet-id $KUBE2_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --pod-cidr 10.244.0.0/16 --enable-managed-identity --kubernetes-version $KUBE_VERSION --uptime-sla --no-wait KUBE3_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE3_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" KUBE_NAME=pgcluster3 NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin kubenet --vnet-subnet-id $KUBE3_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.3.0.10 --service-cidr 10.3.0.0/24 --pod-cidr 10.243.0.0/16 --enable-managed-identity --kubernetes-version $KUBE_VERSION --uptime-sla --no-wait KUBE4_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE4_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" KUBE_NAME=pgcluster4 NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE4_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.4.0.10 --service-cidr 10.4.0.0/24 --enable-managed-identity --kubernetes-version $KUBE_VERSION --uptime-sla --no-wait az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME az aks list --query '[].{Name:name, ClientId:servicePrincipalProfile.clientId, MsiId:identity.principalId}' -o table az aks get kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-int-ing-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml RESOURCE_ID=/subscriptions/$SUBSCRIPTION_ID/resourceGroups/net_pg_networks/providers/Microsoft.Network/networkInterfaces/dzjumpbox527 az network nic show-effective-route-table --ids $RESOURCE_ID VMSS_RESOURCE_ID=/subscriptions/$SUBSCRIPTION_ID/resourceGroups/net_pg_clusters_pgcluster1_nodes_australiaeast/providers/Microsoft.Compute/virtualMachineScaleSets/aks-nodepool1-15360881-vmss/virtualMachines/0/networkInterfaces/aks-nodepool1-15360881-vmss az network nic show-effective-route-table --ids $VMSS_RESOURCE_ID<file_sep># Certificates ## Create self-signed certificate ``` echo "create private key" openssl genrsa -des3 -out CAPrivate.key 2048 echo "create ca root certificate" openssl req -x509 -new -nodes -key CAPrivate.key -sha256 -days 365 -out CAPrivate.pem echo "create private key" openssl genrsa -out MyPrivate.key 2048 echo "create signing request" openssl req -new -key MyPrivate.key -extensions v3_ca -out MyRequest.csr echo "create extensions file" touch openssl.ss.cnf basicConstraints=CA:FALSE subjectAltName=DNS:*.mydomain.tld extendedKeyUsage=serverAuth echo "generate certificate using CSR" openssl x509 -req -in MyRequest.csr -CA CAPrivate.pem -CAkey CAPrivate.key -CAcreateserial -extfile openssl.ss.cnf -out MyCert.crt -days 365 -sha256 ```<file_sep>https://github.com/mohmdnofal/aks-best-practices/blob/master/stateful_workloads/zrs/README.md cat <<EOF | kubectl apply -f - kind: StorageClass apiVersion: storage.k8s.io/v1 metadata: name: zrs-class provisioner: disk.csi.azure.com parameters: skuname: Premium_ZRS allowVolumeExpansion: true reclaimPolicy: Delete volumeBindingMode: WaitForFirstConsumer EOF kubectl apply -f https://raw.githubusercontent.com/mohmdnofal/aks-best-practices/master/stateful_workloads/zrs/mysql-configmap.yaml kubectl apply -f https://raw.githubusercontent.com/mohmdnofal/aks-best-practices/master/stateful_workloads/zrs/mysql-services.yaml kubectl apply -f https://raw.githubusercontent.com/mohmdnofal/aks-best-practices/master/stateful_workloads/zrs/mysql-statefulset.yaml kubectl get svc -l app=mysql kubectl get pods -l app=mysql --watch kubectl run mysql-client --image=mysql:5.7 -i --rm --restart=Never --\ mysql -h mysql-0.mysql <<EOF CREATE DATABASE zrstest; CREATE TABLE zrstest.messages (message VARCHAR(250)); INSERT INTO zrstest.messages VALUES ('Hello from ZRS'); EOF kubectl run mysql-client --image=mysql:5.7 -i -t --rm --restart=Never --\ mysql -h mysql-read -e "SELECT * FROM zrstest.messages" kubectl describe nodes | grep -i topology.kubernetes.io/zone kubectl get nodes --output=custom-columns=NAME:.metadata.name,ZONE:".metadata.labels.topology\.kubernetes\.io/zone" kubectl get pods -l app=mysql -o wide kubectl delete nodes aks-nodepool1-25938197-vmss000002 kubectl get pods -l app=mysql --watch -o wide kubectl apply -f https://raw.githubusercontent.com/mohmdnofal/aks-best-practices/master/stateful_workloads/zrs/zrs-deployment.yaml kubectl apply -f https://raw.githubusercontent.com/mohmdnofal/aks-best-practices/master/stateful_workloads/zrs/zrs-pvc.yaml CSI V2 https://github.com/kubernetes-sigs/azuredisk-csi-driver/blob/master/deploy/example/failover/README.md helm repo add azuredisk-csi-driver https://raw.githubusercontent.com/kubernetes-sigs/azuredisk-csi-driver/master/charts helm install azuredisk-csi-driver-v2 azuredisk-csi-driver/azuredisk-csi-driver \ --namespace kube-system \ --version v2.0.0-alpha.1 \ --values=https://raw.githubusercontent.com/kubernetes-sigs/azuredisk-csi-driver/master/charts/v2.0.0-alpha.1/azuredisk-csi-driver/side-by-side-values.yaml cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: zrs-class parameters: cachingmode: None skuName: StandardSSD_ZRS maxShares: "2" provisioner: disk2.csi.azure.com reclaimPolicy: Delete volumeBindingMode: Immediate allowVolumeExpansion: true EOF<file_sep># APIM with otel #https://github.com/open-telemetry/opentelemetry-helm-charts/commit/5a01f839474dc3556fa461b46beff6cada71bbfa#diff-d34732aba6898ffb96752242a9ff4baed96595a2d6c97c6263af690139dda368 helm repo add open-telemetry https://open-telemetry.github.io/opentelemetry-helm-charts helm repo update cat << EOF > opentelemetry-collector-config.yml mode: deployment config: exporters: prometheus: endpoint: "0.0.0.0:8889" namespace: azure_apim send_timestamps: true service: pipelines: metrics: exporters: - prometheus service: type: LoadBalancer ports: jaeger-compact: enabled: false prom-exporter: enabled: true containerPort: 8889 servicePort: 8889 protocol: TCP EOF helm upgrade --install opentelemetry-collector --namespace azure-apim --create-namespace open-telemetry/opentelemetry-collector --values ./opentelemetry-collector-config.yml APIM_NAME="" APIM_URI="$APIM_NAME.configuration.azure-api.net" APIM_KEY="" SUBSCRIPTION_KEY=" helm repo add azure-apim-gateway https://azure.github.io/api-management-self-hosted-gateway/helm-charts/ helm repo update helm search repo azure-apim-gateway helm upgrade --install azure-api-management-gateway --namespace azure-apim --create-namespace \ --set gateway.configuration.uri="$APIM_URI" \ --set gateway.auth.key="$APIM_KEY" \ --set observability.opentelemetry.enabled=true \ --set observability.opentelemetry.collector.uri=http://opentelemetry-collector:4317 \ --set service.type=LoadBalancer \ azure-apim-gateway/azure-api-management-gateway kubectl get all -l app.kubernetes.io/instance=apim-gateway -n azure-apim curl -i "http://azure-api-management-gateway.azure-apim.svc.cluster.local:8080/echo/resource?param1=sample/echo/resource?param1=sample&subscription-key=$SUBSCRIPTION_KEY" curl -i "https://$APIM_NAME.azure-api.net/echo/resource?param1=sample/echo/resource?param1=sample&subscription-key=$SUBSCRIPTION_KEY" curl -i "https://$APIM_NAME.azure-api.net/ping?&subscription-key=$SUBSCRIPTION_KEY" curl -i "http://10.2.0.84:8080/ping?subscription-key=$SUBSCRIPTION_KEY" -H "Ocp-Apim-Trace: true" curl -i "http://azure-api-management-gateway.azure-apim.svc.cluster.local:8080/echo/resource?param1=sample&subscription-key=$SUBSCRIPTION_KEY" curl -i "http://azure-api-management-gateway.azure-apim.svc.cluster.local:8080/apis/cluster-dummy-logger/ping" curl -i "http://azure-api-management-gateway.azure-apim.svc.cluster.local:8080/cluster-dummy-logger/ping" https://techcommunity.microsoft.com/t5/azure-observability-blog/visualizing-data-in-realtime-with-azure-managed-grafana/ba-p/3606421 # NOTE: Before deploying to a production environment, please review the documentation -> https://aka.ms/self-hosted-gateway-production --- apiVersion: v1 kind: ConfigMap metadata: name: america-env data: config.service.endpoint: ".configuration.azure-api.net" --- apiVersion: apps/v1 kind: Deployment metadata: name: america spec: replicas: 1 selector: matchLabels: app: america strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 0 maxSurge: 25% template: metadata: labels: app: america spec: terminationGracePeriodSeconds: 60 containers: - name: america image: mcr.microsoft.com/azure-api-management/gateway:v2 ports: - name: http containerPort: 8080 - name: https containerPort: 8081 readinessProbe: httpGet: path: /status-0123456789abcdef port: http scheme: HTTP initialDelaySeconds: 0 periodSeconds: 5 failureThreshold: 3 successThreshold: 1 env: - name: config.service.auth valueFrom: secretKeyRef: name: america-token key: value envFrom: - configMapRef: name: america-env --- apiVersion: v1 kind: Service metadata: name: america spec: type: LoadBalancer externalTrafficPolicy: Local ports: - name: http port: 80 targetPort: 8080 - name: https port: 443 targetPort: 8081 selector: app: america<file_sep># Kusto query ``` let queryStartTime = ago(21600000ms); let queryEndTime = now(); let tollerance = 1; let tonullneg1 = (arg0: real) { iff(arg0 == -1., real(null), arg0) }; let NODE_LIMITS = Perf | where TimeGenerated > ago(10m) | where CounterName == "memoryAllocatableBytes" or CounterName == "cpuAllocatableNanoCores" | as T | where CounterName == "memoryAllocatableBytes" | summarize memoryAllocatableBytes = any(CounterValue) by Computer | join ( T | where CounterName == "cpuAllocatableNanoCores" | summarize cpuAllocatableNanoCores = any(CounterValue) by Computer ) on Computer | project memoryAllocatableBytes, cpuAllocatableNanoCores, Computer; // let perfdata = materialize(Perf | project TimeGenerated, ObjectName, InstanceName, _ResourceId, CounterName, CounterValue, Computer | where TimeGenerated >= queryStartTime and TimeGenerated <= queryEndTime | where ObjectName == 'K8SContainer' | where ((CounterName == 'memoryLimitBytes' or CounterName == 'memoryRequestBytes' or CounterName == 'cpuLimitNanoCores' or CounterName == 'cpuRequestNanoCores') and TimeGenerated > (queryEndTime - 1h)) or CounterName == 'memoryRssBytes' or CounterName == 'cpuUsageNanoCores' | extend ClusterName = tostring(iff(InstanceName contains '/providers/microsoft.containerservice/managedclusters', split(InstanceName, '/')[8], iff(InstanceName contains '/subscriptions/', split(InstanceName, '/')[4], split(InstanceName, '/')[0]))) | extend PodUid = tostring(iff(InstanceName contains '/providers/microsoft.containerservice/managedclusters', split(InstanceName, '/')[9], iff(InstanceName contains '/subscriptions/', split(InstanceName, '/')[5], split(InstanceName, '/')[1]))) | extend ContainerName = tostring(iff(InstanceName contains '/providers/microsoft.containerservice/managedclusters', split(InstanceName, '/')[10], iff(InstanceName contains '/subscriptions/', split(InstanceName, '/')[6], split(InstanceName, '/')[2]))) | where isnotempty(PodUid) | extend ResourceName = strcat(ClusterName, '/', PodUid, '/', ContainerName) | join kind = inner NODE_LIMITS on Computer | join kind = inner ( KubePodInventory | where TimeGenerated >= queryEndTime - 10m and TimeGenerated <= queryEndTime | summarize any(Name, Namespace, ControllerName, ControllerKind, ClusterId) by PodUid | project PodName = any_Name, ControllerNameMaybe = any_ControllerName, ControllerKindMaybe = any_ControllerKind, Namespace = any_Namespace, PodUid ) on PodUid | project-away PodUid1 // not all pods have controllers | extend ControllerName = iff(isnull(ControllerNameMaybe) or ControllerNameMaybe == "", strcat(PodName, " (dummy value)"), ControllerNameMaybe) | extend ControllerKind = iff(isnull(ControllerKindMaybe) or ControllerKindMaybe == "", "single pod (dummy value)", ControllerKindMaybe) | project-away ControllerKindMaybe, ControllerNameMaybe // | extend hasMemLimit = iff(CounterValue == memoryAllocatableBytes, -1., CounterValue) // no limit check | extend hasMemRequest = iff(CounterValue == memoryAllocatableBytes, -1., CounterValue) // no request check | extend hasCpuRequest = iff(CounterValue == cpuAllocatableNanoCores, -1., CounterValue) // no request check | extend hasCpuLimit = iff(CounterValue == cpuAllocatableNanoCores, -1., CounterValue) // no limit check | summarize measurement_counts = count(), _max = max(CounterValue), p90=percentile(CounterValue, 90), p99=percentile(CounterValue, 99), measurementEndTime = max(TimeGenerated), measurementStartTime = min(TimeGenerated), hasMemLimit=min(hasMemLimit), hasMemRequest=min(hasMemRequest), hasCpuRequest=min(hasCpuRequest), hasCpuLimit=min(hasCpuLimit) by ClusterName, Namespace, ControllerName, ControllerKind, ContainerName, CounterName ); // perfdata | where CounterName == 'memoryLimitBytes' | project memLimitCount = measurement_counts, memLimitVal = tonullneg1(hasMemLimit), ClusterName, Namespace, ControllerName, ControllerKind, ContainerName // | join kind = fullouter ( perfdata | where CounterName == 'memoryRequestBytes' | project memRequestCount = measurement_counts, memRequestVal = tonullneg1(hasMemRequest), ClusterName, Namespace, ControllerName, ControllerKind, ContainerName ) on ClusterName, Namespace, ControllerName, ControllerKind, ContainerName | project-away ClusterName1, Namespace1, ControllerName1, ControllerKind1, ContainerName1 // | join kind = fullouter ( perfdata | where CounterName == 'memoryRssBytes' | project mem_measurement_counts = measurement_counts, mem_max = _max, mem_p90=p90, mem_p99=p99, measurementEndTime = measurementEndTime, measurementStartTime = measurementStartTime, ClusterName, Namespace, ControllerName, ControllerKind, ContainerName ) on ClusterName, Namespace, ControllerName, ControllerKind, ContainerName | project-away ClusterName1, Namespace1, ControllerName1, ControllerKind1, ContainerName1 // | join kind = fullouter ( perfdata | where CounterName == 'cpuRequestNanoCores' | project cpuRequestCount = measurement_counts, cpuRequestVal = tonullneg1(hasCpuRequest), ClusterName, Namespace, ControllerName, ControllerKind, ContainerName ) on ClusterName, Namespace, ControllerName, ControllerKind, ContainerName | project-away ClusterName1, Namespace1, ControllerName1, ControllerKind1, ContainerName1 // | join kind = fullouter ( perfdata | where CounterName == 'cpuLimitNanoCores' | project cpuLimitCount = measurement_counts, cpuLimitVal = tonullneg1(hasCpuLimit), ClusterName, Namespace, ControllerName, ControllerKind, ContainerName ) on ClusterName, Namespace, ControllerName, ControllerKind, ContainerName | project-away ClusterName1, Namespace1, ControllerName1, ControllerKind1, ContainerName1 // | join kind = fullouter ( perfdata | where CounterName == 'cpuUsageNanoCores' | project cpu_measurement_counts = measurement_counts, cpu_max = _max, cpu_p90=p90, cpu_p99=p99, ClusterName, Namespace, ControllerName, ControllerKind, ContainerName ) on ClusterName, Namespace, ControllerName, ControllerKind, ContainerName | project-away ClusterName1, Namespace1, ControllerName1, ControllerKind1, ContainerName1 // | where cpuLimitCount > 2 and memLimitCount > 2 and mem_measurement_counts >= 1 and cpu_measurement_counts >= 1 // ensure there are enough measurements | extend suggestedMemRequest = mem_p99 * 1.5 | extend suggestedMemLimit = mem_p99 * 3 | extend suggestedCpuRequest = cpu_p99 * 1.5 + 5 | extend suggestedCpuLimit = cpu_p99 * 3 + 5 | extend diffMemRequest = abs(suggestedMemRequest - memRequestVal) / suggestedMemRequest | extend diffMemLimit = abs(suggestedMemLimit - memLimitVal) / suggestedMemLimit | extend diffCpuRequest = abs(suggestedCpuRequest - cpuRequestVal) / suggestedCpuRequest | extend diffCpuLimit = abs(suggestedCpuLimit - cpuLimitVal) / suggestedCpuLimit | extend distAboveTolerance = max_of(diffMemRequest / tollerance, diffMemLimit / tollerance, diffCpuRequest / tollerance, diffCpuLimit / tollerance) | extend hasnulls = (isnull(cpuRequestVal) or isnull(cpuLimitVal) or isnull(memRequestVal) or isnull(memLimitVal)) | extend colorKey = iff(hasnulls, real(null), log10(distAboveTolerance)) | where (not(hasnulls) and ("all" == "set" or "all" == "all")) or (hasnulls and ("all" == "notset" or "all" == "all")) | extend containerKey = base64_encode_tostring(strcat(ClusterName, "/", Namespace, "/", ControllerKind, "/", ControllerName, "/", ContainerName)) | project ClusterName, Namespace, ControllerName, ControllerKind, ContainerName, memRequestVal, memLimitVal, mem_p90, mem_p99, mem_max, cpuRequestVal, cpuLimitVal, cpu_p90, cpu_p99, cpu_max, suggestedMemRequest, suggestedMemLimit, suggestedCpuRequest, suggestedCpuLimit, distAboveTolerance, colorKey, containerKey // | extend memRequestVal_final = iff(isnull(memRequestVal), -1.0, memRequestVal), memLimitVal_final = iff(isnull(memLimitVal), -1.0, memLimitVal), cpuRequestVal_final = iff(isnull(cpuRequestVal), -1.0, cpuRequestVal), cpuLimitVal_final = iff(isnull(cpuLimitVal), -1.0, cpuLimitVal) | project-away memRequestVal, memLimitVal, cpuRequestVal, cpuLimitVal | project-rename memRequestVal = memRequestVal_final, memLimitVal = memLimitVal_final, cpuRequestVal = cpuRequestVal_final, cpuLimitVal = cpuLimitVal_final ```<file_sep> # Preview feature GPUDedicatedVHDPreview KUBE_GROUP="dzscalers" KUBE_NAME="akspot" LOCATION="westeurope" KUBE_VERSION="1.18.6" az account set --subscription $ENG_SUB_ID az feature register --namespace "Microsoft.Compute" --name "SharedDisksForPremium" az feature register --name UseCustomizedContainerRuntime --namespace Microsoft.ContainerService az feature register --name UseCustomizedUbuntuPreview --namespace Microsoft.ContainerService az feature register --name GPUDedicatedVHDPreview --namespace Microsoft.ContainerService az provider register --namespace Microsoft.ContainerService SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET az group create -n $KUBE_GROUP -l $LOCATION az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --vm-set-type VirtualMachineScaleSets --load-balancer-sku standard --kubernetes-version $KUBE_VERSION \ --node-count 3 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd,UseGPUDedicatedVHD=true az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n gpuvhdct --mode user -c 1 --node-vm-size Standard_NC6 --enable-cluster-autoscaler --min-count 0 --max-count 3 az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n gpuvhdct -c 1 --mode user --node-vm-size Standard_NC6 --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd,UseGPUDedicatedVHD=true az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --vm-set-type VirtualMachineScaleSets --load-balancer-sku standard --kubernetes-version $KUBE_VERSION \ --node-count 3 --enable-managed-identity cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: DaemonSet metadata: name: nvidia-device-plugin-daemonset namespace: gpu-resources spec: selector: matchLabels: name: nvidia-device-plugin-ds updateStrategy: type: RollingUpdate template: metadata: # Mark this pod as a critical add-on; when enabled, the critical add-on scheduler # reserves resources for critical add-on pods so that they can be rescheduled after # a failure. This annotation works in tandem with the toleration below. annotations: scheduler.alpha.kubernetes.io/critical-pod: "" labels: name: nvidia-device-plugin-ds spec: tolerations: # Allow this pod to be rescheduled while the node is in "critical add-ons only" mode. # This, along with the annotation above marks this pod as a critical add-on. - key: CriticalAddonsOnly operator: Exists - key: nvidia.com/gpu operator: Exists effect: NoSchedule containers: - image: nvidia/k8s-device-plugin:1.11 name: nvidia-device-plugin-ctr securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] volumeMounts: - name: device-plugin mountPath: /var/lib/kubelet/device-plugins volumes: - name: device-plugin hostPath: path: /var/lib/kubelet/device-plugins EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: labels: app: samples-tf-mnist-demo name: samples-tf-mnist-demo spec: template: metadata: labels: app: samples-tf-mnist-demo spec: containers: - name: samples-tf-mnist-demo image: microsoft/samples-tf-mnist-demo:gpu args: ["--max_steps", "500"] imagePullPolicy: IfNotPresent resources: limits: nvidia.com/gpu: 1 restartPolicy: OnFailure EOF kubectl get pods --selector app=samples-tf-mnist-demo ## aci az aks enable-addons \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --addons virtual-node \ --subnet-name aci-2-subnet STORAGE_ACCOUNT=$KUBE_NAME NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az storage account create --resource-group $NODE_GROUP --name $STORAGE_ACCOUNT --location $LOCATION --sku Standard_LRS --kind StorageV2 --access-tier hot --https-only false STORAGE_KEY=$(az storage account keys list --account-name $STORAGE_ACCOUNT --resource-group $NODE_GROUP --query "[0].value") az storage share create -n job --quota 10 --account-name $STORAGE_ACCOUNT --account-key $STORAGE_KEY kubectl create secret generic azurefile-secret --from-literal=azurestorageaccountname=$STORAGE_ACCOUNT --from-literal=azurestorageaccountkey=$STORAGE_KEY # Create a storage account STORAGE_ACCOUNT=dzkubv1 az storage account create -n $STORAGE_ACCOUNT -g $KUBE_GROUP -l $LOCATION --sku Standard_LRS # Export the connection string as an environment variable, this is used when creating the Azure file share export AZURE_STORAGE_CONNECTION_STRING=$(az storage account show-connection-string -n $STORAGE_ACCOUNT -g $KUBE_GROUP -o tsv) # Create the file share az storage share create -n $STORAGE_ACCOUNT --connection-string $AZURE_STORAGE_CONNECTION_STRING # Get storage account key STORAGE_KEY=$(az storage account keys list --resource-group $KUBE_GROUP --account-name $STORAGE_ACCOUNT --query "[0].value" -o tsv) # Echo storage account name and key echo Storage account name: $STORAGE_ACCOUNT echo Storage account key: $STORAGE_KEY kubectl create secret generic azurefilev1-secret --from-literal=azurestorageaccountname=$STORAGE_ACCOUNT --from-literal=azurestorageaccountkey=$STORAGE_KEY <file_sep># Install Operator Framework ## Install ``` kubectl apply -f https://github.com/jetstack/cert-manager/releases/latest/download/cert-manager.yaml kubectl apply -f bestpractices/operators.yaml AZURE_SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) AZURE_CLIENT_ID=$(az ad sp show --id $KUBE_NAME -o json | jq -r '.[0].appId') if [ "$AZURE_CLIENT_ID" == "" ]; then AZURE_CLIENT_ID=$(az ad sp create-for-rbac --name $KUBE_NAME --scopes /subscriptions/$AZURE_SUBSCRIPTION_ID --role contributor -o json | jq -r '.appId') fi AZURE_CLIENT_SECRET=$(az ad app credential reset --append --id $AZURE_CLIENT_ID -o json | jq '.password' -r) cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Secret metadata: name: aso-controller-settings namespace: azureoperator-system stringData: AZURE_SUBSCRIPTION_ID: "$AZURE_SUBSCRIPTION_ID" AZURE_TENANT_ID: "$AZURE_TENANT_ID" AZURE_CLIENT_ID: "$AZURE_CLIENT_ID" AZURE_CLIENT_SECRET: "$AZURE_CLIENT_SECRET" EOF az keyvault set-policy -n $VAULT_NAME --secret-permissions set get list --spn $AZURE_CLIENT_ID cat <<EOF | kubectl apply -f - apiVersion: microsoft.resources.azure.com/v1alpha1api20200601 kind: ResourceGroup metadata: name: foo2019 spec: location: $LOCATION EOF cat <<EOF | kubectl apply -f - apiVersion: microsoft.storage.azure.com/v1alpha1api20210401 kind: StorageAccount metadata: name: samplekubestorage namespace: default spec: location: westcentralus kind: BlobStorage sku: name: Standard_LRS owner: name: foo2019 accessTier: Hot EOF kubectl get StorageAccount kubectl delete StorageAccount samplekubestorage kubectl get ResourceGroup kubectl delete ResourceGroup foo2019 ```<file_sep># Create container cluster (AKS) https://docs.microsoft.com/en-us/azure/aks/kubernetes-walkthrough 0. Variables ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv) KUBE_GROUP="akssimple" KUBE_NAME="aksrouter" LOCATION="westeurope" KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" REGISTRY_NAME="" APPINSIGHTS_KEY="" SERVICE_PRINCIPAL_ID= SERVICE_PRINCIPAL_SECRET= SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET az ad sp create-for-rbac --sdk-auth --role contributor ``` Select subscription ``` az account set --subscription $SUBSCRIPTION_ID ``` 1. Create the resource group ``` az group create -n $KUBE_GROUP -l $LOCATION ``` get available version ``` az aks get-versions -l $LOCATION -o table ``` 2. Create the aks cluster ``` KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_VNET_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 3 --generate-ssh-keys --kubernetes-version $KUBE_VERSION az aks create -g $KUBE_GROUP -n $KUBE_NAME --kubernetes-version $KUBE_VERSION --node-count 1 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION az aks create -g $KUBE_GROUP -n $KUBE_NAME --kubernetes-version $KUBE_VERSION --node-count 1 --enable-cluster-autoscaler --min-count 1 --max-count 3 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --enable-vmss az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --network-plugin azure --vm-set-type VirtualMachineScaleSets --load-balancer-sku standard --kubernetes-version $KUBE_VERSION \ --node-count 1 --enable-managed-identity --enable-node-public-ip --ssh-key-value ~/.ssh/id_rsa.pub --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd --node-resource-group $KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --network-plugin azure --vm-set-type VirtualMachineScaleSets --load-balancer-sku standard --kubernetes-version $KUBE_VERSION \ --node-count 3 --enable-managed-identity --enable-node-public-ip --ssh-key-value ~/.ssh/id_rsa.pub --aks-custom-headers EnableAzureDiskFileCSIDriver=true --node-resource-group $KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 az aks nodepool add --name ubuntu1804 --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --enable-node-public-ip --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd az aks nodepool add --name ubuntucsi --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd,EnableAzureDiskFileCSIDriver=true az aks nodepool add --name ub1804pip --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --enable-node-public-ip --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804 --vnet-subnet-id $KUBE_AGENT_SUBNET_ID az aks update --enable-cluster-autoscaler --min-count 1 --max-count 5 -g $KUBE_GROUP -n $KUBE_NAME ``` with existing keys and latest version ``` az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 3 --ssh-key-value ~/.ssh/id_rsa.pub --kubernetes-version $KUBE_VERSION --enable-addons http_application_routing ``` with existing service principal ``` az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 3 --ssh-key-value ~/.ssh/id_rsa.pub --kubernetes-version $KUBE_VERSION --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --enable-addons http_application_routing ``` with rbac (is now default) ``` az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 3 --ssh-key-value ~/.ssh/id_rsa.pub --kubernetes-version $KUBE_VERSION --enable-rbac --aad-server-app-id $AAD_APP_ID --aad-server-app-secret $AAD_APP_SECRET --aad-client-app-id $AAD_CLIENT_ID --aad-tenant-id $TENANT_ID --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --node-vm-size "Standard_D2s_v3" --enable-addons http_application_routing monitoring az aks create \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --enable-vmss \ --node-count 1 \ --ssh-key-value ~/.ssh/id_rsa.pub \ --kubernetes-version $KUBE_VERSION \ --enable-rbac \ --enable-addons monitoring ``` without rbac () ``` --disable-rbac ``` show deployment ``` az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME ``` deactivate routing addon ``` az aks disable-addons --addons http_application_routing --resource-group $KUBE_GROUP --name $KUBE_NAME ``` az aks enable-addons \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --addons virtual-node \ --subnet-name aci-2-subnet # deploy zones, msi, slb via arm ``` az group create -n $KUBE_GROUP -l $LOCATION az group deployment create \ --name spot \ --resource-group $KUBE_GROUP \ --template-file "arm/spot_template.json" \ --parameters "arm/spot_parameters.json" \ --parameters "resourceName=$KUBE_NAME" \ "location=$LOCATION" \ "dnsPrefix=$KUBE_NAME" \ "kubernetesVersion=$KUBE_VERSION" \ "servicePrincipalClientId=$SERVICE_PRINCIPAL_ID" \ "servicePrincipalClientSecret=$SERVICE_PRINCIPAL_SECRET" az group deployment create \ --name spot \ --resource-group $KUBE_GROUP \ --template-file "arm/azurecni_template.json" \ --parameters "arm/azurecni_parameters.json" \ --parameters "resourceName=$KUBE_NAME" \ "location=$LOCATION" \ "dnsPrefix=$KUBE_NAME" \ "kubernetesVersion=$KUBE_VERSION" \ "vnetSubnetID=$KUBE_AGENT_SUBNET_ID" ``` 3. Export the kubectrl credentials files ``` az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME ``` or If you are not using the Azure Cloud Shell and don’t have the Kubernetes client kubectl, run ``` az aks install-cli ``` or download the file manually ``` scp azureuser@($KUBE_NAME)mgmt.westeurope.cloudapp.azure.com:.kube/config $HOME/.kube/config ``` 4. Check that everything is running ok ``` kubectl version kubectl config current-contex ``` Use flag to use context ``` kubectl --kube-context ``` 5. Activate the kubernetes dashboard ``` az aks browse --resource-group=$KUBE_GROUP --name=$KUBE_NAME http://localhost:8001/api/v1/namespaces/kube-system/services/kubernetes-dashboard/proxy/#!/login ``` 6. Get all upgrade versions ``` az aks get-upgrades --resource-group=$KUBE_GROUP --name=$KUBE_NAME --output table ``` 7. Perform upgrade ``` az aks upgrade --resource-group=$KUBE_GROUP --name=$KUBE_NAME --kubernetes-version 1.10.6 ``` # Add agent pool ``` az aks enable-addons \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --addons virtual-node \ --subnet-name aci-2-subnet az aks disable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons virtual-node cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: aci-helloworld spec: replicas: 1 selector: matchLabels: app: aci-helloworld template: metadata: labels: app: aci-helloworld spec: containers: - name: aci-helloworld image: microsoft/aci-helloworld ports: - containerPort: 80 nodeSelector: kubernetes.io/role: agent beta.kubernetes.io/os: linux type: virtual-kubelet tolerations: - key: virtual-kubelet.io/provider operator: Exists - key: azure.com/aci effect: NoSchedule EOF az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n gpu1pool -c 1 --node-vm-size Standard_NC6 --mode user az aks nodepool scale -g $KUBE_GROUP --cluster-name $KUBE_NAME -n gpu1pool -c 0 SCALE_SET_NAME=$(az vmss list --resource-group $NODE_GROUP --query [0].name -o tsv) az vmss scale --name $SCALE_SET_NAME --new-capacity 0 --resource-group $NODE_GROUP az aks nodepool scale -g $KUBE_GROUP --cluster-name $KUBE_NAME -n gpupool -c 0 az aks nodepool delete -g $KUBE_GROUP --cluster-name $KUBE_NAME -n gpupool az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n mynodepool --mode system az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n linuxpool2 -c 1 az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n scalingpool -c 0 --enable-cluster-autoscaler --min-count 0 --max-count 3 az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME --os-type Windows -n winpoo -c 1 --node-vm-size Standard_D2_v2 az aks nodepool list -g $KUBE_GROUP --cluster-name $KUBE_NAME -o table az aks nodepool scale -g $KUBE_GROUP --cluster-name $KUBE_NAME -n scalingpool -c 0 az aks nodepool scale -g $KUBE_GROUP --cluster-name $KUBE_NAME -n cheap -c 1 az aks nodepool scale -g $KUBE_GROUP --cluster-name $KUBE_NAME -n agentpool -c 1 ``` # autoscaler https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md#im-running-cluster-with-nodes-in-multiple-zones-for-ha-purposes-is-that-supported-by-cluster-autoscaler https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/cloudprovider/azure/README.md ``` az aks nodepool scale -g $KUBE_GROUP --cluster-name $KUBE_NAME -n agentpool1 -c 1 az aks nodepool update --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --name agentpool1 --enable-cluster-autoscaler --min-count 1 --max-count 3 ``` ``` az aks nodepool add -g $KUBE_GROUP --cluster-name $KUBE_NAME -n gpuworkers -c 1 --mode user --labels workload=zeroscaler --node-taints expensive=true:NoSchedule --node-vm-size Standard_NC6 az aks nodepool delete -g $KUBE_GROUP --cluster-name $KUBE_NAME -n gpuworker kubectl -n kube-system describe configmap cluster-autoscaler-status kubectl label node aks-nodepool1-36260817-vmss000000 workload=core kubectl label node aks-scalingpool-36260817-vmss000000 workload=zeroscaler kubectl taint node aks-gpuworker-36260817-vmss000001 expensive=true:NoSchedule [?storageProfile.osDisk.osType=='Linux'].{Name:name, admin:osProfile.adminUsername}" --output tabl SUBSCRIPTION_ID=$(az account show --query id -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv) SERVICE_PRINCIPAL_ID=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query servicePrincipalProfile.clientId -o tsv) SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID --append --credential-description "autoscaler" -o json | jq '.password' -r) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) SCALE_SET_NAME=$(az vmss list --resource-group $NODE_GROUP --query [0].name -o tsv) az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP B_SERVICE_PRINCIPAL_ID=$(echo $SERVICE_PRINCIPAL_ID | base64 ) B_SERVICE_PRINCIPAL_SECRET=$(echo $SERVICE_PRINCIPAL_SECRET | base64 ) B_KUBE_NAME=$(echo $KUBE_NAME | base64 ) B_KUBE_GROUP=$(echo $KUBE_GROUP | base64 ) B_NODE_GROUP=$(echo $NODE_GROUP | base64 ) B_SUBSCRIPTION_ID=$(echo $SUBSCRIPTION_ID | base64 ) B_TENANT_ID=$(echo $TENANT_ID | base64 ) helm template my-release stable/cluster-autoscaler --set "cloudProvider=azure,autoscalingGroups[0].name=your-asg-name,autoscalingGroups[0].maxSize=10,autoscalingGroups[0].minSize=0,autoDiscovery.enabled=true" cat <<EOF | kubectl apply -f - apiVersion: v1 data: ClientID: $B_SERVICE_PRINCIPAL_ID ClientSecret: $B_SERVICE_PRINCIPAL_SECRET ResourceGroup: $B_NODE_GROUP SubscriptionID: $B_SUBSCRIPTION_ID TenantID: $B_TENANT_ID VMType: dm1zcw== kind: Secret metadata: name: cluster-autoscaler-azure namespace: kube-system EOF for aKS cat <<EOF | kubectl apply -f - apiVersion: v1 data: ClientID: $B_SERVICE_PRINCIPAL_ID ClientSecret: $B_SERVICE_PRINCIPAL_SECRET ResourceGroup: $B_KUBE_GROUP SubscriptionID: $B_SUBSCRIPTION_ID TenantID: $B_TENANT_ID VMType: QUtTCg== ClusterName: $B_KUBE_NAME NodeResourceGroup: $B_NODE_GROUP kind: Secret metadata: name: cluster-autoscaler-azure namespace: kube-system EOF kubectl get secret cluster-autoscaler-azure -n kube-system -o yaml kubectl delete secret cluster-autoscaler-azure -n kube-system kubectl apply -f bestpractices/zeroscaler.yaml kubectl logs -l app=cluster-autoscaler --tail 2 -n kube-system cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" resources: limits: nvidia.com/gpu: 1 EOF kubectl patch deployment dummy-logger -p \ '{"spec":{"template":{"spec":{"tolerations":[{"key":"expensive","operator":"Equal","value":"true","effect":"NoSchedule"}]}}}}' kubectl patch svc mying --type='json' -p='[{"op": "add", "path": "/metadata/annotations/kubernetes.io~1ingress.class", "value":"nginx"}]' cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos1 spec: nodeSelector: workload: zeroscaler tolerations: - key: "expensive" operator: "Equal" value: "true" effect: "NoSchedule" containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" resources: limits: nvidia.com/gpu: 1 EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: tolerations: - key: "expensive" operator: "Equal" value: "true" effect: "NoSchedule" containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" resources: limits: nvidia.com/gpu: 1 EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: labels: app: samples-tf-mnist-demo name: samples-tf-mnist-demo spec: template: metadata: labels: app: samples-tf-mnist-demo spec: tolerations: - key: "expensive" operator: "Equal" value: "true" effect: "NoSchedule" containers: - name: samples-tf-mnist-demo image: microsoft/samples-tf-mnist-demo:gpu args: ["--max_steps", "500"] imagePullPolicy: IfNotPresent resources: limits: nvidia.com/gpu: 1 restartPolicy: OnFailure EOF ``` # Create SSH access https://docs.microsoft.com/en-us/azure/aks/ssh ``` NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) SCALE_SET_NAME=$(az vmss list --resource-group $NODE_GROUP --query [0].name -o tsv) az vmss list-instances --resource-group kub_ter_a_m_dapr5_nodes_northeurope --name aks-default-33188643-vmss --query '[].[name, storageProfile.dataDisks[]]' | less az vmss extension set \ --resource-group $NODE_GROUP \ --vmss-name $SCALE_SET_NAME \ --name VMAccessForLinux \ --publisher Microsoft.OSTCExtensions \ --version 1.4 \ --protected-settings "{\"username\":\"dennis\", \"ssh_key\":\"$(cat ~/.ssh/id_rsa.pub)\"}" az vmss update-instances --instance-ids '*' \ --resource-group $NODE_GROUP \ --name $SCALE_SET_NAME kubectl run -it --rm aks-ssh --image=debian kubectl -n test exec -it $(kubectl -n test get pod -l run=aks-ssh -o jsonpath='{.items[0].metadata.name}') -- /bin/sh kubectl cp ~/.ssh/id_rsa $(kubectl get pod -l run=aks-ssh -o jsonpath='{.items[0].metadata.name}'):/id_rsa ``` # Delete everything ``` az group delete -n $KUBE_GROUP ``` <file_sep>## Trace network apt-get install curl apt-get install nc nc -ul 15683 nc -ul -p 15683 nc 30102 kubectl get events --sortby .lastTimeStamp -w ## ksniff ( set -x; cd "$(mktemp -d)" && curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/krew.tar.gz" && tar zxvf krew.tar.gz && KREW=./krew-"$(uname | tr '[:upper:]' '[:lower:]')_$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm.*$/arm/')" && "$KREW" install krew ) export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH" kubectl krew install sniff kubectl >= 1.12: kubectl sniff <POD_NAME> [-n <NAMESPACE_NAME>] [-c <CONTAINER_NAME>] [-i <INTERFACE_NAME>] [-f <CAPTURE_FILTER>] [-o OUTPUT_FILE] [-l LOCAL_TCPDUMP_FILE] [-r REMOTE_TCPDUMP_FILE] POD_NAME: Required. the name of the kubernetes pod to start capture it's traffic. NAMESPACE_NAME: Optional. Namespace name. used to specify the target namespace to operate on. CONTAINER_NAME: Optional. If omitted, the first container in the pod will be chosen. INTERFACE_NAME: Optional. Pod Interface to capture from. If omitted, all Pod interfaces will be captured. CAPTURE_FILTER: Optional. specify a specific tcpdump capture filter. If omitted no filter will be used. OUTPUT_FILE: Optional. if specified, ksniff will redirect tcpdump output to local file instead of wireshark. Use '-' for stdout. LOCAL_TCPDUMP_FILE: Optional. if specified, ksniff will use this path as the local path of the static tcpdump binary. REMOTE_TCPDUMP_FILE: Optional. if specified, ksniff will use the specified path as the remote path to upload static tcpdump to. kubectl sniff <your-apache-pod-name> -p kubectl sniff <your-apache-pod-name> -f "port 8080" -p kubectl sniff <your-coredns-pod-name> -p -n kube-system -o dns.pcap kubectl exec -it <your-apache-pod-name> -- curl kubesandclouds.com <file_sep> https://learn.hashicorp.com/tutorials/vault/getting-started-install brew tap hashicorp/tap brew install hashicorp/tap/vault brew upgrade hashicorp/tap/vault kubectl create namespace vault kubectl --namespace='vault' get all helm repo add hashicorp https://helm.releases.hashicorp.com helm search repo hashicorp/vault helm install vault hashicorp/vault --namespace vault az ad sp create-for-rbac --name http://vaultsp --role reader --scopes /subscriptions/AZURE_SUBSCRIPTION_ID helm install vault hashicorp/vault \ --namespace vault \ --set "server.ha.enabled=true" \ --set "server.ha.replicas=5" \ --dry-run helm delete vault -n vault helm upgrade vault hashicorp/vault --install \ --namespace vault \ -f hashicorpvault.yaml \ --dry-run export VAULT_ADDR='http://[::]:8200' The unseal key and root token are displayed below in case you want to seal/unseal the Vault or re-authenticate. Unseal Key: = Root Token: <PASSWORD> kubectl get pods --selector='app.kubernetes.io/name=vault' --namespace=' vault' kubectl exec --stdin=true -n vault --tty=true vault-0 -- vault operator init kubectl port-forward vault-0 8200:8200 -n vault Error parsing Seal configuration: error fetching Azure Key Vault wrapper key information: azure.BearerAuthorizer#WithAuthorization: Failed to refresh the Token for request to https://dvadzvault.vault.azure.net/keys/vaultkey/?api-version=7.0: StatusCode=400 -- Original Error: adal: Refresh request failed. Status Code = '400'. Response body: {"error":"invalid_request","error_description":"Multiple user assigned identities exist, please specify the clientId / resourceId of the identity in the token request"} Endpoint http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net 2021-06-24T12:04:39.565Z [INFO] proxy environment: http_proxy="" https_proxy="" no_proxy=""<file_sep> More: https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/ For each pod, list whether it containers run on a read-only root filesystem or not: ``` kubectl get pods --all-namespaces -o go-template --template='{{range .items}}{{.metadata.name}}{{"\n"}}{{range .spec.containers}} read-only: {{if .securityContext.readOnlyRootFilesystem}}{{printf "\033[32m%t\033[0m" .securityContext.readOnlyRootFilesystem}} {{else}}{{printf "\033[91m%s\033[0m" "false"}}{{end}} ({{.name}}){{"\n"}}{{end}}{{"\n"}}{{end}}' ``` Get pod count per node ``` kubectl get po -o json --all-namespaces | jq '.items | group_by(.spec.nodeName) | map({"nodeName": .[0].spec.nodeName, "count": length}) | sort_by(.count)' ``` Get nodes internal ips ``` kubectl get no -o json | jq -r '.items[].status.addresses[] | select(.type=="InternalIP") | .address' ``` get pvc sizes ``` kubectl get pv -o json | jq -r '.items | sort_by(.spec.capacity.storage)[]|[.metadata.name,.spec.capacity.storage]| @tsv' ``` get nodes memory capacizy ``` kubectl get no -o json | jq -r '.items | sort_by(.status.capacity.memory)[]|[.metadata.name,.status.capacity.memory]| @tsv' ``` curl -X GET $APISERVER/api/v1/nodes --header "Authorization: Bearer $TOKEN" --insecure curl -X GET $APISERVER/api/v1/nodes?fieldSelector="metadata.name" --header "Authorization: Bearer $TOKEN" --insecure kubectl get nodes --field-selector<file_sep>https://github.com/weaveworks/kured#installation https://docs.microsoft.com/en-us/azure/aks/node-updates-kured Check reboot status ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/bestpractices/checkreboot.yaml kubectl logs -l name=check-reboot --tail 1 -n kube-system ``` Restrat all vm in resource group ``` az vm restart --ids $(az vm list -g $KUBE_GROUP --query "[].id" -o tsv) ``` let ContainerIdList = KubePodInventory | where TimeGenerated > ago(1d) | where ContainerName contains 'check-reboot' | distinct ContainerID; ContainerLog | where TimeGenerated > ago(1d) | where ContainerID in (ContainerIdList) | project ClusterName, LogEntry, TimeGenerated, Computer | where LogEntry startswith "check-reboot status" and LogEntry contains "reboot required" | render table let ContainerIdList = KubePodInventory | where TimeGenerated > ago(1h) | where ContainerName contains 'check-reboot' | distinct ContainerID; ContainerLog | where TimeGenerated > ago(1d) | where ContainerID in (ContainerIdList) | project LogEntry, TimeGenerated, Computer | where LogEntry startswith "check-reboot status" and LogEntry contains "reboot required" | distinct Computer | join kind= innerunique (KubeNodeInventory) on Computer | project ClusterName, Computer | render table let ContainerIdList = KubePodInventory | where TimeGenerated > ago(1h) | where ContainerName contains 'check-reboot' | distinct ContainerID; ContainerLog | where TimeGenerated > ago(1d) | where ContainerID in (ContainerIdList) | project LogEntry, TimeGenerated, Computer | where LogEntry startswith "check-reboot status" and LogEntry contains "reboot required" | join kind= innerunique (KubeNodeInventory | where TimeGenerated > ago(1h) | distinct Computer, ClusterName ) on Computer | project ClusterName, Computer | render table let ContainerIdList = KubePodInventory | where TimeGenerated > ago(1h) | where ContainerName contains 'check-reboot' | distinct ContainerName; ContainerLog | where TimeGenerated > ago(1h) | where Name in (ContainerIdList) | project LogEntry, TimeGenerated, Computer | where LogEntry startswith "check-reboot status" and LogEntry contains "reboot required" | join kind= innerunique ( KubeNodeInventory | where TimeGenerated > ago(1d) | distinct Computer, ClusterName ) on Computer | project ClusterName, Computer | render table { "text":"There are #searchresultcount worker nodes needing a reboot", "IncludeSearchResults":true } {"text":"There are 1 worker nodes needing a reboot","IncludeSearchResults":true,"SearchResult": { "tables":[ {"name":"PrimaryResult","columns": [ {"name":"$table","type":"string"}, {"name":"Id","type":"string"}, {"name":"TimeGenerated","type":"datetime"} ], "rows": [ ["Fabrikam","33446677a","2018-02-02T15:03:12.18Z"], ["Contoso","33445566b","2018-02-02T15:16:53.932Z"] ] } ] } } helm install --name prometheus stable/prometheus --namespace prometheus kubectl --namespace prometheus port-forward $(kubectl get pod --namespace prometheus -l prometheus=kube-prometheus -l app=prometheus -o template --template "{{(index .items 0).metadata.name}}") 9090:9090 helm install --name grafana stable/grafana --namespace grafana kubectl --namespace grafana port-forward $(kubectl get pod --namespace grafana -l app=kube-prometheus-grafana -o template --template "{{(index .items 0).metadata.name}}") 3000:3000 kubectl apply -f https://github.com/weaveworks/kured/releases/download/1.1.0/kured-1.1.0.yaml az vmss extension list --resource-group $KUBE_GROUP --vmss-name k8s-workers-14540501-vmss az vmss extension set \ --publisher Folder.Creator \ --version 2.0 \ --name CustomScript \ --resource-group $KUBE_GROUP \ --vmss-name k8s-workers-14540501-vmss \ --settings arm/cse-config.json az vm extension set \ --resource-group $KUBE_GROUP \ --vm-name exttest \ --name customScript \ --publisher Microsoft.Azure.Extensions \ --protected-settings '{"fileUris": ["https://raw.githubusercontent.com/Microsoft/dotnet-core-sample-templates/master/dotnet-core-music-linux/scripts/config-music.sh"],"commandToExecute": "./config-music.sh"}'<file_sep>#!/bin/bash # ./getmekube.sh dzdemo int we a m 1.10.9 echo "This script will create you a kubernetes cluster" export cluster_name="$1" export subscription="$2" export cluster_region="$3" export cni_type="$4" export cluster_size="$5" export kube_version="$6" export kube_auth="$7" OUTPUT_PATH=$HOME/terra_out TERRA_PATH=$HOME/lib/terraform/terraform CONFIG_PATH=$HOME/config VM_SIZE="Standard_D2s_v3" VM_COUNT=3 MIN_VM_COUNT=3 MAX_VM_COUNT=4 VNET_FILE=$PWD/terraform/vnet.tf LOGS_FILE=$PWD/terraform/logs.tf KUBE_TEMPLATE_FILE=$PWD/terraform/azurecni.tf SUBSCRIPTION_FILE=$CONFIG_PATH/variables_$subscription.tf VARIABLE_FILE=$CONFIG_PATH/variables_common.tf HELM_FILE=$PWD/terraform/helm.tf AMBASSADOR_FILE=$PWD/terraform/ingress_ambassador.tf NGINX_FILE=$PWD/terraform/ingress_nginx.tf TRAEFIK_FILE=$PWD/terraform/ingress_traefik.tf TRAEFIK_YAML=$PWD/terraform/traefik.yaml KONG_FILE=$PWD/terraform/ingress_kong.tf ACR_FILE=$PWD/terraform/containerregistry.tf LOKI_FILE=$PWD/terraform/monitoring_loki.tf GRAFANA_FILE=$PWD/terraform/monitoring_grafana.tf SP_FILE=$PWD/terraform/serviceprincipal.tf KV_FILE=$PWD/terraform/keyvault.tf if [ "$subscription" == "" ]; then echo "Subscription [int], [dev], [nin]?: " read -n 3 subscription echo fi SUBSCRIPTION_FILE=$CONFIG_PATH/variables_$subscription.tf if [ "$cluster_region" == "" ]; then echo "Region [we]westeurope, [ea]eastus, [ne]northeurope?, [as]australiaeast, [wc] westcentralus " read -n 2 cluster_region echo fi if [ "$cluster_region" == "ne" ]; then cluster_region="NorthEurope" elif [ "$cluster_region" == "ea" ]; then cluster_region="EastUs" elif [ "$cluster_region" == "as" ]; then cluster_region="australiaeast" elif [ "$cluster_region" == "wc" ]; then cluster_region="westcentralus" else cluster_region="WestEurope" fi if [ "$cluster_name" == "" ]; then echo "Name of the cluster: " read cluster_name echo fi if [ "$cni_type" == "" ]; then echo "What cni plugin [a]zure, [k]ubenet?: " read -n 1 cni_type echo fi if [ "$cni_type" == "k" ]; then KUBE_TEMPLATE_FILE=$PWD/terraform/kubenet.tf fi if [ "$cluster_size" == "" ]; then echo "Size of the cluster [s]mall, [m]edium, [l]arge?: " read -n 1 cluster_size echo fi if [ "$autoscaler" == "" ]; then echo "turn on autoscaler? [y], [n]: " read -n 1 autoscaler echo fi if [ "$kube_auth" == "" ]; then echo "turn on msi? [m], [s]: " read -n 1 kube_auth echo fi if [ "$cluster_size" == "s" ]; then VM_SIZE="Standard_B2s" VM_COUNT=1 MIN_VM_COUNT=1 MAX_VM_COUNT=2 elif [ "$cluster_size" == "m" ]; then VM_SIZE="Standard_D2s_v3" VM_COUNT=2 MIN_VM_COUNT=2 MAX_VM_COUNT=3 else VM_SIZE="Standard_F4s" VM_COUNT=3 MIN_VM_COUNT=3 MAX_VM_COUNT=4 fi if [ "$kube_version" == "" ]; then echo "Kubernetes version [1.10.9], [1.11.3], [1.11.4]?: " az aks get-versions --location $cluster_region -o table read kube_version echo fi if [ "$ingress" == "" ]; then echo "Install ingress [a]mbassador, [n]ginx, [t]raefik, [k]ong, [s]kip?: " read -n 1 ingress echo fi if [ "$monitoring" == "" ]; then echo "Install [g]rafana, [l]oki: " read -n 1 monitoring echo fi if [ "$flux" == "" ]; then echo "Install [f]lux: " read -n 1 flux echo fi if [ "$acr" == "" ]; then echo "deploy acr [y/n]?: " read -n 1 acr echo fi TERRAFORM_STORAGE_NAME=dzt$cluster_name KUBE_RG="kub_ter_"$cni_type"_"$cluster_size"_"$cluster_name LOCATION=$cluster_region echo "Resource Group: $KUBE_RG" echo "Terraform State: $TERRAFORM_STORAGE_NAME" echo "Location: $LOCATION" echo "$KUBE_TEMPLATE_FILE" echo "$SUBSCRIPTION_FILE" echo "using terraform version:" $TERRA_PATH version if [ -d $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME ] then echo "Deployment already exists ... waiting for interrupt" sleep 1 echo "*" sleep 1 echo "*" sleep 1 echo "*" TERRAFORM_STORAGE_KEY=$(az storage account keys list --account-name $TERRAFORM_STORAGE_NAME --resource-group $KUBE_RG --query "[0].value" -o tsv) echo "terraform state $TERRAFORM_STORAGE_KEY" else echo "starting new deployment..." sleep 1 echo "*" sleep 1 echo "*" sleep 1 echo "*" echo "initialzing terraform state storage..." az group create -n $KUBE_RG -l $LOCATION --output none az storage account create --resource-group $KUBE_RG --name $TERRAFORM_STORAGE_NAME --location $LOCATION --sku Standard_LRS --output none TERRAFORM_STORAGE_KEY=$(az storage account keys list --account-name $TERRAFORM_STORAGE_NAME --resource-group $KUBE_RG --query "[0].value" -o tsv) export ARM_ACCESS_KEY=$TERRAFORM_STORAGE_KEY az storage container create -n tfstate --account-name $TERRAFORM_STORAGE_NAME --account-key $TERRAFORM_STORAGE_KEY --output none echo $TERRAFORM_STORAGE_NAME echo $TERRAFORM_STORAGE_KEY mkdir $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME fi cp $SUBSCRIPTION_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME/variables.tf if [ "$kube_auth" == "s" ]; then cp $SP_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME fi cp $LOGS_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME cp $VNET_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME cp $KV_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME RG_ID=$(az group show -n $KUBE_RG --query id -o tsv) if [ "$ingress" == "n" ]; then cp $HELM_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME cp $NGINX_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME elif [ "$ingress" == "a" ]; then cp $HELM_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME cp $AMBASSADOR_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME elif [ "$ingress" == "t" ]; then cp $HELM_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME cp $TRAEFIK_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME cp $TRAEFIK_YAML $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME elif [ "$ingress" == "k" ]; then cp $HELM_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME cp $KONG_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME fi if [ "$acr" == "y" ]; then cp $ACR_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME fi if [ "$monitoring" == "l" ]; then cp $HELM_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME cp $LOKI_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME elif [ "$monitoring" == "g" ]; then cp $HELM_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME cp $GRAFANA_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME fi if [ "$autoscaler" == "y" ]; then AUTOSCALER="true" elif [ "$autoscaler" == "n" ]; then AUTOSCALER="false" fi sed -e "s/VAR_TERRAFORM_NAME/$TERRAFORM_STORAGE_NAME/ ; s/VAR_AGENT_COUNT/$VM_COUNT/ ; s/VAR_VM_SIZE/$VM_SIZE/ ; s/VAR_AUTOSCALER/$AUTOSCALER/ ; s/VAR_MIN_VM_COUNT/$MIN_VM_COUNT/ ; s/VAR_MAX_VM_COUNT/$MAX_VM_COUNT/ ; s/VAR_KUBE_VERSION/$kube_version/ ; s/VAR_KUBE_NAME/$cluster_name/ ; s/VAR_KUBE_RG/$KUBE_RG/ ; s/VAR_KUBE_LOCATION/$LOCATION/" $VARIABLE_FILE >> $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME/variables.tf if [ "$autoscaler" == "y" ]; then sed -e "s/#SCALER//" $KUBE_TEMPLATE_FILE > $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME/kube.tf else cp $KUBE_TEMPLATE_FILE $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME/kube.tf fi #export ARM_ACCESS_KEY=$TERRAFORM_STORAGE_KEY less $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME/variables.tf (cd $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME && $TERRA_PATH init -backend-config="storage_account_name=$TERRAFORM_STORAGE_NAME" -backend-config="container_name=tfstate" -backend-config="access_key=$TERRAFORM_STORAGE_KEY" -backend-config="key=codelab.microsoft.tfstate" ) # (cd $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME && $TERRA_PATH init ) (cd $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME && $TERRA_PATH import azurerm_resource_group.aksrg $RG_ID) (cd $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME && $TERRA_PATH plan -out $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME/out.plan) (cd $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME && $TERRA_PATH apply $OUTPUT_PATH/$TERRAFORM_STORAGE_NAME/out.plan) <file_sep>#!/bin/bash sudo mkdir /opt/msifix sudo chmod o+rw /opt/msifix set -x echo "starting... v1" >> /opt/msifix/out.log echo $(date +"%T") >> /opt/msifix/out.log echo $(date) " - Starting Script" echo $(date) " - Setting kubeconfig" export KUBECONFIG=/var/lib/kubelet/kubeconfig echo $(date) " - Waiting for API Server to start" kubernetesStarted=1 for i in {1..600}; do if [ -e /usr/local/bin/kubectl ] then if /usr/local/bin/kubectl cluster-info then echo "kubernetes started" kubernetesStarted=0 break fi else if /usr/bin/docker ps | grep apiserver then echo "kubernetes started" kubernetesStarted=0 break fi fi sleep 1 done if [ $kubernetesStarted -ne 0 ] then echo "kubernetes did not start" exit 1 fi master_nodes() { kubectl get no -L kubernetes.io/role -l kubernetes.io/role=master --no-headers -o jsonpath="{.items[*].metadata.name}" | tr " " "\n" | sort | head -n 1 } wait_for_master_nodes() { ATTEMPTS=90 SLEEP_TIME=10 ITERATION=0 while [[ $ITERATION -lt $ATTEMPTS ]]; do echo $(date) " - Is kubectl returning master nodes? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)" FIRST_K8S_MASTER=$(master_nodes) if [[ -n $FIRST_K8S_MASTER ]]; then echo $(date) " - kubectl is returning master nodes" return fi ITERATION=$(( $ITERATION + 1 )) sleep $SLEEP_TIME done echo $(date) " - kubectl failed to return master nodes in the alotted time" return 1 } if ! wait_for_master_nodes; then echo $(date) " - Error while waiting for kubectl to output master nodes. Exiting" exit 1 fi echo $(date +"%T") >> /opt/msifix/out.log sleep 60 echo $(date +"%T") >> /opt/msifix/out.log sudo docker restart $(docker ps -q) echo $(date +"%T") >> /opt/msifix/out.log PODNAME=$(kubectl -n kube-system get pod -l "component=kube-controller-manager" -o jsonpath='{.items[0].metadata.name}') kubectl -n kube-system logs $PODNAME >> /opt/msifix/out.log echo $(date +"%T") >> /opt/msifix/out.log<file_sep>var config = {} config.port = process.env.PORT || 80; config.metricReset = process.env.METRICRESET || 2; config.name = process.env.NAME || "default"; module.exports = config; <file_sep># Azure DNS https://github.com/kubernetes-incubator/external-dns/blob/master/docs/tutorials/azure.md https://github.com/helm/charts/tree/master/stable/external-dns ``` az network dns zone create -g $KUBE_GROUP -n example.com ``` https://stackoverflow.com/questions/53290626/can-aks-be-configured-to-work-with-an-azure-private-dns-zone publishInternalServices=true<file_sep>#!/bin/bash set -e # infrastructure deployment properties PROJECT_NAME="$1" LOCATION="$2" CONTROLLER_IDENTITY_NAME="$3" AKS_SUBNET_RESOURCE_ID="$4" AKS_ADMINGROUP_ID="$5" if [ "$PROJECT_NAME" == "" ]; then echo "No project name provided - aborting" exit 0; fi if [ "$LOCATION" == "" ]; then echo "No location provided - aborting" exit 0; fi if [[ $PROJECT_NAME =~ ^[a-z0-9]{5,9}$ ]]; then echo "project name $PROJECT_NAME is valid" else echo "project name $PROJECT_NAME is invalid - only numbers and lower case min 5 and max 8 characters allowed - aborting" exit 0; fi RESOURCE_GROUP="$PROJECT_NAME" AZURE_CORE_ONLY_SHOW_ERRORS="True" if [ $(az group exists --name $RESOURCE_GROUP) = false ]; then echo "creating resource group $RESOURCE_GROUP..." az group create -n $RESOURCE_GROUP -l $LOCATION -o none echo "resource group $RESOURCE_GROUP created" else echo "resource group $RESOURCE_GROUP already exists" LOCATION=$(az group show -n $RESOURCE_GROUP --query location -o tsv) fi AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $RESOURCE_GROUP --query "[?contains(name, '$CONTROLLER_IDENTITY_NAME')].id" -o tsv)" if [ "$AKS_CONTROLLER_RESOURCE_ID" == "" ]; then echo "controller identity $CONTROLLER_IDENTITY_NAME does not exist in resource group $RESOURCE_GROUP" exit 0; else echo "controller identity $AKS_CONTROLLER_RESOURCE_ID already exists" fi echo "aks subnet $AKS_SUBNET_RESOURCE_ID" az deployment group create -g $RESOURCE_GROUP -f ./main.bicep -p projectName=$PROJECT_NAME -p controllerIdentity=$AKS_CONTROLLER_RESOURCE_ID -p nodePoolSubnetId=$AKS_SUBNET_RESOURCE_ID -p aksAdminGroupId=$AKS_ADMINGROUP_ID -o none <file_sep># deploy demo apps ``` DEMO_NS=demo export CRASHING_APP_IP=$(kubectl get svc --namespace $DEMO_NS crashing-app -o jsonpath='{.status.loadBalancer.ingress[0].ip}') export DUMMY_LOGGER_IP=$(kubectl get svc --namespace $DEMO_NS dummy-logger-svc-lb -o jsonpath='{.status.loadBalancer.ingress[0].ip}') export DUMMY_LOGGER_IP=$(kubectl get svc dummy-logger-pub-lb -o jsonpath='{.status.loadBalancer.ingress[0].ip}') curl -X POST http://$DUMMY_LOGGER_IP/api/log -H "message: {more: content}" curl -X POST http://$DUMMY_LOGGER_IP/api/log -H "message: hi" for i in {1..100}; do curl -s -w "%{time_total}\n" -o /dev/null -X POST http://$DUMMY_LOGGER_IP/api/log -H "message: hi"; done for i in {1..100000}; do curl -s -w "%{time_total}\n" -X POST http://$DUMMY_LOGGER_IP/api/log -H "message: hi $i"; done curl -X GET http://$CRASHING_APP_IP/crash ``` Built in issue detection https://docs.microsoft.com/en-gb/azure/azure-monitor/insights/container-insights-analyze?toc=%2Fazure%2Fmonitoring%2Ftoc.json#view-performance-directly-from-an-aks-cluster az role assignment create --assignee 88cf3744-9ed9-4d55-a563-e027e7f8687f --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$KUBE_GROUP/providers/Microsoft.ContainerService/managedClusters/$KUBE_NAME --role "Monitoring Metrics Publisher" # cluster health https://docs.microsoft.com/en-us/azure/azure-monitor/insights/container-insights-health # coredns ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: ConfigMap metadata: name: coredns-custom namespace: kube-system data: log.override: | log EOF ``` ``` InsightsMetrics | where Namespace contains "prometheus" | where TimeGenerated > ago(1h) | where Name startswith "coredns_" | summarize max(Val) by Name, bin(TimeGenerated, 1m) | render timechart InsightsMetrics | where Namespace contains "prometheus" | where TimeGenerated > ago(1h) | where Name == "coredns_forward_request_duration_seconds" or Name == "coredns_dns_request_duration_seconds" | summarize max(Val) by Name, bin(TimeGenerated, 1m) | render timechart ``` ## Full stack ``` kubectl create namespace monitoring helm repo add prometheus-operator https://kubernetes-charts.storage.googleapis.com helm repo add loki https://grafana.github.io/loki/charts helm repo add promtail https://grafana.github.io/loki/charts helm repo update helm upgrade --install po prometheus-operator/prometheus-operator -n=monitoring helm upgrade --install loki -n=monitoring loki/loki-stack --set grafana.enabled=true,prometheus.enabled=true,prometheus.alertmanager.persistentVolume.enabled=true,prometheus.server.persistentVolume.enabled=true,persistence.enabled=true helm upgrade --install promtail -n=monitoring promtail/promtail kubectl get secret --namespace monitoring loki-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo kubectl port-forward --namespace monitoring service/loki-grafana 3000:80 ``` ## Loki https://github.com/grafana/helm-charts/blob/main/charts/grafana/README.md ``` helm repo add grafana https://grafana.github.io/helm-charts helm repo update ``` ## Troubleshooting Logs https://raw.githubusercontent.com/microsoft/Docker-Provider/ci_prod/kubernetes/container-azm-ms-agentconfig.yaml ``` KUBE_NAME= LOCATION=westeurope KUBE_GROUP=kub_ter_a_m_$KUBE_NAME KUBE_VERSION=1.19.7 az rest --method get --url "https://management.azure.com/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft. OperationalInsights/workspaces/$KUBE_NAME-lga/tables/ContainerLog?api-version=2020-10-01" az rest --method get --url "https://management.azure.com/subscriptions//resourceGroups/dzcheapobs/providers/Microsoft.OperationalInsights/workspaces/dzcheapobs/tables/ContainerLog?api-version=2020-10-01" { "name": "ContainerLog", "properties": { "isTroubleshootingAllowed": true, "isTroubleshootEnabled": true, "retentionInDays": 30 }, } az rest --method put --url "https://management.azure.com/subscriptions//resourceGroups/dzcheapobs/providers/Microsoft.OperationalInsights/workspaces/dzcheapobs/tables/ContainerLog?api-version=2020-10-01" --body @container_log.json wget https://raw.githubusercontent.com/microsoft/Docker-Provider/ci_prod/kubernetes/container-azm-ms-agentconfig.yaml ``` ## API Server Statistics Requests per minute by VERB | where PreciseTimeStamp >= datetime({startTime}) and PreciseTimeStamp < datetime({endTime}) | where resourceID == | where category == 'kube-audit' | extend event=parse_json(tostring(parse_json(properties).log)) | where event.stage == "ResponseComplete" | where event.verb != "watch" | where event.objectRef.subresource !in ("proxy", "exec") | extend verb=tostring(event.verb) | extend subresource=tostring(event.objectRef.subresource) | summarize count() by bin(PreciseTimeStamp, 1m), verb Request latency per VERB | where PreciseTimeStamp >= datetime({startTime}) and PreciseTimeStamp < datetime({endTime}) | where resourceID == <<Customer cluster resourceID >> AzureDiagnostics | where category == 'kube-audit' | extend event=parse_json(tostring(parse_json(properties).log)) | where event.stage == "ResponseComplete" | where event.verb != "watch" | where event.objectRef.subresource !in ("proxy", "exec") | extend verb=tostring(event.verb) | extend subresource=tostring(event.objectRef.subresource) | extend latency=datetime_diff('Millisecond', todatetime(event.stageTimestamp), todatetime(event.requestReceivedTimestamp)) | summarize max(latency), avg(latency) by bin(PreciseTimeStamp, 1m), verb Number of watchers | where PreciseTimeStamp >= datetime({startTime}) and PreciseTimeStamp < datetime({endTime}) | where resourceID == <<Customer cluster resourceID >> AzureDiagnostics | where category == 'kube-audit' | extend event=parse_json(tostring(parse_json(properties).log)) | where event.stage == "ResponseComplete" | where event.verb != "watch" | where event.objectRef.subresource !in ("proxy", "exec") | extend verb=tostring(event.verb) | extend code=tostring(event.responseStatus.code) | extend subresource=tostring(event.objectRef.subresource) | extend lat=datetime_diff('Millisecond', todatetime(event.stageTimestamp), todatetime(event.requestReceivedTimestamp)) | summarize count() by bin(PreciseTimeStamp, 1m), code az deployment group create --resource-group $KUBE_GROUP --template-file ./existingClusterOnboarding.json --parameters @./existingClusterParam.json <file_sep># Jaeger https://blog.nobugware.com/post/2019/kubernetes_quick_development_setup_minikube_prometheus_grafana/ https://github.com/jaegertracing/jaeger-kubernetes/#production-setup https://github.com/jaegertracing/jaeger/issues/1105 https://github.com/jaegertracing/jaeger/issues/1752 LOCATION="westeurope" NODE_GROUP=MC_kub_ter_a_s_tracing9_tracing9_westeurope KUBE_GROUP=kub_ter_a_s_tracing9 KUBE_NAME=tracing9 IP_NAME=traefik-ingress-pip MY_ID= CASSANDRA_GROUP=tracing CASSANDRA_NAME=dztraces CASSANDRA_HOST=$CASSANDRA_NAME.cassandra.cosmos.azure.com CASSANDRA_PASSWORD= CASSANDRA_PORT=10350 CASSANDRA_USERNAME=dztraces CASSANDRA_KEYSPACE=traces 0. create cosmosdb and keyspace ``` az group create -n $CASSANDRA_GROUP -l $LOCATION az cosmosdb create --name $CASSANDRA_NAME --resource-group $CASSANDRA_GROUP --capabilities EnableCassandra --enable-automatic-failover false --enable-multiple-write-locations false --enable-virtual-network false --kind GlobalDocumentDB CASSANDRA_PASSWORD=$(az cosmosdb keys list --name $CASSANDRA_NAME --resource-group $CASSANDRA_GROUP --type keys --query "primaryMasterKey" | tr -d '"') az cosmosdb cassandra keyspace create --name $CASSANDRA_KEYSPACE --account-name $CASSANDRA_NAME --resource-group $CASSANDRA_GROUP az cosmosdb cassandra keyspace list --account-name $CASSANDRA_NAME --resource-group $CASSANDRA_GROUP ``` 0. deploy jaeger schema ``` docker pull jaegertracing/jaeger-query:latest docker pull jaegertracing/jaeger-cassandra-schema:latest docker run -d --restart always \ --name jaeger-query \ -e CASSANDRA_SERVERS=$CASSANDRA_HOST \ -e CASSANDRA_PORT=10350 \ -e CASSANDRA_PASSWORD=$CASSANDRA_PASSWORD \ -e CASSANDRA_USERNAME=$CASSANDRA_USERNAME \ -e CASSANDRA_TLS=true \ -e CASSANDRA_KEYSPACE=$CASSANDRA_KEYSPACE \ -e CASSANDRA_CONNECTIONS_PER_HOST=1 \ -e CASSANDRA_TLS_VERIFY_HOST=false \ jaegertracing/jaeger-query:latest docker run --rm -it -e CASSANDRA_USER=$CASSANDRA_USERNAME -e CASSANDRA_PASS=$<PASSWORD> -e CASSANDRA_HOST=$CASSANDRA_HOST -e SSL_VALIDATE=false -e SSL_VERSION=TLSv1_2 -e keyspace=$CASSANDRA_KEYSPACE -e replication=1 -e trace_ttl=172800 -e dependencies_ttl=0 --entrypoint bash jaegertracing/jaeger-cassandra-schema:latest -c 'sed -e "s/--.*$//g" -e "/^\s*$/d" -e "s/\${keyspace}/${keyspace}/" -e "s/\${replication}/${replication}/" -e "s/\${trace_ttl}/${trace_ttl}/" -e "s/\${dependencies_ttl}/${dependencies_ttl}/" /cassandra-schema/v001.cql.tmpl > /cassandra-schema/v001.cql ; cqlsh ${CASSANDRA_HOST} 10350 -u ${CASSANDRA_USER} -p ${CASSANDRA_PASS} --ssl -f /cassandra-schema/v001.cql' ``` Output of schema creation ``` /cassandra-schema/v001.cql:11:SyntaxException: line 9:233 no viable alternative at input ') (... text, value_bool boolean, value_long bigint, value_double double, value_binary blob, )...) /cassandra-schema/v001.cql:15:SyntaxException: line 4:95 no viable alternative at input ') (... bigint, fields list<frozen<keyvalue>>, )...) /cassandra-schema/v001.cql:20:SyntaxException: line 5:124 no viable alternative at input ') (...ext, trace_id blob, span_id bigint, )...) /cassandra-schema/v001.cql:24:SyntaxException: line 4:113 no viable alternative at input ') (..._name text, tags list<frozen<keyvalue>>, )...) /cassandra-schema/v001.cql:48:InvalidRequest: Error from server: code=2200 [Invalid query] message="gc_grace_seconds value must be zero." /cassandra-schema/v001.cql:61:InvalidRequest: Error from server: code=2200 [Invalid query] message="gc_grace_seconds value must be zero." /cassandra-schema/v001.cql:75:InvalidRequest: Error from server: code=2200 [Invalid query] message="gc_grace_seconds value must be zero." /cassandra-schema/v001.cql:91:InvalidRequest: Error from server: code=2200 [Invalid query] message="gc_grace_seconds value must be zero." /cassandra-schema/v001.cql:107:InvalidRequest: Error from server: code=2200 [Invalid query] message="gc_grace_seconds value must be zero." /cassandra-schema/v001.cql:125:InvalidRequest: Error from server: code=2200 [Invalid query] message="gc_grace_seconds value must be zero." /cassandra-schema/v001.cql:144:InvalidRequest: Error from server: code=2200 [Invalid query] message="gc_grace_seconds value must be zero." /cassandra-schema/v001.cql:149:SyntaxException: line 5:126 no viable alternative at input ') (...ext, child text, call_count bigint, )...) /cassandra-schema/v001.cql:161:InvalidRequest: Error from server: code=2200 [Invalid query] message="Unknown type traces.dependency" /cassandra-schema/v001.cql:164:ConfigurationException: When using custom indexes, must have a class name and set to a supported class. Supported class names are ['CosmosDefaultIndex','AzureSearchIndex','CosmosClusteringIndex'] Got 'org.apache.cassandra.index.sasi.SASIIndex' ``` drop keyspace jaeger_v1_test; CREATE KEYSPACE IF NOT EXISTS jaeger_v1_test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}; CREATE TYPE IF NOT EXISTS jaeger_v1_test.keyvalue ("key" text,"value_type" text,"value_string" text,"value_bool" boolean,"value_long" bigint,"value_double" double,"value_binary" blob); CREATE TYPE IF NOT EXISTS jaeger_v1_test.log ("ts" bigint,"fields" list<frozen>); CREATE TYPE IF NOT EXISTS jaeger_v1_test.span_ref ("ref_type" text,"trace_id" blob,"span_id" bigint); CREATE TYPE IF NOT EXISTS jaeger_v1_test.process ("service_name" text,"tags" list<frozen>); CREATE TABLE IF NOT EXISTS jaeger_v1_test.traces ("trace_id" blob,"span_id" bigint,"span_hash" bigint,"parent_id" bigint,"operation_name" text,"flags" int,"start_time" bigint,"duration" bigint,"tags" list<frozen>,"logs" list<frozen>,"refs" list<frozen<span_ref>>,"process" frozen,PRIMARY KEY (trace_id, span_id, span_hash)) WITH compaction = {'compaction_window_size': '1','compaction_window_unit': 'HOURS','class': 'org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy'} AND dclocal_read_repair_chance = 0.0 AND default_time_to_live = 172800 AND speculative_retry = 'NONE' AND gc_grace_seconds = 0; CREATE TABLE IF NOT EXISTS jaeger_v1_test.service_names ("service_name" text,PRIMARY KEY ("service_name")) WITH compaction = {'min_threshold': '4','max_threshold': '32','class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'} AND dclocal_read_repair_chance = 0.0 AND default_time_to_live = 172800 AND speculative_retry = 'NONE' AND gc_grace_seconds = 0; CREATE TABLE IF NOT EXISTS jaeger_v1_test.operation_names ("service_name" text,"operation_name" text,PRIMARY KEY (("service_name"), "operation_name")) WITH compaction = {'min_threshold': '4','max_threshold': '32','class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'} AND dclocal_read_repair_chance = 0.0 AND default_time_to_live = 172800 AND speculative_retry = 'NONE' AND gc_grace_seconds = 0; CREATE TABLE IF NOT EXISTS jaeger_v1_test.service_operation_index ("service_name" text,"operation_name" text,"start_time" bigint,"trace_id" blob,PRIMARY KEY (("service_name", "operation_name"), "start_time")) WITH CLUSTERING ORDER BY (start_time DESC) AND compaction = {'compaction_window_size': '1','compaction_window_unit': 'HOURS','class': 'org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy'} AND dclocal_read_repair_chance = 0.0 AND default_time_to_live = 172800 AND speculative_retry = 'NONE' AND gc_grace_seconds = 0; CREATE TABLE IF NOT EXISTS jaeger_v1_test.service_name_index ("service_name" text,"bucket" int,"start_time" bigint,"trace_id" blob,PRIMARY KEY (("service_name", "bucket"), "start_time")) WITH CLUSTERING ORDER BY (start_time DESC) AND compaction = {'compaction_window_size': '1','compaction_window_unit': 'HOURS','class': 'org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy'} AND dclocal_read_repair_chance = 0.0 AND default_time_to_live = 172800 AND speculative_retry = 'NONE' AND gc_grace_seconds = 0; CREATE TABLE IF NOT EXISTS jaeger_v1_test.duration_index ("service_name" text,"operation_name" text,"bucket" timestamp, "duration" bigint,"start_time" bigint,"trace_id" blob, PRIMARY KEY ((service_name, operation_name, bucket), "duration", start_time, trace_id)) WITH CLUSTERING ORDER BY ("duration" DESC, start_time DESC, trace_id DESC) AND compaction = {'compaction_window_size': '1', 'compaction_window_unit': 'HOURS', 'class': 'org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy'} AND dclocal_read_repair_chance = 0.0 AND default_time_to_live = 172800 AND speculative_retry = 'NONE' AND gc_grace_seconds = 0; CREATE TABLE IF NOT EXISTS jaeger_v1_test.tag_index (service_name text,tag_key text,tag_value text,start_time bigint,trace_id blob,span_id bigint,PRIMARY KEY ((service_name, tag_key, tag_value), start_time, trace_id, span_id)) WITH CLUSTERING ORDER BY (start_time DESC, trace_id DESC, span_id DESC) AND compaction = {'compaction_window_size': '1','compaction_window_unit': 'HOURS','class': 'org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy'} AND dclocal_read_repair_chance = 0.0 AND default_time_to_live = 172800 AND speculative_retry = 'NONE' AND gc_grace_seconds = 0; CREATE TYPE IF NOT EXISTS jaeger_v1_test.dependency ("parent" text,"child" text,"call_count" bigint); CREATE TABLE IF NOT EXISTS jaeger_v1_test.dependencies (ts timestamp,ts_index timestamp,dependencies list<frozen>,PRIMARY KEY (ts)) WITH compaction = {'min_threshold': '4','max_threshold': '32','class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'} AND default_time_to_live = 0; CREATE CUSTOM INDEX ON jaeger_v1_test.dependencies (ts_index) USING 'org.apache.cassandra.index.sasi.SASIIndex' WITH OPTIONS = {'mode': 'SPARSE'}; DNS=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query dnsSettings.fqdn --output tsv) IP=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query ipAddress --output tsv) helm upgrade traefikingress stable/traefik --install --namespace kube-system --set dashboard.enabled=true,dashboard.domain=dashboard.localhost,rbac.enabled=true,loadBalancerIP=$IP,externalTrafficPolicy=Local,replicas=1,ssl.enabled=true,ssl.permanentRedirect=true,ssl.insecureSkipVerify=true,acme.enabled=true,acme.challengeType=http-01,acme.email=$MY_ID,acme.staging=false helm upgrade grafana stable/grafana --install --set ingress.enabled=true --set ingress.hosts\[0\]=grafana.localhost --set persistence.enabled=true --set persistence.size=100Mi --namespace grafana helm upgrade prometheus stable/prometheus --install --set server.ingress.enabled=true --set server.ingress.hosts\[0\]=prometheus.localhost --set alertmanager.enabled=false --set kubeStateMetrics.enabled=false --set nodeExporter.enabled=false --set server.persistentVolume.enabled=true --set server.persistentVolume.size=1Gi --set pushgateway.enabled=false --namespaces prometheus jaeger_v1_dc1 helm template incubator/jaeger --name myjaeger --set provisionDataStore.cassandra=false --set storage.cassandra.host=$CASSANDRA_HOST --set storage.cassandra.port=$CASSANDRA_PORT --set storage.cassandra.user=$CASSANDRA_USERNAME --set storage.cassandra.password=$<PASSWORD> --set hotrod.enabled=true > jaeger.yaml helm upgrade myjaeger incubator/jaeger --install --set provisionDataStore.cassandra=false --set storage.cassandra.host=$CASSANDRA_HOST --set storage.cassandra.port=$CASSANDRA_PORT --set storage.cassandra.user=$CASSANDRA_USERNAME --set storage.cassandra.password=$<PASSWORD> helm install incubator/jaeger --name myrel --set cassandra.config.max_heap_size=512M --set cassandra.config.heap_new_size=256M --set cassandra.resources.requests.memory=512Mi --set cassandra.resources.requests.cpu=0.4 --set cassandra.resources.limits.memory=1024Mi --set cassandra.resources.limits.cpu=0.4 --namespace jaegerkube kubectl apply -f https://raw.githubusercontent.com/jaegertracing/jaeger-kubernetes/master/all-in-one/jaeger-all-in-one-template.yml kubectl -n default port-forward $(kubectl get pod -l app.kubernetes.io/component=hotrod -o jsonpath='{.items[0].metadata.name}') 8081:8080 https://github.com/helm/charts/tree/master/stable/traefik helm upgrade traefikingress stable/traefik --install --namespace kube-system --set dashboard.enabled=true,dashboard.domain=dashboard.localhost,rbac.enabled=true,loadBalancerIP=$IP,externalTrafficPolicy=Local,replicas=1,ssl.enabled=true,ssl.permanentRedirect=true,ssl.insecureSkipVerify=true,acme.enabled=true,acme.challengeType=http-01,acme.email=$MY_ID,acme.staging=false,tracing.enabled=true,tracing.backend=jaeger,tracing.jaeger.localAgentHostPort=myjaeger-agent:6831,tracing.serviceName=jaeger,tracing.jaeger.samplingServerUrl=myjaeger-agent:5778/sampling tracing9.westeurope.cloudapp.azure.com 172.16.17.32 driver=T769745C cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: hotrod annotations: kubernetes.io/ingress.class: traefik ingress.kubernetes.io/whitelist-x-forwarded-for: "true" traefik.ingress.kubernetes.io/redirect-permanent: "false" traefik.ingress.kubernetes.io/preserve-host: "true" spec: rules: - host: $DNS http: paths: - path: / backend: serviceName: myjaeger-hotrod servicePort: 80 EOF <file_sep>https://docs.microsoft.com/en-gb/java/openjdk/containers#create-a-custom-java-runtime<file_sep> ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: debian spec: containers: - name: debian image: debian ports: - containerPort: 80 command: - sleep - "3600" EOF postStart: exec: command: - /bin/sh - -c - "/bin/echo 'options single-request-reopen' >> /etc/resolv.conf" cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: centoss-deployment labels: app: centos spec: replicas: 1 selector: matchLabels: app: centoss template: metadata: labels: app: centoss spec: containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF for i in {1..1000}; do curl -s -w "%{time_total}\n" -o /dev/null http://www.microsoft.com/; done for i in {1..1000}; do curl -s -w "%{time_total}\n" -o /dev/null http://http://192.168.3.11; done kubectl delete pod -n kube-system --selector="k8s-app=kube-dns" kubectl delete pod -n kube-system --selector="component=azure-cni-networkmonitor" kubectl delete pod -n kube-system --selector="component=kube-svc-redirect" kubectl delete pod centos kubectl delete deployment centoss-deployment6 while(true); do sleep 1; kubectl delete pod -n kube-system --selector "component=azure-cni-networkmonitor"; done component=kube-svc-redirect sudo apt-get update sudo apt-get install linux-image-4.15.0-1030-azure sudo systemctl reboot repro cni kubectl exec -ti centos -- /bin/bash [root@centos /]# for i in {1..100}; do curl -s -w "%{time_total}\n" -o /dev/null http://www.bing.com/; done 5.593 5.596 0.096 0.101 5.602 0.110 for i in `seq 1 1000`;do time nslookup kubernetes.default; done We are still getting customer feedback that are complaining about dns timeouts after applying the kernel patch. However what is different that the timeouts are no longer visible in empty clusters - therefore here a set of things I have done to get some load. I used a centos for testing cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: debian spec: containers: - name: debian image: debian ports: - containerPort: 80 command: - sleep - "3600" EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: dnstools spec: containers: - name: dnstools image: ngayall/dnstools ports: - containerPort: 80 command: - sleep - "3600" EOF dnstools# dig +short @169.254.20.10 google.com 192.168.127.12 dnstools# dig +short @10.0.0.10 google.com ;; connection timed out; no servers could be reached dnstools# dig +short google.com ;; connection timed out; no servers could be reached cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: redis labels: name: redis spec: containers: - name: redis image: redis:4.0.11-alpine args: ["--requirepass", "<PASSWORD>"] ports: - containerPort: 6379 --- apiVersion: v1 kind: Pod metadata: name: rediscli labels: name: rediscli spec: containers: - name: redis image: redis --- apiVersion: v1 kind: Service metadata: name: redis-svc labels: name: redis-svc spec: selector: name: redis type: ClusterIP ports: - port: 6379 targetPort: 6379 protocol: TCP EOF redis-cli -h redis-svc -p 6379 -a MySuperSecretRedis ping redis-cli -h redis-svc -p 6379 ping I also used bing for testing the dns timeout (just in case google was messing with us ;) kubectl exec -ti centos -- /bin/bash for i in {1..100}; do curl -s -w "%{time_total}\n" -o /dev/null http://www.google.com/; done Without the kernel patch the dns timeout occurs like clockwork almost every 5-10 calls [root@centos /]# for i in {1..100}; do curl -s -w "%{time_total}\n" -o /dev/null http://www.bing.com/; done 5.593 5.596 0.096 0.101 5.602 However after applying the kernel patch and rebooting all nodes I cannot repro the dns timeout on kubenet based clusters (that is promising). However I can repro it on my azure cni based cluster with the following setup (and some load in the cluster). I need to have some load inside the cluster therefore I launch the azure voting sample kubectl apply -f https://raw.githubusercontent.com/Azure-Samples/azure-voting-app-redis/master/azure-vote-all-in-one-redis.yaml Scale the deployment and generate some load kubectl scale --replicas=20 deployment/azure-vote-front kubectl scale --replicas=3 deployment/azure-vote-back Using chaoskube who is killing random pods after 2 seconds https://github.com/linki/chaoskube cat > asdfas << EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: chaoskube spec: containers: - name: chaoskube image: quay.io/linki/chaoskube:v0.11.0 args: # kill a pod every 10 minutes - --interval=0m1s # only target pods in the test environment - --labels=app=azure-vote-front # exclude all pods in the kube-system namespace - --namespaces=!kube-system - --no-dry-run EOF In addition some random traffic that is hitting the frontend svc of SERVICE_IP=$(kubectl get svc azure-vote-front --template="{{range .status.loadBalancer.ingress}}{{.ip}}{{end}}") for i in {1..1000}; do curl -s -w "%{time_total}\n" -o /dev/null http://$SERVICE_IP; done Now after running the centos I can get a dns timeout for one in 300 curls to bing running this. var=1; while true ; do res=$( { curl -o /dev/null -s -w %{time_namelookup}\\n http://www.bing.com; } 2>&1 ) var=$((var+1)) now=$(date +"%T") if [[ $res =~ ^[1-9] ]]; then now=$(date +"%T") echo "$var slow: $res $now" break fi done var=1; while true ; do res=$( { curl -o /dev/null -s -w %{time_namelookup}\\n http://www.bing.com; } 2>&1 ) var=$((var+1)) now=$(date +"%T") if [[ $res =~ ^[1-9] ]]; then now=$(date +"%T") echo "$var slow: $res $now" break fi done [root@centos /]# while true ; do res=$( { curl -o /dev/null -s -w %{time_namelookup}\\n http://www.bing.com; } 2>&1 ); var=$((var+1)); now=$(date +"%T"); if [[ $res =~ ^[1-9] ]]; then now=$(date +"%T"); echo "$var slow: $res $now"; break; fi; done 183 slow: 10.517 22:09:27 [root@centos /]# while true ; do res=$( { curl -o /dev/null -s -w %{time_namelookup}\\n http://www.bing.com; } 2>&1 ); var=$((var+1)); now=$(date +"%T"); if [[ $res =~ ^[1-9] ]]; then now=$(date +"%T"); echo "$var slow: $res $now"; break; fi; done 204 slow: 10.519 22:10:28 ``` while true ; do res=$( { do time nslookup kubernetes.default } 2>&1 ); var=$((var+1)); now=$(date +"%T"); if [[ $res =~ ^[1-9] ]]; then now=$(date +"%T"); echo "$var slow: $res $now"; break; fi; done for i in `seq 1 100000`;do time nslookup kubernetes.default; sleep 100; done<file_sep># Kubeflow ## Install https://operatorhub.io/operator/kubeflow ``` curl -sL https://github.com/operator-framework/operator-lifecycle-manager/releases/download/v0.20.0/install.sh | bash -s v0.20.0 kubectl create -f https://operatorhub.io/install/kubeflow.yaml kubectl get csv -n operators kubectl get pod -n operators https://github.com/kubeflow/manifests/blob/v1.2-branch/kfdef/kfctl_azure_aad.v1.2.0.yaml ```<file_sep># kubectl create ns jenkins helm install my-jenkins stable/jenkins -n jenkins printf $(kubectl get secret --namespace jenkins my-jenkins -o jsonpath="{.data.jenkins-admin-password}" | base64 --decode);echo export POD_NAME=$(kubectl get pods --namespace jenkins -l "app.kubernetes.io/component=jenkins-master" -l "app.kubernetes.io/instance=my-jenkins" -o jsonpath="{.items[0].metadata.name}") echo http://127.0.0.1:8080 kubectl --namespace jenkins port-forward $POD_NAME 8080:8080<file_sep># Nginx https://github.com/kubernetes/ingress-nginx/blob/master/docs/user-guide/nginx-configuration/annotations.md https://github.com/kubernetes/ingress-nginx/blob/master/charts/ingress-nginx/values.yaml ## Install nginx ``` NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) IP_NAME=k$KUBE_NAME az network public-ip create --resource-group $NODE_GROUP --name $IP_NAME --sku Standard --allocation-method static --dns-name dznginx IP=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query ipAddress --output tsv) DNS=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query dnsSettings.fqdn --output tsv) helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx helm repo update helm search repo nginx-ingress AKS_CONTROLLER_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-ctl-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-clt-id')].id" -o tsv)" IP_ID=$(az network public-ip list -g $KUBE_GROUP --query "[?contains(name, 'dznginx')].id" -o tsv) if [ "$IP_ID" == "" ]; then echo "creating ingress ip dznginx" az network public-ip create -g $KUBE_GROUP -n dznginx --sku STANDARD --dns-name k$KUBE_NAME -o none IP_ID=$(az network public-ip show -g $KUBE_GROUP -n dznginx -o tsv --query id) IP=$(az network public-ip show -g $KUBE_GROUP -n dznginx -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n dznginx -o tsv --query dnsSettings.fqdn) echo "created ip $IP_ID with $IP on $DNS" az role assignment create --role "Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $IP_ID -o none else IP=$(az network public-ip show -g $KUBE_GROUP -n dznginx -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n dznginx -o tsv --query dnsSettings.fqdn) echo "AKS $AKS_ID already exists with $IP on $DNS" fi kubectl create ns nginx helm upgrade ingress-nginx ingress-nginx/ingress-nginx --install \ --namespace ingress --create-namespace\ --set controller.replicaCount=2 \ --set controller.metrics.enabled=true \ --set controller.service.loadBalancerIP="$IP" \ --set defaultBackend.enabled=true \ --set controller.service.annotations."service\.beta\.kubernetes\.io/azure-load-balancer-health-probe-request-path"=/healthz \ --set controller.service.externalTrafficPolicy=Local \ --set-string controller.tolerations.app=game \ --set-string controller.nodeSelector.ingress=true \ --set-string controller.service.annotations.'service\.beta\.kubernetes\.io/azure-load-balancer-resource-group'="$KUBE_GROUP" \ --set-string controller.service.annotations.'service\.beta\.kubernetes\.io/azure-pip-name'="dznginx" -f consul-helm/values.yaml helm upgrade my-ingress-controller nginx/nginx-ingress --install --set controller.stats.enabled=true --set controller.replicaCount=2 --set controller.service.externalTrafficPolicy=Local --namespace=nginx helm upgrade my-ingress-controller nginx/nginx-ingress --install --set controller.service.loadBalancerIP="$IP" --set controller.stats.enabled=true --set controller.replicaCount=2 --set controller.service.externalTrafficPolicy=Local --namespace=nginx helm install nginx nginx/nginx-ingress \ --namespace nginx --set controller.service.loadBalancerIP="$IP" --set controller.service.externalTrafficPolicy=Local \ --set controller.replicaCount=2 \ --set controller.nodeSelector."beta\.kubernetes\.io/os"=linux \ --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux helm upgrade my-ingress-controller nginx/nginx-ingress --install --set controller.stats.enabled=true --set controller.replicaCount=2 --set controller.service.externalTrafficPolicy=Local --namespace=nginx ``` ## Metrics ``` InsightsMetrics | extend tags=parse_json(Tags) | where tostring(tags.controller_class) == "nginx" Calculate requests per minute: InsightsMetrics | where Name == "nginx_ingress_controller_nginx_process_connections_total" | summarize Val=any(Val) by TimeGenerated=bin(TimeGenerated, 1m) | sort by TimeGenerated asc | extend RequestsPerMinute = Val - prev(Val) | sort by TimeGenerated desc bar chart InsightsMetrics | where Name == "nginx_ingress_controller_nginx_process_connections_total" | summarize Val=any(Val) by TimeGenerated=bin(TimeGenerated, 1m) | sort by TimeGenerated asc | project RequestsPerMinute = Val - prev(Val), TimeGenerated | render barchart InsightsMetrics | extend tags=parse_json(Tags) | where Name == "nginx_connections_accepted" InsightsMetrics | where Name == "nginx_http_requests_total" | summarize Val=any(Val) by TimeGenerated=bin(TimeGenerated, 1m) | sort by TimeGenerated asc | extend RequestsPerMinute = Val - prev(Val) | sort by TimeGenerated desc InsightsMetrics | where Name == "nginx_http_requests_total" | summarize Val=any(Val) by TimeGenerated=bin(TimeGenerated, 1m) | sort by TimeGenerated asc | project RequestsPerMinute = Val - prev(Val), TimeGenerated | render barchart ``` ## demo app ``` kubectl create deployment hello-echo --image=gcr.io/kuar-demo/kuard-amd64:1 --port=8080 kubectl expose deployment echoserver --type=LoadBalancer --port=8080 --namespace=ingress-basic cat <<EOF | kubectl apply -f - apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: http-dummy-logger-app namespace: default annotations: nginx.ingress.kubernetes.io/rewrite-target: / nginx.ingress.kubernetes.io/enable-modsecurity: "true" nginx.ingress.kubernetes.io/modsecurity-snippet: | SecRuleEngine On SecRule &REQUEST_HEADERS:X-Azure-FDID \"@eq 0\" \"log,deny,id:106,status:403,msg:\'Front Door ID not present\'\" SecRule REQUEST_HEADERS:X-Azure-FDID \"@rx ^(?!4bc12b25-fa53-43c3-ab49-1ec3950b5290).*$\" \"log,deny,id:107,status:403,msg:\'Wrong Front Door ID\'\" spec: ingressClassName: nginx rules: - host: dznginx.eastus.cloudapp.azure.com http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 EOF curl -H "X-Azure-FDID:4bc12b25-fa53-43c3-ab49-1ec3950b5290" dznginx.eastus.cloudapp.azure.com apiVersion: extensions/v1beta1 kind: Ingress metadata: name: kuard annotations: kubernetes.io/ingress.class: "nginx" #cert-manager.io/issuer: "letsencrypt-staging" spec: tls: - hosts: - example.example.com secretName: quickstart-example-tls rules: - host: example.example.com http: paths: - path: / backend: serviceName: kuard servicePort: 80 ``` ## Lets encrypt ``` kubectl label namespace nginx cert-manager.io/disable-validation=true helm repo add jetstack https://charts.jetstack.io helm repo update helm upgrade \ cert-manager --install \ --namespace nginx \ --version v1.3.1 \ --set installCRDs=true \ --set nodeSelector."beta\.kubernetes\.io/os"=linux \ jetstack/cert-manager ``` ## Non HTTP Ingress https://www.nginx.com/blog/announcing-nginx-ingress-controller-for-kubernetes-release-1-7-0/ https://docs.nginx.com/nginx-ingress-controller/configuration/global-configuration/globalconfiguration-resource/ ``` apiVersion: k8s.nginx.org/v1alpha1 kind: GlobalConfiguration metadata: name: nginx-configuration namespace: nginx-ingress spec: listeners: - name: dns-udp port: 5353 protocol: UDP - name: dns-tcp port: 5353 protocol: TCP apiVersion: k8s.nginx.org/v1alpha1 kind: TransportServer metadata: name: dns-tcp spec: listener: name: dns-tcp protocol: TCP upstreams: - name: dns-app service: coredns port: 5353 action: pass: dns-app apiVersion: k8s.nginx.org/v1alpha1 kind: TransportServer metadata: name: secure-app spec: listener: name: tls-passthrough protocol: TLS_PASSTHROUGH host: app.example.com upstreams: - name: secure-app service: secure-app port: 8443 action: pass: secure-app ``` https://github.com/nginxinc/kubernetes-ingress/tree/v1.7.0-rc1/examples-of-custom-resources/basic-tcp-udp ``` docker run -p 8080:8080 hashicorp/http-echo -listen=:8080 -text="hello world" ```<file_sep># Setting up oauth2 on your ingress https://github.com/helm/charts/tree/master/stable/oauth2-proxy https://geek-cookbook.funkypenguin.co.nz/reference/oauth_proxy/ Requirements - nginx ingress controller deployed with dns - trusted ssl certificate (letsencrypt-prod) on your dns - use https://github.com/buzzfeed/sso instead of oauthproxy - https://github.com/pusher/oauth2_proxy sample for azure ad https://github.com/brbarnett/k8s-aad-auth/tree/master/k8s-manifests ## Register an app Using github auth: https://github.com/settings/applications/new Using azure ad: https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#create-an-azure-active-directory-application use the following sign-on url https://$DNSNAME.westeurope.cloudapp.azure.com/oauth2/callback https://$DNSNAME.westeurope.cloudapp.azure.com/oauth2 azuread ``` API_CLIENT_ID= API_CLIENT_SECRET= AZURE_TENANT_ID= API_COOKIE_SECRET= ``` github ``` API_CLIENT_ID= API_CLIENT_SECRET= API_COOKIE_SECRET= ``` generate cookie secret: python -c 'import os,base64; print base64.b64encode(os.urandom(16))' ## Deploy oauth2 proxy for github ``` helm install --name authproxy \ --namespace=kube-system \ --set config.clientID=$API_CLIENT_ID \ --set config.clientSecret=$API_CLIENT_SECRET \ --set config.cookieSecret=$API_COOKIE_SECRET \ --set extraArgs.provider=github \ stable/oauth2-proxy ```` for azure ad ``` helm install --name authproxy \ --namespace=kube-system \ --set config.clientID=$API_CLIENT_ID \ --set config.clientSecret=$API_CLIENT_SECRET \ --set config.cookieSecret=$API_COOKIE_SECRET \ --set extraArgs.provider=azure \ stable/oauth2-proxy ``` ``` set args - args: - --provider=azure - --email-domain=.com - --upstream=file:///dev/null - --http-address=0.0.0.0:4180 - --azure-tenant=$AZURE_TENANT_ID ``` set up without helm chart ``` cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: oauth2-proxy namespace: kube-system spec: replicas: 1 selector: matchLabels: app: oauth2-proxy template: metadata: labels: app: oauth2-proxy spec: containers: - args: - --provider=azure - --email-domain=microsoft.com - --upstream=file:///dev/null - --http-address=0.0.0.0:4180 - --azure-tenant=$AZURE_TENANT_ID env: - name: OAUTH2_PROXY_CLIENT_ID value: $API_CLIENT_ID - name: OAUTH2_PROXY_CLIENT_SECRET value: $API_CLIENT_SECRET - name: OAUTH2_PROXY_COOKIE_SECRET value: $API_COOKIE_SECRET image: docker.io/colemickens/oauth2_proxy:latest imagePullPolicy: Always name: oauth2-proxy ports: - containerPort: 4180 protocol: TCP EOF cat <<EOF | kubectl create -f - apiVersion: v1 kind: Service metadata: name: oauth2-proxy namespace: kube-system spec: ports: - name: http port: 4180 protocol: TCP targetPort: 4180 selector: app: oauth2-proxy EOF cat <<EOF | kubectl create -f - apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: oauth2-proxy-ingress namespace: kube-system annotations: kubernetes.io/ingress.class: nginx kubernetes.io/tls-acme: "true" spec: tls: - hosts: - $DNS secretName: hello-tls-secret rules: - host: $DNS http: paths: - path: /oauth2 backend: serviceName: oauth2-proxy servicePort: 4180 EOF cat <<EOF | kubectl apply -f - apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: hello-auth annotations: kubernetes.io/ingress.class: nginx kubernetes.io/tls-acme: "true" nginx.ingress.kubernetes.io/rewrite-target: / nginx.ingress.kubernetes.io/auth-url: "https://\$host/oauth2/auth" nginx.ingress.kubernetes.io/auth-signin: "https://\$host/oauth2/start" #nginx.ingress.kubernetes.io/auth-url: "http://oauth2-proxy.kube-system.svc.cluster.local:80/oauth2/auth" #nginx.ingress.kubernetes.io/auth-signin: "http://\$host/oauth2/start?rd=\$request_uri" spec: tls: - hosts: - $DNS secretName: hello-tls-secret rules: - host: $DNS http: paths: - backend: serviceName: hello-app servicePort: 80 path: /hello-auth EOF #### old create the ingress with oauth2 support ``` cat <<EOF | kubectl create -f - apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: authproxy-ingress namespace: kube-system annotations: kubernetes.io/ingress.class: nginx kubernetes.io/tls-acme: "true" spec: tls: - hosts: - $DNS secretName: hello-tls-secret rules: - host: $DNS http: paths: - backend: serviceName: authproxy-oauth2-proxy servicePort: 80 path: /oauth2 EOF ``` Create dummy app ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/aci-helloworld/helloapp.yaml kubectl expose deployment hello-app ``` Deploy ingress for service ``` cat <<EOF | kubectl create -f - apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: hello-external-oauth2 annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/rewrite-target: / certmanager.k8s.io/cluster-issuer: letsencrypt-prod kubernetes.io/ingress.class: nginx kubernetes.io/tls-acme: "true" nginx.ingress.kubernetes.io/auth-url: "http://authproxy-oauth2-proxy.kube-system.svc.cluster.local:80/oauth2/auth" nginx.ingress.kubernetes.io/auth-signin: "http://\$host/oauth2/start?rd=\$request_uri" spec: tls: - hosts: - dzapi.westus.cloudapp.azure.com secretName: hello-tls-secret rules: - host: dzapi.westus.cloudapp.azure.com http: paths: - backend: serviceName: hello-app servicePort: 80 path: /demo EOF ``` a reload of the backend and ingress controller may be required cleanup ``` kubectl delete ingress hello-external-oauth2 kubectl delete deployment hello-app kubectl delete service hello-app kubectl delete ingress authproxy-ingress -n kube-system helm delete authproxy --purge ```<file_sep>Ingress - https://www.express-gateway.io/ - https://github.com/kubernetes-incubator/external-dns/blob/master/docs/tutorials/azure.md - https://k8s.af - https://github.com/GoogleCloudPlatform/metacontroller - headless auth - https://github.com/cosh/PrometheusToAdx - https://github.com/Azure/aks-periscope/blob/master/README.md - https://github.com/bitnami-labs/sealed-secrets - https://github.com/microsoft/IgniteTheTour/tree/master/MIG%20-%20Migrating%20Applications%20to%20the%20Cloud/MIG50 - https://github.com/lucky-sideburn/KubeInvaders - https://github.com/karydia/karydia - https://github.com/nirmata/kube-static-egress-ip - https://stian.tech/disk-performance-on-aks-part-1/ - https://github.com/microsoft/Application-Insights-K8s-Codeless-Attach - https://github.com/weinong/kubectl-aad-login and https://github.com/weinong/kubelogin-azure - https://github.com/cncf/financial-user-group/tree/master/projects/k8s-threat-model - https://github.com/kubernetes-simulator/simulator - https://medium.com/hashicorp-engineering/hashicorp-vault-delivering-secrets-with-kubernetes-1b358c03b2a3 - https://github.com/dmauser/PrivateLink/tree/master/DNS-Integration-Scenarios#74-server-name-indication-sni-on-tls-request-client-hello GPU https://github.com/microsoft/az-deep-realtime-score https://github.com/microsoft/KubeGPU https://github.com/Microsoft/KubeDevice https://github.com/Azure/kubelogin <file_sep> ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) az login --service-principal -u SPN_USER_NAME -p PASSWORD --tenant TENANT_ID_OR_NAME az role definition create --role-definition '{ "Name": "Custom Container Service", "Description": "Cannot read Container service credentials", "Actions": [ "Microsoft.ContainerService/managedClusters/read" ], "DataActions": [ ], "NotDataActions": [ ], "AssignableScopes": [ "/subscriptions/xxx" ] }' ``` ``` az role definition create --role-definition '{ "Name": "SecretProviderViewer", "Description": "Can read secretprovider", "Actions": [ "Microsoft.ContainerService/managedClusters/*/read" ], "DataActions": [ ], "NotDataActions": [ ], "AssignableScopes": [ "/subscriptions//resourcegroups/dzallincluded/providers/Microsoft.ContainerService/managedClusters/dzallincluded" ] }' az role assignment create --assignee $SERVICE_PRINCIPAL_ID --scope $AKS_ID --role "SecretProviderViewer" ```<file_sep># Kong https://docs.konghq.com/install/kubernetes/ https://docs.konghq.com/install/kubernetes/?_ga=2.196695532.195122953.1563518403-599058245.1563518403#postgres-backed-kong https://hub.kubeapps.com/charts/stable/kong https://docs.konghq.com/hub/ ## kong ingress https://github.com/Kong/kubernetes-ingress-controller/blob/master/docs/tutorials/getting-started.md helm repo add kong https://charts.konghq.com helm repo update kubectl create namespace kong helm upgrade kong-ingress kong/kong --install --values https://bit.ly/2UAv0ZE --set ingressController.installCRDs=false --namespace kong \ --set serviceMonitor.enabled=true --set proxy.enabled=true --set admin.enabled=true --set manager.enabled=true --set portal.enabled=true helm upgrade kong-ingress kong/kong --install --set ingressController.installCRDs=false --namespace kong helm install --name kong-ingress stable/kong --set ingressController.enabled=true --set proxy.type=LoadBalancer --set postgresql.enabled=false --set env.database=off --namespace kong IP= DB_HOST=kong.postgres.database.azure.com DB_PW= DB_USER=kongadmin env: database: postgres pg_host: kong.postgres.database.azure.com pg_password: pg_user: helm install --name kong-ingress stable/kong --set ingressController.enabled=true --set proxy.type=LoadBalancer --set proxy.loadBalancerIP=$IP --set postgresql.enabled=false --set env.database=kong --set env.pg_host=$DB_HOST --set env.pg_password=$DB_PW --set env.pg_user=$DB_USER --set env.pg_port=5432 --namespace kong helm install --name kong-ingress stable/kong --set ingressController.enabled=true --set proxy.type=LoadBalancer --set proxy.loadBalancerIP=$IP --set env.cassandra_contact_points= --set env.cassandra_port= --namespace kong helm install --name kong-ingress stable/kong --set ingressController.enabled=true --set proxy.type=LoadBalancer --set proxy.loadBalancerIP=$IP --namespace kong export PROXY_IP=$(kubectl get -o jsonpath="{.status.loadBalancer.ingress[0].ip}" service -n kong kong-ingress-kong-proxy) kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/yaml/echoserver.yaml echo " apiVersion: extensions/v1beta1 kind: Ingress metadata: name: demo annotations: kubernetes.io/ingress.class: kong spec: rules: - http: paths: - path: /foo backend: serviceName: echo servicePort: 80 " | kubectl apply -f - ingress.extensions/demo created # GRPC https://github.com/Kong/kubernetes-ingress-controller/blob/master/docs/guides/using-ingress-with-grpc.md KONG_PROXY_IP=172.16.58.3 grpcurl -v -d '{"greeting": "Kong Hello world!"}' -insecure $KONG_PROXY_IP:443 hello.HelloService.SayHello cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: httpbin-free annotations: kubernetes.io/ingress.class: kong konghq.com/protocols: http spec: rules: - http: paths: - path: /free backend: serviceName: httpbin servicePort: 80 EOF cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: httpbin-paid annotations: kubernetes.io/ingress.class: kong spec: rules: - http: paths: - path: /paid backend: serviceName: httpbin servicePort: 80 EOF KONG_PROXY_IP=172.16.58.3 curl -X GET $KONG_PROXY_IP/free/status/200 --insecure ## Monitoring echo 'apiVersion: configuration.konghq.com/v1 kind: KongClusterPlugin metadata: name: prometheus annotations: kubernetes.io/ingress.class: kong labels: global: "true" plugin: prometheus ' | kubectl apply -f - while true; do curl http://$KONG_PROXY_IP/billing/status/200 curl http://localhost:8000/billing/status/501 curl http://localhost:8000/invoice/status/201 curl http://localhost:8000/invoice/status/404 curl http://localhost:8000/comments/status/200 curl http://localhost:8000/comments/status/200 sleep 0.01 done ## ACL https://github.com/Kong/kubernetes-ingress-controller/blob/master/docs/guides/configure-acl-plugin.md PROXY_IP=172.16.58.3 curl -i $PROXY_IP/get echo " apiVersion: configuration.konghq.com/v1 kind: KongPlugin metadata: name: app-jwt plugin: jwt " | kubectl apply -f - echo ' apiVersion: extensions/v1beta1 kind: Ingress metadata: name: demo-get annotations: konghq.com/plugins: app-jwt konghq.com/strip-path: "false" kubernetes.io/ingress.class: kong spec: rules: - http: paths: - path: /get backend: serviceName: httpbin servicePort: 80 ' | kubectl apply -f - echo ' apiVersion: extensions/v1beta1 kind: Ingress metadata: name: demo-post annotations: konghq.com/plugins: app-jwt konghq.com/strip-path: "false" kubernetes.io/ingress.class: kong spec: rules: - http: paths: - path: /post backend: serviceName: httpbin servicePort: 80 ' | kubectl apply -f - curl -i --data "foo=bar" -X POST $PROXY_IP/post echo " apiVersion: configuration.konghq.com/v1 kind: KongConsumer metadata: name: admin annotations: kubernetes.io/ingress.class: kong username: admin " | kubectl apply -f - echo " apiVersion: configuration.konghq.com/v1 kind: KongConsumer metadata: name: plain-user annotations: kubernetes.io/ingress.class: kong username: plain-user " | kubectl apply -f - echo " apiVersion: configuration.konghq.com/v1 kind: KongPlugin metadata: name: plain-user-acl plugin: acl config: whitelist: ['app-user','app-admin'] " | kubectl apply -f - echo ' apiVersion: extensions/v1beta1 kind: Ingress metadata: name: demo-post annotations: konghq.com/plugins: app-jwt,admin-acl konghq.com/strip-path: "false" kubernetes.io/ingress.class: kong spec: rules: - http: paths: - path: /post backend: serviceName: httpbin servicePort: 80 ' | kubectl apply -f - https://linkerd.io/2/tasks/using-ingress/#kong ## Linkerd echo " apiVersion: configuration.konghq.com/v1 kind: KongPlugin metadata: name: set-l5d-header namespace: emojivoto plugin: request-transformer config: add: headers: - l5d-dst-override:$(headers.host).svc.cluster.local " | kubectl apply -f - echo " apiVersion: extensions/v1beta1 kind: Ingress metadata: name: web-ingress namespace: emojivoto annotations: kubernetes.io/ingress.class: "kong" konghq.com/plugins: set-l5d-header spec: rules: - host: 172.16.31.10.xip.io http: paths: - path: /api/vote backend: serviceName: web-svc servicePort: http - path: /api/vote backend: serviceName: web-svc servicePort: http - path: / backend: serviceName: web-svc servicePort: http " | kubectl apply -f - kubectl get deployment kong-ingress-kong -n kong -o yaml | linkerd inject --ingress - | kubectl apply -f - kubectl get deployment <ingress-controller> -n <ingress-namespace> -o yaml | linkerd inject --ingress - | kubectl apply -f - kubectl edit deployment vote-bot -n emojivoto env: # Target the Kong ingress instead of the Emojivoto web service - name: WEB_HOST value: kong-ingress-kong-proxy.kong:80 # Override the host header on requests so that it can be used to set the l5d-dst-override header - name: HOST_OVERRIDE value: web-svc.emojivoto curl -X POST "https://login.microsoftonline.com/<your_tenant_id>/oauth2/v2.0/token" \ --data scope="<your_client_id>/.default" \ --data grant_type="client_credentials" \ --data client_id="<your_client_id>" \ --data client_secret="<your_client_secret>" curl --header 'Authorization: bearer <token_from_above>' '<admin-hostname>:8000/httpbin-azure' <file_sep>## Run a hello world container in Azure Container instances See https://docs.microsoft.com/en-us/azure/container-instances/container-instances-quickstart 1. Login into azure cli ``` az login ``` 2. Create a resource group ``` az group create --name "$ACI_GROUP" --location $LOCATION ``` 3. Create a container instance ``` az container create --name "$ACI_HELLO_NAME" --image microsoft/aci-helloworld --resource-group "$ACI_GROUP" --ip-address public ``` 4. Confirm creation ``` az container show --name "$ACI_HELLO_NAME" --resource-group "$ACI_GROUP" ``` 5. Pull container logs ``` az container logs --name "$ACI_HELLO_NAME" --resource-group "$ACI_GROUP" ``` 6. Cleanup the resource group ``` az group delete --name "$ACI_GROUP" --yes az container delete --resource-group "$ACI_GROUP" --name "$ACI_HELLO_NAME" --yes ``` ## Build a container, push it to registry and launch it https://docs.microsoft.com/en-us/azure/container-instances/container-instances-tutorial-deploy-app https://github.com/Azure-Samples/aci-helloworld 1. Set Docker Host (https://docs.docker.com/machine/reference/env/) Check in the Docker Daemon in "General" the setting "Expose daemon on tcp://localhost:2375 without TLS" ``` sudo apt install docker.io export DOCKER_HOST=tcp://127.0.0.1:2375 ``` 2. Create container registry https://docs.microsoft.com/en-us/azure/container-registry/container-registry-intro ``` REGISTRY_NAME="hellodemodz234" az acr create --resource-group "$RESOURCE_GROUP" --name "$REGISTRY_NAME" --sku Basic --admin-enabled true ``` 3. Get login info (eval used because of the double quotation) Get the registry login server ``` az acr show --name "$REGISTRY_NAME" --query loginServer REGISTRY_URL=$(az acr show --name "$REGISTRY_NAME" --query loginServ er) ``` Get the login password ``` az acr credential show --name "$REGISTRY_NAME" --query passwords[0].value ``` or automate it ``` REGISTRY_URL=$(az acr show --name "$REGISTRY_NAME" --query loginServer) REGISTRY_PASSWORD=$(az acr credential show --name "$REGISTRY_NAME" --query passwords[0].value) eval "docker login --username="$REGISTRY_NAME" --password=$REGISTRY_PASSWORD $REGISTRY_URL" ``` 4. Pull, tag and push the latest image to the registry ``` docker pull microsoft/aci-helloworld eval "docker tag microsoft/aci-helloworld $REGISTRY_URL/aci-helloworld:v1" eval "docker push $REGISTRY_URL/aci-helloworld:v1" ``` or ``` docker tag microsoft/aci-helloworld hellodemo345.azurecr.io/aci-helloworld:v1 docker push "hellodemo345.azurecr.io/aci-helloworld:v1" ``` 5. Clone the source code depot. Build the image and push it to the registry. Run it on a new container instance. ``` git clone https://github.com/Azure-Samples/aci-helloworld.git cd aci-helloworld less Dockerfile docker build -t aci-tut-app . docker images eval "docker tag aci-tut-app $REGISTRY_URL/aci-tut-app:v1" eval "docker push $REGISTRY_URL/aci-tut-app:v1" CONTAINER_APP_NAME="acihelloworldapp" az container create -g $RESOURCE_GROUP --name $CONTAINER_APP_NAME --image hellodemo345.azurecr.io/aci-tut-app:v1 --registry-password $DOCKER_PASSWORD ``` ## Automate it by using VSTS ## Create a build process template 1. Create a build process for your git repo ![](/img/2017-08-07-07-44-35.png) 2. Get sources task ![](/img/2017-08-07-07-47-29.png) 3. Build an image task with image name using the repo name and the build id as label ``` $(Build.Repository.Name):$(Build.BuildId) ``` ![](/img/2017-08-07-07-48-22.png) 4. Push an image task ![](/img/2017-08-07-07-48-47.png) 5. Configure the trigger for git repo changes ![](/img/2017-08-07-07-49-50.png) ## Create release process template Since this has to run on a private agent go for [VSTS Build Agent Setup](VstsSetup.md) and configure one. The overall launch task is very simple: ![](/img/2017-08-07-07-52-31.png) 1. Take a azure cli task from the marketplace and configure it to use your agent. ![](/img/2017-08-07-07-55-16.png) 2. Configure the azure cli task to use the following arguments: ![](/img/2017-08-07-07-55-56.png) 3. Configure the variables and registry password (put lock on it): ``` az container create --name "aci$(RegistryName)$(BUILD.BUILDID)" --image "$(RegistryUrl)/denniszielke/aci-helloworld:$(BUILD.BUILDID)" --resource-group "helloworld" --ip-address public --registry-password $(RegistryPassword) ``` ![](/img/2017-08-07-07-56-37.png) <file_sep># Gatekeeper V2 <file_sep> kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/pod-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-int-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-lb-logger.yaml cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos spec: containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF kubectl exec -ti centos -- /bin/bash SERVICE_IP=$(kubectl get svc azure-vote-front --template="{{range .status.loadBalancer.ingress}}{{.ip}}{{end}}") for i in {1..1000}; do curl -s -w "%{time_total}\n" -o /dev/null http://$SERVICE_IP; done KUBENET_PPG POD_IP=10.244.1.2 SERVICE_IP=10.0.147.134 LB_IP=172.16.17.32 KUBENET_ZONES POD_IP=10.244.1.3 SERVICE_IP=10.0.33.202 LB_IP=192.168.127.12 for i in {1..1000}; do curl -s -w "%{time_total}\n" -o /dev/null http://$POD_IP; done for i in {1..1000}; do curl -s -w "%{time_total}\n" -o /dev/null http://$SERVICE_IP; done for i in {1..1000}; do curl -s -w "%{time_total}\n" -o /dev/null http://$LB_IP; done<file_sep>#!/bin/bash set -e # infrastructure deployment properties PROJECT_NAME="$1" # here enter unique deployment name (ideally short and with letters for global uniqueness) REGISTRY_OWNER="denniszielke" IMAGE_TAG="latest" APP_NAMESPACE="calculator" FRONTEND_NAMESPACE="calculator-frontend" BACKEND_NAMESPACE="calculator-backend" if [ "$PROJECT_NAME" == "" ]; then echo "No project name provided - aborting" exit 0; fi if [[ $PROJECT_NAME =~ ^[a-z0-9]{5,13}$ ]]; then echo "project name $PROJECT_NAME is valid" else echo "project name $PROJECT_NAME is invalid - only numbers and lower case min 5 and max 8 characters allowed - aborting" exit 0; fi RESOURCE_GROUP="$PROJECT_NAME" AZURE_CORE_ONLY_SHOW_ERRORS="True" if [ $(az group exists --name $RESOURCE_GROUP) = false ]; then echo "resource group $RESOURCE_GROUP does not exist" error=1 else echo "resource group $RESOURCE_GROUP already exists" LOCATION=$(az group show -n $RESOURCE_GROUP --query location -o tsv) fi # KUBE_NAME=$(az aks list -g $RESOURCE_GROUP --query '[0].name' -o tsv) # if [ "$KUBE_NAME" == "" ]; then # echo "no AKS cluster found in Resource Group $RESOURCE_GROUP" # error=1 # fi # echo "found cluster $KUBE_NAME" # echo "getting kubeconfig for cluster $KUBE_NAME" #az aks get-credentials --resource-group=$RESOURCE_GROUP --name=$KUBE_NAME --admin # CONTROLLER_ID=$(az aks show -g $RESOURCE_GROUP -n $KUBE_NAME --query identity.principalId -o tsv) # echo "controller id is $CONTROLLER_ID" # NODE_GROUP=$(az aks show -g $RESOURCE_GROUP -n $KUBE_NAME --query nodeResourceGroup -o tsv) AI_CONNECTIONSTRING=$(az resource show -g $RESOURCE_GROUP -n appi-$PROJECT_NAME --resource-type "Microsoft.Insights/components" --query properties.ConnectionString -o tsv | tr -d '[:space:]') echo $AI_CONNECTIONSTRING replaces="s/{.registry}/$REGISTRY_OWNER/;"; replaces="$replaces s/{.tag}/$IMAGE_TAG/; "; replaces="$replaces s/{.version}/$IMAGE_TAG/; "; replaces="$replaces s/{.frontend-namespace}/$FRONTEND_NAMESPACE/; "; replaces="$replaces s/{.backend-namespace}/$BACKEND_NAMESPACE/; "; replaces="$replaces s/{.requester-namespace}/$APP_NAMESPACE/; "; cat ./yaml/depl-calc-backend.yaml | sed -e "$replaces" | kubectl apply -f - cat ./yaml/depl-calc-frontend.yaml | sed -e "$replaces" | kubectl apply -f - #cat ./yaml/depl-calc-requester.yaml | sed -e "$replaces" | kubectl apply -f - # kubectl create secret generic appconfig -n $APP_NAMESPACE \ # --from-literal=applicationInsightsConnectionString=$AI_CONNECTIONSTRING \ # --save-config --dry-run=client -o yaml | kubectl apply -f - kubectl create secret generic appconfig -n $FRONTEND_NAMESPACE \ --from-literal=applicationInsightsConnectionString=$AI_CONNECTIONSTRING \ --save-config --dry-run=client -o yaml | kubectl apply -f - kubectl create secret generic appconfig -n $BACKEND_NAMESPACE \ --from-literal=applicationInsightsConnectionString=$AI_CONNECTIONSTRING \ --save-config --dry-run=client -o yaml | kubectl apply -f -<file_sep># Setup environment ## Windows You can install Azure CLI 2.0 with the MSI and use it in the Windows command-line, or you can install the CLI with apt-get on Bash on Ubuntu on Windows. ### MSI for the Windows command-line To install the CLI on Windows and use it in the Windows command-line, download and run the [msi](https://aka.ms/InstallAzureCliWindows). > [!NOTE] > When you install with the msi, [`az component`](/cli/azure/component) isn't supported. > To update to the latest CLI, run the [msi](https://aka.ms/InstallAzureCliWindows) again. > > To uninstall the CLI, run the [msi](https://aka.ms/InstallAzureCliWindows) again and choose uninstall. ### apt-get for Bash on Ubuntu on Windows 1. If you don't have Bash on Windows, [install it](https://msdn.microsoft.com/commandline/wsl/install_guide). 2. Open the Bash shell. 3. Modify your sources list. ```bash echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ wheezy main" | sudo tee /etc/apt/sources.list.d/azure-cli.list echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ wheezy main" | sudo tee /etc/apt/sources.list.d/azure-cli.list ``` 4. Run the following sudo commands: ```bash sudo apt-key adv --keyserver packages.microsoft.com --recv-keys 417A0893 sudo apt-get install apt-transport-https sudo apt-get update && sudo apt-get install azure-cli ``` 5. Run the CLI from the command prompt with the `az` command. > [!NOTE] > When you install with apt-get, [`az component`](/cli/azure/component) isn't supported. > To update the CLI, run `sudo apt-get update && sudo apt-get install azure-cli` again. > > To uninstall, run `sudo apt-get remove azure-cli`. 6. Create private keypair ` ssh-keygen -t rsa -b 4096 ` ### install and update azure cli on mac ``` brew update && brew install azure-cli brew upgrade azure-cli wget https://raw.githubusercontent.com/Homebrew/homebrew-core/7607de411f8ac0ad926ff2caadf8a9abf713cec8/Formula/azure-cli.rb brew reinsall azure-cli.rb ``` ### arm client for mac https://github.com/yangl900/armclient-go#how-to-use-it ``` curl -sL https://github.com/yangl900/armclient-go/releases/download/v0.2.3/armclient-go_macOS_64-bit.tar.gz | tar xz ``` ### install and configure kubectl https://kubernetes.io/docs/tasks/tools/install-kubectl/ ``` az aks install-cli brew install kubernetes-cli brew upgrade kubernetes-cli ``` Install autocompletion ``` kubectl completion -h ``` ### install and configure helm https://get.helm.sh ``` brew install kubernetes-helm brew upgrade kubernetes-helm ``` ### install the preview cli ``` az extension add --name aks-preview az extension update --name aks-preview ``` remove existing installation of preview cli ``` az extension remove --name aks-preview ``` ### install ``` https://github.com/ohmyzsh/ohmyzsh https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/kube-ps1 #https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/kube-ps1 #https://github.com/jonmosco/kube-ps1 PROMPT=$PROMPT'$(kube_ps1) ' source "/usr/local/opt/kube-ps1/share/kube-ps1.sh" #https://github.com/zsh-users/zsh-syntax-highlighting/blob/master/INSTALL.md source /usr/local/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=/usr/local/share/zsh-syntax-highlighting/highlighters #ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE="fg=#999999,bg=cyan,bold,underline" #https://github.com/zsh-users/zsh-autosuggestions #bindkey '^ ' forward-word bindkey '^ ' end-of-line #https://blog.nillsf.com/index.php/2020/02/17/setting-up-wsl2-windows-terminal-and-oh-my-zsh/ ```<file_sep>package org.acme.rest.client; import java.util.List; public class CalculationResponse { public String timestamp; public String value; public String error; public String host; public String remote; public String toString() { return this.timestamp + " " + this.value + " " + this.host + " " + this.remote + " " + this.error; } }<file_sep>## Install docker on Ubuntu 16.04 LTS (do not use the docker ubuntu vm from marketplace) in Azure * To install the VM, log into the Azure portal, click "Create new Resource", search for "Ubuntu 16.04 LTS" and follow the wizard. It is recommended to enable auto-shut down. * After deployment, log into the new VM. To access it either log into it via ssh from your client (e.g from Bash on Windows). 1. Install docker via package manager (https://docs.docker.com/install/linux/docker-ce/ubuntu/) ``` sudo apt-get update sudo apt-get install \ apt-transport-https \ ca-certificates \ curl \ software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \ stable" sudo apt-get update sudo apt-get install docker-ce ``` 2. On Ubuntu make sure that the current user is part of the docker group ~~~ sudo usermod -aG docker $USER ~~~ Log in and out to re-evaluate your group membership 3. Test docker engine ~~~ docker run hello-world ~~~ 4. Delete all docker images ``` docker rmi $(docker images -q) ``` 5. Remove unused containers ``` docker system prune -a ```<file_sep># CSI Drivers ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) KUBE_GROUP="kub_ter_a_m_csisecurity" KUBE_NAME="csisecurity" LOCATION="eastus" NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION KUBE_VNET_NAME=$KUBE_NAME"-vnet" KUBE_GW_SUBNET_NAME="gw-1-subnet" KUBE_ACI_SUBNET_NAME="aci-2-subnet" KUBE_FW_SUBNET_NAME="AzureFirewallSubnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" KUBE_AGENT_SUBNET_NAME="aks-5-subnet" KUBE_AGENT2_SUBNET_NAME="aks-6-subnet" KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" ``` ``` az group create -n $KUBE_GROUP -l $LOCATION az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_GW_SUBNET_NAME --address-prefix 10.0.1.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ACI_SUBNET_NAME --address-prefix 10.0.2.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_FW_SUBNET_NAME --address-prefix 10.0.3.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT2_SUBNET_NAME --address-prefix 10.0.6.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage echo "creating cluster 1 with MSI" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" KUBE_VNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 3 --ssh-key-value ~/.ssh/id_rsa.pub --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --node-resource-group $NODE_GROUP --enable-managed-identity --network-policy calico --enable-rbac --enable-addons monitoring --aks-custom-headers EnableAzureDiskFileCSIDriver=true --node-vm-size Standard_D4as_v4 KUBELET_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identityProfile.kubeletidentity.clientId -o tsv) CONTROLLER_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query identity.principalId -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az role assignment create --role "Virtual Machine Contributor" --assignee $KUBELET_ID --scope /subscriptions/$SUBSCRIPTION_ID/resourcegroups/$NODE_GROUP az role assignment create --role "Virtual Machine Contributor" --assignee $CONTROLLER_ID --scope $KUBE_VNET_ID az role assignment create --role "Contributor" --assignee $CONTROLLER_ID -g $KUBE_GROUP az role assignment create --role "Contributor" --assignee $CONTROLLER_ID -g $NODE_GROUP echo "creating cluster 2 with SP" SP_NAME="$KUBE_NAME-sp" SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $SP_NAME -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET KUBE_AGENT_SUBNET2_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT2_SUBNET_NAME" KUBE_VNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME" NODE2_GROUP=$KUBE_GROUP"_"$KUBE_NAME"2_nodes_"$LOCATION az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME-sp --node-count 3 --ssh-key-value ~/.ssh/id_rsa.pub --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET2_ID --docker-bridge-address 1172.16.17.32/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --node-resource-group $NODE2_GROUP --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --network-policy calico --enable-rbac --enable-addons monitoring --aks-custom-headers EnableAzureDiskFileCSIDriver=true --node-vm-size Standard_D4as_v4 ``` ## Azure Disk https://github.com/kubernetes-sigs/azuredisk-csi-driver ### Cloning https://github.com/kubernetes-sigs/azuredisk-csi-driver/tree/master/deploy/example/cloning https://raw.githubusercontent.com/kubernetes-sigs/azuredisk-csi-driver/master/deploy/example/cloning/pvc-azuredisk-cloning.yaml ### CSI Topology Features https://kubernetes-csi.github.io/docs/topology.html # Storage Account ``` STORAGE_ACCOUNT=$KUBE_NAME NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az storage account create --resource-group $NODE_GROUP --name $STORAGE_ACCOUNT --location $LOCATION --sku Premium_LRS --kind FileStorage --access-tier hot --https-only false STORAGE_KEY=$(az storage account keys list --account-name $STORAGE_ACCOUNT --resource-group $NODE_GROUP --query "[0].value") az storage share create -n job --quota 10 --account-name $STORAGE_ACCOUNT --account-key $STORAGE_KEY kubectl create secret generic azurefile-secret --from-literal=azurestorageaccountname=$STORAGE_ACCOUNT --from-literal=azurestorageaccountkey=$STORAGE_KEY ``` ## Storage Classes ## Performance Test https://raw.githubusercontent.com/logdna/dbench/master/dbench.yaml ### NFS ``` $KUBE_NAME-sp STORAGE_ACCOUNT=$KUBE_NAME"2" NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) az storage account create --resource-group $NODE_GROUP --name $STORAGE_ACCOUNT --location $LOCATION --sku Premium_LRS --kind FileStorage --access-tier hot --https-only false STORAGE_KEY=$(az storage account keys list --account-name $STORAGE_ACCOUNT --resource-group $NODE_GROUP --query "[0].value") kubectl create secret generic azure-secret --from-literal accountname=$STORAGE_ACCOUNT --from-literal accountkey="$STORAGE_KEY" --type=Opaque cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: azurefiledemo provisioner: kubernetes.io/azure-file parameters: skuName: Standard_LRS storageAccount: dzprivate1 EOF cat <<EOF | kubectl apply -f - kind: PersistentVolumeClaim apiVersion: v1 metadata: name: dbench-pv-claim-net1 spec: storageClassName: azurefiledemo accessModes: - ReadWriteOnce resources: requests: storage: 10Gi EOF cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: azurefile-csi-net provisioner: file.csi.azure.com parameters: storageAccount: $STORAGE_ACCOUNT resourceGroup: $KUBE_GROUP reclaimPolicy: Delete volumeBindingMode: Immediate EOF cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: azurefile-csi-large provisioner: file.csi.azure.com parameters: storageAccount: $STORAGE_ACCOUNT shareName: large reclaimPolicy: Delete volumeBindingMode: Immediate EOF cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: azurefile-csi-nfs provisioner: file.csi.azure.com parameters: resourceGroup: $NODE_GROUP storageAccount: $STORAGE_ACCOUNT protocol: nfs fsType: nfs EOF cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: azurefile-csi-nfs provisioner: file.csi.azure.com parameters: resourceGroup: kub_ter_a_m_csisecurity_csisecurity_nodes_eastus storageAccount: dzpremium1 protocol: nfs fsType: nfs csi.storage.k8s.io/provisioner-secret-name: azure-secret csi.storage.k8s.io/provisioner-secret-namespace: default csi.storage.k8s.io/node-stage-secret-name: azure-secret csi.storage.k8s.io/node-stage-secret-namespace: default csi.storage.k8s.io/controller-expand-secret-name: azure-secret csi.storage.k8s.io/controller-expand-secret-namespace: default EOF cat <<EOF | kubectl apply -f - kind: PersistentVolumeClaim apiVersion: v1 metadata: name: dbench-pv-claim-net1 spec: storageClassName: azurefile-csi-net accessModes: - ReadWriteOnce resources: requests: storage: 10Gi EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: dbench spec: template: spec: containers: - name: dbench image: denniszielke/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" # - name: FIO_SIZE # value: 1G # - name: FIO_OFFSET_INCREMENT # value: 256M # - name: FIO_DIRECT # value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: dbench-pv-claim-nfs backoffLimit: 4 EOF cat <<EOF | kubectl apply -f - kind: PersistentVolumeClaim apiVersion: v1 metadata: name: dbench-pv-claim-nfs spec: storageClassName: azurefile-csi-large accessModes: - ReadWriteOnce resources: requests: storage: 100Ti EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: dbench spec: template: spec: containers: - name: dbench image: denniszielke/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" # - name: FIO_SIZE # value: 1G # - name: FIO_OFFSET_INCREMENT # value: 256M # - name: FIO_DIRECT # value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: dbench-pv-claim-nfs backoffLimit: 4 EOF cat <<EOF | kubectl apply -f - --- apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: azurefile-csi-nfs-test provisioner: file.csi.azure.com parameters: storageAccount: dzpremium1 protocol: nfs # use "fsType: nfs" in v0.8.0 reclaimPolicy: Delete volumeBindingMode: Immediate allowVolumeExpansion: true EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: StatefulSet metadata: name: statefulset-azurefile labels: app: nginx spec: serviceName: statefulset-azurefile replicas: 1 template: metadata: labels: app: nginx spec: nodeSelector: "kubernetes.io/os": linux containers: - name: statefulset-azurefile image: mcr.microsoft.com/oss/nginx/nginx:1.17.3-alpine command: - "/bin/sh" - "-c" - while true; do echo $(date) >> /mnt/azurefile/outfile; sleep 1; done volumeMounts: - name: persistent-storage mountPath: /mnt/azurefile updateStrategy: type: RollingUpdate selector: matchLabels: app: nginx volumeClaimTemplates: - metadata: name: persistent-storage annotations: volume.beta.kubernetes.io/storage-class: azurefile-csi-nfs-test spec: accessModes: ["ReadWriteMany"] resources: requests: storage: 100Gi EOF ``` ### Files CSI ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: dbench-pv-claim-csi-files spec: accessModes: - ReadWriteMany resources: requests: storage: 100Gi storageClassName: azurefile-csi EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: dbench spec: template: spec: containers: - name: dbench image: denniszielke/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" - name: FIO_SIZE value: 1G - name: FIO_OFFSET_INCREMENT value: 256M - name: FIO_DIRECT value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: dbench-pv-claim-csi-files backoffLimit: 4 EOF ``` ### Files ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: dbench-pv-claim-files spec: accessModes: - ReadWriteMany resources: requests: storage: 100Gi storageClassName: azurefile EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: dbench spec: template: spec: containers: - name: dbench image: denniszielke/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" # - name: FIO_SIZE # value: 1G # - name: FIO_OFFSET_INCREMENT # value: 256M # - name: FIO_DIRECT # value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: dbench-pv-claim-files backoffLimit: 4 EOF ``` ### Files CSI Premium ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: dbench-pv-claim-csi-prem-files spec: accessModes: - ReadWriteMany resources: requests: storage: 100Gi storageClassName: azurefile-csi-premium EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: dbench spec: template: spec: containers: - name: dbench image: denniszielke/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" # - name: FIO_SIZE # value: 1G # - name: FIO_OFFSET_INCREMENT # value: 256M # - name: FIO_DIRECT # value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: dbench-pv-claim-csi-prem-files backoffLimit: 4 EOF ``` ### Premium Files ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: dbench-pv-claim-prem-files spec: accessModes: - ReadWriteMany resources: requests: storage: 100Gi storageClassName: azurefile-premium EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: dbench spec: template: spec: containers: - name: dbench image: denniszielke/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" # - name: FIO_SIZE # value: 1G # - name: FIO_OFFSET_INCREMENT # value: 256M # - name: FIO_DIRECT # value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: dbench-pv-claim-prem-files backoffLimit: 4 EOF ``` ### Managed Premium Disk CSI ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: dbench-pv-claim-premium-csi-disk spec: accessModes: - ReadWriteMany resources: requests: storage: 100Gi storageClassName: managed-csi-premium EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: dbench spec: template: spec: containers: - name: dbench image: logdna/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" # - name: FIO_SIZE # value: 1G # - name: FIO_OFFSET_INCREMENT # value: 256M # - name: FIO_DIRECT # value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: dbench-pv-claim-premium-csi-disk backoffLimit: 4 EOF ``` ### Managed Premium ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: dbench-pv-claim-premium-disk spec: accessModes: - ReadWriteMany resources: requests: storage: 100Gi storageClassName: managed-premium EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: dbench spec: template: spec: containers: - name: dbench image: logdna/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" # - name: FIO_SIZE # value: 1G # - name: FIO_OFFSET_INCREMENT # value: 256M # - name: FIO_DIRECT # value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: dbench-pv-claim-premium-disk backoffLimit: 4 EOF kubectl logs -f job/dbench ``` ## Storage NFS 3 https://github.com/kubernetes-sigs/blob-csi-driver/tree/master/deploy/example/nfs ``` curl -skSL https://raw.githubusercontent.com/kubernetes-sigs/blob-csi-driver/master/deploy/install-driver.sh | bash -s master -- kubectl -n kube-system get pod -o wide -l app=csi-blob-controller kubectl -n kube-system get pod -o wide -l app=csi-blob-node curl -skSL https://raw.githubusercontent.com/kubernetes-sigs/blob-csi-driver/master/deploy/uninstall-driver.sh | bash -s master -- kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/blob-csi-driver/master/deploy/v1.0.0/rbac-csi-blob-node.yaml kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/blob-csi-driver/master/deploy/v1.0.0/rbac-csi-blob-controller.yaml kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/blob-csi-driver/master/deploy/v1.0.0/csi-blob-node.yaml kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/blob-csi-driver/master/deploy/v1.0.0/csi-blob-controller.yaml kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/blob-csi-driver/master/deploy/v1.0.0/csi-blob-driver.yaml cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: blob-nfs provisioner: blob.csi.azure.com parameters: resourceGroup: kub_ter_a_s_store3 # optional, only set this when storage account is not in the same resource group as agent node storageAccount: dzstore3 protocol: nfs EOF cat <<EOF | kubectl apply -f - --- apiVersion: apps/v1 kind: StatefulSet metadata: name: statefulset-blob labels: app: dbench spec: serviceName: dbench replicas: 1 template: metadata: labels: app: dbench spec: nodeSelector: "kubernetes.io/os": linux containers: - name: dbench image: denniszielke/dbench:latest env: - name: DBENCH_MOUNTPOINT value: /mnt/blob volumeMounts: - name: persistent-storage mountPath: /mnt/blob updateStrategy: type: RollingUpdate selector: matchLabels: app: dbench volumeClaimTemplates: - metadata: name: persistent-storage annotations: volume.beta.kubernetes.io/storage-class: blob-nfs spec: accessModes: ["ReadWriteMany"] resources: requests: storage: 100Gi EOF cat <<EOF | kubectl apply -f - --- apiVersion: apps/v1 kind: StatefulSet metadata: name: statefulset-blob labels: app: nginx spec: serviceName: statefulset-blob replicas: 1 template: metadata: labels: app: nginx spec: nodeSelector: "kubernetes.io/os": linux containers: - name: statefulset-blob image: mcr.microsoft.com/oss/nginx/nginx:1.17.3-alpine command: - "/bin/sh" - "-c" - while true; do echo $(date) >> /mnt/blob/outfile; sleep 1; done volumeMounts: - name: persistent-storage mountPath: /mnt/blob updateStrategy: type: RollingUpdate selector: matchLabels: app: nginx volumeClaimTemplates: - metadata: name: persistent-storage annotations: volume.beta.kubernetes.io/storage-class: blob-nfs spec: accessModes: ["ReadWriteMany"] resources: requests: storage: 100Gi EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: dbench spec: template: spec: containers: - name: dbench image: logdna/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" # - name: FIO_SIZE # value: 1G # - name: FIO_OFFSET_INCREMENT # value: 256M # - name: FIO_DIRECT # value: "0" volumeClaimTemplates: - metadata: name: persistent-storage annotations: volume.beta.kubernetes.io/storage-class: blob-nfs spec: accessModes: ["ReadWriteMany"] resources: requests: storage: 100Gi backoffLimit: 4 EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolume metadata: name: pv-blob-fuse spec: capacity: storage: 100Gi accessModes: - ReadWriteMany persistentVolumeReclaimPolicy: Retain # If set as "Delete" container would be removed after pvc deletion storageClassName: azureblob-nfs-premium mountOptions: - nconnect=8 # only supported on linux kernel version >= 5.3 csi: driver: blob.csi.azure.com readOnly: false volumeHandle: unique-volumeid volumeAttributes: resourceGroup: $NODE_GROUP storageAccount: a2f$KUBE_NAME containerName: blobs protocol: nfs EOF cat <<EOF | kubectl apply -f - kind: PersistentVolumeClaim apiVersion: v1 metadata: name: pvc-blob-nfs annotations: volume.beta.kubernetes.io/storage-class: azureblob-nfs-premium spec: accessModes: - ReadWriteMany resources: requests: storage: 100Gi storageClassName: azureblob-nfs-premium EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: blobnfs spec: template: spec: containers: - name: dbench image: denniszielke/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" - name: FIO_SIZE value: 1G - name: FIO_OFFSET_INCREMENT value: 256M # - name: FIO_DIRECT # value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: pvc-blob-nfs backoffLimit: 4 EOF cat <<EOF | kubectl apply -f - kind: PersistentVolumeClaim apiVersion: v1 metadata: name: pvc-blob-fuse annotations: volume.beta.kubernetes.io/storage-class: azureblob-fuse-premium spec: accessModes: - ReadWriteMany resources: requests: storage: 100Gi storageClassName: azureblob-fuse-premium EOF cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: name: blobfuse spec: template: spec: containers: - name: dbench image: denniszielke/dbench:latest imagePullPolicy: Always env: - name: DBENCH_MOUNTPOINT value: /data # - name: DBENCH_QUICK # value: "yes" #- name: FIO_SIZE # value: 1G #- name: FIO_OFFSET_INCREMENT # value: 256M # - name: FIO_DIRECT # value: "0" volumeMounts: - name: dbench-pv mountPath: /data restartPolicy: Never volumes: - name: dbench-pv persistentVolumeClaim: claimName: pvc-blob-fuse backoffLimit: 4 EOF cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: nginx-blob spec: nodeSelector: "kubernetes.io/os": linux containers: - image: mcr.microsoft.com/oss/nginx/nginx:1.17.3-alpine name: nginx-blob volumeMounts: - name: blob01 mountPath: "/mnt/blob" volumes: - name: blob01 persistentVolumeClaim: claimName: pvc-blob-fuse EOF ``` # Results - 1.17.X # westeurope csi azure files Random Read/Write IOPS: 643/1016. BW: 71.7MiB/s / 70.1MiB/s Average Latency (usec) Read/Write: 20.49/ Sequential Read/Write: 69.7MiB/s / 74.6MiB/s Mixed Random Read/Write IOPS: 738/245 # westeurope azure files Random Read/Write IOPS: 727/1019. BW: 75.7MiB/s / 68.3MiB/s Average Latency (usec) Read/Write: 18.14/ Sequential Read/Write: 74.6MiB/s / 73.9MiB/s Mixed Random Read/Write IOPS: 756/246 # eastus csi nfs files Random Read/Write IOPS: 303/290. BW: 38.9MiB/s / 38.8MiB/s Average Latency (usec) Read/Write: 13.70/13.23 Sequential Read/Write: 305MiB/s / 177MiB/s Mixed Random Read/Write IOPS: 157/55 Random Read/Write IOPS: 303/292. BW: 38.9MiB/s / 38.8MiB/s Average Latency (usec) Read/Write: 13.49/13.33 Sequential Read/Write: 313MiB/s / 171MiB/s Mixed Random Read/Write IOPS: 161/52 # eastus csi azure files Random Read/Write IOPS: 997/1012. BW: 118MiB/s / 71.4MiB/s Average Latency (usec) Read/Write: / Sequential Read/Write: 67.4MiB/s / 75.2MiB/s Mixed Random Read/Write IOPS: 770/256 Random Read/Write IOPS: 796/1016. BW: 80.3MiB/s / 82.8MiB/s Average Latency (usec) Read/Write: / Sequential Read/Write: 69.4MiB/s / 84.9MiB/s Mixed Random Read/Write IOPS: 755/248 # eastus azure files Random Read/Write IOPS: 1013/1006. BW: 125MiB/s / 69.6MiB/s Average Latency (usec) Read/Write: / Sequential Read/Write: 67.9MiB/s / 71.8MiB/s Mixed Random Read/Write IOPS: 771/251 Random Read/Write IOPS: 749/1015. BW: 79.4MiB/s / 85.3MiB/s Average Latency (usec) Read/Write: / Sequential Read/Write: 66.7MiB/s / 85.5MiB/s Mixed Random Read/Write IOPS: 728/251 # eastus csi premium files Random Read/Write IOPS: 302/304. BW: 38.6MiB/s / 37.9MiB/s Average Latency (usec) Read/Write: 13.28/13.19 Sequential Read/Write: 218MiB/s / 68.9MiB/s Mixed Random Read/Write IOPS: 211/72 Random Read/Write IOPS: 306/290. BW: 38.8MiB/s / 37.3MiB/s Average Latency (usec) Read/Write: 13.22/13.74 Sequential Read/Write: 305MiB/s / 84.9MiB/s Mixed Random Read/Write IOPS: 164/54 # eastus premium files Random Read/Write IOPS: 303/303. BW: 38.3MiB/s / 37.7MiB/s Average Latency (usec) Read/Write: 13.36/13.09 Sequential Read/Write: 265MiB/s / 72.8MiB/s Mixed Random Read/Write IOPS: 183/60 # Results - 1.18.8 # eastus csi nfs files Random Read/Write IOPS: 303/289. BW: 38.8MiB/s / 38.8MiB/s Average Latency (usec) Read/Write: 13.47/13.48 Sequential Read/Write: 293MiB/s / 176MiB/s Mixed Random Read/Write IOPS: 164/53 # increased storage to 10TB Random Read/Write IOPS: 11.2k/10.7k. BW: 192MiB/s / 180MiB/s Average Latency (usec) Read/Write: 1973.15/3883.61 Sequential Read/Write: 326MiB/s / 180MiB/s Mixed Random Read/Write IOPS: 7049/2340 # eastus csi azure files Random Read/Write IOPS: 594/1024. BW: 83.8MiB/s / 128MiB/s Average Latency (usec) Read/Write: / Sequential Read/Write: 125MiB/s / 170MiB/s Mixed Random Read/Write IOPS: 761/255 # eastus azure files Random Read/Write IOPS: 782/1015. BW: 98.3MiB/s / 128MiB/s Average Latency (usec) Read/Write: / Sequential Read/Write: 132MiB/s / 184MiB/s Mixed Random Read/Write IOPS: 768/252 # eastus csi premium files Random Read/Write IOPS: 307/296. BW: 38.8MiB/s / 38.9MiB/s Average Latency (usec) Read/Write: 13.28/13.71 Sequential Read/Write: 228MiB/s / 179MiB/s Mixed Random Read/Write IOPS: 192/65 # increased storage to 10TB Random Read/Write IOPS: 18.9k/13.5k. BW: 219MiB/s / 181MiB/s Average Latency (usec) Read/Write: 2681.44/1879.12 Sequential Read/Write: 232MiB/s / 184MiB/s Mixed Random Read/Write IOPS: 11.7k/3849 # blob nfs Random Read/Write IOPS: 6473/44. BW: 811MiB/s / 5682KiB/s Average Latency (usec) Read/Write: 6595.41/490.90 Sequential Read/Write: 1208MiB/s / 32.6MiB/s Mixed Random Read/Write IOPS: 51/17 https://docs.microsoft.com/en-us/azure/storage/files/storage-troubleshooting-files-nfs https://github.com/kubernetes-sigs/azurefile-csi-driver <file_sep> ## Azure Monitor scrape config https://review.learn.microsoft.com/en-us/azure/azure-monitor/essentials/prometheus-metrics-scrape-configuration?branch=pr-en-us-210933 ## Create prometheus config https://review.learn.microsoft.com/en-us/azure/azure-monitor/essentials/prometheus-metrics-scrape-validate?branch=pr-en-us-210933#apply-config-file https://github.com/Azure/prometheus-collector/blob/main/otelcollector/configmaps/ama-metrics-prometheus-config-node-windows-configmap.yaml ``` kubectl create configmap ama-metrics-prometheus-config --from-file=prometheus-config -n kube-system ```<file_sep># Install https://github.com/dapr/docs/blob/master/getting-started/environment-setup.md#installing-dapr-on-a-kubernetes-cluster helm repo add dapr https://daprio.azurecr.io/helm/v1/repo helm repo update kubectl create namespace dapr-system helm install dapr dapr/dapr --namespace dapr-system --set dapr_operator.logLevel=debug --set dapr_placement.logLevel=debug --set dapr_sidecar_injector.logLevel=debug kubectl get pods -n dapr-system -w helm uninstall dapr -n dapr-system <file_sep>#!/bin/sh set -e KUBE_NAME=$1 KUBE_GROUP=$2 SUBSCRIPTION_ID=$(az account show --query id -o tsv) #subscriptionid LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) AKS_SUBNET_ID=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query "agentPoolProfiles[0].vnetSubnetId" -o tsv) AKS_SUBNET_NAME="aks-5-subnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" APP_NAMESPACE="dummy-logger" SECRET_NAME="kong-cert-secret" VAULT_NAME=dzkv$KUBE_NAME AKS_CONTROLLER_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-ctl-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-clt-id')].id" -o tsv)" IP_ID=$(az network public-ip list -g $KUBE_GROUP --query "[?contains(name, 'kongingress')].id" -o tsv) if [ "$IP_ID" == "" ]; then echo "creating ingress ip kongingress" az network public-ip create -g $KUBE_GROUP -n kongingress --sku STANDARD --dns-name k$KUBE_NAME -o none IP_ID=$(az network public-ip show -g $KUBE_GROUP -n kongingress -o tsv --query id) IP=$(az network public-ip show -g $KUBE_GROUP -n kongingress -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n kongingress -o tsv --query dnsSettings.fqdn) echo "created ip $IP_ID with $IP on $DNS" az role assignment create --role "Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $IP_ID -o none else IP=$(az network public-ip show -g $KUBE_GROUP -n kongingress -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n kongingress -o tsv --query dnsSettings.fqdn) echo "AKS $AKS_ID already exists with $IP on $DNS" fi if kubectl get namespace ingress; then echo -e "Namespace ingress found." else kubectl create namespace ingress echo -e "Namespace ingress created." fi if kubectl get namespace $APP_NAMESPACE; then echo -e "Namespace $APP_NAMESPACE found." else kubectl create namespace $APP_NAMESPACE echo -e "Namespace $APP_NAMESPACE created." fi sleep 2 kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml -n $APP_NAMESPACE #kubectl apply -f logging/dummy-logger/svc-cluster-logger.yaml -n dummy-logger kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml -n $APP_NAMESPACE # Add the kong repository helm repo add kong https://charts.konghq.com helm repo add kuma https://kumahq.github.io/charts # Update the helm repo(s) helm repo update # https://github.com/Kong/charts/blob/main/charts/kong/README.md helm upgrade kong-ingress kong/kong --install \ --set ingressController.installCRDs=false \ --namespace ingress \ --set replicaCount=2 \ --set proxy.loadBalancerIP="$IP" \ --set proxy.externalTrafficPolicy="Local" \ --set-string proxy.annotations.'service\.beta\.kubernetes\.io/azure-load-balancer-resource-group'="$KUBE_GROUP" \ --set-string proxy.annotations.'service\.beta\.kubernetes\.io/azure-pip-name'="kongingress" \ --set autoscaling.enabled=true --wait # helm upgrade kong-ingress kong/kong --install \ # --set ingressController.installCRDs=false \ # --namespace ingress \ # --set replicaCount=2 \ # --set proxy.externalTrafficPolicy="Local" \ # --set-string proxy.annotations.'service\.beta\.kubernetes\.io/azure-load-balancer-internal'="true" \ # --set-string proxy.annotations.'service\.beta\.kubernetes\.io/azure-pls-create'="true" \ # --set-string proxy.annotations.'service\.beta\.kubernetes\.io/azure-pls-name'="internalpls" \ # --set-string proxy.annotations.'service\.beta\.kubernetes\.io/azure-pls-ip-configuration-subnet'="ing-4-subnet" \ # --set-string proxy.annotations.'service\.beta\.kubernetes\.io/azure-pls-proxy-protocol'="false" \ # --set-string proxy.annotations.'service\.beta\.kubernetes\.io/azure-pls-visibility'="*" \ # --set autoscaling.enabled=true --wait sleep 5 #helm upgrade kuma kuma/kuma --create-namespace --namespace kuma-system --install #kubectl port-forward svc/kuma-control-plane -n kuma-system 5681:5681 echo " apiVersion: configuration.konghq.com/v1 kind: KongPlugin metadata: name: request-id config: header_name: my-request-id plugin: correlation-id " | kubectl apply -f - kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: http-$APP_NAMESPACE namespace: $APP_NAMESPACE annotations: konghq.com/plugins: request-id spec: ingressClassName: kong rules: - http: paths: - path: / pathType: ImplementationSpecific backend: service: name: dummy-logger port: number: 80 EOF kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.9.1/cert-manager.yaml kubectl apply -f - <<EOF apiVersion: cert-manager.io/v1 kind: ClusterIssuer metadata: name: letsencrypt-prod spec: acme: email: <EMAIL> #please change this/this is an optional, but recommended setting privateKeySecretRef: name: letsencrypt-prod server: https://acme-v02.api.letsencrypt.org/directory solvers: - http01: ingress: podTemplate: metadata: annotations: kuma.io/sidecar-injection: "false" # If ingress is running in Kuma/Kong Mesh, disable sidecar injection sidecar.istio.io/inject: "false" # If using Istio, disable sidecar injection class: kong EOF kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-$APP_NAMESPACE namespace: $APP_NAMESPACE annotations: cert-manager.io/cluster-issuer: letsencrypt-prod spec: tls: - hosts: - $DNS secretName: $SECRET_NAME ingressClassName: kong rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 EOF echo $DNS <file_sep> NODE_GROUP=MC_kub_ter_a_m_scale51_scale51_westeurope IP_NAME= IP=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query ipAddress --output tsv) az network public-ip list --resource-group $NODE_GROUP --output json --query '[].{IP:ipAddress, tags:tags}' i=100; while true ; do echo "starting creating lb $i" SVC_NAME=dummy-cl-$i echo " apiVersion: v1 kind: Service metadata: name: dummy-cl-$i spec: ports: - port: 80 targetPort: 80 selector: app: dummy-logger type: LoadBalancer " | kubectl apply -f - external_ip="" while [ -z $external_ip ]; do sleep 10 echo "waiting for dummy-cl-$i" external_ip=$(kubectl get svc dummy-cl-$i --template="{{range .status.loadBalancer.ingress}}{{.ip}}{{end}}") done echo "got public ip $external_ip for dummy-cl-$i" az network public-ip list --resource-group $NODE_GROUP --output json --query '[].{IP:ipAddress, tags:tags}' | jq '.[] | select(.IP=="$external_ip")' echo "deleting dummy-cl-$i with $external_ip" kubectl delete svc dummy-cl-$i externalIpExists=$external_ip while [ ! -z $externalIpExists ]; do sleep 10 echo "waiting for dummy-cl-$i and $external_ip to delete" externalIpExists=$(az network public-ip list --resource-group $NODE_GROUP --output json --query '[].{IP:ipAddress, tags:tags}' | jq | grep $external_ip) done echo "deleted $external_ip" i=$((i+1)) now=$(date +"%T") echo "starting again at $now with $i" done external_ip="" i=1 SVC_NAME=dummy-cl-$i kubectl get svc $SVC_NAME -o jsonpath='{.status.loadBalancer.ingress[0].ip}' while [ -z $external_ip ]; do sleep 10 echo "waiting for $SVC_NAME" external_ip=$(kubectl get svc $SVC_NAME -o jsonpath='{.status.loadBalancer.ingress[0].ip}') done az network public-ip show --resource-group $NODE_GROUP --output json<file_sep># ASOF ``` kubectl apply -f https://github.com/jetstack/cert-manager/releases/download/v1.8.2/cert-manager.yaml ```<file_sep># Dapr using ServiceBus KUBE_GROUP= HUB_NAMESPACE=dzdapr$RANDOM LOCATION=westeurope az eventhubs namespace create --name $HUB_NAMESPACE --resource-group $KUBE_GROUP az eventhubs eventhub create --name events --resource-group $KUBE_GROUP --namespace-name $HUB_NAMESPACE az eventhubs namespace authorization-rule keys list --name RootManageSharedAccessKey --namespace-name $HUB_NAMESPACE --resource-group $KUBE_GROUP --query "primaryConnectionString" | tr -d '"' HUB_CONNECTIONSTRING=$(az eventhubs namespace authorization-rule keys list --name RootManageSharedAccessKey --namespace-name $HUB_NAMESPACE --resource-group $KUBE_GROUP --query "primaryConnectionString" | tr -d '"') kubectl delete component eventhubs-input cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: eventhubs-input spec: type: bindings.azure.eventhubs metadata: - name: connectionString value: $HUB_CONNECTIONSTRING EOF curl -H 'Authorization: SharedAccessSignature sr={Service Bus Namespace}.servicebus.windows.net&sig={Url Encoded Shared Access Key}&se={Time Stamp with Shared Access Key expration}&skn={Shared Access Policy name}' -H 'Content-Type:application/atom+xml;type=entry;charset=utf-8' --data '{Event Data}' https://{Service Bus Namespace}.servicebus.windows.net/{Event Hub Name}/messages kubectl delete component eventhubs-input kubectl delete component eventhubs-input kubectl logs -l demo=pubsub curl -X POST http://localhost:3500/v1.0/publish/deathStarStatus \ -H "Content-Type: application/json" \ -d '{ "status": "completed" }'<file_sep># Falco ## Install https://github.com/falcosecurity/charts/tree/master/falco#introduction ``` helm repo add falcosecurity https://falcosecurity.github.io/charts helm repo update kubectl create namespace falco helm upgrade falco falcosecurity/falco --set fakeEventGenerator.enabled=true --set falcosidekick.enabled=true --set falcosidekick.webui.enabled=true --namespace falco --install kubectl -n falco port-forward svc/falco-falcosidekick 2801 curl -s http://localhost:2801/ping kubectl -n falco logs deployment/falco-falcosidekick kubectl port-forward svc/falco-falcosidekick-ui -n falco 2802 http://localhost:2802/ui/#/ kubectl run nginx --image=nginx kubectl exec -it nginx -- /bin/sh etc/shadow ``` ## Test falco ``` kubectl run shell --restart=Never -it --image krisnova/hack:latest \ --rm --attach \ --overrides \ '{ "spec":{ "hostPID": true, "containers":[{ "name":"scary", "image": "krisnova/hack:latest", "imagePullPolicy": "Always", "stdin": true, "tty": true, "command":["/bin/bash"], "nodeSelector":{ "dedicated":"master" }, "securityContext":{ "privileged":true } }] } }' ``` <file_sep># Multi Attach Storage https://github.com/kubernetes-sigs/azuredisk-csi-driver/tree/master/deploy/example/sharedisk https://github.com/kubernetes-sigs/azuredisk-csi-driver/blob/master/docs/install-csi-driver-master.md https://docs.microsoft.com/en-gb/azure/virtual-machines/linux/disks-shared https://discourse.ubuntu.com/t/ubuntu-high-availability-corosync-pacemaker-shared-disk-environments/14874 https://datamattsson.tumblr.com/post/187582900281/running-traditional-ha-clusters-on-kubernetes https://github.com/kubernetes-sigs/azuredisk-csi-driver/blob/master/deploy/example/failover/README.md KUBE_GROUP="dzielkedefstor" KUBE_NAME="aksdiskshared" LOCATION="westcentralus" KUBE_VERSION="1.18.6" ENG_SUB_ID az account set --subscription $ENG_SUB_ID az feature register --namespace "Microsoft.Compute" --name "SharedDisksForPremium" az feature register --name UseCustomizedContainerRuntime --namespace Microsoft.ContainerService az feature register --name UseCustomizedUbuntuPreview --namespace Microsoft.ContainerService az provider register --namespace Microsoft.ContainerService SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET az group create -n $KUBE_GROUP -l $LOCATION az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --vm-set-type VirtualMachineScaleSets --load-balancer-sku standard --kubernetes-version $KUBE_VERSION \ --node-count 3 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd Check if the feature is active ``` az feature list -o table --query "[?contains(name, 'Microsoft.RedHatOpenShift')].{Name:name,State:properties.state}" curl -skSL https://raw.githubusercontent.com/kubernetes-sigs/azuredisk-csi-driver/master/deploy/install-driver.sh | bash -s master -- cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: managed-csi provisioner: disk.csi.azure.com parameters: skuname: Premium_LRS # Currently shared disk only available with premium SSD maxShares: "2" cachingMode: None # ReadOnly cache is not available for premium SSD with maxShares>1 reclaimPolicy: Delete --- kind: PersistentVolumeClaim apiVersion: v1 metadata: name: pvc-azuredisk spec: accessModes: - ReadWriteMany resources: requests: storage: 256Gi # minimum size of shared disk is 256GB (P15) volumeMode: Block storageClassName: managed-csi EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: labels: app: nginx name: deployment-azuredisk spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx name: deployment-azuredisk spec: ports: containers: - name: deployment-azuredisk image: nginx ports: - containerPort: 80 volumeDevices: - name: azuredisk devicePath: /dev/sdx volumes: - name: azuredisk persistentVolumeClaim: claimName: pvc-azuredisk EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: labels: app: ubuntu name: deployment-ubuntu spec: replicas: 2 selector: matchLabels: app: ubuntu template: metadata: labels: app: ubuntu name: deployment-ubuntu spec: ports: containers: - name: deployment-ubuntu image: ubuntu ports: - containerPort: 80 command: - sleep - "3600" volumeDevices: - name: azuredisk devicePath: /dev/sdx volumes: - name: azuredisk persistentVolumeClaim: claimName: pvc-azuredisk EOF POD1=deployment-ubuntu-64f568d66b-ln59r POD2=deployment-ubuntu-64f568d66b-wq4cv dd if=/dev/zero of=/dev/sdx bs=1024k count=1024 du -sh /dev/sdx losetup -fP /dev/sdx kubectl exec -it $POD1 -- /bin/bash kubectl exec -it $POD2 -- /bin/bash mkfs.ext4 /dev/sdx losetup /dev/loop0 /dev/sdx cat /proc/mounts | grep /dev/loop mkdir /mnt/shareddrive mount -o loop=/dev/loop0 /dev/sdx /mnt/shareddrive echo 'Hello shell demo' > /dev/sdx/a.txt blkid mkdir /mnt/shareddrive ls /mnt/ mount -t ext4 -U 924ad3a0-0515-4f5e-babe-3824e5c3d33e /mnt/shareddrive sudo mount -o ro,noload /dev/sdx /mnt/shareddrive mount -o ro -t ext4 /dev/sdx /mnt/shareddrive df -h https://opensource.com/article/19/4/create-filesystem-linux-partition cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: azure-managed-disk spec: accessModes: - ReadWriteOnce storageClassName: managed-premium resources: requests: storage: 5Gi EOF cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: mypod spec: containers: - name: mypod image: nginx:1.15.5 resources: requests: cpu: 100m memory: 128Mi limits: cpu: 250m memory: 256Mi volumeMounts: - mountPath: "/mnt/azure" name: volume volumes: - name: volume persistentVolumeClaim: claimName: azure-managed-disk EOF<file_sep>//dependencies const grpc = require("@grpc/grpc-js"); const protoLoader = require("@grpc/proto-loader"); //path to our proto file const PROTO_FILE = "./service_def.proto"; //options needed for loading Proto file const options = { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true, }; const pkgDefs = protoLoader.loadSync(PROTO_FILE, options); //load Definition into gRPC const UserService = grpc.loadPackageDefinition(pkgDefs).UserService; //create the Client const client = new UserService( "127.0.0.1:9001", grpc.credentials.createInsecure() ); //make a call to GetUser client.GetUser({}, (error, user) => { if (error) { console.log(error); } else { console.log(user); } });<file_sep>FROM python:2.7-alpine WORKDIR /app ADD echo.py /app/ ADD requirements.txt /app/ RUN pip install -r requirements.txt CMD ["python echo.py"]<file_sep>#!/bin/sh set -euqq sudo apt update sudo apt install nodejs sudo apt install npm<file_sep>require('dotenv-extended').load(); const config = require('./config'); const express = require('express'); const app = express(); const morgan = require('morgan'); const OS = require('os'); // add logging middleware app.use(morgan('dev')); var d = new Date(); var requestStats = { totalRequestNumber :0, totalRequestFailed: 0, totalRequestThrottled: 0, timeslot: 0}; requestStats.timeslot = d.getHours() * 100 + Math.floor(d.getMinutes() / config.metricReset); var checkStats = function(newValue, incrementer){ d = new Date(); var currentTimeSlot = d.getHours() * 100 + Math.floor(d.getMinutes() / config.metricReset); if (currentTimeSlot > requestStats.timeslot){ requestStats.timeslot = currentTimeSlot; requestStats.totalRequestNumber = 0; requestStats.totalRequestFailed = 0; requestStats.totalRequestThrottled = 0; } } // Routes app.get('/', function(req, res) { console.log('received request'); requestStats.totalRequestNumber++; checkStats(); res.send('Hi!'); }); app.get('/metrics', function(req, res) { console.log('received fail request'); console.log(requestStats); var output = "# HELP http_requests_total Total number of HTTP requests made." + OS.EOL + "# TYPE http_requests_total counter" + OS.EOL + "http_requests_total{code=\"200\",handler=\"prometheus\",method=\"get\"} " + requestStats.totalRequestNumber + OS.EOL + "# HELP http_requests_throttled Total number of throttled HTTP requests made." + OS.EOL + "# TYPE http_requests_throttled counter" + OS.EOL + "http_requests_throttled{code=\"200\",handler=\"prometheus\",method=\"get\"} " + requestStats.totalRequestThrottled + "\n"; res.send(output); }); app.get('/fail/500', function(req, res) { console.log('received fail request'); requestStats.totalRequestFailed++; checkStats(); res.status(500); res.send('Failed with internal error - 500'); }); app.get('/rate/me', function(req, res) { var randomNumber = Math.floor((Math.random() * 4)); if (randomNumber < 1){ console.log('randomly sending 429'); requestStats.totalRequestThrottled++; checkStats(); res.status(429); res.send('Please slow down - 429'); }else { console.log('randomly sending 200'); requestStats.totalRequestNumber++; checkStats(); res.status(200); res.send('Please continue'); } }); app.get('/start', function(req, res) { console.log('received start request'); res.send('Started'); }); app.get('/stop', function(req, res) { console.log('received stop request'); res.status(200); res.send('stopped'); }); app.get('/ping', function(req, res) { console.log('received ping'); var startDate = new Date(); var month = (((startDate.getMonth()+1)<10) ? '0' + (startDate.getMonth()+1) : (startDate.getMonth()+1)); var day = (((startDate.getDate())<10) ? '0' + (startDate.getDate()) : (startDate.getDate())); var hour = (((startDate.getHours())<10) ? '0' + (startDate.getHours()) : (startDate.getHours())); var minute = (((startDate.getMinutes())<10) ? '0' + (startDate.getMinutes()) : (startDate.getMinutes())); var seconds = (((startDate.getSeconds())<10) ? '0' + (startDate.getSeconds()) : (startDate.getSeconds())); var logDate = startDate.getFullYear() + "-" + month+ "-" + day + " " + hour + ":" + minute + ":" + seconds; var sourceIp = req.connection.remoteAddress; var forwardedFrom = (req.headers['x-forwarded-for'] || '').split(',').pop(); var logObject = { timestamp: logDate, host: OS.hostname(), source: sourceIp, forwarded: forwardedFrom, message: "Pong!"}; var serverResult = JSON.stringify(logObject ); requestStats.totalRequestNumber++; checkStats(); console.log(serverResult.toString()); res.send(serverResult.toString()); }); app.post('/api/log', function(req, res) { console.log("received client request:"); var messageReceived = "no"; if (req.headers.message){ console.log(req.headers.message); messageReceived = req.headers.message; } var startDate = new Date(); var month = (((startDate.getMonth()+1)<10) ? '0' + (startDate.getMonth()+1) : (startDate.getMonth()+1)); var day = (((startDate.getDate())<10) ? '0' + (startDate.getDate()) : (startDate.getDate())); var hour = (((startDate.getHours())<10) ? '0' + (startDate.getHours()) : (startDate.getHours())); var minute = (((startDate.getMinutes())<10) ? '0' + (startDate.getMinutes()) : (startDate.getMinutes())); var seconds = (((startDate.getSeconds())<10) ? '0' + (startDate.getSeconds()) : (startDate.getSeconds())); var logDate = startDate.getFullYear() + "-" + month+ "-" + day + " " + hour + ":" + minute + ":" + seconds; var randomNumber = Math.floor((Math.random() * 100) + 1); var sourceIp = //(req.headers['x-forwarded-for'] || '').split(',').pop() || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; var logObject = { timestamp: logDate, value: randomNumber, host: OS.hostname(), source: sourceIp, message: messageReceived}; var serverResult = JSON.stringify(logObject ); console.log("string:"); console.log(serverResult.toString()); console.log(logDate + "," + randomNumber + "," + OS.hostname() + "," + sourceIp + "," + messageReceived); // console.log("json object:"); // console.log(logObject); res.send(serverResult.toString()); }); console.log(config); console.log(OS.hostname()); app.listen(config.port); console.log('Listening on localhost:'+ config.port); process.once('SIGQUIT', function (code) { console.log("Caught sigquit...."); }); process.once('SIGTERM', function (code) { console.log("Caught sigterm...."); }); setInterval(function() { var startDate = new Date(); var month = (((startDate.getMonth()+1)<10) ? '0' + (startDate.getMonth()+1) : (startDate.getMonth()+1)); var day = (((startDate.getDate())<10) ? '0' + (startDate.getDate()) : (startDate.getDate())); var hour = (((startDate.getHours())<10) ? '0' + (startDate.getHours()) : (startDate.getHours())); var minute = (((startDate.getMinutes())<10) ? '0' + (startDate.getMinutes()) : (startDate.getMinutes())); var seconds = (((startDate.getSeconds())<10) ? '0' + (startDate.getSeconds()) : (startDate.getSeconds())); var logDate = startDate.getFullYear() + "-" + month+ "-" + day + " " + hour + ":" + minute + ":" + seconds; console.log(OS.hostname() + " still alive " + logDate); }, 1000);<file_sep>#!/bin/sh set -e KUBE_NAME=$1 KUBE_GROUP=$2 USE_ADDON=$3 SUBSCRIPTION_ID=$(az account show --query id -o tsv) #subscriptionid LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) AKS_SUBNET_ID=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query "agentPoolProfiles[0].vnetSubnetId" -o tsv) AKS_SUBNET_NAME="aks-5-subnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" APP_NAMESPACE="dummy-logger" SECRET_NAME="mytls-cert-secret" VAULT_NAME=dzkv$KUBE_NAME CERT_MANAGER_REGISTRY=quay.io CERT_MANAGER_TAG=v1.3.1 CERT_MANAGER_IMAGE_CONTROLLER=jetstack/cert-manager-controller CERT_MANAGER_IMAGE_WEBHOOK=jetstack/cert-manager-webhook CERT_MANAGER_IMAGE_CAINJECTOR=jetstack/cert-manager-cainjector AKS_CONTROLLER_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-ctl-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-clt-id')].id" -o tsv)" IP_ID=$(az network public-ip list -g $KUBE_GROUP --query "[?contains(name, 'nginxingressauth')].id" -o tsv) if [ "$IP_ID" == "" ]; then echo "creating ingress ip nginxingressauth" az network public-ip create -g $KUBE_GROUP -n nginxingressauth --sku STANDARD --dns-name $KUBE_NAME-auth -o none IP_ID=$(az network public-ip show -g $KUBE_GROUP -n nginxingressauth -o tsv --query id) IP=$(az network public-ip show -g $KUBE_GROUP -n nginxingressauth -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n nginxingressauth -o tsv --query dnsSettings.fqdn) echo "created ip $IP_ID with $IP on $DNS" az role assignment create --role "Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $IP_ID -o none else IP=$(az network public-ip show -g $KUBE_GROUP -n nginxingressauth -o tsv --query ipAddress) DNS=$(az network public-ip show -g $KUBE_GROUP -n nginxingressauth -o tsv --query dnsSettings.fqdn) echo "AKS $AKS_ID already exists with $IP on $DNS" fi helm upgrade nginx-ingress-auth ingress-nginx/ingress-nginx --install \ --namespace ingress-auth \ --set controller.replicaCount=1 \ --set controller.metrics.enabled=true \ --set controller.service.loadBalancerIP="$IP" \ --set defaultBackend.enabled=true \ --set controller.ingressClassByName=true \ --set controller.ingressClassResource.name=nginx-auth \ --set controller.service.annotations."service\.beta\.kubernetes\.io/azure-load-balancer-health-probe-request-path"=/healthz \ --set-string controller.service.annotations.'service\.beta\.kubernetes\.io/azure-load-balancer-resource-group'="$KUBE_GROUP" \ --set-string controller.service.annotations.'service\.beta\.kubernetes\.io/azure-pip-name'="nginxingressauth" \ --set controller.service.externalTrafficPolicy=Local --wait --timeout 60s exit export CERT_NAME=ingresscert openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ -out ingress-tls.crt \ -keyout ingress-tls.key \ -subj "/CN=dzallincl-auth.westeurope.cloudapp.azure.com/O=ingress-tls" openssl pkcs12 -export -in ingress-tls.crt -inkey ingress-tls.key -out $CERT_NAME.pfx az keyvault certificate import --vault-name ${VAULT_NAME} -n $SECRET_NAME -f "$CERT_NAME.pfx" cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1 kind: SecretProviderClass metadata: name: azure-tls spec: provider: azure secretObjects: # secretObjects defines the desired state of synced K8s secret objects - secretName: ingress-tls-csi type: kubernetes.io/tls data: - objectName: $CERT_NAME key: tls.key - objectName: $CERT_NAME key: tls.crt parameters: usePodIdentity: "false" useVMManagedIdentity: "true" userAssignedIdentityID: "$AKS_KUBELET_CLIENT_ID" keyvaultName: $AKV_NAME # the name of the KeyVault objects: | array: - | objectName: $CERT_NAME objectType: secret tenantId: $TENANT_ID # the tenant ID of the KeyVault EOF if kubectl get namespace ingress; then echo -e "Namespace ingress found." else kubectl create namespace ingress echo -e "Namespace ingress created." fi if kubectl get namespace $APP_NAMESPACE; then echo -e "Namespace $APP_NAMESPACE found." else kubectl create namespace $APP_NAMESPACE echo -e "Namespace $APP_NAMESPACE created." fi sleep 2 kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml -n $APP_NAMESPACE #kubectl apply -f logging/dummy-logger/svc-cluster-logger.yaml -n dummy-logger kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml -n $APP_NAMESPACE # register aad app AD_APP_NAME="dzallincl" TLS_SECRET_NAME=$APP_HOSTNAME-tls APP_HOSTNAME="$AD_APP_NAME.$LOCATION.cloudapp.azure.com" HOMEPAGE=https://$APP_HOSTNAME IDENTIFIER_URIS=$HOMEPAGE REPLY_URLS=https://$APP_HOSTNAME/msal/signin-oidc CLIENT_ID="" OBJECT_ID="" CLIENT_SECRET="" AZURE_TENANT_ID="" cat << EOF > manifest.json [ { "resourceAccess" : [ { "id" : "e1fe6dd8-ba31-4d61-89e7-88639da4683d", "type" : "Scope" } ], "resourceAppId" : "00000003-0000-0000-c000-000000000000" } ] EOF cat manifest.json # Create the Azure AD SP for our application and save the Client ID to a variable CLIENT_ID=$(az ad app create --display-name $AD_APP_NAME --homepage $HOMEPAGE --reply-urls $REPLY_URLS --required-resource-accesses @manifest.json -o json | jq -r '.appId') echo $CLIENT_ID OBJECT_ID=$(az ad app show --id $CLIENT_ID -o json | jq '.objectId' -r) echo $OBJECT_ID az ad app update --id $OBJECT_ID --set "isEnabled=false" az ad app update --id $OBJECT_ID --set "oauth2Permissions=[]" # The newly registered app does not have a password. Use "az ad app credential reset" to add password and save to a variable. CLIENT_SECRET=$(az ad app credential reset --id $CLIENT_ID -o json | jq '.password' -r) echo $CLIENT_SECRET # Get your Azure AD tenant ID and save to variable AZURE_TENANT_ID=$(az account show -o json | jq '.tenantId' -r) echo $AZURE_TENANT_ID kubectl create secret generic aad-secret -n dummy-logger \ --from-literal=AZURE_TENANT_ID=$AZURE_TENANT_ID \ --from-literal=CLIENT_ID=$CLIENT_ID \ --from-literal=CLIENT_SECRET=$CLIENT_SECRET helm upgrade msal-proxy ./charts/msal-proxy --install -n dummy-logger kubectl run kuard-pod --image=gcr.io/kuar-demo/kuard-amd64:1 --expose --port=8080 -n dummy-logger cat << EOF > ./kuard-ingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-$APP_NAMESPACE namespace: $APP_NAMESPACE annotations: cert-manager.io/cluster-issuer: letsencrypt nginx.ingress.kubernetes.io/auth-url: "https://\$host/msal/auth" nginx.ingress.kubernetes.io/auth-signin: "https://\$host/msal/index?rd=\$escaped_request_uri" nginx.ingress.kubernetes.io/auth-response-headers: "x-injected-aio,x-injected-name,x-injected-nameidentifier,x-injected-objectidentifier,x-injected-preferred_username,x-injected-tenantid,x-injected-uti" nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" nginx.ingress.kubernetes.io/configuration-snippet: | proxy_ssl_name "default.dummy-logger.cluster.local"; nginx.ingress.kubernetes.io/proxy-ssl-secret: "kube-system/osm-nginx-client-cert" nginx.ingress.kubernetes.io/proxy-ssl-verify: "on" nginx.ingress.kubernetes.io/rewrite-target: /\$1 spec: tls: - hosts: - $DNS secretName: $SECRET_NAME ingressClassName: nginx rules: - host: $DNS http: paths: - backend: service: name: kuard-pod port: number: 8080 path: /(.*) pathType: ImplementationSpecific --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: msal-proxy namespace: $APP_NAMESPACE spec: rules: - host: $DNS http: paths: - backend: service: name: msal-proxy port: number: 80 path: /msal pathType: ImplementationSpecific tls: - hosts: - $DNS secretName: $SECRET_NAME EOF <file_sep># Scrapping Nginx metrics for Container insights https://docs.microsoft.com/en-us/azure/azure-monitor/insights/container-insights-agent-config#overview-of-configurable-prometheus-scraping-settings ``` # HELP nginx_ingress_controller_nginx_process_requests_total total number of client requests # TYPE nginx_ingress_controller_nginx_process_requests_total counter nginx_ingress_controller_nginx_process_requests_total{controller_class="nginx",controller_namespace="kube-system",controller_pod="nginx-ingress-controller-95d976c8b-4km4p"} 566 ``` ``` # HELP promhttp_metric_handler_requests_total Total number of scrapes by HTTP status code. # TYPE promhttp_metric_handler_requests_total counter promhttp_metric_handler_requests_total{code="200"} 6 ``` wget https://raw.githubusercontent.com/microsoft/OMS-docker/ci_feature_prod/Kubernetes/container-azm-ms-agentconfig.yaml <file_sep># Deploy voting app ``` kubectl apply -f https://raw.githubusercontent.com/Azure-Samples/azure-voting-app-redis/master/azure-vote-all-in-one-redis.yaml kubectl get pod -o wide kubectl scale --replicas=6 deployment/azure-vote-front kubectl scale --replicas=4 deployment/azure-vote-back kubectl autoscale deployment azure-vote-front --cpu-percent=20 --min=20 --max=30 kubectl get hpa kubectl run -it busybox-replicas --rm --image=busybox -- sh for i in 1 2 3 4 5; do wget -q -O- http://azure-vote-front done kubectl run -it busybox-replicas --rm --image=busybox -- sh for i in 1 ... 1000; do \ wget -q -O- http://6192.168.127.12 \ done for i in `seq 1 100`; do time curl -s http://40.85.173.109 > /dev/null; done for i in {1...200} \ do \ curl -q -O- "http://azure-vote-front?i="$i \ done while true; do sleep 1; curl http://40.85.173.109; echo -e '\n\n\n\n'$(date);done for i in {1..2000} wget -q -O- http://6172.16.58.34?{1..2000} ``` # Virtual node autoscaling https://github.com/Azure-Samples/virtual-node-autoscale ``` helm install --name vn-affinity ./charts/vn-affinity-admission-controller kubectl label namespace default vn-affinity-injection=enabled --overwrite export VK_NODE_NAME=virtual-node-aci-linux export INGRESS_EXTERNAL_IP=172.16.58.3 export INGRESS_CLASS_ANNOTATION=nginx helm install ./charts/online-store --name online-store --set counter.specialNodeName=$VK_NODE_NAME,app.ingress.host=store.$INGRESS_EXTERNAL_IP.nip.io,appInsight.enabled=false,app.ingress.annotations."kubernetes\.io/ingress\.class"=$INGRESS_CLASS_ANNOTATION --namespace store kubectl -n kube-system get po nginx-ingress-controller-7db8d69bcc-t5zww -o yaml | grep ingress-class | sed -e 's/.*=//' helm install stable/grafana --version 1.26.1 --name grafana -f grafana/values.yaml kubectl get secret --namespace default grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo 5D7bs0dkBOxvutbEbpGBHRghxMhCWAuHyyYXawfH export POD_NAME=$(kubectl get pods --namespace default -l "app=grafana" -o jsonpath="{.items[0].metadata.name}") kubectl --namespace default port-forward $POD_NAME 3000 open http://localhost:3000 az aks get-credentials --resource-group dzburstdemo2 --name dzburst export GOPATH=~/go export PATH=$GOPATH/bin:$PATH go get -u github.com/rakyll/hey PUBLIC_IP="store.192.168.3.113.nip.io/" hey -z 20m http://$PUBLIC_IP ``` # Keda https://github.com/kedacore/sample-hello-world-azure-functions ``` KEDA_STORAGE=dzmesh33 LOCATION=westeurope az group create -l $LOCATION -n $KUBE_GROUP az storage account create --sku Standard_LRS --location $LOCATION -g $KUBE_GROUP -n $KEDA_STORAGE CONNECTION_STRING=$(az storage account show-connection-string --name $KEDA_STORAGE --query connectionString) az storage queue create -n js-queue-items --connection-string $CONNECTION_STRING az storage account show-connection-string --name $KEDA_STORAGE --query connectionString kubectl create namespace keda-app helm install --name vn-affinity ./charts/vn-affinity-admission-controller kubectl label namespace keda vn-affinity-injection=disabled --overwrite KEDA_NS=keda-app KEDA_IN=hello-keda func kubernetes install --namespace $KEDA_NS func kubernetes deploy --name $KEDA_IN --registry denniszielke --namespace $KEDA_NS --polling-interval 5 --cooldown-period 30 kubectl get ScaledObject $KEDA_IN --namespace $KEDA_NS -o yaml kubectl delete deploy $KEDA_IN --namespace $KEDA_NS kubectl delete ScaledObject $KEDA_IN --namespace $KEDA_NS kubectl delete Secret $KEDA_IN --namespace $KEDA_NS helm install --name vn-affinity ./charts/vn-affinity-admission-controller kubectl label namespace default vn-affinity-injection=enabled helm install ./charts/online-store --name online-store --set counter.specialNodeName=$VK_NODE_NAME,app.ingress.host=store.$INGRESS_EXTERNAL_IP.nip.io,appInsight.enabled=false,app.ingress.annotations."kubernetes\.io/ingress\.class"=$INGRESS_CLASS_ANNOTATION ``` ## Cluster autoscaler test ``` kubectl run nginx --image=nginx --requests=cpu=1000m,memory=1024Mi --expose --port=80 --replicas=5 kubectl scale deployment nginx --replicas=10 ``` while true; do sleep 1; curl http://10.0.1.14/ping; echo -e '\n\n\n\n'$(date);done az network lb rule list --lb-name kubernetes-internal --resource-group kub_ter_a_m_scaler2_nodes_westeurope az network lb rule update --name a13c54ea6e04e11e984ea82987248e36-ing-4-subnet-TCP-80 --lb-name kubernetes-internal --resource-group kub_ter_a_m_scaler2_nodes_westeurope --enable-tcp-reset true az network lb rule list --lb-name kubernetes-internal --resource-group kub_ter_a_m_scaler_nodes_westeurope az network lb rule update --name a69b6ac41e04e11e98bc46e0d4f805cb-ing-4-subnet-TCP-80 --lb-name kubernetes-internal --resource-group kub_ter_a_m_scaler_nodes_westeurope --enable-tcp-reset true # Scaling with custom metrics https://github.com/Azure/azure-k8s-metrics-adapter ``` AKS_GROUP=dzphix_520 AKS_NAME=dzphix-520 BLOB_NAME=dzphinx520 LOCATION=westeurope AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) AZURE_SUBSCRIPTION_NAME=$(az account show --query name -o tsv) AZURE_SUBSCRIPTION_ID=$(az account show --query id -o tsv) AKS_METRICS_PRINCIPAL_ID=$(az ad sp create-for-rbac -n "$BLOB_NAME-sp" --role "Monitoring Reader" --scopes /subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$AKS_GROUP -o json | jq -r '.appId') AKS_METRICS_PRINCIPAL_SECRET=$(az ad app credential reset --id $AKS_METRICS_PRINCIPAL_ID -o json | jq '.password' -r) az storage account create --resource-group $AKS_GROUP --name $BLOB_NAME --location $LOCATION --sku Standard_LRS --output none STORAGE_KEY=$(az storage account keys list --account-name $BLOB_NAME --resource-group $AKS_GROUP --query "[0].value" -o tsv) az storage container create -n tfstate --account-name $BLOB_NAME --account-key $STORAGE_KEY --output none #use values from service principle created above to create secret kubectl create secret generic azure-k8s-metrics-adapter -n custom-metrics \ --from-literal=azure-tenant-id=$AZURE_TENANT_ID \ --from-literal=azure-client-id=$AKS_METRICS_PRINCIPAL_ID \ --from-literal=azure-client-secret=$AKS_METRICS_PRINCIPAL_SECRET kubectl apply -f https://raw.githubusercontent.com/Azure/azure-k8s-metrics-adapter/master/deploy/adapter.yaml cat <<EOF | kubectl apply -f - apiVersion: azure.com/v1alpha2 kind: ExternalMetric metadata: name: external-metric-blobs namespace: custom-metrics spec: type: azuremonitor azure: resourceGroup: $AKS_GROUP resourceName: resourceProviderNamespace: Microsoft.Storage resourceType: storageAccounts/$BLOB_NAME/blobServices metric: metricName: BlobCount aggregation: Total filter: BlobType eq 'Block blob' EOF kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1" | jq . kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/custom-metrics/external-metric-blobs" | jq . cat <<EOF | kubectl apply -f - apiVersion: autoscaling/v2beta2 kind: HorizontalPodAutoscaler metadata: name: external-metric-blobs spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: consumer minReplicas: 1 maxReplicas: 10 metrics: - type: External external: metricName: external-metric-blobs targetValue: 30 EOF ``` # metrics ``` AKS_GROUP=dzphix_520 AKS_NAME=dzphix-520 BLOB_NAME=dzphinx520 LOCATION=westeurope AZURE_TENANT_ID=$(az account show --query tenantId -o tsv) AZURE_SUBSCRIPTION_NAME=$(az account show --query name -o tsv) AZURE_SUBSCRIPTION_ID=$(az account show --query id -o tsv) AKS_METRICS_PRINCIPAL_ID=$(az ad sp create-for-rbac -n "$BLOB_NAME-sp" --role "Monitoring Reader" --scopes /subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$AKS_GROUP -o json | jq -r '.appId') AKS_METRICS_PRINCIPAL_SECRET=$(az ad app credential reset --id $AKS_METRICS_PRINCIPAL_ID -o json | jq '.password' -r) curl -X POST https://login.microsoftonline.com/$AZURE_TENANT_ID/oauth2/token -F "grant_type=client_credentials" -F "$AKS_METRICS_PRINCIPAL_ID" -F "client_secret=$AKS_METRICS_PRINCIPAL_SECRET" -F "resource=https://monitoring.azure.com/" ``` # Promitor wget -b https://raw.githubusercontent.com/tomkerkhove/promitor/master/charts/promitor-agent-scraper/values.yaml https://github.com/tomkerkhove/promitor/blob/master/docs/configuration/v2.x/metrics/blob-storage.md helm repo add promitor https://promitor.azurecr.io/helm/v1/repo helm upgrade promitor-agent-scraper promitor/promitor-agent-scraper \ --set azureAuthentication.appId="$AKS_METRICS_PRINCIPAL_ID" \ --set azureAuthentication.appKey="$AKS_METRICS_PRINCIPAL_SECRET" \ --set azureMetadata.tenantId="$AZURE_TENANT_ID" \ --set azureMetadata.subscriptionId="$AZURE_SUBSCRIPTION_ID" \ --set azureMetadata.resourceGroupName="$AKS_GROUP" \ --values values.yaml --install helm delete promitor-agent-scraper export POD_NAME=$(kubectl get pods --namespace default -l "app=promitor-agent-scraper,release=promitor-agent-scraper" -o jsonpath="{.items[0].metadata.name}") kubectl port-forward --namespace default $POD_NAME 8080:8080 http://0.0.0.0:8080/metrics ``` # keda ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Secret metadata: name: azure-monitor-secrets data: activeDirectoryClientId: $AKS_METRICS_PRINCIPAL_ID activeDirectoryClientPassword: $<PASSWORD> --- apiVersion: keda.k8s.io/v1alpha1 kind: TriggerAuthentication metadata: name: azure-monitor-trigger-auth spec: secretTargetRef: - parameter: activeDirectoryClientId name: azure-monitor-secrets key: activeDirectoryClientId - parameter: activeDirectoryClientPassword name: azure-monitor-secrets key: activeDirectoryClientPassword --- apiVersion: keda.k8s.io/v1alpha1 kind: ScaledObject metadata: name: azure-monitor-scaler labels: app: azure-monitor-example spec: scaleTargetRef: deploymentName: azure-monitor-example minReplicaCount: 1 maxReplicaCount: 10 triggers: - type: azure-monitor metadata: resourceURI: Microsoft.ContainerService/managedClusters/azureMonitorCluster tenantId: $AZURE_TENANT_ID subscriptionId: $AZURE_SUBSCRIPTION_ID resourceGroupName: $AKS_GROUP metricName: kube_pod_status_ready metricFilter: namespace eq 'default' metricAggregationInterval: "0:1:0" metricAggregationType: Average targetValue: "1" authenticationRef: name: azure-monitor-trigger-auth EOF ``` # builtin cat <<EOF | kubectl apply -f - apiVersion: autoscaling/v2beta2 kind: HorizontalPodAutoscaler metadata: name: dummy-logger spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: dummy-logger minReplicas: 1 maxReplicas: 10 metrics: - type: Pods pods: metric: name: packets-per-second target: type: AverageValue averageValue: 10 EOF cat <<EOF | kubectl apply -f - apiVersion: autoscaling/v2beta2 kind: HorizontalPodAutoscaler metadata: name: dummy-logger spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: dummy-logger minReplicas: 1 maxReplicas: 10 metrics: - type: Pods pods: metric: name: http_requests target: type: AverageValue averageValue: 10 EOF ### kubectl create deployment hello-echo --image=k8s.gcr.io/echoserver:1.10 --namespace=ingress-basic kubectl expose deployment echoserver --type=LoadBalancer --port=8080 --namespace=ingress-basic cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: calculator-ingress namespace: ingress-basic annotations: kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt spec: tls: - hosts: - 172.16.31.10.xip.io secretName: tls-secret rules: - host: 172.16.31.10.xip.io http: paths: - backend: serviceName: echoserver servicePort: 8080 path: / EOF<file_sep># AKS Admission Controllers ## PodNodeSelector cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Namespace metadata: annotations: scheduler.alpha.kubernetes.io/node-selector: env=development name: dev EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: nginx namespace: dev spec: containers: - name: nginx image: nginx EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: nginx namespace: dev spec: containers: - name: nginx image: nginx nodeSelecor: env: prod EOF ## PodTolerationRestriction apiVersion: v1 kind: Namespace metadata: name: apps-that-need-nodes-exclusively annotations: scheduler.alpha.kubernetes.io/defaultTolerations: '[{"operator": "Exists", "effect": "NoSchedule", "key": "dedicated-node"}]' cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: nginx namespace: apps-that-need-nodes-exclusively spec: containers: - name: nginx image: nginx EOF ## ExtendedResourceToleration kubectl taint no aks-nodes-32411630-vmss000000 nvidia.com/gpu:NoSchedule cat <<EOF | kubectl apply -f - apiVersion: batch/v1 kind: Job metadata: labels: app: samples-tf-mnist-demo name: samples-tf-mnist-demo spec: template: metadata: labels: app: samples-tf-mnist-demo spec: containers: - name: samples-tf-mnist-demo image: microsoft/samples-tf-mnist-demo:gpu args: ["--max_steps", "500"] imagePullPolicy: IfNotPresent resources: limits: nvidia.com/gpu: 1 restartPolicy: OnFailure EOF<file_sep> ## logging ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/pod-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-lb-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-int-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-lb-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-lb-pl-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-node-logger.yaml export DUMMY_LOGGER_IP=$(kubectl get svc --namespace $DEMO_NS dummy-logger-svc-lb -o jsonpath='{.status.loadBalancer.ingress[0].ip}') export DUMMY_LOGGER_IP=$(kubectl get svc dummy-logger-pub-lb -o jsonpath='{.status.loadBalancer.ingress[0].ip}') kubectl patch deployment simple --type=json -p='[{"op": "add", "path": "/spec/template/metadata/labels/this", "value": "that"}]' kubectl patch svc dummy-logger-pub-lb --type='json' -p='[{"op": "add", "path": "/metadata/annotations/service.beta.kubernetes.io/azure-load-balancer-internal", "value":"true"}]' kubectl patch svc dummy-logger-pub-lb -p '{"metadata": {"annotations":{"service.beta.kubernetes.io/azure-load-balancer-internal":"true"}} }' kubectl patch svc azure-vote-front -p '{"metadata": {"annotations":{"service.beta.kubernetes.io/azure-load-balancer-internal":"true"}} }' curl -X POST http://$DUMMY_LOGGER_IP/api/log -H "message: {more: content}" curl -X POST http://$DUMMY_LOGGER_IP/api/log -H "message: hi" cat <<EOF | kubectl apply -f - apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: dummy-ingress annotations: kubernetes.io/ingress.class: nginx spec: rules: - host: $DNS http: paths: - path: / backend: serviceName: dummy-logger-int-lb servicePort: 80 EOF ``` ## echo ``` kubectl run hello-world --quiet --image=busybox --restart=OnFailure -- echo "Hello Kubernetes!" cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos namespace: calculator spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF ``` ## emojivoto ``` kubectl create namespace emojivoto osm namespace add emojivoto --mesh-name osm curl -sL https://run.linkerd.io/emojivoto.yml \ | kubectl apply -f - kubectl -n emojivoto port-forward svc/web-svc 8080:80 ``` ## dummy ``` kubectl create namespace dummy osm namespace add dummy --mesh-name osm kubectl run --generator=run-pod/v1 --image=dummy-logger dummy-logger --port=80 -n aadsecured kubectl port-forward -n osm-simple-app frontend-7794dbcdc7-rdmjz 8080:80 ``` ## crashing app ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/crashing-app/crashing-depl.yaml kubectl scale deployment crashing-app -n crashing-app --replicas=4 ``` ## nginx ``` helm upgrade --install ingress-nginx ingress-nginx \ --repo https://kubernetes.github.io/ingress-nginx \ --namespace ingress-nginx --create-namespace ``` ## calc ``` helm repo add phoenix 'https://raw.githubusercontent.com/denniszielke/phoenix/master/' helm repo update helm search repo phoenix AZURE_CONTAINER_REGISTRY_NAME=phoenix KUBERNETES_NAMESPACE=calculator BUILD_BUILDNUMBER=latest AZURE_CONTAINER_REGISTRY_URL=denniszielke APPINSIGHTY_KEY=InstrumentationKey= AZURE_REDIS_HOST=dzcache.redis.cache.windows.net AZURE_REDIS_KEY= DNS=ndzcilium3.northeurope.cloudapp.azure.com kubectl create namespace $KUBERNETES_NAMESPACE kubectl label namespace $KUBERNETES_NAMESPACE istio.io/rev=asm-1-17 helm upgrade calculator $AZURE_CONTAINER_REGISTRY_NAME/multicalculator --namespace $KUBERNETES_NAMESPACE --install --create-namespace --set replicaCount=2 --set image.frontendTag=$BUILD_BUILDNUMBER --set image.backendTag=$BUILD_BUILDNUMBER --set image.repository=$AZURE_CONTAINER_REGISTRY_URL --set dependencies.usePodRedis=false --set ingress.enabled=false --set service.type=LoadBalancer --set ingress.tls=false --set introduceRandomResponseLag=true --set introduceRandomResponseLagValue=2 --set dependencies.useAppInsights=false --set dependencies.useAzureRedis=false --wait helm upgrade calculatornotls $AZURE_CONTAINER_REGISTRY_NAME/multicalculator --namespace calculatornotls --install --create-namespace --set replicaCount=4 --set image.frontendTag=$BUILD_BUILDNUMBER --set image.backendTag=$BUILD_BUILDNUMBER --set image.repository=$AZURE_CONTAINER_REGISTRY_URL --set dependencies.usePodRedis=false --set ingress.enabled=true --set ingress.tls=false --set ingress.host=172.16.31.10.nip.io --set introduceRandomResponseLag=true --set introduceRandomResponseLagValue=2 --set ingress.class=webapprouting.kubernetes.azure.com --wait --timeout 45s helm upgrade calculator $AZURE_CONTAINER_REGISTRY_NAME/multicalculator --namespace $KUBERNETES_NAMESPACE --install --create-namespace --set replicaCount=4 --set image.frontendTag=$BUILD_BUILDNUMBER --set image.backendTag=$BUILD_BUILDNUMBER --set image.repository=$AZURE_CONTAINER_REGISTRY_URL --set dependencies.usePodRedis=true --set ingress.enabled=true --set ingress.tls=true --set ingress.host=$DNS --set noProbes=true --set introduceRandomResponseLag=true --set introduceRandomResponseLagValue=2 --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTY_KEY --wait --timeout 45s helm upgrade calculator $AZURE_CONTAINER_REGISTRY_NAME/multicalculator --namespace $KUBERNETES_NAMESPACE --install --create-namespace --set replicaCount=4 --set image.frontendTag=$BUILD_BUILDNUMBER --set image.backendTag=$BUILD_BUILDNUMBER --set image.repository=$AZURE_CONTAINER_REGISTRY_URL --set dependencies.usePodRedis=false --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTY_KEY --set ingress.enabled=false --set service.type=LoadBalancer --set noProbes=true --set introduceRandomResponseLag=true --set introduceRandomResponseLagValue=2 --wait --timeout 45s helm upgrade calculator $AZURE_CONTAINER_REGISTRY_NAME/multicalculator --namespace $KUBERNETES_NAMESPACE --install --create-namespace --set replicaCount=1 --set image.frontendTag=$BUILD_BUILDNUMBER --set image.backendTag=$BUILD_BUILDNUMBER --set image.repository=$AZURE_CONTAINER_REGISTRY_URL --set dependencies.usePodRedis=true --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTY_KEY --set ingress.enabled=false --set service.type=LoadBalancer --set noProbes=true --set introduceRandomResponseLag=true --set introduceRandomResponseLagValue=2 --set dependencies.useAzureRedis=true --set dependencies.redisHostValue=$AZURE_REDIS_HOST --set dependencies.redisKeyValue=$AZURE_REDIS_KEY --set dependencies.usePodRedis=false --wait --timeout 45s helm upgrade calculator $AZURE_CONTAINER_REGISTRY_NAME/multicalculator --namespace $KUBERNETES_NAMESPACE --install --create-namespace --set replicaCount=4 --set image.frontendTag=$BUILD_BUILDNUMBER --set image.backendTag=$BUILD_BUILDNUMBER --set image.repository=$AZURE_CONTAINER_REGISTRY_URL --set dependencies.useAzureRedis=true --set dependencies.redisHostValue=$AZURE_REDIS_HOST --set dependencies.redisKeyValue=$AZURE_REDIS_KEY --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTY_KEY --set dependencies.useIngress=true --set ingress.enabled=true --set ingress.host=$DNS --set service.type=ClusterIP --set noProbes=true --set introduceRandomResponseLag=true --set introduceRandomResponseLagValue=3 --wait --timeout 45s helm upgrade calculator $AZURE_CONTAINER_REGISTRY_NAME/multicalculator --namespace $KUBERNETES_NAMESPACE --install --create-namespace --set replicaCount=1 --set image.frontendTag=$BUILD_BUILDNUMBER --set image.backendTag=$BUILD_BUILDNUMBER --set image.repository=$AZURE_CONTAINER_REGISTRY_URL --set dependencies.useAzureRedis=true --set dependencies.redisHostValue=$AZURE_REDIS_HOST --set dependencies.redisKeyValue=$AZURE_REDIS_KEY --set dependencies.useAppInsights=true --set dependencies.appInsightsSecretValue=$APPINSIGHTY_KEY --set dependencies.useIngress=true --set ingress.enabled=true --set ingress.tls=false --set ingress.host=$DNS --set service.type=ClusterIP --set noProbes=false --set introduceRandomResponseLag=true --set introduceRandomResponseLagValue=3 --set deployRequester=true --wait --timeout 45s helm delete calculator -n $KUBERNETES_NAMESPACE kubectl apply -f - <<EOF apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: calculator-gateway-external namespace: $KUBERNETES_NAMESPACE spec: selector: istio: aks-istio-ingressgateway-external servers: - port: number: 80 name: http protocol: HTTP hosts: - "*" --- apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: calculator-vs-external namespace: $KUBERNETES_NAMESPACE spec: hosts: - "*" gateways: - calculator-gateway-external http: - match: - uri: prefix: / route: - destination: host: calculator-multicalculator-frontend-svc port: number: 80 EOF ``` apiVersion: cilium.io/v2 kind: CiliumNetworkPolicy metadata: name: allowed spec: endpointSelector: {} ingress: - fromEntities: - cluster egress: - toFQDNs: - matchPattern: "*.in.applicationinsights.azure.com" toPorts: - ports: - port: "443" - toFQDNs: - matchPattern: "*.livediagnostics.monitor.azure.com" toPorts: - ports: - port: "443" - toFQDNs: - matchName: dzcache.redis.cache.windows.net toPorts: - ports: - port: "443" kubectl apply -f - <<EOF kind: NetworkPolicy apiVersion: networking.k8s.io/v1 metadata: name: backend-policy namespace: calculator spec: podSelector: matchLabels: role: backend ingress: - from: - podSelector: matchLabels: role: frontend EOF ``` ``` ## crashing ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/crashing-app/crashing-app.yaml export CRASHING_APP_IP=$(kubectl get svc --namespace $DEMO_NS crashing-app -o jsonpath='{.status.loadBalancer.ingress[0].ip}') curl -X GET http://$CRASHING_APP_IP/crash ``` ## color kubectl create namespace colors osm namespace add colors kubectl apply -f https://raw.githubusercontent.com/DanielMeixner/DebugContainer/master/yamls/red-green-yellow.yaml -n colors kubectl port-forward -n colors deploy/appa 8009:80 ## vm logger ``` curl -sL https://run.linkerd.io/install | sh ``` ## dapr ``` helm repo add bitnami https://charts.bitnami.com/bitnami helm repo update helm upgrade redis bitnami/redis --install --set cluster.enabled=false --set password=<PASSWORD> --namespace default helm delete redis cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: statestore spec: type: state.redis version: v1 metadata: - name: redisHost value: redis-master:6379 - name: redisPassword value: <PASSWORD> EOF kubectl apply -f https://raw.githubusercontent.com/dapr/quickstarts/master/distributed-calculator/deploy/dotnet-subtractor.yaml kubectl apply -f https://raw.githubusercontent.com/dapr/quickstarts/master/distributed-calculator/deploy/go-adder.yaml kubectl apply -f https://raw.githubusercontent.com/dapr/quickstarts/master/distributed-calculator/deploy/node-divider.yaml kubectl apply -f https://raw.githubusercontent.com/dapr/quickstarts/master/distributed-calculator/deploy/python-multiplier.yaml kubectl apply -f https://raw.githubusercontent.com/dapr/quickstarts/master/distributed-calculator/deploy/react-calculator.yaml kubectl apply -f https://raw.githubusercontent.com/dapr/quickstarts/master/distributed-calculator/deploy/redis.yaml ``` ## linkerd smi https://linkderdsmi.westeurope.cloudapp.azure.com/ https://aka.ms/ci-privatepreview http://aka.ms/AMPMonitoring https://aka.ms/smartinsights <file_sep> ## Kubernetes on Azure <file_sep>(function() { $(document).ready(function(){ $("button").click(function(){ var text = $("#message").val(); var uid = uuidv4(); $.ajax({ url: 'publish', contentType : 'application/json', dataType: 'json', data: JSON.stringify({ "message": text, "guid": uid}), type: 'post', success: function(data) { // check if available $("#result").text("Result: " + data.message + " " + data.guid); }, error: function(e) { // error logging $("#result").text("Result: " + e.statusText); } }); }); }); function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); };<file_sep>SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id KUBE_GROUP="kubes_fw_knet" # here enter the resources group name of your AKS cluster KUBE_NAME="dzkubekube" # here enter the name of your kubernetes resource LOCATION="westeurope" # here enter the datacenter location KUBE_VNET_NAME="knets" # here enter the name of your vnet KUBE_FW_SUBNET_NAME="AzureFirewallSubnet" # this you cannot change APPGW_SUBNET_NAME="gw-1-subnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" # here enter the name of your ingress subnet KUBE_AGENT_SUBNET_NAME="aks-5-subnet" # here enter the name of your AKS subnet FW_NAME="dzkubenetfw" # here enter the name of your azure firewall resource APPGW_NAME="dzkubeappgw" KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" # here enter the kubernetes version of your AKS KUBE_CNI_PLUGIN="azure" az account set --subscription $SUBSCRIPTION_ID az group create -n $KUBE_GROUP -l $LOCATION echo "setting up service principal" SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) sleep 5 # wait for replication az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP echo "setting up vnet" az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_FW_SUBNET_NAME --address-prefix 10.0.3.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $APPGW_SUBNET_NAME --address-prefix 10.0.2.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage echo "setting up azure firewall" az extension add --name azure-firewall az network public-ip create -g $KUBE_GROUP -n $FW_NAME-ip --sku Standard FW_PUBLIC_IP=$(az network public-ip show -g $KUBE_GROUP -n $FW_NAME-ip --query ipAddress) az network firewall create --name $FW_NAME --resource-group $KUBE_GROUP --location $LOCATION az network firewall ip-config create --firewall-name $FW_NAME --name $FW_NAME --public-ip-address $FW_NAME-ip --resource-group $KUBE_GROUP --vnet-name $KUBE_VNET_NAME FW_PRIVATE_IP=$(az network firewall show -g $KUBE_GROUP -n $FW_NAME --query "ipConfigurations[0].privateIpAddress" -o tsv) az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $FW_NAME-lgw --location $LOCATION echo "setting up user defined routes" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az network route-table create -g $KUBE_GROUP --name $FW_NAME-rt az network route-table route create --resource-group $KUBE_GROUP --name $FW_NAME --route-table-name $FW_NAME-rt --address-prefix 0.0.0.0/0 --next-hop-type VirtualAppliance --next-hop-ip-address $FW_PRIVATE_IP az network vnet subnet update --route-table $FW_NAME-rt --ids $KUBE_AGENT_SUBNET_ID az network route-table route list --resource-group $KUBE_GROUP --route-table-name $FW_NAME-rt echo "setting up network rules" az network firewall network-rule create --firewall-name $FW_NAME --collection-name "time" --destination-addresses "*" --destination-ports 123 --name "allow network" --protocols "UDP" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "aks node time sync rule" --priority 101 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "dns" --destination-addresses "*" --destination-ports 53 --name "allow network" --protocols "Any" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "aks node dns rule" --priority 102 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "servicetags" --destination-addresses "AzureContainerRegistry" "MicrosoftContainerRegistry" "AzureActiveDirectory" "AzureMonitor" --destination-ports "*" --name "allow service tags" --protocols "Any" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "allow service tags" --priority 110 az network firewall network-rule create --firewall-name $FW_NAME --collection-name "hcp" --destination-addresses "AzureCloud.$LOCATION" --destination-ports "1194" --name "allow master tags" --protocols "UDP" --resource-group $KUBE_GROUP --source-addresses "*" --action "Allow" --description "allow aks link access to masters" --priority 120 echo "setting up application rules" az network firewall application-rule create --firewall-name $FW_NAME --resource-group $KUBE_GROUP --collection-name 'aksfwar' -n 'fqdn' --source-addresses '*' --protocols 'http=80' 'https=443' --fqdn-tags "AzureKubernetesService" --action allow --priority 101 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "osupdates" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $KUBE_GROUP --action "Allow" --target-fqdns "download.opensuse.org" "security.ubuntu.com" "packages.microsoft.com" "azure.archive.ubuntu.com" "changelogs.ubuntu.com" "snapcraft.io" "api.snapcraft.io" "motd.ubuntu.com" --priority 102 az network firewall application-rule create --firewall-name $FW_NAME --collection-name "dockerhub" --name "allow network" --protocols http=80 https=443 --source-addresses "*" --resource-group $KUBE_GROUP --action "Allow" --target-fqdns "*auth.docker.io" "*cloudflare.docker.io" "*cloudflare.docker.com" "*registry-1.docker.io" --priority 200 echo "setting up aks" KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --network-plugin $KUBE_CNI_PLUGIN --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --no-ssh-key --outbound-type userDefinedRouting echo "setting up azure monitor" az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --location $LOCATION WORKSPACE_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME -o json | jq '.id' -r) az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons monitoring --workspace-resource-id $WORKSPACE_ID<file_sep>## Stage 1 : build with maven builder image with native capabilities FROM quay.io/quarkus/ubi-quarkus-native-image:21.3.1-java11 AS build COPY --chown=quarkus:quarkus mvnw /code/mvnw COPY --chown=quarkus:quarkus .mvn /code/.mvn COPY --chown=quarkus:quarkus pom.xml /code/ USER quarkus WORKDIR /code RUN ./mvnw -B org.apache.maven.plugins:maven-dependency-plugin:3.1.2:go-offline COPY src /code/src RUN ./mvnw package -Pnative FROM quay.io/quarkus/quarkus-micro-image:1.0 WORKDIR /work/ COPY --from=build /code/target/*-runner /work/application # set up permissions for user `1001` RUN chmod 775 /work /work/application \ && chown -R 1001 /work \ && chmod -R "g+rwX" /work \ && chown -R 1001:root /work EXPOSE 8080 USER 1001 CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] # FROM registry.access.redhat.com/ubi8/ubi-minimal:8.4 # ARG JAVA_PACKAGE=java-11-openjdk-headless # ARG RUN_JAVA_VERSION=1.3.8 # ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' # # ENV APPLICATIONINSIGHTS_CONNECTION_STRING='InstrumentationKey=' # # ENV ENDPOINT_HOST=host.docker.internal # #ENV ENDPOINT_HOST=localhost # ENV ENDPOINT_PORT=3000 # # Install java and the run-java script # # Also set up permissions for user `1001` # RUN microdnf install curl ca-certificates ${JAVA_PACKAGE} \ # && microdnf update \ # && microdnf clean all \ # && mkdir /deployments \ # && chown 1001 /deployments \ # && chmod "g+rwX" /deployments \ # && chown 1001:root /deployments \ # && curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \ # && chown 1001 /deployments/run-java.sh \ # && chmod 540 /deployments/run-java.sh \ # && echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/conf/security/java.security # # Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. # ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager -javaagent:/deployments/agent/applicationinsights-agent.jar" # # We make four distinct layers so if there are application changes the library layers can be re-used # COPY --from=BUILD --chown=1001 target/quarkus-app/lib/ /deployments/lib/ # COPY --from=BUILD --chown=1001 target/quarkus-app/lib/main/com.microsoft.azure.applicationinsights-agent-*.jar /deployments/agent/applicationinsights-agent.jar # COPY --from=BUILD --chown=1001 target/quarkus-app/*.jar /deployments/ # COPY --from=BUILD --chown=1001 target/quarkus-app/app/ /deployments/app/ # COPY --from=BUILD --chown=1001 target/quarkus-app/quarkus/ /deployments/quarkus/ # EXPOSE 8080 # USER 1001 # ENTRYPOINT [ "/deployments/run-java.sh" ] # ## Stage 2 : create the docker final image # FROM registry.access.redhat.com/ubi8/ubi-minimal # WORKDIR /usr/src/app/target/ # COPY --from=BUILD /usr/src/app/target/lib/* /deployments/lib/ # COPY --from=BUILD /usr/src/app/target/*-runner.jar /deployments/app.jar # COPY --from=build /tmp/my-project/target/*-runner /usr/src/app/target/application # COPY --from=build /tmp/my-project/applicationinsights-agent-3.2.7.jar /usr/src/app/target/ # RUN chmod 775 /usr/src/app/target # ENV JAVA_OPTS="-javaagent:/usr/src/app/target/applicationinsights-agent-3.2.7.jar" # EXPOSE 8080 # ENTRYPOINT [ "/deployments/run-java.sh" ] # # CMD ["./application", "-XX:+PrintGC", "-XX:+PrintGCTimeStamps", "-XX:+VerboseGC", "+XX:+PrintHeapShape", "-Xmx256m", "-Dquarkus.http.host=0.0.0.0"]<file_sep># install https://kubecost.com/install ``` kubectl create namespace kubecost helm repo add kubecost https://kubecost.github.io/cost-analyzer/ helm install kubecost kubecost/cost-analyzer --namespace kubecost --set kubecostToken="<KEY>" kubectl port-forward --namespace kubecost deployment/kubecost-cost-analyzer 9090 helm repo add stable https://kubernetes-charts.storage.googleapis.com helm install kubecost-ingress stable/nginx-ingress -n kubecost export IGCIP=$(kubectl get svc -o jsonpath="{.status.loadBalancer.ingress[0].ip}" kubecost-ingress-nginx-ingress-controller -n kubecost) htpasswd -c auth kubecost-admin kubectl create secret generic \ kubecost-auth \ --from-file auth \ -n kubecost echo " apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: nginx.ingress.kubernetes.io/auth-realm: Authentication Required - ok nginx.ingress.kubernetes.io/auth-secret: kubecost-auth nginx.ingress.kubernetes.io/auth-type: basic labels: app: cost-analyzer name: kubecost-cost-analyzer namespace: kubecost spec: rules: - host: $IGCIP.xip.io http: paths: - backend: serviceName: kubecost-cost-analyzer servicePort: 9090 path: / " | kubectl apply -f - echo " apiVersion: extensions/v1beta1 kind: Ingress metadata: labels: app: cost-analyzer name: kubecost-cost-analyzer namespace: kubecost spec: rules: - host: $IGCIP.xip.io http: paths: - backend: serviceName: kubecost-cost-analyzer servicePort: 9090 path: / " | kubectl apply -f - ``` <file_sep>//dependencies const grpc = require("@grpc/grpc-js"); const protoLoader = require("@grpc/proto-loader"); //path to our proto file const PROTO_FILE = "./service_def.proto"; //options needed for loading Proto file const options = { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true, }; const pkgDefs = protoLoader.loadSync(PROTO_FILE, options); //load Definition into gRPC const userProto = grpc.loadPackageDefinition(pkgDefs); //create gRPC server const server = new grpc.Server(); //implement UserService server.addService(userProto.UserService.service, { //implment GetUser GetUser: (input, callback) => { try { callback(null, { name: "Dennis", age: 25 }); } catch (error) { callback(error, null); } }, }); //start the Server server.bindAsync( //port to serve on "0.0.0.0:9001", //authentication settings grpc.ServerCredentials.createInsecure(), //server start callback (error, port) => { console.log(`listening on port ${port}`); server.start(); } );<file_sep>// package org.acme.rest.client; // import static io.restassured.RestAssured.given; // import static org.hamcrest.CoreMatchers.hasItem; // import static org.hamcrest.CoreMatchers.is; // import static org.hamcrest.Matchers.greaterThan; // import org.junit.jupiter.api.Test; // import org.acme.rest.client.*; // import org.acme.rest.client.resources.WireMockExtensions; // import io.quarkus.test.common.QuarkusTestResource; // import io.quarkus.test.junit.QuarkusTest; // @QuarkusTest // @QuarkusTestResource(WireMockExtensions.class) // public class CalculationResourceTest { // @Test // public void testExtensionsIdEndpoint() { // given() // .when().get("/extension/id/io.quarkus:quarkus-rest-client") // .then() // .statusCode(200) // .body("$.size()", is(1), // "[0].id", is("io.quarkus:quarkus-rest-client"), // "[0].name", is("REST Client"), // "[0].keywords.size()", greaterThan(1), // "[0].keywords", hasItem("rest-client")); // } // }<file_sep># Install ``` TENANT_ID= API_APP_NAME= API_APP_ID= API_APP_URI_ID= API_APP_SECRET= ``` ## Nginx ``` INGRESS_NAMESPACE="ingress" DNS="dzapps1.westeurope.cloudapp.azure.com" APP_NAMESPACE="loggers" kubectl create ns $INGRESS_NAMESPACE kubectl create ns $APP_NAMESPACE controller: podAnnotations: dapr.io/enabled: "true" dapr.io/app-id: "nginx" dapr.io/app-protocol: "http" dapr.io/app-port: "80" dapr.io/api-token-secret: "dapr-api-token" dapr.io/config: "ingress-config" dapr.io/log-as-json: "true" echo "create ingress" helm upgrade nginx-controller ingress-nginx/ingress-nginx --install --set controller.stats.enabled=true --set controller.replicaCount=1 --set controller.service.externalTrafficPolicy=Local --set-string controller.pod.annotations.'dapr\.io/enabled'="true" --set-string controller.pod.annotations.'dapr\.io/app-id'="nginx" --set-string controller.pod.annotations.'dapr\.io/app-protocol'="http" --set-string controller.pod.annotations.'dapr\.io/app-port'="80" --set-string controller.pod.annotations.'dapr\.io/port'="80" --namespace=$INGRESS_NAMESPACE kubectl patch deployment nginx -n app-routing-system -p '{"spec": {"template":{"metadata":{"annotations":{"dapr.io/app-por":"80"}}}} }' SERVICE_IP=$(kubectl get svc --namespace $INGRESS_NAMESPACE nginx-controller-nginx-ingress -o jsonpath='{.status.loadBalancer.ingress[0].ip}') cat <<EOF | kubectl apply -f - apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: dapr-ingress namespace: $INGRESS_NAMESPACE annotations: kubernetes.io/ingress.class: nginx spec: rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: nginx-dapr port: number: 80 - path: /v1.0/invoke pathType: Prefix backend: service: name: nginx-dapr port: number: 80 EOF cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: dapr-ingress namespace: $INGRESS_NAMESPACE annotations: kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt spec: tls: - hosts: - $DNS secretName: tls-secret rules: - host: $DNS http: paths: - backend: serviceName: nginx-dapr servicePort: 80 path: / pathType: Prefix - backend: serviceName: nginx-dapr servicePort: 80 path: /v1.0/invoke pathType: Prefix EOF cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: dapr-ingress namespace: $INGRESS_NAMESPACE annotations: kubernetes.io/ingress.class: nginx spec: rules: - host: $DNS http: paths: - backend: serviceName: nginx-dapr servicePort: 80 path: / pathType: Prefix - backend: serviceName: nginx-dapr servicePort: 80 path: /v1.0/invoke pathType: Prefix EOF echo "test" echo "without auth token" curl -i \ -H "Content-type: application/json" \ "http://$DNS/v1.0/healthz" curl -i \ -H "Content-type: application/json" \ "http://$DNS/v1.0/healthz" echo "with auth token" curl -i \ -H "Content-type: application/json" \ -H "dapr-api-token: ${API_TOKEN}" \ "http://$DNS/v1.0/healthz" cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: dummy-logger namespace: $INGRESS_NAMESPACE spec: replicas: 1 minReadySeconds: 10 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1 selector: matchLabels: app: dummy-logger template: metadata: labels: app: dummy-logger annotations: dapr.io/enabled: "true" dapr.io/app-id: "dummy-logger" dapr.io/app-port: "80" spec: containers: - name: dummy-logger image: denniszielke/dummy-logger:latest ports: - containerPort: 80 imagePullPolicy: Always resources: requests: memory: "58Mi" cpu: "50m" limits: memory: "156Mi" cpu: "100m" EOF curl -i \ -H "Content-type: application/json" \ "http://$DNS/v1.0/invoke/dummy-logger.$INGRESS_NAMESPACE/method/ping" curl -i \ -H "Content-type: application/json" \ "http://$DNS/v1.0/invoke/dummy-logger.$INGRESS_NAMESPACE/method/api/log" echo "create role binding" cat <<EOF | kubectl apply -f - apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: secret-reader namespace: $INGRESS_NAMESPACE rules: - apiGroups: [""] resources: ["secrets"] verbs: ["get"] --- kind: RoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: dapr-secret-reader namespace: $INGRESS_NAMESPACE subjects: - kind: ServiceAccount name: default roleRef: kind: Role name: secret-reader apiGroup: rbac.authorization.k8s.io EOF echo "create api token" API_TOKEN=$(openssl rand -base64 32) kubectl create secret generic dapr-api-token --from-literal=token="${API_TOKEN}" -n $INGRESS_NAMESPACE cat <<EOF | kubectl apply -f - --- apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: ingress-config namespace: $INGRESS_NAMESPACE spec: mtls: enabled: true workloadCertTTL: "24h" allowedClockSkew: "15m" tracing: samplingRate: "1" secrets: scopes: - storeName: kubernetes defaultAccess: deny allowedSecrets: ["dapr-api-token"] --- apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: tracing namespace: $INGRESS_NAMESPACE spec: tracing: samplingRate: "1" zipkin: endpointAddress: "http://otel-collector.default.svc.cluster.local:9411/api/v2/spans" EOF helm upgrade nginx-controller nginx/nginx-ingress --install --set controller.stats.enabled=true --set controller.replicaCount=1 --set controller.service.externalTrafficPolicy=Local --set-string controller.pod.annotations.'dapr\.io/enabled'="true" --set-string controller.pod.annotations.'dapr\.io/app-id'="nginx" --set-string controller.pod.annotations.'dapr\.io/app-protocol'="http" --set-string controller.pod.annotations.'dapr\.io/app-port'="80" --set-string controller.pod.annotations.'dapr\.io/port'="80" --set-string controller.pod.annotations.'dapr\.io/api-token-secret'="dapr-api-token" --set-string controller.pod.annotations.'dapr\.io/config'="ingress-config" --set-string controller.pod.annotations.'dapr\.io/log-as-json'="true" --namespace=$INGRESS_NAMESPACE kubectl create secret generic dapr-api-token --from-literal=token="${API_TOKEN}" -n $APP_NAMESPACE API_TOKEN=$(kubectl get secret dapr-api-token -o jsonpath="{.data.token}" -n ${APP_NAMESPACE} | base64 --decode) API_TOKEN=$(kubectl get secret dapr-api-token -o jsonpath="{.data.token}" -n ${INGRESS_NAMESPACE} | base64 --decode) cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: dummy-logger namespace: $APP_NAMESPACE spec: replicas: 1 minReadySeconds: 10 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1 selector: matchLabels: app: dummy-logger template: metadata: labels: app: dummy-logger annotations: dapr.io/enabled: "true" dapr.io/app-id: "dummy-logger" dapr.io/app-port: "80" spec: containers: - name: dummy-logger image: denniszielke/dummy-logger:latest ports: - containerPort: 80 imagePullPolicy: Always resources: requests: memory: "58Mi" cpu: "50m" limits: memory: "156Mi" cpu: "100m" EOF curl -i \ -H "Content-type: application/json" \ "http://$DNS/v1.0/invoke/dummy-logger.$APP_NAMESPACE/method/ping" curl -i \ -H "Content-type: application/json" \ -H "dapr-api-token: ${API_TOKEN}" \ "http://$DNS/v1.0/invoke/dummy-logger.$APP_NAMESPACE/method/ping" curl -i \ -H "Content-type: application/json" \ "http://$DNS/v1.0/invoke/dummy-logger.$APP_NAMESPACE/method/api/log" curl -i -X POST \ -H "Content-type: application/json" \ -H "dapr-api-token: ${API_TOKEN}" \ "http://$DNS/v1.0/invoke/dummy-logger.$APP_NAMESPACE/method/api/log" echo "hard lock down traffic from ingress to app" cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: dummy-logger-config namespace: $APP_NAMESPACE spec: mtls: enabled: true workloadCertTTL: "24h" allowedClockSkew: "15m" tracing: samplingRate: "1" secrets: scopes: - storeName: kubernetes defaultAccess: deny allowedSecrets: ["dapr-api-token"] accessControl: defaultAction: deny trustDomain: "loggers" policies: - appId: nginx defaultAction: deny trustDomain: "public" namespace: "$INGRESS_NAMESPACE" operations: - name: /api/log httpVerb: ["POST"] action: allow - name: /ping httpVerb: ["GET"] action: deny EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: dummy-logger-auth-policy namespace: $APP_NAMESPACE spec: replicas: 1 minReadySeconds: 10 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1 selector: matchLabels: app: dummy-logger template: metadata: labels: app: dummy-logger annotations: dapr.io/enabled: "true" dapr.io/app-id: "dummy-logger-auth-policy" dapr.io/app-port: "80" dapr.io/config: "dummy-logger-config" dapr.io/log-as-json: "true" dapr.io/log-level: "debug" dapr.io/api-token-secret: "dapr-api-token" spec: containers: - name: dummy-logger image: denniszielke/dummy-logger:latest ports: - containerPort: 80 imagePullPolicy: Always resources: requests: memory: "58Mi" cpu: "50m" limits: memory: "156Mi" cpu: "100m" EOF curl -i \ -H "Content-type: application/json" \ -H "dapr-api-token: ${API_TOKEN}" \ "http://$DNS/v1.0/invoke/dummy-logger-auth-policy.$APP_NAMESPACE/method/ping" curl -i -X POST \ -H "Content-type: application/json" \ -H "dapr-api-token: ${API_TOKEN}" \ "http://$DNS/v1.0/invoke/dummy-logger-auth-policy.$APP_NAMESPACE/method/api/log" echo "aad client credentials validation" https://docs.dapr.io/operations/security/oauth/ TENANT_ID=$(az account show --query tenantId -o tsv) TENANT_NAME=microsoft.onmicrosoft.com API_APP_NAME=dapr-demo-app1 API_APP_ID= API_APP_URI_ID=https://$TENANT_NAME/$API_APP_NAME API_APP_ID=$(az ad app create --display-name $API_APP_NAME --homepage http://localhost --identifier-uris $API_APP_URI_ID -o json | jq -r '.appId') URI_REDIRECT="http://localhost:80/v1.0/invoke/dummy-logger-oauth-client/method/headers" API_APP_SECRET=$(az ad app credential reset --id $API_APP_ID -o json | jq '.password' -r) open https://login.microsoftonline.com/$TENANT_ID/adminconsent?client_id=$API_APP_ID&state=12345&redirect_uri=http://localhost/$API_APP_NAME/permissions curl -X POST -H "Content-Type: application/x-www-form-urlencoded" \ --data "client_id=$API_APP_ID" \ --data "resource=$API_APP_URI_ID" \ --data-urlencode "client_secret=$API_APP_SECRET" \ --data "grant_type=client_credentials" \ "https://login.microsoftonline.com/$TENANT_ID/oauth2/token" echo "bearer validation" cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: bearer-token namespace: $APP_NAMESPACE spec: type: middleware.http.bearer version: v1 metadata: - name: clientId value: "$API_APP_ID" - name: issuerURL value: "https://sts.windows.net/$TENANT_ID/" EOF cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: bearer-config namespace: $APP_NAMESPACE spec: httpPipeline: handlers: - name: bearer-token type: middleware.http.bearer EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: dummy-logger-bearer namespace: $APP_NAMESPACE spec: replicas: 1 minReadySeconds: 10 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1 selector: matchLabels: app: dummy-logger template: metadata: labels: app: dummy-logger annotations: dapr.io/enabled: "true" dapr.io/app-id: "dummy-logger-bearer" dapr.io/app-port: "80" dapr.io/config: "bearer-config" dapr.io/log-as-json: "true" dapr.io/log-level: "debug" spec: containers: - name: dummy-logger image: denniszielke/dummy-logger:latest ports: - containerPort: 80 imagePullPolicy: Always EOF curl -i \ -H "Content-type: application/json" \ -H "Authorization: Bearer $TOKEN" \ "http://$DNS/v1.0/invoke/dummy-logger-bearer.$APP_NAMESPACE/method/headers" curl -i \ -H "Content-type: application/json" \ -H "Authorization: Bearer bla" \ "http://$DNS/v1.0/invoke/dummy-logger-bearer.$APP_NAMESPACE/method/headers" cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: oauth2 namespace: $APP_NAMESPACE spec: type: middleware.http.oauth2 version: v1 metadata: - name: clientId value: "$API_APP_ID" - name: clientSecret value: "$API_APP_SECRET" - name: scopes value: "Do.All" - name: authURL value: "https://login.microsoftonline.com/$TENANT_ID/oauth2/authorize" - name: tokenURL value: "https://login.microsoftonline.com/$TENANT_ID/oauth2/token" - name: redirectURL value: "http://$DNS/v1.0/invoke/dummy-logger-oauth2.$APP_NAMESPACE/method/headers" - name: authHeaderName value: "Authorization" - name: forceHTTPS value: "false" EOF cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: oauth2-pipeline namespace: $APP_NAMESPACE spec: httpPipeline: handlers: - name: oauth2 type: middleware.http.oauth2 EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: dummy-logger-oauth2 namespace: $APP_NAMESPACE spec: replicas: 1 minReadySeconds: 10 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1 selector: matchLabels: app: dummy-logger template: metadata: labels: app: dummy-logger annotations: dapr.io/enabled: "true" dapr.io/app-id: "dummy-logger-oauth2" dapr.io/app-port: "80" dapr.io/config: "oauth2-pipeline" dapr.io/log-as-json: "true" dapr.io/log-level: "debug" dapr.io/api-token-secret: "dapr-api-token" spec: containers: - name: dummy-logger image: denniszielke/dummy-logger:latest ports: - containerPort: 80 imagePullPolicy: Always resources: requests: memory: "58Mi" cpu: "50m" limits: memory: "156Mi" cpu: "100m" EOF cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: my-oauth-component namespace: $APP_NAMESPACE spec: type: middleware.http.oauth2clientcredentials version: v1 metadata: - name: clientId value: "$API_APP_ID" - name: clientSecret value: "$API_APP_SECRET" - name: scopes value: "Do.All" - name: tokenURL value: "https://login.microsoftonline.com/$TENANT_ID/oauth2/token" - name: headerName value: "Authorization" - name: authStyle value: "0" EOF cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: ingress-config namespace: $INGRESS_NAMESPACE spec: mtls: enabled: true workloadCertTTL: "24h" allowedClockSkew: "15m" httpPipeline: handlers: - name: my-oauth-component type: middleware.http.oauth2clientcredentials EOF cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: my-oauth-component namespace: $INGRESS_NAMESPACE spec: type: middleware.http.oauth2clientcredentials version: v1 metadata: - name: clientId value: "$API_APP_ID" - name: clientSecret value: "$API_APP_SECRET" - name: scopes value: "Do.All" - name: tokenURL value: "https://login.microsoftonline.com/$TENANT_ID/oauth2/token" - name: headerName value: "Authorization" - name: authStyle value: "0" EOF cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: dummy-logger-oauth2-pipeline namespace: $APP_NAMESPACE spec: mtls: enabled: true workloadCertTTL: "24h" allowedClockSkew: "15m" httpPipeline: handlers: - name: my-oauth-component type: middleware.http.oauth2clientcredentials EOF cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: bearer-token namespace: $APP_NAMESPACE spec: type: middleware.http.bearer version: v1 metadata: - name: clientId value: "$API_APP_ID" - name: issuerURL value: "https://sts.windows.net/f9175784-360c-4d85-8f75-dc042fbde38a" EOF cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: dummy-logger-oauth2-pipeline namespace: $APP_NAMESPACE spec: httpPipeline: handlers: - name: bearer-token type: middleware.http.bearer EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: dummy-logger-oauth-client namespace: $APP_NAMESPACE spec: replicas: 1 minReadySeconds: 10 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 1 maxSurge: 1 selector: matchLabels: app: dummy-logger template: metadata: labels: app: dummy-logger annotations: dapr.io/enabled: "true" dapr.io/app-id: "dummy-logger-oauth-client" dapr.io/app-port: "80" dapr.io/config: "dummy-logger-oauth2-pipeline" dapr.io/log-as-json: "true" dapr.io/log-level: "debug" dapr.io/api-token-secret: "dapr-api-token" spec: containers: - name: dummy-logger image: denniszielke/dummy-logger:latest ports: - containerPort: 80 imagePullPolicy: Always resources: requests: memory: "58Mi" cpu: "50m" limits: memory: "156Mi" cpu: "100m" EOF curl -i \ -H "Content-type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -H "dapr-api-token: ${API_TOKEN}" \ "http://$DNS/v1.0/invoke/dummy-logger-oauth-client.$APP_NAMESPACE/method/headers" curl -i \ -H "Content-type: application/json" \ -H "dapr-api-token: ${API_TOKEN}" \ "http://$DNS/v1.0/invoke/dummy-logger-oauth-client.$APP_NAMESPACE/method/headers" ```<file_sep># Cillium ## CLI ``` ``` ## Install https://docs.cilium.io/en/latest/gettingstarted/k8s-install-aks/ curl -L --remote-name-all https://github.com/cilium/cilium-cli/releases/download/v0.10.0/cilium-darwin-amd64.tar.gz shasum -a 256 -c cilium-darwin-amd64.tar.gz.sha256sum sudo tar xzvfC cilium-darwin-amd64.tar.gz /usr/local/bin rm cilium-darwin-amd64.tar.gz{,.sha256sum} ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $KUBE_NAME-sp -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET RG_ID=$(az group show -n $KUBE_GROUP --query id -o tsv) NODE_RG_ID=$(az group show -n $NODE_GROUP --query id -o tsv) az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID --scope $RG_ID -o none az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID --scope $NODE_RG_ID -o none az role assignment create --role "Reader" --assignee 21e02cfc-b6dc-4727-b1b5-bbe200f08dd9 --scope $RG_ID -o none nodepool_to_delete=$(az aks nodepool list --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --output tsv --query "[0].name") az aks nodepool add --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME \ --name systempool \ --mode system \ --node-count 1 \ --node-taints "CriticalAddonsOnly=true:NoSchedule" \ --no-wait az aks nodepool add --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME \ --name userpool \ --mode user \ --node-count 2 \ --node-taints "node.cilium.io/agent-not-ready=true:NoSchedule" \ --no-wait az aks nodepool delete --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME \ --name "${nodepool_to_delete}" helm repo add cilium https://helm.cilium.io/ helm upgrade cilium cilium/cilium --install --version 1.11.0 \ --namespace kube-system \ --set azure.enabled=true \ --set azure.resourceGroup=$NODE_GROUP \ --set azure.subscriptionID=$SUBSCRIPTION_ID \ --set azure.tenantID=$TENANT_ID \ --set azure.clientID=$SERVICE_PRINCIPAL_ID \ --set azure.clientSecret=$SERVICE_PRINCIPAL_SECRET \ --set tunnel=disabled \ --set ipam.mode=azure \ --set enableIPv4Masquerade=false \ --set nodeinit.enabled=true kubectl get pods --all-namespaces -o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,HOSTNETWORK:.spec.hostNetwork --no-headers=true | grep '<none>' | awk '{print "-n "$1" "$2}' | xargs -L 1 -r kubectl delete pod kubectl create ns cilium-test kubectl apply -n cilium-test -f https://raw.githubusercontent.com/cilium/cilium/v1.9/examples/kubernetes/connectivity-check/connectivity-check.yaml kubectl get pods -n cilium-test kubectl apply -f https://raw.githubusercontent.com/cilium/cilium/HEAD/examples/kubernetes/connectivity-check/connectivity-check.yaml kubectl logs -l name=echo kubectl logs -l name=probe ``` ## Configure Hubble https://github.com/cilium/hubble ``` export CILIUM_NAMESPACE=kube-system helm upgrade cilium cilium/cilium --version 1.9.11 \ --namespace $CILIUM_NAMESPACE \ --reuse-values \ --set hubble.listenAddress=":4244" \ --set hubble.relay.enabled=true \ --set hubble.ui.enabled=true kubectl port-forward -n $CILIUM_NAMESPACE svc/hubble-ui --address 0.0.0.0 --address :: 12000:80 export HUBBLE_VERSION=$(curl -s https://raw.githubusercontent.com/cilium/hubble/master/stable.txt) curl -LO "https://github.com/cilium/hubble/releases/download/$HUBBLE_VERSION/hubble-darwin-amd64.tar.gz" curl -LO "https://github.com/cilium/hubble/releases/download/$HUBBLE_VERSION/hubble-darwin-amd64.tar.gz.sha256sum" shasum -a 256 -c hubble-darwin-amd64.tar.gz.sha256sum tar zxf hubble-darwin-amd64.tar.gz sudo mv hubble /usr/local/bin kubectl port-forward -n $CILIUM_NAMESPACE svc/hubble-relay --address 0.0.0.0 --address :: 4245:80 hubble --server localhost:4245 status hubble --server localhost:4245 observe ``` ## DNS Policy ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos labels: org: secured spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos1 spec: containers: - name: centos image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF httpbin.org/get ipinfo.io/ip cat <<EOF | kubectl apply -f - apiVersion: "cilium.io/v2" kind: CiliumNetworkPolicy metadata: name: "fqdn" spec: endpointSelector: {} ingress: - fromEndpoints: - matchLabels: org: secured egress: - toFQDNs: - matchName: "ipinfo.io" - toEndpoints: - matchLabels: "k8s:io.kubernetes.pod.namespace": kube-system "k8s:k8s-app": kube-dns toPorts: - ports: - port: "53" protocol: ANY rules: dns: - matchPattern: "*" EOF ``` ## Layer 7 visibility ``` kubectl annotate pod foo -n bar policy.cilium.io/proxy-visibility="<Egress/53/UDP/DNS>,<Egress/80/TCP/HTTP>" kubectl annotate pod calculator-multicalculator-backend-b7d75c597-5vvwg -n calculator policy.cilium.io/proxy-visibility="<Egress/53/UDP/DNS>,<Egress/80/TCP/HTTP>" kubectl annotate pod calculator-multicalculator-backend-b7d75c597-dzzhv -n calculator policy.cilium.io/proxy-visibility="<Egress/53/UDP/DNS>,<Egress/80/TCP/HTTP>" kubectl annotate pod calculator-multicalculator-backend-b7d75c597-frbj4 -n calculator policy.cilium.io/proxy-visibility="<Egress/53/UDP/DNS>,<Egress/80/TCP/HTTP>" kubectl annotate pod calculator-multicalculator-backend-b7d75c597-qqfp6 -n calculator policy.cilium.io/proxy-visibility="<Egress/53/UDP/DNS>,<Egress/80/TCP/HTTP>" kubectl annotate pod calculator-multicalculator-frontend-86c8866b47-6ftqz -n calculator policy.cilium.io/proxy-visibility="<Egress/53/UDP/DNS>,<Egress/80/TCP/HTTP>" kubectl annotate pod calculator-multicalculator-frontend-86c8866b47-6zhhj -n calculator policy.cilium.io/proxy-visibility="<Egress/53/UDP/DNS>,<Egress/80/TCP/HTTP>" kubectl annotate pod calculator-multicalculator-frontend-86c8866b47-dm2w2 -n calculator policy.cilium.io/proxy-visibility="<Egress/53/UDP/DNS>,<Egress/80/TCP/HTTP>" kubectl annotate pod calculator-multicalculator-frontend-86c8866b47-fvmmw -n calculator policy.cilium.io/proxy-visibility="<Egress/53/UDP/DNS>,<Egress/80/TCP/HTTP>" ``` ## Enterprise ``` az k8s-extension update -c $CLUSTER_NAME -t managedClusters -g $RG_NAME -n cilium --configuration-settings namespace=kube-system hubble.enabled=true az k8s-extension update -c $CLUSTER_NAME -t managedClusters -g $RG_NAME -n cilium --configuration-settings hubble.relay.enabled=true az k8s-extension show --cluster-name $CLUSTER_NAME --resource-group $RG_NAME --cluster-type managedClusters -n cilium kubectl --namespace=kube-system exec -i -t ds/cilium -- cilium version # cee = cilium enterprise edition cilium status kubectl -n kube-system exec ds/cilium -- cilium-health status kubectl describe deploy cilium-operator -n kube-system | grep "Image:" # Temporary work around to install Hubble UI OSS version in Enterprise version (this will be available soon) helm install --namespace kube-system cilium cilium/cilium --version 1.13.4 -f hubble-standalone-values.yaml ``` hubble stand alone values ```` agent: false operator: enabled: false cni: install: false hubble: enabled: false relay: # set this to false as Hubble relay is already installed enabled: false tls: server: # set this to true if tls is enabled on Hubble relay server side enabled: false ui: # enable Hubble UI enabled: true standalone: # enable Hubble UI standalone deployment enabled: true ``` cilium hubble port-forward # In another terminal cilium hubble ui ℹ️ Opening "http://localhost:12000" in your browser.<file_sep># Pod Security policy https://docs.bitnami.com/kubernetes/how-to/secure-kubernetes-cluster-psp/ https://kubernetes.io/docs/concepts/policy/pod-security-policy/ 0. Variables ``` KUBE_GROUP="KubePSPs" KUBE_NAME="kubesecurity" LOCATION="westeurope" KUBE_VERSION="1.12.7" CLUSTER_NAME="security" az group create -n $KUBE_GROUP -l $LOCATION az aks update -g $KUBE_GROUP -n $KUBE_NAME --enable-pod-security-policy az group deployment create \ --name pspaks101 \ --resource-group $KUBE_GROUP \ --template-file "arm/psp_template.json" \ --parameters "arm/psp_parameters.json" \ --parameters "resourceName=$KUBE_NAME" \ "location=$LOCATION" \ "dnsPrefix=$KUBE_NAME" \ "servicePrincipalClientId=$SERVICE_PRINCIPAL_ID" \ "servicePrincipalClientSecret=$SERVICE_PRINCIPAL_SECRET" \ "kubernetesVersion=$KUBE_VERSION" KUBE_GROUP="$(az aks list -o tsv | grep $CLUSTER_NAME | cut -f15)" KUBE_NAME="$(az aks list -o tsv | grep $CLUSTER_NAME | cut -f4)" ``` 5. Export the kubectrl credentials files ``` az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME ``` 1. Create psp cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos1 spec: containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF kubectl exec -ti centos1 -- /bin/bash kubectl get psp kubectl get clusterrolebindings default:restricted -o yaml kubectl create namespace psp-aks kubectl create serviceaccount --namespace psp-aks nonadmin-user kubectl create rolebinding --namespace psp-aks psp-aks-editor --clusterrole=edit --serviceaccount=psp-aks:nonadmin-user kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/bestpractices/mountsp.yaml --as=system:serviceaccount:psp-aks:nonadmin-user -n psp-aks alias kubectl-admin='kubectl --namespace psp-aks' alias kubectl-nonadminuser='kubectl --as=system:serviceaccount:psp-aks:nonadmin-user --namespace psp-aks' cat <<EOF | kubectl apply --as=system:serviceaccount:psp-aks:nonadmin-user --namespace psp-aks -f - apiVersion: v1 kind: Pod metadata: name: nginx-privileged spec: containers: - name: nginx-privileged image: nginx:1.14.2 securityContext: privileged: true EOF cat <<EOF | kubectl apply --as=system:serviceaccount:psp-aks:nonadmin-user --namespace psp-aks -f - apiVersion: v1 kind: Pod metadata: name: nginx-unprivileged spec: containers: - name: nginx-unprivileged image: nginx:1.14.2 EOF cat <<EOF | kubectl apply --as=system:serviceaccount:psp-aks:nonadmin-user --namespace psp-aks -f - apiVersion: v1 kind: Pod metadata: name: nginx-unprivileged-high-port labels: nginx: unprivileged spec: containers: - name: nginx-unprivileged-high-port image: nginx:1.14.2 env: - name: NGINX_PORT value: "3000" ports: - containerPort: 3000 securityContext: runAsUser: 2000 EOF cat <<EOF | kubectl apply --as=system:serviceaccount:psp-aks:nonadmin-user --namespace psp-aks -f - apiVersion: v1 kind: Service metadata: labels: nginx: unprivileged name: nginx-unprivileged spec: ports: - port: 80 protocol: TCP targetPort: 8080 selector: nginx: unprivileged sessionAffinity: None type: LoadBalancer EOF kubectl delete svc nginx-unprivileged -n psp-aks kubectl logs nginx-unprivileged-high-port -n psp-aks kubectl delete pod nginx-unprivileged-high-port -n psp-aks cat <<EOF | kubectl apply --as=system:serviceaccount:psp-aks:nonadmin-user --namespace psp-aks -f - apiVersion: v1 kind: Pod metadata: name: bitnami-nginx-unprivileged-high-port labels: nginx: unprivileged spec: containers: - name: bitnami-nginx-unprivileged-high-port image: bitnami/nginx ports: - containerPort: 8080 securityContext: runAsUser: 2000 EOF kubectl delete pod bitnami-nginx-unprivileged-high-port -n psp-aks cat <<EOF | kubectl apply -f - apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: psp-deny-privileged spec: privileged: false seLinux: rule: RunAsAny supplementalGroups: rule: RunAsAny runAsUser: rule: RunAsAny fsGroup: rule: RunAsAny volumes: - '*' EOF cat <<EOF | kubectl apply -f - kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: psp-deny-privileged-clusterrole rules: - apiGroups: - extensions resources: - podsecuritypolicies resourceNames: - psp-deny-privileged verbs: - use --- apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: psp-deny-privileged-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: psp-deny-privileged-clusterrole subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:serviceaccounts EOF 2. Try to launch priviledged pod cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: nginx-privileged labels: run: nginx spec: containers: - name: nginx-privileged image: nginx:1.14.2 securityContext: privileged: true EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: nginx-unprivileged labels: run: nginx spec: containers: - name: nginx-unprivileged image: nginx:1.14.2 EOF # Delete everything ``` az aks update-cluster -g $KUBE_GROUP -n $KUBE_NAME --disable-pod-security-policy ```<file_sep># Tracing with Azure Monitor ## setting up local forwarder https://docs.microsoft.com/en-us/azure/azure-monitor/app/opencensus-local-forwarder#linux # Tracing with Zipkin https://github.com/dapr/docs/blob/master/howto/diagnose-with-tracing/zipkin.md ``` kubectl run zipkin --image openzipkin/zipkin --port 9411 kubectl expose deploy zipkin --type ClusterIP --port 9411 kubectl apply -f zipkin.yaml kubectl port-forward svc/zipkin 9411:9411 ``` # Debug https://github.com/dapr/docs/blob/master/best-practices/troubleshooting/logs.md kubectl logs -l app=dapr-operator -n dapr-system kubectl logs -l app=dapr-sidecar-injector -n dapr-system kubectl logs -l app=dapr-placement -n dapr-system kubectl logs -l app=demoactor daprd kubectl logs -l app=demoactor demoactor<file_sep># Dapr using ServiceBus KUBE_GROUP=appconfig SB_NAMESPACE=dzdapr$RANDOM LOCATION=westeurope az servicebus namespace create --resource-group $KUBE_GROUP --name $SB_NAMESPACE --location $LOCATION az servicebus namespace authorization-rule keys list --name RootManageSharedAccessKey --namespace-name $SB_NAMESPACE --resource-group $KUBE_GROUP --query "primaryConnectionString" | tr -d '"' SB_CONNECTIONSTRING=$(az servicebus namespace authorization-rule keys list --name RootManageSharedAccessKey --namespace-name $SB_NAMESPACE --resource-group $KUBE_GROUP --query "primaryConnectionString" | tr -d '"') kubectl delete component messagebus cat <<EOF | kubectl apply -f - apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: dzpubsub spec: type: pubsub.azure.servicebus version: v1 metadata: - name: connectionString value: '$SB_CONNECTIONSTRING' - name: timeoutInSec value: 80 - name: maxDeliveryCount value: 15 - name: lockDurationInSec value: 5 - name: defaultMessageTimeToLiveInSec value: 2 EOF kubectl delete component messagebus kubectl delete component pubsub-azure-service-bus kubectl delete pod -l app=dapr-operator -n dapr-system kubectl logs -l app=dapr-operator kubectl logs -l demo=pubsub curl -X POST http://localhost:3500/v1.0/publish/deathStarStatus \ -H "Content-Type: application/json" \ -d '{ "status": "completed" }'<file_sep># Disk ``` NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) DISK_ID=$(az disk create --resource-group $NODE_GROUP --name myAKSDisk --size-gb 20 --query id --output tsv) cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: stapps spec: replicas: 1 selector: matchLabels: name: stapps template: metadata: labels: name: stapps spec: containers: - name: stapps image: mcr.microsoft.com/oss/nginx/nginx:1.15.5-alpine volumeMounts: - name: azure mountPath: /mnt/azure volumes: - name: azure azureDisk: kind: Managed diskName: myAKSDisk diskURI: $DISK_ID EOF ``` ## Install CSI Driver https://github.com/kubernetes-sigs/azuredisk-csi-driver curl -skSL https://raw.githubusercontent.com/kubernetes-sigs/azuredisk-csi-driver/master/deploy/install-driver.sh | bash -s master -- Uninstall curl -skSL https://raw.githubusercontent.com/kubernetes-sigs/azuredisk-csi-driver/master/deploy/uninstall-driver.sh | bash -s master -- ## CSI Migration Hostpath ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolume metadata: name: task-pv-volume labels: type: local spec: storageClassName: manual capacity: storage: 10Gi accessModes: - ReadWriteOnce hostPath: path: "/var/log" EOF cat <<EOF | kubectl apply -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: task-pv-claim spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 3Gi EOF ``` ## Zone https://github.com/kubernetes-sigs/azuredisk-csi-driver/blob/master/deploy/example/e2e_usage.md ``` curl -skSL https://raw.githubusercontent.com/kubernetes-sigs/azuredisk-csi-driver/master/deploy/install-driver.sh | bash -s master -- kubectl describe nodes | grep -e "Name:" -e "failure-domain.beta.kubernetes.io/zone" kubectl get no --show-labels | grep topo cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: managed-zone-csi provisioner: disk.csi.azure.com parameters: skuname: Premium_ZRS reclaimPolicy: Delete volumeBindingMode: Immediate EOF cat <<EOF | kubectl apply -f - kind: PersistentVolumeClaim apiVersion: v1 metadata: name: pvc-zone-azuredisk spec: accessModes: - ReadWriteOnce resources: requests: storage: 10Gi storageClassName: "managed-zone-csi" EOF cat <<EOF | kubectl apply -f - apiVersion: apps/v1 kind: Deployment metadata: name: stapps spec: replicas: 1 selector: matchLabels: name: stapps template: metadata: labels: name: stapps spec: containers: - image: mcr.microsoft.com/oss/nginx/nginx:1.17.3-alpine name: nginx-azuredisk command: - "/bin/sh" - "-c" - while true; do echo $(date) >> /mnt/azuredisk/outfile; sleep 1; done volumeMounts: - name: azuredisk01 mountPath: "/mnt/azuredisk" volumes: - name: azuredisk01 persistentVolumeClaim: claimName: pvc-zone-azuredisk EOF --- kind: Pod apiVersion: v1 metadata: name: nginx-azuredisk spec: nodeSelector: kubernetes.io/os: linux containers: - image: mcr.microsoft.com/oss/nginx/nginx:1.17.3-alpine name: nginx-azuredisk command: - "/bin/sh" - "-c" - while true; do echo $(date) >> /mnt/azuredisk/outfile; sleep 1; done volumeMounts: - name: azuredisk01 mountPath: "/mnt/azuredisk" volumes: - name: azuredisk01 persistentVolumeClaim: claimName: pvc-azuredisk az disk ``` ## ZRS CSI Driver V2 https://apache.github.io/solr-operator/docs/local_tutorial ``` DNS="dzdublin7.northeurope.cloudapp.azure.com" cat <<EOF | kubectl apply -f - apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: azuredisk2-standard-ssd-zrs-replicas parameters: cachingmode: None skuName: StandardSSD_ZRS maxShares: "2" provisioner: disk2.csi.azure.com reclaimPolicy: Delete volumeBindingMode: Immediate allowVolumeExpansion: true EOF kubectl patch storageclass default -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}' kubectl patch storageclass azuredisk2-standard-ssd-zrs-replicas -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}' kubectl get sc | grep azuredisk https://apache.github.io/solr-operator/docs/local_tutorial helm repo add apache-solr https://solr.apache.org/charts helm repo update kubectl create -f https://solr.apache.org/operator/downloads/crds/v0.5.1/all-with-dependencies.yaml https://artifacthub.io/packages/helm/apache-solr/solr helm upgrade solr-operator apache-solr/solr-operator --version 0.5.1 --install helm upgrade example-solr apache-solr/solr --version 0.5.1 --install \ --set image.tag=8.3 \ --set solrOptions.javaMemory="-Xms300m -Xmx300m" \ --set addressability.external.method=Ingress \ --set addressability.external.domainName="running.de" \ --set addressability.external.useExternalAddress="true" \ --set ingressOptions.ingressClassName="nginx" \ --set dataStorage.type="persistent" \ --set dataStorage.persistent.pvc.storageClassName="azuredisk2-standard-ssd-zrs-replicas" kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: solr spec: ingressClassName: nginx rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 EOF open "http://default-example-solrcloud.running.de/solr/#/~cloud?view=nodes" open "http://$DNS/solr/#/~cloud?view=nodes" curl "http://default-example-solrcloud.running.de/solr/admin/collections?action=CREATE&name=mycoll&numShards=1&replicationFactor=3&maxShardsPerNode=2&collection.configName=_default" open "http://default-example-solrcloud.running.de/solr/#/~cloud?view=graph" curl -XPOST -H "Content-Type: application/json" \ -d '[{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}, {id: 7}, {id: 8}]' \ "http://default-example-solrcloud.running.de/solr/mycoll/update/" ```<file_sep> RG_NAME="dzaca67" # here the deployment LOCATION="westeurope" SUBNET_RESOURCE_ID=" az deployment group create -g $RG_NAME -f main.bicep -p internalOnly=true <file_sep># Create container cluster in a VNET (AKs) https://docs.microsoft.com/en-us/cli/azure/acs?view=azure-cli-latest#az_acs_create https://docs.microsoft.com/en-us/azure/aks/networking-overview 0. Variables ``` SUBSCRIPTION_ID=$(az account show --query id -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv) KUBE_NAME="podsub2" KUBE_GROUP="kub_ter_a_m_$KUBE_NAME" LOCATION="westcentralus" NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION KUBE_VNET_NAME=$KUBE_NAME"-vnet" KUBE_GW_SUBNET_NAME="gw-1-subnet" KUBE_ACI_SUBNET_NAME="aci-2-subnet" KUBE_FW_SUBNET_NAME="AzureFirewallSubnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" KUBE_AGENT_SUBNET_NAME="aks-5-subnet" KUBE_AGENT2_SUBNET_NAME="aks-6-subnet" KUBE_AGENT3_SUBNET_NAME="aks-7-subnet" KUBE_VERSION="$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv)" SERVICE_PRINCIPAL_ID= SERVICE_PRINCIPAL_SECRET= AAD_APP_NAME="" AAD_APP_ID= AAD_APP_SECRET= AAD_CLIENT_NAME= AAD_CLIENT_ID= TENANT_ID= ``` Select subscription ``` az account set --subscription $SUBSCRIPTION_ID ``` 1. Create the resource group ``` az group create -n $KUBE_GROUP -l $LOCATION ``` 2. Create VNETs ``` az network vnet create -g $KUBE_GROUP -n $KUBE_VNET_NAME --address-prefixes 192.168.0.0/20 172.16.0.0/16 10.0.0.0/16 ``` Get available service endpoints ``` az network vnet list-endpoint-services -l $LOCATION ``` create ip prefix ``` az network public-ip prefix create --length 31 --location $LOCATION --name aksprefix --resource-group $KUBE_GROUP ``` Assign permissions on vnet ``` az identity create --name $KUBE_NAME -g $KUBE_GROUP SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $SP_NAME -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET az role assignment create --role "Virtual Machine Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP ``` Create dns zone ``` az network dns zone create -g $KUBE_GROUP -n runningcode.local --zone-type Private --registration-vnets $KUBE_VNET_NAME ``` 3. Create Subnets Register azure firewall https://docs.microsoft.com/en-us/azure/firewall/public-preview ``` az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_GW_SUBNET_NAME --address-prefix 10.0.1.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ACI_SUBNET_NAME --address-prefix 10.0.2.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_FW_SUBNET_NAME --address-prefix 10.0.3.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT2_SUBNET_NAME --address-prefix 10.0.6.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT2_SUBNET_NAME --address-prefix 192.168.0.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT3_SUBNET_NAME --address-prefix 172.16.0.0/24 --service-endpoints Microsoft.Sql Microsoft.AzureCosmosDB Microsoft.KeyVault Microsoft.Storage ``` 4. Create the aks cluster get vm sizes ``` az vm list-sizes -l $LOCATION ``` create cluster without rbac ``` KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" KUBE_AGENT2_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT2_SUBNET_NAME" KUBE_AGENT3_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT3_SUBNET_NAME" CONTROLLER_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.ManagedIdentity/userAssignedIdentities/$KUBE_NAME" MSI_CLIENT_ID=$(az identity show -n $KUBE_NAME -g $KUBE_GROUP --query clientId -o tsv) az role assignment create --role "Contributor" --assignee $MSI_CLIENT_ID -g $KUBE_GROUP # will be done by aks-engine az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --network-policy calico --enable-rbac --enable-addons monitoring az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --pod-subnet-id $KUBE_AGENT3_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --network-policy calico --enable-rbac --aks-custom-headers EnableSwiftNetworking=true --enable-addons monitoring az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --network-policy calico --enable-rbac --enable-addons monitoring --enable-managed-identity --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --enable-vmss --network-plugin kubenet --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --network-policy calico --enable-rbac --enable-addons monitoring --enable-managed-identity --assign-identity $CONTROLLER_ID --outbound-type userDefinedRouting az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --enable-vmss --network-plugin kubenet --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --enable-rbac --kubernetes-version $KUBE_VERSION --enable-addons monitoring --enable-managed-identity --assign-identity $CONTROLLER_ID ``` for additional rbac ``` az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --enable-rbac --aad-server-app-id $AAD_APP_ID --aad-server-app-secret $AAD_APP_SECRET --aad-client-app-id $AAD_CLIENT_ID --aad-tenant-id $TENANT_ID --node-vm-size "Standard_B2s" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --enable-rbac --node-vm-size "Standard_D2s_v3" ``` with kubenet ``` az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --node-count 2 --ssh-key-value ~/.ssh/id_rsa.pub --network-plugin kubenet --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --pod-cidr 10.244.0.0/16 --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --enable-rbac --node-vm-size "Standard_D2s_v3" --vm-set-type VirtualMachineScaleSets --load-balancer-sku standard --enable-private-cluster az aks nodepool add --name router --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd --vnet-subnet-id $KUBE_AGENT2_SUBNET_ID --mode user --labels workload=nonrouter az aks nodepool add --name ub1804pip --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd --vnet-subnet-id $KUBE_AGENT2_SUBNET_ID az aks nodepool add --name router --resource-group $KUBE_GROUP --cluster-name $KUBE_NAME --aks-custom-headers CustomizedUbuntu=aks-ubuntu-1804,ContainerRuntime=containerd --vnet-subnet-id $KUBE_AGENT3_SUBNET_ID --mode user --labels workload=router ``` AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv)" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME --location $LOCATION --max-pods 250 --node-count 2 --network-plugin azure --vnet-subnet-id $HOST_VNET_ID --pod-subnet-id $POD_VNET_ID --kubernetes-version $KUBE_VERSION --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --no-ssh-key --assign-identity $AKS_CONTROLLER_RESOURCE_ID --enable-managed-identity --node-vm-size "Standard_B2s" --node-vm-size "Standard_D2s_v3" create cluster via arm ``` sed -e "s/KUBE_NAME/$KUBE_NAME/ ; s/LOCATION/$LOCATION/ ; s/SERVICE_PRINCIPAL_ID/$SERVICE_PRINCIPAL_ID/ ; s/SERVICE_PRINCIPAL_SECRET/$SERVICE_PRINCIPAL_SECRET/ ; s/KUBE_VERSION/$KUBE_VERSION/ ; s/SUBSCRIPTION_ID/$SUBSCRIPTION_ID/ ; s/KUBE_GROUP/$KUBE_GROUP/ ; s/GROUP_ID/$GROUP_ID/" acsengvnet-ha.json > acsengvnet_out.json az group deployment create \ --name dz-vnet-acs \ --resource-group $KUBE_GROUP \ --template-file "arm/azurecni_template.json" \ --parameters "arm/azurecni_parameters.json" ``` create private cluster ``` KUBE_AGENT_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT_SUBNET_NAME" az aks create \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --node-resource-group $NODE_GROUP \ --load-balancer-sku standard \ --enable-private-cluster \ --network-plugin azure \ --vnet-subnet-id $KUBE_AGENT_SUBNET_ID \ --docker-bridge-address 172.17.0.1/16 \ --dns-service-ip 10.2.0.10 \ --service-cidr 10.2.0.0/24 \ --client-secret $SERVICE_PRINCIPAL_SECRET \ --service-principal $SERVICE_PRINCIPAL_ID KUBE_AGENT2_SUBNET_ID="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$KUBE_GROUP/providers/Microsoft.Network/virtualNetworks/$KUBE_VNET_NAME/subnets/$KUBE_AGENT2_SUBNET_NAME" az aks create \ --resource-group $KUBE_GROUP \ --name $KUBE_NAME \ --node-resource-group $NODE_GROUP \ --load-balancer-sku standard \ --enable-private-cluster \ --network-plugin azure \ --vnet-subnet-id $KUBE_AGENT2_SUBNET_ID \ --docker-bridge-address 172.17.0.1/16 \ --dns-service-ip 10.3.0.10 \ --service-cidr 10.3.0.0/24 \ --client-secret $SERVICE_PRINCIPAL_SECRET \ --service-principal $SERVICE_PRINCIPAL_ID az aks create -n $KUBE_NAME -g $KUBE_GROUP --load-balancer-sku standard --enable-private-cluster --node-resource-group $NODE_GROUP --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID --kubernetes-version $KUBE_VERSION --network-plugin kubenet --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 az aks create -g $KUBE_GROUP -n $KUBE_NAME --enable-managed-identity --kubernetes-version $KUBE_VERSION ``` 5. Export the kubectrl credentials files ``` az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME ``` or RBAC https://github.com/denniszielke/container_demos/blob/master/KubernetesRBAC.md ``` az aks get-credentials --resource-group $KUBE_GROUP --name $KUBE_NAME --admin ``` create addition dns record ``` az network dns zone list --resource-group $KUBE_GROUP az network dns record-set list -g $KUBE_GROUP -z runningcode.local az network dns zone show -g $KUBE_GROUP -n contoso.com -o json az network dns record-set a add-record \ -g $KUBE_GROUP \ -z runningcode.local \ -n dummy \ -a 10.0.4.24 curl 10.0.4.24 curl nginx.runningcode.local ``` create internal load balancer for nginx ``` kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/services/nginx-internal.yaml ``` ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: name: internal-nginx annotations: service.beta.kubernetes.io/azure-load-balancer-internal: "true" spec: type: LoadBalancer ports: - port: 80 selector: run: nginx EOF ``` ``` cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos1 spec: containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF ``` # Peer ``` JUMPBOX_GROUP=jumpbox-we JUMPBOX_VNET=jumpbox-we-vnet ``` ``` az network vnet peering create -g $JUMPBOX_GROUP -n KubeToVMPeer --vnet-name $KUBE_VNET_NAME --remote-vnet $JUMPBOX_VNET --allow-vnet-access az network vnet peering create -g $JUMPBOX_GROUP -n VMToKubePeer --vnet-name $JUMPBOX_VNET --remote-vnet $KUBE_VNET_NAME --allow-vnet-access ``` # BYO Outbound IP ``` az network public-ip show --resource-group myResourceGroup --name myPublicIP --query id -o tsv IP="/subscriptions/$SUBSCRIPTION_ID/resourceGroups/aksoutbound/providers/Microsoft.Network/publicIPAddresses/aksoutbound1" SP_NAME="aksoutbound" KUBE_GROUP="aksoutbound" SERVICE_PRINCIPAL_ID=$(az ad sp create-for-rbac --skip-assignment --name $SP_NAME -o json | jq -r '.appId') echo $SERVICE_PRINCIPAL_ID SERVICE_PRINCIPAL_SECRET=$(az ad app credential reset --id $SERVICE_PRINCIPAL_ID -o json | jq '.password' -r) echo $SERVICE_PRINCIPAL_SECRET az role assignment create --role "Contributor" --assignee $SERVICE_PRINCIPAL_ID -g $KUBE_GROUP az aks create \ --resource-group aksoutbound \ --name myAKSCluster --network-plugin kubenet \ --client-secret $SERVICE_PRINCIPAL_SECRET --service-principal $SERVICE_PRINCIPAL_ID \ --load-balancer-outbound-ips $IP service.beta.kubernetes.io/azure-load-balancer-resource-group service.beta.kubernetes.io/azure-pip-name KUBE_NAME=myAKSCluster KUBE_GROUP=aksoutbound kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Service metadata: name: dummy-logger-pub-lb namespace: default annotations: service.beta.kubernetes.io/azure-load-balancer-resource-group: aksoutbound service.beta.kubernetes.io/azure-pip-name: aksoutbound1 spec: ports: - port: 80 targetPort: 80 selector: app: dummy-logger type: LoadBalancer EOF ``` ## Pod Subnet https://ms.portal.azure.com/#@microsoft.onmicrosoft.com/resource/subscriptions/$SUBSCRIPTION_ID/resourceGroups/kubes_fw_knet/overview KUBE_NAME=dzkubekube-3 LOCATION=westcentralus KUBE_GROUP=kubes_fw_knet KUBE_VERSION=1.18.14 NODE_GROUP=kubes_fw_knet_dzkubek az aks get-credentials -g $KUBE_GROUP -n $KUBE_NAME --admin ssh dennis@192.168.127.12 az aks command invoke -g $KUBE_GROUP -n $KUBE_NAME$AKS_POSTFIX -c "kubectl get pods -n kube-system" az aks command invoke -g $KUBE_GROUP -n $KUBE_NAME$AKS_POSTFIX -c "kubectl apply -f deployment.yaml -n default" -f deployment.yaml az aks command invoke -g $KUBE_GROUP -n $KUBE_NAME$AKS_POSTFIX -c "kubectl apply -f deployment.yaml -n default" -f . az aks command invoke -g $KUBE_GROUP -n $KUBE_NAME$AKS_POSTFIX -c "helm repo add bitnami https://charts.bitnami.com/bitnami && helm repo update && helm install my-release -f values.yaml bitnami/nginx" -f values.yaml <file_sep> ``` echo 'installing nginx....' NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) IP_NAME=nginx-ingress-pip az network public-ip create --resource-group $NODE_GROUP --name $IP_NAME --sku Standard --allocation-method static --dns-name dznginx IP=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query ipAddress --output tsv) helm repo add nginx https://helm.nginx.com/stable helm search repo nginx-ingress kubectl create ns nginx helm upgrade my-ingress-controller nginx/nginx-ingress --install --set controller.service.loadBalancerIP="$IP" --set controller.stats.enabled=true --set controller.replicaCount=2 --set controller.service.externalTrafficPolicy=Local --namespace=nginx echo 'installing cert-manager' kubectl apply -f https://github.com/jetstack/cert-manager/releases/download/v1.1.0/cert-manager.yaml kubectl create namespace cert-manager kubectl label namespace cert-manager cert-manager.io/disable-validation=true helm repo add jetstack https://charts.jetstack.io helm repo update helm upgrade --install \ cert-manager \ --namespace cert-manager \ --version v1.1.0 \ --set installCRDs=true \ jetstack/cert-manager cat <<EOF | kubectl apply -f - apiVersion: cert-manager.io/v1alpha2 kind: ClusterIssuer metadata: name: letsencrypt spec: acme: server: https://acme-v02.api.letsencrypt.org/directory email: <EMAIL> privateKeySecretRef: name: letsencrypt solvers: - http01: ingress: class: nginx EOF echo 'creating ingress objects' kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml kubectl apply -f - <<EOF apiVersion: extensions/v1beta1 kind: Ingress metadata: name: appgw-dummy-ingress annotations: kubernetes.io/ingress.class: azure/application-gateway certmanager.k8s.io/cluster-issuer: letsencrypt spec: tls: - hosts: - <PLACEHOLDERS.COM> secretName: guestbook-secret-name rules: - host: <PLACEHOLDERS.COM> http: paths: - backend: serviceName: frontend servicePort: 80 EOF NGINXDNS=$(az network public-ip show --resource-group $NODE_GROUP --name $IP_NAME --query dnsSettings.fqdn --output tsv) cat <<EOF | kubectl apply -f - apiVersion: extensions/v1beta1 kind: Ingress metadata: name: nginx-dummy-ingress annotations: kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt spec: tls: - hosts: - $NGINXDNS secretName: nginx-secret rules: - host: $NGINXDNS http: paths: - backend: serviceName: nginx servicePort: 80 path: / EOF kubectl apply -f - <<EOF --- apiVersion: extensions/v1beta1 kind: Ingress metadata: name: bookbuyer-ingress namespace: bookbuyer annotations: kubernetes.io/ingress.class: nginx spec: rules: - host: dzapps.westcentralus.cloudapp.azure.com http: paths: - path: / backend: serviceName: bookbuyer servicePort: 14001 backend: serviceName: bookbuyer servicePort: 14001 EOF kubectl apply -f - <<EOF --- apiVersion: extensions/v1beta1 kind: Ingress metadata: name: bookbuyer-ingress namespace: bookbuyer annotations: kubernetes.io/ingress.class: nginx spec: rules: - host: bookbuyer.contoso.com http: paths: - path: / backend: serviceName: bookbuyer servicePort: 14001 backend: serviceName: bookbuyer servicePort: 14001 EOF curl -H 'Host: bookbuyer.contoso.com' http://dzapps.westcentralus.cloudapp.azure.com/ ```<file_sep>## Addon https://github.com/openservicemesh/osm https://github.com/microsoft/Docker-Provider/blob/ci_dev/Documentation/OSMPrivatePreview/ReadMe.md ``` az aks enable-addons --addons "open-service-mesh" --name $KUBE_NAME --resource-group $KUBE_GROUP kubectl get configmap -n kube-system osm-config -o JSON kubectl edit ConfigMap osm-config -n kube-system move to permissive mode kubectl patch ConfigMap -n kube-system osm-config --type merge --patch '{"data":{"permissive_traffic_policy_mode":"false"}}' kubectl patch ConfigMap -n kube-system osm-config --type merge --patch '{"data":{"permissive_traffic_policy_mode":"true"}}' kubectl patch ConfigMap osm-config -n kube-system -p '{"data":"permissive_traffic_policy_mode":"true"}}' --type=merge kubectl patch ConfigMap osm-config -n osm-system -p '{"data":{"use_https_ingress":"true"}}' --type=merge kubectl patch ConfigMap osm-config -n kube-system -p '{"data":"use_https_ingress":"true"}}' --type=merge kubectl get configmap -n kube-system osm-config -o json | jq '.data.prometheus_scraping' kubectl patch ConfigMap -n kube-system osm-config --type merge --patch '{"data":{"prometheus_scraping":"true"}}' kubectl patch configmap osm-config -n kube-system -p '{"data":{"tracing_enable":"true", "tracing_address":"otel-collector.default.svc.cluster.local", "tracing_port":"9411", "tracing_endpoint":"/api/v2/spans"}}' --type=merge otel-collector.default.svc.cluster.local --tracing-port 9411 --tracing-endpoint /api/v2/spans osm namespace add bookbuyer --mesh-name osm --enable-sidecar-injection osm namespace add bookstore --mesh-name osm --enable-sidecar-injection ``` ## OSM Binary https://blog.nillsf.com/index.php/2020/08/11/taking-the-open-service-mesh-for-a-test-drive/ ``` OSM_VERSION=v0.8.0 curl -sL "https://github.com/openservicemesh/osm/releases/download/$OSM_VERSION/osm-$OSM_VERSION-linux-amd64.tar.gz" | tar -vxzf - wget https://github.com/openservicemesh/osm/releases/download/v0.4.0/osm-v0.4.0-darwin-amd64.tar.gz tar -xvzf osm-v0.3.0-darwin-amd64.tar.gz cp darwin-amd64/osm ~/lib/osm alias osm='/Users/dennis/lib/osm/osm' osm install git clone https://github.com/openservicemesh/osm.git cd osm ``` ## OSM Custom Demo ``` kubectl create ns debugdemo kubectl apply -f tracing -n debugdemo osm namespace add debugdemo osm metrics enable --namespace debugdemo cat <<EOF | kubectl apply -f - kind: ConfigMap apiVersion: v1 data: schema-version: #string.used by agent to parse OSM config. supported versions are {v1}. Configs with other schema versions will be rejected by the agent. v1 config-version: #string.used by OSM addon team to keep track of this config file's version in their source control/repository (max allowed 10 chars, other chars will be truncated) ver1 osm-metric-collection-configuration: |- # OSM metric collection settings [osm_metric_collection_configuration.settings] # Namespaces to monitor # monitor_namespaces = ["debugdemo"] metadata: name: container-azm-ms-osmconfig namespace: kube-system EOF kubectl rollout restart deploy -n debugdemo ``` ## OSM Demo ``` kubectl create ns bookstore kubectl create ns bookthief kubectl create ns bookwarehouse kubectl create ns bookbuyer osm namespace add bookstore osm namespace add bookthief osm namespace add bookwarehouse osm namespace add bookbuyer kubectl apply -f osm/osm-full.yaml kubectl rollout status deployment --timeout 300s -n bookstore bookstore-v1 kubectl rollout status deployment --timeout 300s -n bookstore bookstore-v2 kubectl rollout status deployment --timeout 300s -n bookthief bookthief kubectl rollout status deployment --timeout 300s -n bookwarehouse bookwarehouse kubectl rollout status deployment --timeout 300s -n bookbuyer bookbuyer kubectl port-forward -n bookthief deploy/bookthief 8081:14001 kubectl port-forward -n bookbuyer deploy/bookbuyer 8080:14001 kubectl port-forward -n bookstore deploy/bookstore-v1 8085:80 kubectl port-forward -n bookbuyer deploy/bookbuyer 8080:14001 ``` ## OSM Demo https://github.com/openservicemesh/osm/blob/main/demo/README.md ``` cat <<EOF | kubectl apply -f - apiVersion: specs.smi-spec.io/v1alpha3 kind: HTTPRouteGroup metadata: name: bookstore-service-routes namespace: bookstore spec: matches: - name: books-bought pathRegex: /books-bought methods: - GET headers: - "user-agent": ".*-http-client/*.*" - "client-app": "bookbuyer" - name: buy-a-book pathRegex: ".*a-book.*new" methods: - GET - name: update-books-bought pathRegex: /update-books-bought methods: - POST EOF cat <<EOF | kubectl apply -f - kind: TrafficTarget apiVersion: access.smi-spec.io/v1alpha2 metadata: name: bookbuyer-access-bookstore namespace: "bookstore" spec: destination: kind: ServiceAccount name: bookstore namespace: "bookstore" rules: - kind: HTTPRouteGroup name: bookstore-service-routes matches: - buy-a-book - books-bought sources: - kind: ServiceAccount name: bookbuyer namespace: "bookbuyer" EOF cat <<EOF | kubectl apply -f - kind: TrafficTarget apiVersion: access.smi-spec.io/v1alpha2 metadata: name: bookbuyer-access-bookstore-v2 namespace: bookstore spec: destination: kind: ServiceAccount name: bookstore namespace: bookstore rules: - kind: HTTPRouteGroup name: bookstore-service-routes matches: - buy-a-book - books-bought sources: - kind: ServiceAccount name: bookbuyer namespace: bookbuyer EOF cat <<EOF | kubectl apply -f - apiVersion: split.smi-spec.io/v1alpha2 kind: TrafficSplit metadata: name: bookstore-split namespace: bookstore spec: service: bookstore.bookstore backends: - service: bookstore-v1 weight: 25 - service: bookstore-v2 weight: 75 EOF ``` # TrafficTarget is deny-by-default policy: if traffic from source to destination is not # explicitly declared in this policy - it will be blocked. # Should we ever want to allow traffic from bookthief to bookstore the block below needs # uncommented. ``` cat <<EOF | kubectl apply -f - kind: TrafficTarget apiVersion: access.smi-spec.io/v1alpha2 metadata: name: bookbuyer-access-bookstore namespace: "bookstore" spec: destination: kind: ServiceAccount name: bookstore namespace: "bookstore" rules: - kind: HTTPRouteGroup name: bookstore-service-routes matches: - buy-a-book - books-bought sources: - kind: ServiceAccount name: bookbuyer namespace: "bookbuyer" - kind: ServiceAccount name: bookthief namespace: "bookthief" EOF kubectl edit TrafficTarget bookbuyer-access-bookstore-v1 -n bookstore kubectl edit trafficsplits bookstore-split -n bookstore ``` kubectl apply -f - <<EOF apiVersion: v1 kind: Service metadata: name: bookbuyer namespace: bookbuyer labels: app: bookbuyer spec: ports: - port: 14001 name: inbound-port selector: app: bookbuyer EOF kubectl apply -f - <<EOF --- apiVersion: extensions/v1beta1 kind: Ingress metadata: name: bookbuyer-ingress namespace: bookbuyer annotations: kubernetes.io/ingress.class: azure/application-gateway spec: rules: - host: $APPGW_DNS http: paths: - path: / backend: serviceName: bookbuyer servicePort: 14001 backend: serviceName: bookbuyer servicePort: 14001 EOF ## Tracing ``` osm mesh upgrade --enable-tracing --tracing-address otel-collector.default.svc.cluster.local --tracing-port 9411 --tracing-endpoint /api/v2/spans ``` ## cleanup kubectl delete service bookstore-v2 -n bookstore kubectl delete deployment bookstore-v2 -n bookstore kubectl delete traffictarget bookbuyer-access-bookstore-v2 -n bookstore kubectl delete traffictarget bookbuyer-access-bookstore -n bookstore kubectl delete HTTPRouteGroup bookstore-service-routes -n bookstore kubectl delete TrafficTarget bookstore-access-bookwarehouse -n bookwarehouse kubectl delete HTTPRouteGroup bookwarehouse-service-routes -n bookwarehouse kubectl delete TrafficSplit bookstore-split -n bookstore kubectl apply -f - <<EOF apiVersion: split.smi-spec.io/v1alpha2 kind: TrafficSplit metadata: name: bookstore-split namespace: bookstore spec: service: bookstore.bookstore backends: - service: bookstore weight: 25 - service: bookstore-v2 weight: 75 EOF<file_sep>KUBE_NAME=$1 KUBE_GROUP=$2 USE_ADDON=$3 SUBSCRIPTION_ID=$(az account show --query id -o tsv) #subscriptionid LOCATION=$(az group show -n $KUBE_GROUP --query location -o tsv) NODE_GROUP=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query nodeResourceGroup -o tsv) AKS_SUBNET_ID=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query "agentPoolProfiles[0].vnetSubnetId" -o tsv) AKS_SUBNET_NAME="aks-5-subnet" APPGW_SUBNET_ID=$(echo ${AKS_SUBNET_ID%$AKS_SUBNET_NAME*}gw-1-subnet) echo "creating appgw in subnet $APPGW_SUBNET_ID ..." APPGW_PUBLIC_IP=$(az network public-ip show -g $KUBE_GROUP -n appgw-pip --query ipAddress -o tsv) if [ "$APPGW_PUBLIC_IP" == "" ]; then echo "creating public ip appgw-pip ..." az network public-ip create --resource-group $KUBE_GROUP --name appgw-pip --allocation-method Static --sku Standard --dns-name $KUBE_NAME APPGW_PUBLIC_IP=$(az network public-ip show -g $KUBE_GROUP -n appgw-pip --query ipAddress -o tsv) fi APPGW_RESOURCE_ID=""#$(az network application-gateway list --resource-group=$KUBE_GROUP -o json | jq -r ".[0].id") #if [ "$APPGW_RESOURCE_ID" == "" ]; then echo "creating application gateway $KUBE_NAME-appgw..." az network application-gateway create --name $KUBE_NAME-appgw --resource-group $KUBE_GROUP --location $LOCATION --http2 Enabled --min-capacity 0 --max-capacity 10 --sku WAF_v2 --subnet $APPGW_SUBNET_ID --http-settings-cookie-based-affinity Disabled --frontend-port 80 --http-settings-port 80 --http-settings-protocol Http --public-ip-address appgw-pip --private-ip-address "10.0.2.100" APPGW_NAME=$(az network application-gateway list --resource-group=$KUBE_GROUP -o json | jq -r ".[0].name") APPGW_RESOURCE_ID=$(az network application-gateway list --resource-group=$KUBE_GROUP -o json | jq -r ".[0].id") APPGW_SUBNET_ID=$(az network application-gateway list --resource-group=$KUBE_GROUP -o json | jq -r ".[0].gatewayIpConfigurations[0].subnet.id") #fi exit APPGW_ADDON_ENABLED=$(az aks show --resource-group $KUBE_GROUP --name $KUBE_NAME --query addonProfiles.ingressApplicationGateway.enabled --output tsv) if [ "$APPGW_ADDON_ENABLED" == "" ]; then echo "enabling ingress-appgw addon for $APPGW_RESOURCE_ID" az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME -a ingress-appgw --appgw-id $APPGW_RESOURCE_ID fi exit APPGW_DNS=$(az network public-ip show --resource-group $KUBE_GROUP --name appgw-pip --query dnsSettings.fqdn --output tsv) kubectl apply -f https://raw.githubusercontent.com/jetstack/cert-manager/release-0.13/deploy/manifests/00-crds.yaml --validate=false kubectl create namespace cert-manager kubectl label namespace cert-manager cert-manager.io/disable-validation=true helm repo add jetstack https://charts.jetstack.io helm repo update helm upgrade --install cert-manager \ --namespace cert-manager \ --version v0.13.0 \ jetstack/cert-manager --wait echo 'creating ingress objects' kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml --wait true kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml --wait true cat <<EOF | kubectl apply -f - apiVersion: cert-manager.io/v1alpha2 kind: ClusterIssuer metadata: name: letsencryptappgw spec: acme: server: https://acme-v02.api.letsencrypt.org/directory email: <EMAIL> privateKeySecretRef: name: letsencrypt solvers: - http01: ingress: class: azure/application-gateway EOF kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml kubectl apply -f - <<EOF apiVersion: extensions/v1beta1 kind: Ingress metadata: name: appgw-dummy-ingress annotations: kubernetes.io/ingress.class: azure/application-gateway certmanager.k8s.io/cluster-issuer: letsencryptappgw cert-manager.io/acme-challenge-type: http01 spec: tls: - hosts: - $APPGW_DNS secretName: dummy-secret-name rules: - host: $APPGW_DNS http: paths: - backend: serviceName: dummy-logger-cluster servicePort: 80 EOF kubectl apply -f - <<EOF apiVersion: extensions/v1beta1 kind: Ingress metadata: name: appgw-dummy-ingress annotations: kubernetes.io/ingress.class: azure/application-gateway spec: rules: - host: $APPGW_DNS http: paths: - backend: serviceName: dummy-logger-cluster servicePort: 80 EOF<file_sep>FROM node:alpine ARG basedir="app" ARG build_info="Docker container build" ENV NODE_ENV production ENV BUILD_INFO $build_info # Place our app here WORKDIR /home/app # NPM install packages COPY ${basedir}/package*.json ./ RUN npm install --production --silent # NPM is done, now copy in the the whole project to the workdir COPY ${basedir}/*.js ./ EXPOSE 8080 ENTRYPOINT [ "npm" , "start" ]<file_sep>#!/bin/sh # # wget https://raw.githubusercontent.com/denniszielke/container_demos/master/scripts/aks_vnet.sh # chmod +x ./aks_vnet.sh # bash ./aks_vnet.sh # set -e DEPLOYMENT_NAME="dzmtlsaks3" # here enter unique deployment name (ideally short and with letters for global uniqueness) AAD_GROUP_ID="9329d38c-5296-4ecb-afa5-3e74f9abe09f --enable-azure-rbac" # here the AAD group that will be used to lock down AKS authentication LOCATION="westeurope" # here enter the datacenter location can be eastus or westeurope KUBE_GROUP=$DEPLOYMENT_NAME # here enter the resources group name of your AKS cluster KUBE_NAME=$DEPLOYMENT_NAME # here enter the name of your kubernetes resource NODE_GROUP=$KUBE_GROUP"_"$KUBE_NAME"_nodes_"$LOCATION # name of the node resource group KUBE_VNET_NAME="$DEPLOYMENT_NAME-vnet" KUBE_ING_SUBNET_NAME="ing-4-subnet" # here enter the name of your ingress subnet KUBE_AGENT_SUBNET_NAME="aks-5-subnet" # here enter the name of your AKS subnet VAULT_NAME=dkv$KUBE_NAME SUBSCRIPTION_ID=$(az account show --query id -o tsv) # here enter your subscription id TENANT_ID=$(az account show --query tenantId -o tsv) KUBE_VERSION=$(az aks get-versions -l $LOCATION --query 'orchestrators[?default == `true`].orchestratorVersion' -o tsv) # here enter the kubernetes version of your AKS MY_OWN_OBJECT_ID=$(az ad signed-in-user show --query objectId --output tsv) # this will be your own aad object id az extension add --name aks-preview az extension update --name aks-preview if [ $(az group exists --name $KUBE_GROUP) = false ]; then echo "creating resource group $KUBE_GROUP..." az group create -n $KUBE_GROUP -l $LOCATION -o none echo "resource group $KUBE_GROUP created" else echo "resource group $KUBE_GROUP already exists" fi echo "setting up vnet" VNET_RESOURCE_ID=$(az network vnet list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_VNET_NAME')].id" -o tsv) if [ "$VNET_RESOURCE_ID" == "" ]; then echo "creating vnet $KUBE_VNET_NAME..." az network vnet create --address-prefixes "10.0.0.0/20" -g $KUBE_GROUP -n $KUBE_VNET_NAME -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_ING_SUBNET_NAME --address-prefix 10.0.4.0/24 -o none az network vnet subnet create -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --address-prefix 10.0.5.0/24 -o none VNET_RESOURCE_ID=$(az network vnet show -g $KUBE_GROUP -n $KUBE_VNET_NAME --query id -o tsv) echo "created $VNET_RESOURCE_ID" else echo "vnet $VNET_RESOURCE_ID already exists" fi SECRET_NAME="mySecret" VAULT_ID=$(az keyvault list -g $KUBE_GROUP --query "[?contains(name, '$VAULT_NAME')].id" -o tsv) if [ "$VAULT_ID" == "" ]; then echo "creating keyvault $VAULT_NAME" az keyvault create -g $KUBE_GROUP -n $VAULT_NAME -l $LOCATION -o none az keyvault secret set -n $SECRET_NAME --vault-name $VAULT_NAME --value MySuperSecretThatIDontWantToShareWithYou! -o none VAULT_ID=$(az keyvault show -g $KUBE_GROUP -n $VAULT_NAME -o tsv --query id) echo "created keyvault $VAULT_ID" else echo "keyvault $VAULT_ID already exists" VAULT_ID=$(az keyvault show -g $KUBE_GROUP -n $VAULT_NAME -o tsv --query name) fi KUBE_AGENT_SUBNET_ID=$(az network vnet subnet show -g $KUBE_GROUP --vnet-name $KUBE_VNET_NAME -n $KUBE_AGENT_SUBNET_NAME --query id -o tsv) echo "setting up controller identity" AKS_CONTROLLER_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-ctl-id')].clientId" -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-clt-id')].id" -o tsv)" if [ "$AKS_CONTROLLER_RESOURCE_ID" == "" ]; then echo "creating controller identity $KUBE_NAME-ctl-id in $KUBE_GROUP" az identity create --name $KUBE_NAME-ctl-id --resource-group $KUBE_GROUP -o none sleep 5 # wait for replication AKS_CONTROLLER_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-ctl-id --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-ctl-id --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 25 # wait for replication AKS_CONTROLLER_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-ctl-id --query clientId -o tsv)" AKS_CONTROLLER_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-ctl-id --query id -o tsv)" echo "created controller identity $AKS_CONTROLLER_RESOURCE_ID " echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" sleep 5 # wait for replication az role assignment create --role "Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none else echo "controller identity $AKS_CONTROLLER_RESOURCE_ID already exists" echo "assigning permissions on network $KUBE_AGENT_SUBNET_ID" az role assignment create --role "Contributor" --assignee $AKS_CONTROLLER_CLIENT_ID --scope $KUBE_AGENT_SUBNET_ID -o none fi echo "setting up kubelet identity" AKS_KUBELET_CLIENT_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-kbl-id')].clientId" -o tsv)" AKS_KUBELET_RESOURCE_ID="$(az identity list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME-kbl-id')].id" -o tsv)" if [ "$AKS_KUBELET_CLIENT_ID" == "" ]; then echo "creating kubelet identity $KUBE_NAME-kbl-id in $KUBE_GROUP" az identity create --name $KUBE_NAME-kbl-id --resource-group $KUBE_GROUP -o none sleep 5 # wait for replication AKS_KUBELET_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-kbl-id --query clientId -o tsv)" AKS_KUBELET_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-kbl-id --query id -o tsv)" echo "created kubelet identity $AKS_KUBELET_RESOURCE_ID " sleep 25 # wait for replication AKS_KUBELET_CLIENT_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-kbl-id --query clientId -o tsv)" AKS_KUBELET_RESOURCE_ID="$(az identity show -g $KUBE_GROUP -n $KUBE_NAME-kbl-id --query id -o tsv)" echo "created kubelet identity $AKS_KUBELET_RESOURCE_ID " echo "assigning permissions on keyvault $VAULT_ID" az keyvault set-policy -n $VAULT_NAME --object-id $AKS_KUBELET_CLIENT_ID --key-permissions get --certificate-permissions get -o none else echo "kubelet identity $AKS_KUBELET_RESOURCE_ID already exists" echo "assigning permissions on keyvault $VAULT_ID" az keyvault set-policy -n $VAULT_NAME --object-id $AKS_KUBELET_CLIENT_ID --key-permissions get --certificate-permissions get -o none fi echo "setting up aks" AKS_ID=$(az aks list -g $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$AKS_ID" == "" ]; then echo "creating AKS $KUBE_NAME in $KUBE_GROUP" echo "using host subnet $KUBE_AGENT_SUBNET_ID" az aks create --resource-group $KUBE_GROUP --name $KUBE_NAME$AKS_POSTFIX --ssh-key-value ~/.ssh/id_rsa.pub --node-count 3 --node-vm-size "Standard_B2s" --min-count 3 --max-count 5 --enable-cluster-autoscaler --auto-upgrade-channel patch --node-resource-group $NODE_GROUP --load-balancer-sku standard --enable-vmss --network-plugin azure --vnet-subnet-id $KUBE_AGENT_SUBNET_ID --docker-bridge-address 172.17.0.1/16 --dns-service-ip 10.2.0.10 --service-cidr 10.2.0.0/24 --kubernetes-version $KUBE_VERSION --assign-identity $AKS_CONTROLLER_RESOURCE_ID --assign-kubelet-identity $AKS_KUBELET_RESOURCE_ID --node-osdisk-size 300 --enable-managed-identity --enable-aad --aad-admin-group-object-ids $AAD_GROUP_ID --aad-tenant-id $TENANT_ID --network-policy calico --enable-addons "azure-keyvault-secrets-provider,open-service-mesh" -o none az aks update --resource-group $KUBE_GROUP --name $KUBE_NAME --auto-upgrade-channel node-image # az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="azure-keyvault-secrets-provider" az aks update --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --enable-secret-rotation # az aks enable-addons --resource-group="$KUBE_GROUP" --name="$KUBE_NAME" --addons="open-service-mesh" AKS_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query id -o tsv) echo "created AKS $AKS_ID" else echo "AKS $AKS_ID already exists" fi AKS_OIDC_ISSUER="$(az aks show -n $KUBE_NAME -g $KUBE_GROUP --query "oidcIssuerProfile.issuerUrl" -o tsv)" echo "setting up azure monitor" WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace list --resource-group $KUBE_GROUP --query "[?contains(name, '$KUBE_NAME')].id" -o tsv) if [ "$WORKSPACE_RESOURCE_ID" == "" ]; then echo "creating workspace $KUBE_NAME in $KUBE_GROUP" az monitor log-analytics workspace create --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME --location $LOCATION -o none WORKSPACE_RESOURCE_ID=$(az monitor log-analytics workspace show --resource-group $KUBE_GROUP --workspace-name $KUBE_NAME -o json | jq '.id' -r) az aks enable-addons --resource-group $KUBE_GROUP --name $KUBE_NAME --addons monitoring --workspace-resource-id $WORKSPACE_RESOURCE_ID OMS_CLIENT_ID=$(az aks show -g $KUBE_GROUP -n $KUBE_NAME --query addonProfiles.omsagent.identity.clientId -o tsv) az role assignment create --assignee $OMS_CLIENT_ID --scope $AKS_ID --role "Monitoring Metrics Publisher" fi IP_ID=$(az network public-ip list -g $NODE_GROUP --query "[?contains(name, 'nginxingress')].id" -o tsv) if [ "$IP_ID" == "" ]; then echo "creating ingress ip nginxingress" az network public-ip create -g $NODE_GROUP -n nginxingress --sku STANDARD --dns-name $KUBE_NAME -o none IP_ID=$(az network public-ip show -g $NODE_GROUP -n nginxingress -o tsv) IP=$(az network public-ip show -g $NODE_GROUP -n nginxingress -o tsv --query ipAddress) DNS=$(az network public-ip show -g $NODE_GROUP -n nginxingress -o tsv --query dnsSettings.fqdn) echo "created ip $IP_ID with $IP on $DNS" else IP=$(az network public-ip show -g $NODE_GROUP -n nginxingress -o tsv --query ipAddress) DNS=$(az network public-ip show -g $NODE_GROUP -n nginxingress -o tsv --query dnsSettings.fqdn) echo "AKS $AKS_ID already exists with $IP on $DNS" fi az aks get-credentials --resource-group=$KUBE_GROUP --name=$KUBE_NAME --admin --overwrite-existing echo "created this AKS cluster:" az aks show --resource-group=$KUBE_GROUP --name=$KUBE_NAME kubectl create namespace ingress # Add the ingress-nginx repository helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx # Update the helm repo(s) helm repo update #az aks disable-addons --addons "open-service-mesh" --name $KUBE_NAME --resource-group $KUBE_GROUP osm install kubectl create ns dummy-logger osm namespace add dummy-logger kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/depl-logger.yaml -n dummy-logger kubectl apply -f https://raw.githubusercontent.com/denniszielke/container_demos/master/logging/dummy-logger/svc-cluster-logger.yaml -n dummy-logger # Use Helm to deploy an NGINX ingress controller in the ingress-basic namespace helm upgrade nginx-ingress ingress-nginx/ingress-nginx --install \ --namespace ingress \ --set controller.replicaCount=2 \ --set controller.metrics.enabled=true \ --set controller.service.loadBalancerIP="$IP" \ --set defaultBackend.enabled=true \ --set controller.service.externalTrafficPolicy=Local osm_namespace=osm-system # replace <osm-namespace> with the namespace where OSM is installed osm_mesh_name=osm # replace <osm-mesh-name> with the mesh name (use `osm mesh list` command) nginx_ingress_namespace=ingress # replace <nginx-namespace> with the namespace where Nginx is installed nginx_ingress_service=nginx-ingress-ingress-nginx-controller # replace <nginx-ingress-controller-service> with the name of the nginx ingress controller service nginx_ingress_host="$(kubectl -n "$nginx_ingress_namespace" get service "$nginx_ingress_service" -o jsonpath='{.status.loadBalancer.ingress[0].ip}')" nginx_ingress_port="$(kubectl -n "$nginx_ingress_namespace" get service "$nginx_ingress_service" -o jsonpath='{.spec.ports[?(@.name=="http")].port}')" kubectl label ns "$nginx_ingress_namespace" openservicemesh.io/monitored-by="$osm_mesh_name" kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: http-dummy-logger namespace: dummy-logger spec: ingressClassName: nginx rules: - http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 --- kind: IngressBackend apiVersion: policy.openservicemesh.io/v1alpha1 metadata: name: http-dummy-logger namespace: dummy-logger spec: backends: - name: dummy-logger port: number: 80 protocol: http sources: - kind: Service namespace: "$nginx_ingress_namespace" name: "$nginx_ingress_service" EOF kubectl edit meshconfig osm-mesh-config -n osm-system kubectl patch meshconfig osm-mesh-config -n osm-system -p '{"spec":{"certificate:":{"ingressGateway": {"secret": {"name": "osm-nginx-client-cert","namespace": "osm-system"},"subjectAltNames": ["nginx-ingress-ingress-nginx-controller.ingress.cluster.local"],"validityDuration": "24h"}}}}' --type=merge kubectl get meshconfig osm-mesh-config -n osm-system certificate: ingressGateway: secret: name: osm-nginx-client-cert namespace: osm-system subjectAltNames: - nginx-ingress-ingress-nginx-controller.ingress.cluster.local validityDuration: 24h kubectl label namespace ingress-basic cert-manager.io/disable-validation=true helm repo add jetstack https://charts.jetstack.io helm repo update CERT_MANAGER_REGISTRY=quay.io CERT_MANAGER_TAG=v1.3.1 CERT_MANAGER_IMAGE_CONTROLLER=jetstack/cert-manager-controller CERT_MANAGER_IMAGE_WEBHOOK=jetstack/cert-manager-webhook CERT_MANAGER_IMAGE_CAINJECTOR=jetstack/cert-manager-cainjector # Install the cert-manager Helm chart helm upgrade cert-manager jetstack/cert-manager \ --namespace ingress --install \ --version $CERT_MANAGER_TAG \ --set installCRDs=true \ --set image.repository=$CERT_MANAGER_REGISTRY/$CERT_MANAGER_IMAGE_CONTROLLER \ --set image.tag=$CERT_MANAGER_TAG \ --set webhook.image.repository=$CERT_MANAGER_REGISTRY/$CERT_MANAGER_IMAGE_WEBHOOK \ --set webhook.image.tag=$CERT_MANAGER_TAG \ --set cainjector.image.repository=$CERT_MANAGER_REGISTRY/$CERT_MANAGER_IMAGE_CAINJECTOR \ --set cainjector.image.tag=$CERT_MANAGER_TAG kubectl apply -f - <<EOF apiVersion: cert-manager.io/v1 kind: ClusterIssuer metadata: name: letsencrypt spec: acme: server: https://acme-v02.api.letsencrypt.org/directory email: <EMAIL> privateKeySecretRef: name: letsencrypt solvers: - http01: ingress: class: nginx EOF kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: https-dummy-logger namespace: dummy-logger annotations: cert-manager.io/cluster-issuer: letsencrypt spec: tls: - hosts: - $DNS secretName: dummy-cert-secret ingressClassName: nginx rules: - host: $DNS http: paths: - path: / pathType: Prefix backend: service: name: dummy-logger port: number: 80 EOF curl -sI http://"$DNS"/get kubectl get secret dummy-cert-secret -n dummy-logger -o json | jq '.data | map_values(@base64d)' openssl pkcs12 -export -in ingress-tls.crt -inkey ingress-tls.key -out $CERT_NAME.pfx # skip Password prompt az keyvault certificate import --vault-name ${KEYVAULT_NAME} -n $CERT_NAME -f $CERT_NAME.pfx cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1alpha1 kind: SecretProviderClass metadata: name: ingress-tls namespace: ingress spec: provider: azure parameters: usePodIdentity: "false" useVMManagedIdentity: "true" userAssignedIdentityID: "$AKS_KUBELET_CLIENT_ID" keyvaultName: "$VAULT_NAME" cloudName: "" # [OPTIONAL for Azure] if not provided, azure environment will default to AzurePublicCloud objects: | array: - | objectName: mySecret objectType: secret # object types: secret, key or cert objectVersion: "" # [OPTIONAL] object versions, default to latest if empty tenantId: "$TENANT_ID" # the tenant ID of the KeyVault EOF cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: busybox-secrets-store-inline-user-msi namespace: ingress spec: containers: - name: busybox image: k8s.gcr.io/e2e-test-images/busybox:1.29 command: - "/bin/sleep" - "10000" volumeMounts: - name: secrets-store01-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store01-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: "ingress-tls" EOF AD_APP_NAME="$DEPLOYMENT_NAME-msal-proxy" APP_HOSTNAME="$DNS" HOMEPAGE=https://$APP_HOSTNAME IDENTIFIER_URIS=$HOMEPAGE REPLY_URLS=https://$APP_HOSTNAME/msal/signin-oidc CLIENT_ID="" OBJECT_ID="" CLIENT_ID=$(az ad app create --display-name $AD_APP_NAME --homepage $HOMEPAGE --reply-urls $REPLY_URLS --required-resource-accesses @manifest.json -o json | jq -r '.appId') echo $CLIENT_ID OBJECT_ID=$(az ad app show --id $CLIENT_ID -o json | jq '.objectId' -r) echo $OBJECT_ID az ad app update --id $OBJECT_ID --set "oauth2Permissions=[]" # The newly registered app does not have a password. Use "az ad app credential reset" to add password and save to a variable. CLIENT_SECRET=$(az ad app credential reset --id $CLIENT_ID -o json | jq '.password' -r) echo $CLIENT_SECRET # Get your Azure AD tenant ID and save to variable AZURE_TENANT_ID=$(az account show -o json | jq '.tenantId' -r) echo $AZURE_TENANT_ID curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F&client_id=ff3756e7-f35e-4128-a352-4b5623c94d43' -H Metadata:true -s export SERVICE_ACCOUNT_NAMESPACE="default" export SERVICE_ACCOUNT_NAME="workload-identity-sa" AKS_OIDC_ISSUER="$(az aks show -n $KUBE_NAME -g $KUBE_GROUP --query "oidcIssuerProfile.issuerUrl" -o tsv)" SECRET_NAME="mySecret" # user assigned identity name export UAID="$KUBE_NAME-fic" # federated identity name export FICID="$KUBE_NAME-fic" VAULT_NAME=dzkv$KUBE_NAME az identity create --name $KUBE_NAME-fic --resource-group $KUBE_GROUP -o none export USER_ASSIGNED_CLIENT_ID="$(az identity show --resource-group "${KUBE_GROUP}" --name "$KUBE_NAME-fic" --query 'clientId' -o tsv)" cat <<EOF | kubectl apply -f - apiVersion: v1 kind: ServiceAccount metadata: annotations: azure.workload.identity/client-id: ${USER_ASSIGNED_CLIENT_ID} labels: azure.workload.identity/use: "true" name: ${SERVICE_ACCOUNT_NAME} namespace: ${SERVICE_ACCOUNT_NAMESPACE} EOF az identity federated-credential create --name ${FICID} --identity-name ${FICID} --resource-group $KUBE_GROUP --issuer ${AKS_OIDC_ISSUER} --subject system:serviceaccount:${SERVICE_ACCOUNT_NAMESPACE}:${SERVICE_ACCOUNT_NAME} cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: quick-start namespace: ${SERVICE_ACCOUNT_NAMESPACE} spec: serviceAccountName: ${SERVICE_ACCOUNT_NAME} containers: - image: ghcr.io/azure/azure-workload-identity/msal-go name: oidc env: - name: KEYVAULT_NAME value: ${VAULT_NAME} - name: SECRET_NAME value: ${SECRET_NAME} nodeSelector: kubernetes.io/os: linux EOF kubectl exec -it centos-token -- /bin/bash cat /var/run/secrets/azure/tokens/azure-identity-token cat <<EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: centos-token namespace: ${SERVICE_ACCOUNT_NAMESPACE} spec: serviceAccountName: ${SERVICE_ACCOUNT_NAME} containers: - name: centoss image: centos ports: - containerPort: 80 command: - sleep - "3600" EOF cat <<EOF | kubectl apply -f - apiVersion: secrets-store.csi.x-k8s.io/v1alpha1 kind: SecretProviderClass metadata: name: azure-kvname-user-msi namespace: default spec: provider: azure parameters: usePodIdentity: "false" clientID: "$USER_ASSIGNED_CLIENT_ID" keyvaultName: "$VAULT_NAME" cloudName: "" # [OPTIONAL for Azure] if not provided, azure environment will default to AzurePublicCloud objects: | array: - | objectName: mySecret objectType: secret # object types: secret, key or cert objectVersion: "" # [OPTIONAL] object versions, default to latest if empty tenantId: "$TENANT_ID" # the tenant ID of the KeyVault EOF cat <<EOF | kubectl apply -f - kind: Pod apiVersion: v1 metadata: name: busybox-secrets-store-inline-wi spec: containers: - name: busybox image: k8s.gcr.io/e2e-test-images/busybox:1.29 command: - "/bin/sleep" - "10000" volumeMounts: - name: secrets-store01-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store01-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: "azure-kvname-user-msi" EOF
1258e1ac7819e7e1c0824424bb6a06db4fa842be
[ "Markdown", "JavaScript", "INI", "Java", "Python", "Dockerfile", "Shell" ]
159
Markdown
denniszielke/container_demos
e58e214ca9fad061c365348288018a749d609ac0
c41ebec08a2085b4c03b5db0848c0b7ba0974230
refs/heads/master
<repo_name>anandgohil/all_django_program<file_sep>/d_jango all examples/Django 7 to 9 AM/Project23/app23/models.py from django.db import models class FilesModel(models.Model): number = models.IntegerField(primary_key=True) name = models.CharField(max_length=100,unique=True) file_path = models.FileField(upload_to='my_documents/')<file_sep>/d_jango all examples/Django 7 to 9 AM/Project21/app21/views.py from django.shortcuts import render from .models import EmployeeModel # Create your views here. def showIndix(request): return render(request,"index.html") def register(request): return render(request,"register.html") def viewall(request): qs = EmployeeModel.objects.all() return render(request,"viewall.html",{"data":qs}) def saveEmploeyee(request): id = request.POST.get("idno") na = request.POST.get("name") sal = request.POST.get("salary") EmployeeModel(salary=sal,idno=id,name=na).save() return render(request,"index.html",{"message":"Employee Created"}) def updateEmploeyee(request): uid = request.GET.get("update_id") #res = EmployeeModel.objects.filter(idno=uid) res = EmployeeModel.objects.get(idno=uid) return render(request,"update.html",{"data":res}) def update_emp(request): id = request.POST.get("u_id") na = request.POST.get("u_name") sal = request.POST.get("u_sal") EmployeeModel.objects.filter(idno=id).update(name=na,salary=sal) return viewall(request) def deleteEmployee(request): did = request.POST.get("del_idno") EmployeeModel.objects.filter(idno=did).delete() return viewall(request)<file_sep>/d_jango all examples/Django 7 to 9 AM/Project31/app31/migrations/0001_initial.py # Generated by Django 2.2.4 on 2019-11-07 04:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BiryaniTypeModel', fields=[ ('bt_no', models.AutoField(primary_key=True, serialize=False)), ('b_type', models.CharField(max_length=30)), ], ), migrations.CreateModel( name='BiryaniModel', fields=[ ('b_no', models.AutoField(primary_key=True, serialize=False)), ('b_name', models.CharField(max_length=30)), ('b_price', models.FloatField()), ('b_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app31.BiryaniTypeModel')), ], ), ] <file_sep>/d_jango all examples/Django 7 to 9 AM/Project32/app32/models.py from django.db import models class PersonModel(models.Model): aadhar = models.IntegerField(primary_key=True) pname = models.CharField(max_length=100) contact = models.IntegerField() address = models.TextField() def __str__(self): return self.pname class PassportModel(models.Model): pno = models.IntegerField(primary_key=True) p_details = models.OneToOneField(PersonModel,on_delete=models.CASCADE) <file_sep>/d_jango all examples/Django 7 to 9 AM/Project25/app25/models.py from django.db import models class LoginDetails(models.Model): username = models.CharField(max_length=30,primary_key=True) password = models.CharField(max_length=30) <file_sep>/d_jango all examples/Django 7 to 9 AM/Project24/app24/migrations/0001_initial.py # Generated by Django 2.2.4 on 2019-10-29 05:14 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='EmployeeModel', fields=[ ('eid', models.AutoField(primary_key=True, serialize=False)), ('email', models.EmailField(max_length=100, unique=True)), ('password', models.CharField(max_length=100)), ('image', models.ImageField(upload_to='emp_images/')), ], ), ] <file_sep>/d_jango all examples/Django 7 to 9 AM/Project22/app22/views.py from django.shortcuts import render from .models import SavingsAccountModel def showIndex(request): auto_acno = 0 try: res = SavingsAccountModel.objects.all()[::-1][0] auto_acno = int(res.acno) + 1 except IndexError: auto_acno = 10000006000 qs = SavingsAccountModel.objects.all() return render(request,"index.html",{"acno":auto_acno,"data":qs}) def saveAccount(request): acno = request.POST.get("acno") name = request.POST.get("name") type = request.POST.get("type") age = request.POST.get("age") gender = request.POST.get("gender") balance = request.POST.get("balance") im = request.FILES["image"] SavingsAccountModel(photo=im,acno=acno,balance=balance,acctype=type,name=name,age=age,gender=gender).save() return showIndex(request)<file_sep>/d_jango all examples/Django 7 to 9 AM/Project30/app30/forms.py from django import forms from .models import Publisher,Article class PublisherForm(forms.ModelForm): class Meta: model = Publisher fields = "__all__" class ArticleForm(forms.ModelForm): class Meta: model = Article fields = "__all__" <file_sep>/d_jango all examples/Django 7 to 9 AM/Project22/app22/models.py from django.db import models class SavingsAccountModel(models.Model): acno = models.IntegerField(primary_key=True) name = models.CharField(max_length=30) acctype = models.CharField(max_length=30) age = models.IntegerField() gender = models.CharField(max_length=10) balance = models.DecimalField(max_digits=10,decimal_places=2) photo = models.ImageField(upload_to="acc_images/",default=False) <file_sep>/d_jango all examples/Django 7 to 9 AM/Project23/app23/views.py from django.views.generic import CreateView, ListView from .models import FilesModel class FileUpload(CreateView): model = FilesModel fields = "__all__" template_name = "index.html" success_url = '/view_all/' class ViewAllFiles(ListView): model = FilesModel template_name = "showall.html" <file_sep>/d_jango all examples/Django 7 to 9 AM/Project24/app24/models.py from django.db import models class EmployeeModel(models.Model): eid = models.AutoField(primary_key=True) email = models.EmailField(max_length=100,unique=True) password = models.CharField(max_length=100) image = models.ImageField(upload_to="emp_images/") <file_sep>/d_jango all examples/Django 7 to 9 AM/Project30/app30/views.py from django.shortcuts import render,redirect from .forms import PublisherForm,ArticleForm from .models import Publisher,Article from django.contrib import messages def openPublisher(request): pf = PublisherForm() return render(request,"addp.html",{"form":pf}) def savePublisher(request): name = request.POST.get("name") Publisher(name=name).save() messages.success(request,"Publisher is Saved") return redirect("main") def openArticle(request): af = ArticleForm() return render(request,"adda.html",{"form":af}) def saveArticle(request): name = request.POST.get("name") p_n = request.POST.getlist("publisher_name") a = Article(name = name) a.save() a.publisher_name.set(p_n) messages.success(request, "Article is Saved") return redirect("main") def viewPublisher(request): qs = Publisher.objects.all() return render(request,"viewp.html",{"data":qs}) def viewArticle(request): return render(request,"viewa.html",{"data":Article.objects.all()})<file_sep>/d_jango all examples/Django 7 to 9 AM/Project24/app24/views.py from django.http import HttpResponseRedirect from django.views.decorators.cache import cache_control from django.shortcuts import render,redirect from django.shortcuts import redirect from .models import EmployeeModel def showIndex(request): try: if eval(request.COOKIES["status"]): email = request.COOKIES["value"] res = EmployeeModel.objects.get(email=email) return render(request,"welcome.html",{"data":res}) else: return render(request,"index.html") except KeyError: return render(request, "index.html") def showRegister(request): return render(request,"register.html") def saveEmployee(request): e = request.POST["email"] f = request.FILES["image"] p = request.POST["password"] EmployeeModel(email=e,password=p,image=f).save() return redirect('main') @cache_control(no_cache=True, must_revalidate=True,no_store=True) def loginCheck(request): em = request.POST["email"] pa = request.POST["password"] try: res = EmployeeModel.objects.get(email=em,password=pa) #HttpResponsePermanentRedirect(request,"welcome.html") response = render(request,"welcome.html",{"data":res}) response.set_cookie("status",True) response.set_cookie("value",em) return response except EmployeeModel.DoesNotExist: return render(request,"index.html",{"err_message":"Invalid User"}) @cache_control(no_cache=True, must_revalidate=True,no_store=True) def logout(request): #response = render(request,"index.html") response = HttpResponseRedirect("/index/") response.set_cookie("status", False) response.set_cookie("value", None) return response<file_sep>/d_jango all examples/Django 7 to 9 AM/Project32/templates/viewpa.html <table align="center" border="2"> <tr> <th>Passport No</th> <th>Person No</th> </tr> {% for x in data %} <tr> <th>{{ x.pno }}</th> <th> {{ x.p_details }} <table border="2"> <tr> <th>{{ x.p_details.aadhar }}</th> <th>{{ x.p_details.contact }}</th> <th>{{ x.p_details.address }}</th> </tr> </table> </th> </tr> {% endfor %} </table><file_sep>/d_jango all examples/Django 7 to 9 AM/Project30/templates/viewa.html <table align="center" border="2"> <tr> <th>IDNO</th> <th>NAME</th> <th>Publisher</th> </tr> {% for x in data %} <tr> <th>{{ x.aid }}</th> <th>{{ x.name }}</th> <th> {% for y in x.publisher_name.all %} {{ y }}<br><br> {% endfor %} </th> </tr> {% endfor %} </table><file_sep>/d_jango all examples/Django 7 to 9 AM/Project22/app22/migrations/0002_savingsaccountmodel_photo.py # Generated by Django 2.2.4 on 2019-10-25 04:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app22', '0001_initial'), ] operations = [ migrations.AddField( model_name='savingsaccountmodel', name='photo', field=models.ImageField(default=False, upload_to='acc_images/'), ), ] <file_sep>/d_jango all examples/Django 7 to 9 AM/Project32/app32/migrations/0001_initial.py # Generated by Django 2.2.4 on 2019-11-07 09:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='PersonModel', fields=[ ('aadhar', models.IntegerField(primary_key=True, serialize=False)), ('pname', models.CharField(max_length=100)), ('contact', models.IntegerField()), ('address', models.TextField()), ], ), migrations.CreateModel( name='PassportModel', fields=[ ('pno', models.IntegerField(primary_key=True, serialize=False)), ('p_details', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='app32.PersonModel')), ], ), ] <file_sep>/d_jango all examples/Django 7 to 9 AM/Project31/app31/models.py from django.db import models class BiryaniTypeModel(models.Model): bt_no = models.AutoField(primary_key=True) b_type = models.CharField(max_length=30) def __str__(self): return self.b_type class BiryaniModel(models.Model): b_no = models.AutoField(primary_key=True) b_name = models.CharField(max_length=30) b_type = models.ForeignKey(BiryaniTypeModel,on_delete=models.CASCADE) b_price = models.FloatField() <file_sep>/d_jango all examples/Django 7 to 9 AM/Project31/app31/views.py from django.shortcuts import render,redirect from .models import BiryaniTypeModel,BiryaniModel from .forms import BiryaniTypeForm,BiryaniForm from django.contrib import messages def addBT(request): return render(request,"addbt.html",{"form":BiryaniTypeForm()}) def saveBT(request): b_type = request.POST.get("b_type") BiryaniTypeModel(b_type = b_type).save() messages.success(request,"Biryani Type is Saved") return redirect('main') def addB(request): return render(request,"addb.html",{"form":BiryaniForm()}) def saveB(request): name= request.POST.get("b_name") type= request.POST.get("b_type") price= request.POST.get("b_price") BiryaniModel(b_name=name,b_type_id=type,b_price=price).save() messages.success(request, name+" -- Biryani is Saved") return redirect('main') def showBT(request): return render(request,"showbt.html",{"data":BiryaniTypeModel.objects.all()}) def showB(request): return render(request,"showb.html",{"data":BiryaniModel.objects.all()})<file_sep>/d_jango all examples/Django 7 to 9 AM/Project30/app30/models.py from django.db import models class Publisher(models.Model): pid = models.AutoField(primary_key=True) name = models.CharField(max_length=30,unique=True) def __str__(self): return self.name class Article(models.Model): aid = models.AutoField(primary_key=True) name = models.CharField(max_length=30) publisher_name = models.ManyToManyField(Publisher) <file_sep>/d_jango all examples/Django 7 to 9 AM/Project32/Project32/urls.py """Project32 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.views.generic import TemplateView from app32 import views urlpatterns = [ path('admin/', admin.site.urls), path('',TemplateView.as_view(template_name="index.html"),name="main"), path('addpe/',views.addPE,name="addpe"), path('addpa/',views.addPA,name="addpa"), path('savepe/',views.savePE,name="savepe"), path('savepa/',views.savePA,name="savepa"), path('viewpe/',views.viewPE,name="viewpe"), path('viewpa/',views.viewPA,name="viewpa"), ] <file_sep>/d_jango all examples/Django 7 to 9 AM/Project31/app31/forms.py from django import forms from .models import BiryaniTypeModel,BiryaniModel class BiryaniTypeForm(forms.ModelForm): class Meta: model = BiryaniTypeModel fields = "__all__" class BiryaniForm(forms.ModelForm): class Meta: model = BiryaniModel fields = "__all__"<file_sep>/d_jango all examples/Django 7 to 9 AM/Project32/app32/forms.py from django import forms from .models import PersonModel,PassportModel class PersonForm(forms.ModelForm): class Meta: model = PersonModel fields = "__all__" class PassportForm(forms.ModelForm): class Meta: model = PassportModel fields = "__all__" <file_sep>/d_jango all examples/Django 7 to 9 AM/Project32/app32/views.py from django.shortcuts import render,redirect from .forms import PassportModel from .forms import PassportForm from .forms import PersonModel from .forms import PersonForm from django.contrib import messages # Create your views here. def addPE(request): return render(request,"addpe.html",{"form":PersonForm()}) def savePE(request): ano = request.POST.get("aadhar") name = request.POST.get("pname") cn = request.POST.get("contact") address = request.POST.get("address") PersonModel(aadhar=ano,pname=name,contact=cn,address=address).save() messages.success(request,"Person Details are Saved") return redirect('main') def viewPE(request): return render(request,"viewpe.html",{"data":PersonModel.objects.all()}) def addPA(request): return render(request, "addpa.html", {"form": PassportForm()}) def savePA(request): no = request.POST.get("pno") details = request.POST.get("p_details") PassportModel(pno=no,p_details_id=details).save() messages.success(request, "Passport Details are Saved") return redirect('main') def viewPA(request): return render(request, "viewpa.html", {"data":PassportModel.objects.all()}) <file_sep>/d_jango all examples/Django 7 to 9 AM/Project23/app23/migrations/0001_initial.py # Generated by Django 2.2.4 on 2019-10-26 04:34 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='FilesModel', fields=[ ('number', models.IntegerField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=100)), ('file_path', models.FileField(upload_to='my_documents/')), ], ), ] <file_sep>/d_jango all examples/Django 7 to 9 AM/Project25/app25/views.py from django.contrib import messages from django.shortcuts import render,redirect from .models import LoginDetails def showIndex(request): try: value = request.session["user"] return render(request,"welcome.html",{'data':value}) except KeyError: return render(request,"index.html") def logincheck(request): uname = request.POST["uname"] upass = request.POST["upass"] print(uname,upass) try: res = LoginDetails.objects.get(username=uname,password=<PASSWORD>) except LoginDetails.DoesNotExist: #return render(request,"index.html",{"error":"Invalid User"}) messages.error(request,"Sorry.. Invalid User") return redirect("main") else: # Writing uname to session request.session["user"] = uname #request.session.set_expiry(0) request.session.set_expiry(60) return render(request,"welcome.html",{"data":uname}) #**** def open_employee(request): # reading uname from seesion try: value = request.session["user"] except KeyError: return showIndex(request) else: return render(request,"employee.html",{"data":value}) def open_faculty(request): return render(request,"faculty.html") def open_student(request): return render(request,"student.html") def logout(request): # deleting uname from session del request.session["user"] return render(request,"index.html")
126619b0aa4410955cb4ef665cd1954edad82106
[ "Python", "HTML" ]
26
Python
anandgohil/all_django_program
576bd7cd23bd310d265644012b86d602ecfd822a
1c69011f0ca0c27f4d7594b6e69e9bbc1d9ab04a
refs/heads/main
<repo_name>deborasilva12/AtividadePratica02<file_sep>/app/clientCrypt.py import rpyc from constRPYC import * class Client: conn_directory = rpyc.connect(DIR_SERVER, DIR_PORT) (address, port) = conn_directory.root.exposed_lookup("ServerCrypt") if address == 'error': print(port) else: print(f"Conexao: {address}:{port}") conn_server = rpyc.connect(address, port) operation = str(input("1)Criptografar \n 2)Descriptografar \n 3) Cancelar\n")) if operation == "1" or operation == "2": if operation == "1": text = input("Mensagem: ") (encText, pub_key) = conn_server.root.exposed_encrypt(text) print(f"Criptografada: {encText}\n Public Key {pub_key}") file = open("enc_message.txt", 'w') file.write(encText) file.close() else: file = open("enc_message.txt", 'r') enc_message = file.read() file.close() print(f"Mensagem criptografada: {enc_message}") pub_key = input("Public Key: ") text = conn_server.root.exposed_decrypt(enc_message, pub_key) print(f"Mensagem: {text}") else: print("Tchauzinho!") <file_sep>/README.md # AtividadePratica02 <h3>Requisitos</h1> É necessário ter instalado a versão mais recente do python, no caso <a href="https://www.python.org/downloads/release/python-385/">python 3.8.5 </a> <h3>Como rodar</h3> 1) Instale o pip3 e o virtualenv do python 3 <code> sudo apt update </code> <p><code> sudo apt install python3-pip python3-virtualenv -y </code> <p><h5> Talvez seja necessário verificar se o virtualenv está instalado </p></h5> <code> sudo apt install virtualenv </code> <p> 2) Clone o repositório </p> <code> git clone https://github.com/deborasilva12/AtividadePratica02.git </code> <p> <file_sep>/app/constRPYC.py DIR_SERVER = 'localhost' DIR_PORT = 20201<file_sep>/app/serverCrypt.py from random import randint import rpyc from socket import gethostbyname,gethostname from constRPYC import * from rpyc.utils.server import ThreadedServer class ServerCrypt(rpyc.Service): priv_key = 1 def __encrypt(self, mensagem, pub_key): value = '' for item in mensagem: value = value + chr((ord(item) + pub_key + self.priv_key)) return value def __decrypt(self, mensagem, pub_key): value = '' for item in mensagem: value = value + chr((ord(item) - int(pub_key) - self.priv_key)) return value def exposed_encrypt(self, text): pub_key = randint(1, 25) enc_message = self.__encrypt(text, pub_key) return (enc_message, pub_key) def exposed_decrypt(self, message, pub_key): return self.__decrypt(message, pub_key) if __name__ == "__main__": server = ThreadedServer(ServerCrypt, port = 20203) conn = rpyc.connect(host=DIR_SERVER, port=DIR_PORT) my_address = gethostbyname(gethostname()) (reg, token) = conn.root.exposed_register("ServerCrypt", my_address, 20203) if reg: print(f"Primeira conexao. Token: {token}") server.start() else: print("Reiniciando") option = str(input("1)Atualizar servico.\n 2)Remover servico.\n 3)Cancelar servico\n")) if option == "1" or option == "2": if option == "1" : token = str(input("Token: ")) update = conn.root.exposed_update_register("ServerCrypt", my_address, 20203, token) if update: print("Atualizado! Inicializando ...") server.start() else: print("Token nao permitido") else: token = str(input("Token: ")) remove = conn.root.exposed_unregister("ServerCrypt", token) if remove: print("Servico removido") else: print("Token nao permitido") else: print("Tchauzinho!")<file_sep>/app/serverDirectory.py from random import randint import rpyc from constRPYC import * from rpyc.utils.server import ThreadedServer servers = {} class Directory(rpyc.Service): def exposed_register(self, server_name, ip_adress, port_number): addr = (ip_adress,port_number) if server_name not in servers: token = str(hash(server_name)+hash(randint(0,50))) servers [server_name] = {'ip': addr , 'token': token} print(f"Full {servers}") print(f"[{server_name}] {ip_adress}:{port_number}\n[{server_name}] {token}\n\n") success = (True, token) return success else: failure = (False, "null") return failure def exposed_update_register(self, server_name, ip_adress, port_number, token): if servers[server_name]['token'] == token: addr = (ip_adress,port_number) servers [server_name]['ip'] = addr print(f"Updated {server_name} = {servers[server_name]}") return True else: return False def exposed_unregister(self, server_name, token): if servers[server_name]['token'] == token: servers.pop(server_name) print(f"Removed {server_name}") print(f"Full: {servers}") return True else: return False def exposed_lookup(self, server_name): if server_name in servers: return servers[server_name]['ip'] else: notreg = ("error", "Service not registered") return notreg if __name__ == "__main__": print (f"Server Started on {DIR_PORT}. Waiting Requests") server_dir = ThreadedServer(Directory, port = DIR_PORT, protocol_config={"allow_public_attrs": True} ) server_dir.start()<file_sep>/app/clientMath.py import rpyc from constRPYC import * class Client: conn_directory = rpyc.connect(DIR_SERVER, DIR_PORT) (address, port) = conn_directory.root.exposed_lookup("ServerCalculadora") if address == 'error': print(port) else: print(f"Conexao: {address}:{port}") numA = int(input("Primeiro numero: ")) numB = int(input("Segundo numero: ")) conn_server = rpyc.connect(address, port) soma = conn_server.root.exposed_sum(numA, numB) sub = conn_server.root.exposed_sub(numA, numB) multi = conn_server.root.exposed_multi(numA, numB) divi =conn_server.root.exposed_divi(numA, numB) print(f"Soma: {soma}") print(f"Subtracao: {sub}") print(f"Multiplicacao: {multi}") print(f"Divisao: {divi}")
b4ade7ff05ad6b98e406deacb864598b6bfb2666
[ "Markdown", "Python" ]
6
Python
deborasilva12/AtividadePratica02
c2537e344bf8bc7dd7d05dbcd8763ed39e00c9ec
6b5522831dea2c3853da70c24beef28b4c09519d
refs/heads/master
<file_sep>package helper; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; public class TemplateTransformer { private final StringReader record; public TemplateTransformer(String recordToTransform) { record = new StringReader(recordToTransform); } public XSLTDataObject transformIntoDataObject(Transformer transformer) { StringWriter transformedRecord = getTransformation(transformer); XSLTDataObject dataObject = new XSLTDataObject(); dataObject.record = transformedRecord.toString(); dataObject.additions = new HashMap<>(); return dataObject; } public String transform(Transformer transformer) { StringWriter transformedRecord = getTransformation(transformer); return transformedRecord.toString(); } StringWriter getTransformation(Transformer transformer) { Source source = new StreamSource(record); StringWriter transformedRecord = new StringWriter(); StreamResult target = new StreamResult(transformedRecord); try { transformer.transform(source, target); } catch (TransformerException tex) { throw new RuntimeException(tex); } return transformedRecord; } }
339bc16fd8c94017f00c5a951ce4ead8282bc6f7
[ "Java" ]
1
Java
guenterh/aggregateGVI
b4b9d04704b73361dded5fc79ffa9f83aa280379
4655a82e924b35f793447f2bc11770981bed911d
refs/heads/master
<repo_name>Shermancipation/surveyApp<file_sep>/public/src/app/create/create.component.ts import { Component, OnInit } from '@angular/core'; import { Poll } from "../poll"; import { HttpService } from "../http.service"; import { Router } from "@angular/router"; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'] }) export class CreateComponent implements OnInit { poll = new Poll() constructor(private _httpService: HttpService, private router: Router) { } ngOnInit() { } newPoll() { this._httpService.newPoll(this.poll) .then((poll) => { console.log("Then promise on newPoll method firing..."); this.router.navigate(['/dashboard']); }) .catch((err) => {console.log("Errors during newPoll method: " + err)}) } } <file_sep>/server/config/routes.js var mongoose = require("mongoose"); const path = require("path"); polls = require("./../controllers/polls.js"); // Routes // Root Request module.exports = function(app){ app.get("/allPolls", function(req, res){ console.log("Inside the express routing all polls method...") polls.getAllPolls(req, res); }) app.post("/setSession", function(req, res){ console.log("Inside the express routing set session method..."); req.session.currentUserName = req.body.username; console.log(req.session.currentUserName); res.json(req.session.currentUserName); }) app.get("/getSession", function(req, res){ console.log("Inside the get session express routing method..."); res.json(req.session.currentUserName); }) app.get("/destroySession", function(req, res){ console.log("Inside the destroy session express routing method..."); req.session.destroy(); res.json(true); }) app.post("/newPoll", function(req,res){ console.log("Inside the new poll express route: " + req.body); polls.addPoll(req,res); }) app.post("/deletePoll", function(req,res){ console.log("Inside the delete poll express route: " + req.body.pollId) polls.deletePoll(req,res); }) app.post("/findCurrentPoll", function(req,res){ console.log("Inside the find current poll express route: " + req.body.currentPollId) polls.getOnePoll(req,res); }) app.post("/updateCurrentPoll", function(req,res){ console.log("Inside the updated current poll express route...") polls.updateCurrentPoll(req,res); }) app.all("*", (req,res,next)=>{ res.sendfile(path.resolve("./public/dist/index.html")) }); } <file_sep>/public/src/app/landing/landing.component.ts import { Component, OnInit } from '@angular/core'; import { User } from "../user"; import { HttpService } from "../http.service"; import { Router } from "@angular/router"; @Component({ selector: 'app-landing', templateUrl: './landing.component.html', styleUrls: ['./landing.component.css'] }) export class LandingComponent implements OnInit { user = new User(); constructor(private _httpService: HttpService, private router: Router) { } ngOnInit() { this.destroySession(); } onSubmit() { this._httpService.setSession(this.user) .then((data) => { console.log("Current session username is " + data); this.router.navigate(['/dashboard']) }) .catch((err) => {console.log("Errors during set session: " + err)}) } destroySession() { this._httpService.destroySession() .then((data) => {console.log("Session successfully destroyed...")}) .catch((err) => {console.log("Errors during session destroy" + err)}) } } <file_sep>/public/src/app/poll/poll.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from "@angular/router"; import { HttpService } from "../http.service"; @Component({ selector: 'app-poll', templateUrl: './poll.component.html', styleUrls: ['./poll.component.css'] }) export class PollComponent implements OnInit { currentPollId; currentPoll; constructor(private _route: ActivatedRoute, private _httpService: HttpService, private router: Router) { this._route.params.subscribe((param)=>{ console.log("Activated Route firing, current Poll ID is: ", param); this.currentPollId = param; }) } ngOnInit() { this.findCurrentPoll(this.currentPollId); } findCurrentPoll(currentPollId) { this._httpService.findCurrentPoll(currentPollId) .then((poll) => { this.currentPoll = poll; }) .catch((err) => {console.log(err)}) } voteUp(pollId, idx) { this._httpService.updateCurrentPoll(pollId, idx) .then((poll) => { console.log("Updated current poll successfully!"); this.findCurrentPoll(this.currentPollId); }) .catch((err) => {console.log("Errors during update current poll method: " + err)}) } } <file_sep>/public/src/app/http.service.ts import { Injectable } from '@angular/core'; import { Http } from "@angular/http"; import "rxjs"; @Injectable() export class HttpService { constructor(private _http: Http) { } setSession(user) { return this._http.post("/setSession", user).map(data => data.json()).toPromise(); } getSession() { return this._http.get("/getSession").map(data => data.json()).toPromise(); } destroySession() { return this._http.get("/destroySession").map(data => data.json()).toPromise(); } newPoll(poll) { return this._http.post("/newPoll", poll).map(data => data.json()).toPromise(); } getAllPolls() { return this._http.get("/allPolls").map(data => data.json()).toPromise(); } deletePoll(pollId) { return this._http.post("/deletePoll", {pollId: pollId}).map(data => data.json()).toPromise(); } findCurrentPoll(currentPollId) { return this._http.post("/findCurrentPoll", {currentPollId: currentPollId.id}).map(data => data.json()).toPromise(); } updateCurrentPoll(pollId, idx) { return this._http.post("/updateCurrentPoll", {pollId: pollId, idx: idx}).map(data => data.json()).toPromise(); } } <file_sep>/public/src/app/dashboard/dashboard.component.ts import { Component, OnInit } from '@angular/core'; import { HttpService } from "../http.service"; import { Router } from "@angular/router"; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit { allPolls = []; currentUserName = ""; search_text; constructor(private _httpService: HttpService, private router: Router) { this.search_text = ""; } ngOnInit() { this.findAllPolls(); this.getSession(); } findAllPolls() { this._httpService.getAllPolls() .then((polls) => {this.allPolls = polls}) .catch((err) => {console.log(err)}) } getSession() { this._httpService.getSession() .then((data) => {this.currentUserName = data}) .catch((err) => {console.log("Errors during get session method: " + err)}) } deletePoll(pollId) { this._httpService.deletePoll(pollId) .then((data) => { console.log("Poll Id " + pollId + "successfully deleted!"); this.findAllPolls(); }) .catch((err) => {console.log("Errors during delete poll method: " + err)}) } } <file_sep>/server/models/poll.js var mongoose = require("mongoose"); var Schema = mongoose.Schema; var pollSchema = new mongoose.Schema({ creator: { type: String, required: true }, question:{ type: String, required: true, minlength:8 }, option1:{ type: String, required: true, minlength: 3, }, option1votes:{ type: Number, }, option2:{ type: String, required: true, minlength: 3, }, option2votes:{ type: Number, }, option3:{ type: String, required: true, minlength: 3, }, option3votes:{ type: Number, }, option4:{ type: String, required: true, minlength: 3, }, option4votes:{ type: Number, }, }, {timestamps:true}); var Poll = mongoose.model("Poll", pollSchema);<file_sep>/server/controllers/polls.js var mongoose = require("mongoose"); var Schema = mongoose.Schema; var Poll = mongoose.model("Poll"); module.exports = { addPoll: function(req, res){ var poll = new Poll({ creator: req.session.currentUserName, question: req.body.question, option1: req.body.option1, option1votes: 0, option2: req.body.option2, option2votes: 0, option3: req.body.option3, option3votes: 0, option4: req.body.option4, option4votes: 0, }); poll.save().then((poll)=>{ console.log("Successfully saved: " + poll); res.json(poll); }).catch((err)=>{ res.status(500); console.log("Inside the .catch, errors found: " + err); res.json(err); }) }, getAllPolls: function(req, res){ Poll.find() .exec((err, allpolls)=>{ if(err) { console.log("Error during Get All Polls express controller method..." + err); } else { console.log("All polls successfully retrieved!"); res.json(allpolls) }}) }, getOnePoll: function(req, res){ Poll.findOne({_id: req.body.currentPollId}) .exec((err, poll)=>{ if(err) { console.log("Error during Get One Poll express controller method..." + err); } else { console.log("Current Poll successfully retrieved!" + poll); res.json(poll) }}) }, deletePoll: function(req, res){ console.log("Inside delete poll method in Express Controller", req.body.pollId); Poll.remove({_id: req.body.pollId}) .then(poll => { console.log(req.body.pollId + " succesfully deleted!"); res.json(true); }) .catch(err => {console.log("Errors during delete poll method " + err)}) }, updateCurrentPoll: function(req, res){ console.log("Inside update current poll method in Express Controller"); Poll.findOne({_id: req.body.pollId}) .then((poll)=> { if(req.body.idx == 1) { poll.option1votes += 1; } else if(req.body.idx == 2) { poll.option2votes += 1; } else if(req.body.idx == 3) { poll.option3votes += 1; } else if(req.body.idx == 4) { poll.option4votes += 1; } poll.save() }) .then(() =>{res.json(true)}) .catch((err) => {"Errors during update current poll method " + err}) }, } <file_sep>/public/src/app/filter.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implements PipeTransform { transform(allPolls: any, search: any): any { if(!allPolls) { return null; } let result = []; for(let poll of allPolls) { if(poll.creator.toLowerCase().includes(search.toLowerCase()) || poll.question.toLowerCase().includes(search.toLowerCase())) { result.push(poll); } } return result; } }
2839f6a5094c35989c07378acff6c23ccf87d6b4
[ "JavaScript", "TypeScript" ]
9
TypeScript
Shermancipation/surveyApp
512b570d77cceaac459c9dc8b17c9f4a6ebfe079
d7129349eb2f9ce912171b62e15bc017fa532f62
refs/heads/master
<repo_name>chaohuxiayun/horizon<file_sep>/src/main/resources/thread/thread.properties thread.corePoolSize=5 thread.maxPoolSize=100 thread.queueCapacity=1000 thread.keepAliveSeconds=60 thread.maxOpenPreparedStatements=20 thread.removebandoned=true thread.removeAbandonedTimeout=1800 thread.logAbandoned=true<file_sep>/src/main/webapp/static/js/page.js /** * 跳转到某一页 */ function pageTo(index) { if ($("#currentPage").val() != index) { $("#currentPage").val(index); $("#page-form").submit(); } } /** * 上一页 */ function previousPage() { var currentPage = $("#currentPage").val(); if (currentPage > 1) { $("#currentPage").val(--currentPage); $("#page-form").submit(); } } /** * 下一页 */ function nextPage() { var currentPage = $("#currentPage").val(); if (currentPage < $("#totalPage").val()) { $("#currentPage").val(++currentPage); $("#page-form").submit(); } } /** * 设置每页显示条数,设置完成后需要将当前页设置成第一页 */ function setPageSize(size) { var pageSize = $("#pageSize").val(); if (pageSize != size) { $("#pageSize").val(size); $("#currentPage").val(1); $("#page-form").submit(); } } /** * 全选,或者全不选 */ function allCheck(obj) { $('[name=selectList]:checkbox').prop('checked', obj.checked); } //扩展Date的format方法 Date.prototype.format = function (format) { var o = { "M+": this.getMonth() + 1, "d+": this.getDate(), "h+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "q+": Math.floor((this.getMonth() + 3) / 3), "S": this.getMilliseconds() }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; }; /** *转换日期对象为日期字符串 * @param date 日期对象 * @param isFull 是否为完整的日期数据, * 为true时, 格式如"2000-03-05 01:05:04" * 为false时, 格式如 "2000-03-05" * @return 符合要求的日期字符串 */ function getSmpFormatDate(date, isFull) { var pattern = ""; if (isFull == true || isFull == undefined) { pattern = "yyyy-MM-dd hh:mm:ss"; } else { pattern = "yyyy-MM-dd"; } return getFormatDate(date, pattern); } /** *转换当前日期对象为日期字符串 * @param date 日期对象 * @param isFull 是否为完整的日期数据, * 为true时, 格式如"2000-03-05 01:05:04" * 为false时, 格式如 "2000-03-05" * @return 符合要求的日期字符串 */ function getSmpFormatNowDate(isFull) { return getSmpFormatDate(new Date(), isFull); } /** *转换long值为日期字符串 * @param l long值 * @param isFull 是否为完整的日期数据, * 为true时, 格式如"2000-03-05 01:05:04" * 为false时, 格式如 "2000-03-05" * @return 符合要求的日期字符串 */ function getSmpFormatDateByLong(l, isFull) { return getSmpFormatDate(new Date(l), isFull); } /** *转换long值为日期字符串 * @param l long值 * @param pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss * @return 符合要求的日期字符串 */ function getFormatDateByLong(l, pattern) { return getFormatDate(new Date(l), pattern); } /** *转换日期对象为日期字符串 * @param l long值 * @param pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss * @return 符合要求的日期字符串 */ function getFormatDate(date, pattern) { if (date == undefined) { date = new Date(); } if (pattern == undefined) { pattern = "yyyy-MM-dd hh:mm:ss"; } return date.format(pattern); } /** * 表单验证 * @formId : 需要验证表单的id */ function verificationForm(formId) { var inputs = $("#" + formId + " .isEmpty"); for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; var value = input.value; if (value == null || value == '') { try { var tagName = input.attributes['tag-name'].nodeValue; alert("请填写" + tagName); input.focus(); return false; } catch (e) { alert("请填写完整!"); return false; } } } return true; } /** * 正整数 */ function judgePlusInteger(formId) { var inputs = $("#" + formId + " .isPlusInteger"); var r = /^\+?[1-9][0-9]*$/; for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; var value = input.value; if (!r.test(value)) { try { var tagName = input.attributes['tag-name'].nodeValue; alert(tagName + "必须是正整数!"); input.focus(); return false; } catch (e) { alert("请注意,某些值只能填写正整数!"); return false; } } } return true; } function judgePlusDouble(formId) { var inputs = $("#" + formId + " .isPlusDouble"); var r = /^\d+(\.\d+)?$/; for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; var value = input.value; if (!r.test(value)) { try { var tagName = input.attributes['tag-name'].nodeValue; alert(tagName + "请填写规范!"); input.focus(); return false; } catch (e) { alert("请注意,某些值只能填写正整数!"); return false; } } } return true; } /** * 下拉框的加载 * @param selectId : 下拉框的id * @param url : 访问的url * @param postData : 数据 * @param valueName : value对应的字段 * @param textName : text对应的字段 * @param selectedId : 需要选中的id * @param firstOption : 第一个option要显示的内容 */ function selectLoad(selectId, url, postData, valueName, textName,selectedId,firstOption) { var optionShow = ''; if(!isEmpty(firstOption)) { optionShow = firstOption; } $.ajax({ type: 'POST', contentType: "application/json; charset=utf-8", url: url, dataType: 'json', data: postData, success: function (data) { $("#" + selectId).empty(); $("#" + selectId).append("<option value=''>"+optionShow+"</option>"); for (var i = 0; i < data.length; i++) { var obj = data[i]; var str = "<option value='" + obj[valueName] + "'>" + obj[textName] + "</option>"; $("#" + selectId).append(str); } if(selectedId != 0){ $("#" + selectId).val(selectedId); } }, error: function (e) { console.log(e); console.log("获取下拉框数据失败!"); } }); } /** * 初始化时间选择器 * @param id * @param format */ function timePicker(id, format) { $("#" + id).jeDate({ format: format, isTime: true, minDate: new Date() }); } function isEmpty(obj){ if(obj == null || typeof(obj) == 'undefined' || obj == ''){ return true; } return false; } // 去除bootstrap -dataTable中的警告信息,,该文件理论上必须在dataTable之后引用 try{ $.fn.dataTable.ext.errMode = 'none'; }catch (e) { console.log(e); } function delObject(confirmFunction,title){ var t = "是否确定删除?"; if(!isEmpty(title)) { t = title; } jeBox.alert(t, { icon: 4, closeBtn: false, maskClose: false, button: [ { name: '确定', callback: function (index) { jeBox.close(index); confirmFunction(); } },{ name:"取消", callback: function (index) { jeBox.close(index); } } ] }); } function alertMessage(data,loading){ var icon = 2; if(data.code != '1'){ icon = 6; } jeBox.alert(data.message, { icon: icon, closeBtn: false, maskClose: false, button: [ { name: '确定', callback: function (index) { jeBox.close(index); if(typeof (loading) == 'function') { loading(); } } } ] }); } function alertSimple(message,i){ var icon = 1; if(!isEmpty(i)){ icon = i; } jeBox.alert(message, { icon: icon, closeBtn: false, maskClose: false, offset: ["300px", "auto"], // 坐标轴,坐标写死,避免页面过长时,提示框在当前页面之外 button: [ { name: '确定', callback: function (index) { jeBox.close(index); } } ] }); } function alertSimple_swal(message){ swal({ title: message, showCancelButton: false, confirmButtonColor: '#DD6B55', confirmButtonText: '确定!', closeOnConfirm: true, closeOnCancel: true } ); } function alertMessage_swal(message,loading,showCancelButton){ swal({ title: message, showCancelButton: showCancelButton, confirmButtonColor: '#DD6B55', confirmButtonText: '确定!', cancelButtonText: '取消!', closeOnConfirm: false, closeOnCancel: true }, function (isConfirm) { if(isConfirm && typeof (loading) == 'function') { loading(); swal.close(); } }); } function delObject_swal(confirmFunction, title) { var t = "是否确定删除?"; if (!isEmpty(title)) { t = title; } swal({ title: t, showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: '确定!', cancelButtonText: '取消!', closeOnConfirm: false, closeOnCancel: true },function (isConfirm) { if (isConfirm) { if (typeof (confirmFunction) == 'function') { confirmFunction(); } } } ) } <file_sep>/src/main/java/pers/xy/horizon/base/dto/PermissionDto.java package pers.xy.horizon.base.dto; /** * @Description * @Date 2019/6/12 * @Created by xiayun */ public class PermissionDto { private Long id; private String code; private String cont; private String icon; private Integer level; private String name; private String parentCode; private Long parentId; private String type; private String url; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getCont() { return cont; } public void setCont(String cont) { this.cont = cont; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getParentCode() { return parentCode; } public void setParentCode(String parentCode) { this.parentCode = parentCode; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } <file_sep>/src/main/webapp/static/js/fileInput.js //初始化文件使用器 //需要在jsp中, // head 引入 // <link href="<%=path%>/assets/css/fileinput.css" rel="stylesheet" type="text/css"> //jsp 中 指定位置添加 <input id="importExcelFile" type="file" data-preview-file-type="xlsx"> //在底部script中引入 // <script src="<%=path%>/assets/js/fileinput.js"></script> // <script src="<%=path%>/assets/js/zh.js"></script> // <script src="<%=path%>/js/FileInput.js"></script> var uploadExtraData=""; var MFileInput={ init:function (fileInputId, uploadUrl,returnFunction) { var control = $('#' + fileInputId); control.fileinput({ language: 'zh', //设置语言 uploadUrl: uploadUrl, //上传的地址 (该方法需返回JSON字符串) allowedFileExtensions: ['png','jpg','jpeg','PNG','JPEG','JPG'],//接收的文件后缀 uploadAsync:true,//是否异步上传 showPreview:true, showUpload: true, //是否显示上传按钮 showCaption: true,//是否显示标题 maxFileCount: 1,//最大上传数量 allowedPreviewTypes: ['png','jpg','jpeg','PNG','JPEG','JPG'], dropZoneEnabled: false, textEncoding:'UTF-8', dropZoneTitleClass:'file-drop-zone-title', autoReplace:true, browseClass: "btn btn-info" ,//按钮样式 //previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", uploadExtraData: function(previewId, index){ return uploadExtraData; } }).on('filebatchselected', function (event, data, id, index) { $(this).fileinput("upload"); }).on("fileuploaded", returnFunction) } }; //设置额外参数 function setUploadExtraData(extraData) { this.uploadExtraData=extraData; }<file_sep>/src/main/resources/jdbc.properties #------- ##\u6570\u636E\u5E93\u7684\u8FDE\u63A5\u914D\u7F6E db.driver=com.mysql.jdbc.Driver #db.driver=oracle.jdbc.driver.OracleDriver db.url=jdbc\:mysql\://localhost\:3306/demo?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai #db.url=jdbc:oracle:thin:@localhost:1521:test db.username=root db.password=<PASSWORD> druid.maxActive=30 druid.initialSize=1 druid.maxWait=60000 druid.minIdle=10 druid.maxIdle=15 druid.timeBetweenEvictionRunsMillis=60000 druid.minEvictableIdleTimeMillis=300000 druid.validationQuery=SELECT 'x' druid.testWhileIdle=true druid.testOnBorrow=false druid.testOnReturn=false druid.maxOpenPreparedStatements=20 druid.removeAbandoned=true druid.removeAbandonedTimeout=1800 druid.logAbandoned=true hibernate.use_second_level_cache=false hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect #hibernate.dialect=org.hibernate.dialect.Oracle10gDialect hibernate.show_sql=false hibernate.format_sql=false hibernate.hbm2ddl.auto=update hibernate.connection.autocommit=false hibernate.cache.provider_configuration_file_resource_path=ehcache.xml hibernate.cache.use_second_level_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory <file_sep>/src/main/java/pers/xy/horizon/base/entity/User.java package pers.xy.horizon.base.entity; public class User extends BaseEntity { private Long id; private Long addTime; private Long deleteTime; private String isDelete; private Long updateTime; private String loginName; private String password; private String userName; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAddTime() { return addTime; } public void setAddTime(Long addTime) { this.addTime = addTime; } public Long getDeleteTime() { return deleteTime; } public void setDeleteTime(Long deleteTime) { this.deleteTime = deleteTime; } public String getIsDelete() { return isDelete; } public void setIsDelete(String isDelete) { this.isDelete = isDelete == null ? null : isDelete.trim(); } public Long getUpdateTime() { return updateTime; } public void setUpdateTime(Long updateTime) { this.updateTime = updateTime; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName == null ? null : loginName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } }<file_sep>/src/main/java/pers/xy/horizon/base/service/PermissionService.java package pers.xy.horizon.base.service; import pers.xy.horizon.base.dto.PermissionDto; import java.util.List; /** * @Description * @Date 2019/6/12 * @Created by xiayun */ public interface PermissionService { List<PermissionDto> findByUserId(Long userId); } <file_sep>/src/main/java/pers/xy/horizon/base/dao/PermissionMapper.java package pers.xy.horizon.base.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import pers.xy.horizon.base.dto.PermissionDto; import pers.xy.horizon.base.entity.Permission; import pers.xy.horizon.base.entity.PermissionExample; public interface PermissionMapper { long countByExample(PermissionExample example); int deleteByExample(PermissionExample example); int insert(Permission record); int insertSelective(Permission record); List<Permission> selectByExample(PermissionExample example); int updateByExampleSelective(@Param("record") Permission record, @Param("example") PermissionExample example); int updateByExample(@Param("record") Permission record, @Param("example") PermissionExample example); List<PermissionDto> findByUserId(Long userId); List<PermissionDto> findByRoleIds(List roleIds); }<file_sep>/src/main/webapp/static/js/dataTable.js var _keywords ; function InitTable(dataTableId,url,columns) { $("#" + dataTableId).DataTable({ "sScrollX": "100%", //表格的宽度 "sScrollXInner": "100%", //表格的内容宽度 "bScrollCollapse": true, //当显示的数据不足以支撑表格的默认的高度时,依然显示纵向的滚动条。(默认是false) "searching": false, "bLengthChange": true, "bFilter": false, "bSort": false, "bInfo": true, "bPaginate":true, "iDisplayLength": 10, "aLengthMenu": [[15,25,50],["15","25" ,"50"]], "PaginationType": "full_numbers", "deferRender": true, "bJQueryUI": true, "aoColumns": columns, //每一列具体显示什么 "destroy": true, "bProcessing": true, // 是否显示取数据时的那个等待提示 "bServerSide": true,//这个用来指明是通过服务端来取数据 "sAjaxSource": url,//这个是请求的地址,Rest API or JSP的action "fnServerData": retrieveData, // 获取数据的处理函数 "oLanguage": { "sProcessing": "正在加载中......", "sLengthMenu": "每页显示 _MENU_ 条记录", "sZeroRecords": "对不起,查询不到相关数据!", "sEmptyTable": "表中无数据存在!", "sInfo": "当前显示 _START_ 到 _END_ 条,共 _TOTAL_ 条记录", "sInfoFiltered": "系统中共为 _MAX_ 条记录", "sSearch": "搜索:", "searchPlaceholder": "关键字搜索", "oPaginate": { "sFirst": "首页", "sPrevious": "上一页", "sNext": "下一页", "sLast": "末页" }, "oAria": { "sSortAscending": ": 以升序排列此列", "sSortDescending": ": 以降序排列此列" } } }); } function retrieveData(postUrl, pageData, fnCallback) { var postData = { "attrs": pageData, "entity": _keywords }; $.ajax({ contentType: "application/json", type: 'POST', url: postUrl,//这个就是请求地址对应sAjaxSource data: JSON.stringify(postData),//这个是把datatable的一些基本数据传给后台,比如起始位置,每页显示的行数 dataType: 'json', async: false,//是否为异步 success: function (result) { fnCallback(result);//把返回的数据传给这个方法就可以了,datatable会自动绑定数据的 }, error: function (data, type, err) { console.log(data); console.log("dataTable加载失败"); } }); } function InitNoSelectTable(dataTableId,url,columns) { $("#" + dataTableId).DataTable({ "sScrollX": "100%", //表格的宽度 "sScrollXInner": "100%", //表格的内容宽度 "bScrollCollapse": true, //当显示的数据不足以支撑表格的默认的高度时,依然显示纵向的滚动条。(默认是false) "searching": false, "bLengthChange": false, "bFilter": false, "bSort": false, "bInfo": true, "bPaginate":true, "iDisplayLength": 10, "aLengthMenu": [10,15,20], "PaginationType": "full_numbers", "deferRender": true, "bJQueryUI": true, "aoColumns": columns, //每一列具体显示什么 "destroy": true, "bProcessing": true, // 是否显示取数据时的那个等待提示 "bServerSide": true,//这个用来指明是通过服务端来取数据 "sAjaxSource": url,//这个是请求的地址,Rest API or JSP的action "fnServerData": retrieveData, // 获取数据的处理函数 "oLanguage": { "sProcessing": "正在加载中......", "sLengthMenu": "每页显示 _MENU_ 条记录", "sZeroRecords": "对不起,查询不到相关数据!", "sEmptyTable": "表中无数据存在!", "sInfo": "当前显示 _START_ 到 _END_ 条,共 _TOTAL_ 条记录", "sInfoFiltered": "系统中共为 _MAX_ 条记录", "sSearch": "搜索:", "searchPlaceholder": "关键字搜索", "oPaginate": { "sFirst": "首页", "sPrevious": "上一页", "sNext": "下一页", "sLast": "末页" }, "oAria": { "sSortAscending": ": 以升序排列此列", "sSortDescending": ": 以降序排列此列" } } }); } function InitSetPageTable(dataTableId,url,columns,length) { $("#" + dataTableId).DataTable({ "sScrollX": "100%", //表格的宽度 "sScrollXInner": "100%", //表格的内容宽度 "bScrollCollapse": true, //当显示的数据不足以支撑表格的默认的高度时,依然显示纵向的滚动条。(默认是false) "searching": false, "bLengthChange": false, "bFilter": false, "bSort": false, "bInfo": true, "bPaginate":true, "iDisplayLength": length, "aLengthMenu": [10,15,20], "PaginationType": "full_numbers", "deferRender": true, "bJQueryUI": true, "aoColumns": columns, //每一列具体显示什么 "destroy": true, "bProcessing": true, // 是否显示取数据时的那个等待提示 "bServerSide": true,//这个用来指明是通过服务端来取数据 "sAjaxSource": url,//这个是请求的地址,Rest API or JSP的action "fnServerData": retrieveData, // 获取数据的处理函数 "oLanguage": { "sProcessing": "正在加载中......", "sLengthMenu": "每页显示 _MENU_ 条记录", "sZeroRecords": "对不起,查询不到相关数据!", "sEmptyTable": "表中无数据存在!", "sInfo": "当前显示 _START_ 到 _END_ 条,共 _TOTAL_ 条记录", "sInfoFiltered": "系统中共为 _MAX_ 条记录", "sSearch": "搜索:", "searchPlaceholder": "关键字搜索", "oPaginate": { "sFirst": "首页", "sPrevious": "上一页", "sNext": "下一页", "sLast": "末页" }, "oAria": { "sSortAscending": ": 以升序排列此列", "sSortDescending": ": 以降序排列此列" } } }); } <file_sep>/src/main/java/pers/xy/horizon/base/service/RoleService.java package pers.xy.horizon.base.service; import pers.xy.horizon.base.entity.Role; /** * @Description * @Date 2019/5/8 * @Created by xiayun */ public interface RoleService { Role selectById(Long id); Role selectByCode(String code); int insert(Role role); int update(Role role); } <file_sep>/src/main/java/pers/xy/horizon/base/entity/Permission.java package pers.xy.horizon.base.entity; public class Permission { private Long id; private Long addTime; private Long deleteTime; private String isDelete; private Long updateTime; private String code; private String cont; private String icon; private Integer level; private String name; private String parentCode; private Long parentId; private String type; private String url; private Long createUser; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAddTime() { return addTime; } public void setAddTime(Long addTime) { this.addTime = addTime; } public Long getDeleteTime() { return deleteTime; } public void setDeleteTime(Long deleteTime) { this.deleteTime = deleteTime; } public String getIsDelete() { return isDelete; } public void setIsDelete(String isDelete) { this.isDelete = isDelete == null ? null : isDelete.trim(); } public Long getUpdateTime() { return updateTime; } public void setUpdateTime(Long updateTime) { this.updateTime = updateTime; } public String getCode() { return code; } public void setCode(String code) { this.code = code == null ? null : code.trim(); } public String getCont() { return cont; } public void setCont(String cont) { this.cont = cont == null ? null : cont.trim(); } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon == null ? null : icon.trim(); } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getParentCode() { return parentCode; } public void setParentCode(String parentCode) { this.parentCode = parentCode == null ? null : parentCode.trim(); } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getType() { return type; } public void setType(String type) { this.type = type == null ? null : type.trim(); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url == null ? null : url.trim(); } public Long getCreateUser() { return createUser; } public void setCreateUser(Long createUser) { this.createUser = createUser; } }<file_sep>/src/main/java/pers/xy/horizon/base/service/impl/UserRoleServiceImpl.java package pers.xy.horizon.base.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pers.xy.horizon.base.dao.RoleMapper; import pers.xy.horizon.base.dao.UserMapper; import pers.xy.horizon.base.dao.UserRoleMapper; import pers.xy.horizon.base.dto.UserRoleDto; import pers.xy.horizon.base.entity.UserRole; import pers.xy.horizon.base.entity.UserRoleExample; import pers.xy.horizon.base.service.RoleService; import pers.xy.horizon.base.service.UserRoleService; import pers.xy.horizon.base.service.UserService; import pers.xy.horizon.base.util.ListUtils; import java.util.List; /** * @Description * @Date 2019/6/8 * @Created by xiayun */ @Service public class UserRoleServiceImpl implements UserRoleService { @Autowired private UserRoleMapper userRoleMapper; @Autowired private UserService userService; @Autowired private RoleService roleService; @Autowired private UserMapper userMapper; @Autowired private RoleMapper roleMapper; @Override public UserRole selectById(Long id) { UserRoleExample userRoleExample = new UserRoleExample(); UserRoleExample.Criteria criteria = userRoleExample.createCriteria(); criteria.andIdEqualTo(id); return (UserRole) ListUtils.getList0(userRoleMapper.selectByExample(userRoleExample)); } @Override public List<UserRoleDto> findListByUserId(Long userId) { return userRoleMapper.selectByUserId(userId); } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>horizon</groupId> <artifactId>horizon</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>horizon Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <springversion>4.3.0.RELEASE</springversion> <hibernateversion>5.2.16.Final</hibernateversion> <jstlversion>1.2</jstlversion> <taglibversion>1.1.2</taglibversion> <servletversion>3.0-alpha-1</servletversion> <jsonversion>1.9.13</jsonversion> <jacksonversion>2.9.4</jacksonversion> <mysqlversion>6.0.6</mysqlversion> <log4jversion>1.2.16</log4jversion> <fileuploadversion>1.3.3</fileuploadversion> <druidversion>1.0.31</druidversion> <commonioversion>2.2</commonioversion> <servletjsp>2.1</servletjsp> <mybatis.version>3.5.1</mybatis.version> <pagehelper.version>3.5.1</pagehelper.version> <ojdbc.version>10.2.0.4</ojdbc.version> <mybatis-generator.version>1.3.7</mybatis-generator.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${springversion}</version> </dependency> <!-- spring web + spring MVC--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${springversion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springversion}</version> </dependency> <!-- hibernate配置--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernateversion}</version> </dependency> <!-- hibernate 缓存, 视情况添加--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernateversion}</version> </dependency> <!--<dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.5.2</version> </dependency> &lt;!&ndash;ehcache依赖于slf4j&ndash;&gt; <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency>--> <!-- jsp页面使用的jstl支持--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstlversion}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibversion}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servletversion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${servletjsp}</version> <scope>provided</scope> </dependency> <!-- DataBase数据库连接 mysql包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysqlversion}</version> </dependency> <!-- json数据 使springMVC可以返回json值 ,视情况添加--> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>${jsonversion}</version> </dependency> <!-- Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jacksonversion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jacksonversion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jacksonversion}</version> </dependency> <!--druid连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druidversion}</version> <scope>compile</scope> </dependency> <!-- log4j配置, 视情况添加--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4jversion}</version> </dependency> <!--文件 上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${fileuploadversion}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.2.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!-- shiro核心库 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-all</artifactId> <version>1.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>${mybatis-generator.version}</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.1</version> </dependency> </dependencies> <build> <finalName>demo</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
c6365e03437b1cbcf6bc86bdcf10dbb9bbd55204
[ "JavaScript", "Java", "Maven POM", "INI" ]
13
INI
chaohuxiayun/horizon
9883b86d6677e75d2ab47aff04097c35a80afaed
e6a39b85b0b63f2a6d6a8ae4f526801d5c1394b5
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using TodoBackend.Models; using TodoBackend.Models.TodoListContexts; namespace TodoBackend.Controller { [ApiController] [Route("api/TodoItems")] public class TodoItemsController : Microsoft.AspNetCore.Mvc.Controller { private readonly TodoContext _context; private readonly GetContext getContext; private readonly PutContext putContext; private readonly DeleteContext deleteContext; private readonly PostContext postContext; public TodoItemsController(TodoContext context) { _context = context; getContext = new GetContext(_context); putContext = new PutContext(_context); deleteContext = new DeleteContext(_context); postContext = new PostContext(_context, getContext); postContext.CreateMockItems(); } [HttpPost] public async Task<ActionResult<TodoListDTO>> PostTodoItem(TodoListDTO item) { return await postContext.CreateTodoItem(item); } // DELETE: api/TodoItems/5 [HttpDelete("{hash:long}")] public async Task<IActionResult> DeleteTodoItem(long hash) { return await deleteContext.DeleteTodoItem(hash); } // PUT: api/TodoItems/5 [HttpPut("{hash:long}")] public async Task<IActionResult> PutTodoItem(long hash, TodoListDTO toDoListDTO) { return await putContext.UpdateTodoList(hash, toDoListDTO); } [HttpGet("{hash:long}")] public async Task<ActionResult<TodoListDTO>> GetToDoItem(long hash) { return await getContext.GetItemAt(hash); } // GET: api/TodoItems/recent/2 [HttpGet("recent/{amount:int}")] public async Task<ActionResult<IEnumerable<TodoListDTO>>> GetTodoItemsSpan(int amount) { return await getContext.GetRecentItems(amount); } // GET: api/TodoItems [HttpGet] public async Task<ActionResult<IEnumerable<TodoListDTO>>> GetTodoItems() { return await getContext.GetTodoItems(); } } } <file_sep>using System; using Newtonsoft.Json; namespace TodoBackend.Utilities { public class JsonPrint { public static void Log(object printable, HTTPMethod method, string headerInformation = "") { ConsoleColor previousColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(BuildHeader(Console.WindowWidth, headerInformation)); Console.WriteLine("\n"); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(method + ": "); Console.ForegroundColor = previousColor; Console.WriteLine(JsonConvert.SerializeObject(printable, Formatting.Indented)); Console.WriteLine("\n"); } private static string BuildHeader(int length, string headerInformation) { string line = new string('-', length / 2 - headerInformation.Length / 2); string final = line + headerInformation + line; return final.Length > length ? final.Substring(1) : final; } } public enum HTTPMethod { POST = 0, GET = 1, PUT = 2, DELETE = 3, } }<file_sep>using System.Linq; using System.Text; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using TodoBackend.Models.Entries; namespace TodoBackend.Models.Converter { public class StringArrayToStringValueConverter : ValueConverter<ToDoEntry[], string> { public StringArrayToStringValueConverter() : base(l => ListToString(l), s => StringToList(s)) { } public static string ListToString(ToDoEntry[] values) { if (values == null || values.Length == 0) return null; StringBuilder builder = new StringBuilder(); foreach (ToDoEntry entry in values) builder.Append(entry.ToJSON()).Append(';'); return builder.ToString(); } public static ToDoEntry[] StringToList(string value) { return string.IsNullOrEmpty(value) ? null : value.Split(';').Select((string json) => new ToDoEntry(json)).ToArray(); } } }<file_sep>using Microsoft.EntityFrameworkCore; using TodoBackend.Models.Converter; namespace TodoBackend.Models { public class TodoContext : DbContext { public TodoContext(DbContextOptions<TodoContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { StringArrayToStringValueConverter converter = new StringArrayToStringValueConverter(); modelBuilder .Entity<ToDoList>() .Property(list => list.Entries) .HasConversion(converter); } public DbSet<ToDoList> TodoLists { get; set; } } }<file_sep>using System; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; using TodoBackend.Models.Entries; namespace TodoBackend.Models { public class ToDoList { [Key] public long Hash { get; set; } public string Title { get; set; } public bool IsComplete { get; set; } public DateTime CreatedAt { get; set; } public ToDoEntry[] Entries { get; set; } public ToDoList(long hash, string title, bool isComplete, DateTime createdAt, ToDoEntry[] entries) { Hash = hash; Title = title; IsComplete = isComplete; CreatedAt = createdAt; Entries = entries; } public override string ToString() { return $"{nameof(Hash)}: {Hash}, {nameof(Title)}: {Title}, {nameof(IsComplete)}: {IsComplete}, {nameof(Entries)}: {Entries}"; } public TodoListDTO ToDTO() => new(this.Title, this.IsComplete, this.Hash, this.Entries); } }<file_sep>using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using TodoBackend.Models.Entries; using TodoBackend.Utilities; namespace TodoBackend.Models.TodoListContexts { public class PostContext : Microsoft.AspNetCore.Mvc.Controller { private static bool CreatedMock = false; private readonly TodoContext context; private readonly GetContext getContext; public PostContext(TodoContext context, GetContext getContext) { this.context = context; this.getContext = getContext; } public async Task<ActionResult<TodoListDTO>> CreateTodoItem(TodoListDTO item) { DateTime now = DateTime.UtcNow; long hash = BitConverter.ToInt64(Guid.NewGuid().ToByteArray()); ToDoList dbItem = new ToDoList(hash, item.Title, item.IsComplete, now, item.Entries); context.TodoLists.Add(dbItem); await context.SaveChangesAsync(); JsonPrint.Log(item, HTTPMethod.POST, $"Creating item: {item.Title}"); item.Hash = dbItem.Hash; string methodName = nameof(GetToDoItem); return CreatedAtAction(methodName, new { hash = dbItem.Hash }, item); } private Task<ActionResult<TodoListDTO>> GetToDoItem(long hash) { return getContext.GetItemAt(hash); } public async void CreateMockItems() { if (CreatedMock) return; Console.WriteLine("Creating initial Mock data..."); string[] titles = {"Walk dog", "Do sport", "Study", "Visit friends"}; foreach (var title in titles) Console.WriteLine(title); Console.WriteLine(); string[] entries = { "https://i.imgur.com/zsmWSA4.png", "Eat with him", "Squads", "Run", "Mathematics", "Computer science", "Julia", "Jessi" }; Random rand = new Random(); for (int i = 0, j = 0; i < 4; i++, j += 2) { ToDoEntry[] e = { new(entries[j], j == 0 ? ToDoEntryType.Img : ToDoEntryType.Str), new(entries[j + 1], ToDoEntryType.Str) }; TodoListDTO item = new TodoListDTO(titles[i], rand.NextDouble() > 0.5f, DateTime.UtcNow.GetHashCode(), e); await CreateTodoItem(item); } CreatedMock = true; } } }<file_sep>using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using TodoBackend.Utilities; namespace TodoBackend.Models { public class GetContext : Microsoft.AspNetCore.Mvc.Controller { private readonly TodoContext context; public GetContext(TodoContext context) { this.context = context; } public async Task<ActionResult<TodoListDTO>> GetItemAt(long hash) { ToDoList item = await context.TodoLists.FindAsync(hash); if (item == null) return NotFound(); JsonPrint.Log(item, HTTPMethod.GET, $"Get: {hash}"); return Ok(item.ToDTO()); } public async Task<ActionResult<IEnumerable<TodoListDTO>>> GetRecentItems(int amount) { List<TodoListDTO> list = await context.TodoLists .OrderByDescending(x => x.CreatedAt) .Select(x => x.ToDTO()) .Take(amount) .ToListAsync(); JsonPrint.Log(list, HTTPMethod.GET, $"GET {amount} most recent items."); return list; } public async Task<ActionResult<IEnumerable<TodoListDTO>>> GetTodoItems() { List<TodoListDTO> list = await context.TodoLists .OrderByDescending(x => x.CreatedAt) .Select((ToDoList x) => x.ToDTO()) .ToListAsync(); JsonPrint.Log(list, HTTPMethod.GET, $"GET all items"); return list; } } }<file_sep>using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using TodoBackend.Utilities; namespace TodoBackend.Models { public class PutContext : Microsoft.AspNetCore.Mvc.Controller { private readonly TodoContext context; public PutContext(TodoContext context) { this.context = context; } private bool TodoItemExists(long hash) => context.TodoLists.Any(e => e.Hash == hash); public async Task<IActionResult> UpdateTodoList(long hash, TodoListDTO toDoListDTO) { if (hash != toDoListDTO.Hash) return BadRequest(); if (toDoListDTO.Entries == null) { ToDoList list = await context.TodoLists.AsNoTracking().FirstOrDefaultAsync(l => l.Hash.Equals(hash)); if (list != null) toDoListDTO.Entries = list.Entries; } context.Entry(toDoListDTO.ToDBObject()).State = EntityState.Modified; try { await context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TodoItemExists(hash)) { return NotFound(); } throw; } JsonPrint.Log(toDoListDTO, HTTPMethod.PUT, $"Updating item: {toDoListDTO.Title}"); return NoContent(); } } }<file_sep>using System.Collections.Generic; using System.Text; namespace TodoBackend.Models.Extensions { public static class Extension { public static string JoinWithChar<T>(this IEnumerable<T> list, char seperator) { StringBuilder builder = new StringBuilder(); builder.AppendJoin(seperator, list); return builder.ToString(); } } }<file_sep>using System; using Newtonsoft.Json; namespace TodoBackend.Models.Entries { public class ToDoEntry { public string Value { get; set; } public ToDoEntryType Type { get; set; } [JsonConstructor] public ToDoEntry(string value, ToDoEntryType type) { Value = value; Type = type; } public ToDoEntry(string jsonRepresentation) { if (jsonRepresentation == null) return; ToDoEntry tempEntry = new ToDoEntry("Not found");//JsonConvert.DeserializeObject<ToDoEntry>(jsonRepresentation); this.Value = tempEntry.Value; this.Type = tempEntry.Type; } public string ToJSON() { return JsonConvert.SerializeObject(this); } } public enum ToDoEntryType { None = 0, Str = 1, Img = 2 } }<file_sep>using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using TodoBackend.Utilities; namespace TodoBackend.Models { public class DeleteContext : Microsoft.AspNetCore.Mvc.Controller { private readonly TodoContext context; public DeleteContext(TodoContext context) { this.context = context; } public async Task<IActionResult> DeleteTodoItem(long hash) { var todoItem = await context.TodoLists.FindAsync(hash); if (todoItem == null) { return NotFound(); } JsonPrint.Log(todoItem, HTTPMethod.DELETE, $"Deleting: {todoItem.Title}"); context.TodoLists.Remove(todoItem); await context.SaveChangesAsync(); return NoContent(); } } }<file_sep>using System; using TodoBackend.Models.Entries; namespace TodoBackend.Models { public class TodoListDTO { public string Title { get; set; } public bool IsComplete { get; set; } public long Hash { get; set; } public ToDoEntry[] Entries { get; set; } public TodoListDTO(string title, bool isComplete, long hash, ToDoEntry[] entries) { Title = title; IsComplete = isComplete; Hash = hash; Entries = entries; } public ToDoList ToDBObject() => new(this.Hash, this.Title, this.IsComplete, DateTime.Now, this.Entries); } }
44379d8cb39f58d2540d81fa5b87730b745543f6
[ "C#" ]
12
C#
Tomyk9991/TodoWithAngular-Backend
ed80d1db97c8a4b015e1c52bb528f4689c67ffe8
e1201e41a7638b62500ce72ad15b8f205a976287
refs/heads/master
<repo_name>jheffernan/memswap<file_sep>/queue.h /* Name: <NAME> UserName: jheffernan Student Number: 638038 */ int time; typedef enum {HOLE, PROCESS} content_t; typedef struct process_t { unsigned short int pid; unsigned short int progress; unsigned int lltime; } process_t; /* A memory segment, or block of memory, which can */ /* contain a process or be a hole */ typedef struct memseg_t { struct memseg_t *prev; content_t content; process_t *proc; unsigned short int size; unsigned int addr; struct memseg_t *next; } memseg_t; typedef struct queue_t { memseg_t* first; memseg_t* last; memseg_t* place; } queue_t; process_t* makeProcess(unsigned int); void rmProcess(process_t*); memseg_t* makeSeg(unsigned short int); void rmSeg(memseg_t*); void linkSegs(memseg_t*, memseg_t*); memseg_t* unlinkSeg(memseg_t*); queue_t* makeQueue(memseg_t*, memseg_t*); void queue(memseg_t*, queue_t*); memseg_t* dequeue(queue_t*); <file_sep>/queue.c /* Name: <NAME> UserName: jheffernan Student Number: 638038 */ #include "queue.h" #include <assert.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> process_t* makeProcess(unsigned int pid) { process_t* proc = (process_t*)malloc(sizeof(process_t)); proc->pid = pid; proc->progress = 0; proc->lltime = 0; return proc; } void rmProcess(process_t* process) { free(process); } memseg_t* makeSeg(unsigned short int size) { memseg_t* seg = (memseg_t*)malloc(sizeof(memseg_t)); assert(seg); seg->prev = NULL; seg->content = HOLE; seg->proc = NULL; seg->size=size; seg->addr=0; seg->next = NULL; return seg; } void rmSeg(memseg_t* seg) { if (seg->prev) { if (seg->prev->next == seg) seg->prev->next = NULL; } if (seg->next) { if (seg->next->prev == seg) seg->next->prev = NULL; } if (seg->content == PROCESS) { assert(seg->proc); free(seg->proc); } free(seg); } void linkSegs(memseg_t* s1, memseg_t* s2) { assert(s1 && s2); s1->next = s2; s2->prev = s1; } memseg_t* unlinkSeg(memseg_t* seg) { assert(seg); if (seg->prev && seg->prev->next == seg) seg->prev->next = NULL; if (seg->next && seg->next->prev== seg) seg->next->prev = NULL; seg->next = seg->prev = NULL; return seg; } queue_t* makeQueue(memseg_t* first, memseg_t* last) { queue_t* q = (queue_t*)malloc(sizeof(queue_t)); assert(q); q->first = q->last = q->place = NULL; if (first) q->first = first; else { assert(!last); return q; } if (last) q->last = last; else q->last = first; q->place = q->first; return q; } void queue(memseg_t* seg, queue_t* q) { assert(seg); assert(q); /* Check that it is not part of a queue */ assert(!seg->prev); assert(!seg->next); if (!q->first) { assert(!q->last); q->first = seg; } else if (!q->last) { linkSegs(q->first, seg); q->last = seg; } else { linkSegs(q->last, seg); q->last = seg; } } memseg_t* dequeue(queue_t* q) { if (q->first) { memseg_t* seg = q->first; q->first = seg->next; if(seg == q->last) q->last = NULL; return unlinkSeg(seg); } else return NULL; } <file_sep>/helpers.h /* Name: <NAME> UserName: jheffernan Student Number: 638038 */ #include <stdio.h> typedef enum { FIRST, BEST, WORST, NEXT} alg_t; void br(); void printMemSeg(memseg_t*); void printQueue(queue_t*); alg_t strToAlg(char *name); void parseOpts(int argc, char** argv, int* memSize,alg_t* alg, char**fName); void printOpts(int, int, char*); void openFile(char*, FILE **); int readProcs(FILE *, queue_t*); void printUpdate(queue_t* mem); <file_sep>/README.md This is a project for assignment 1 of Computer Systems at the University of Melbourne, Semester 1 2015. Memory and the queue of processes ready to be swapped in are both modeled as doubley-linked queues (called mem and ready respectively). These consist of pointers to the head and tail of a doubley-linked list together with a pointer to a third "place-holder" node. The justification for choice of data structure is as follows: - The size of neither list should be fixed before runtime (to allow for varying inputs) - There is a natural ordering to both lists - For the ready list: - finding either the head or the tail of the queue should ideally be O(1) (to queue a swapped-out process or dequeue a process being swapped in to memory) - For memory: - traversing from a node to its predecessor or successor should ideally be O(1) to allow O(1) mergin in the case when a hole is created adjacent ot another hole - finding the "next" memory segment should be O(1) to allow the next-fit algorithm to run as efficiently as first-fit - Finding the best or worst fit is kept to O(n), which should be expected Nodes in a queue are of type memseg_t (memory segment). They may have a "content" data field set to either HOLE or PROCESS. A PROCESS memory segment will ahve a pointer to a process_t data type which contains further information, for example the "progress" of the process (measured in number of times the process has been swapped in). Time is kept by an integer variable which is incremented each time a new process is swapped in to allow for choosing the "eldest" of two equally-sized in-memory processes to swap out. <file_sep>/memManagement.c /* Name: <NAME> UserName: jheffernan Student Number: 638038 */ #include "queue.h" #include "assert.h" #include "helpers.h" #include "memManagement.h" #include <stdio.h> #include <stdlib.h> #define MAXPROG 3 memseg_t* mergeHoles(memseg_t* first, memseg_t* second, queue_t* mem) { assert(first->content == HOLE); assert(second->content == HOLE); first->size += second->size; if (second == mem->last) { mem->last = first; } else { assert(second->next); linkSegs(first, second->next); } unlinkSeg(second); rmSeg(second); return first; } memseg_t* splitHole(memseg_t* hole, int size, queue_t* mem) { assert(hole->size >= size); if (hole->size == size) return hole; memseg_t* leftOver = makeSeg(hole->size - size); leftOver->addr = hole->addr + size; hole->size = size; if (hole->next) linkSegs(leftOver, hole->next); else { assert(hole == mem->last); mem->last = leftOver; } linkSegs(hole, leftOver); return hole; } memseg_t* mergeAround(memseg_t* hole, queue_t* queue) { assert(hole); assert(hole->content == HOLE); if (hole->next) { if (hole->next->content == HOLE) mergeHoles(hole, hole->next, queue); } else assert(hole == queue->last); if (hole->prev && hole->prev->content == HOLE) return mergeHoles(hole->prev, hole, queue); else { return hole; } } int load(memseg_t* process, memseg_t* hole, queue_t* mem) { assert(process->content == PROCESS); assert(hole->content == HOLE); //Cut hole down to size hole = splitHole(hole, process->size, mem); //Supplant hole with process in queue mem if (hole->prev) linkSegs(hole->prev, process); else { assert( hole == mem->first ); mem->first = process; } if (hole->next) linkSegs(process, hole->next); else { assert( hole == mem->last ); mem->last = process; } process->addr = hole->addr; process->proc->progress++; process->proc->lltime = time++; mem->place = process; rmSeg(hole); return 1; } memseg_t* swapOut(memseg_t* process, queue_t* mem, queue_t *waitL) { assert(process && mem && waitL); assert(process->content == PROCESS && process->proc); // Create hole to replace process memseg_t* hole = makeSeg(process->size); hole->addr = process->addr; // Replace process in mem with hole if (mem->place == process) mem->place = hole; if (process->prev) linkSegs(process->prev, hole); else { assert( process == mem->first); mem->first = hole; } if (process->next) linkSegs(hole, process->next); else { assert(process == mem->last); mem->last = hole; } unlinkSeg(process); process->addr = 0; // Retire process, or queue to the waitlist again if (process->proc->progress == MAXPROG) rmSeg(process); else queue(process, waitL); return mergeAround(hole, mem); } memseg_t* firstProcess( queue_t* mem) { assert(mem); memseg_t* process = mem->first; while (process) { if(process->content == PROCESS) return process; process = process->next; } return process; } memseg_t* largestProcess( queue_t* mem) { memseg_t* largest; memseg_t* current; assert(mem); assert(mem->first); current = largest = firstProcess(mem); assert(current); assert(largest); assert(current->size); assert(largest->size); while (current) { if (current->content == HOLE) { current = current->next; continue; } else if (current->size > largest->size) largest = current; else if (current->size == largest->size) { if (current->proc->lltime < largest->proc->lltime) largest = current; } current = current->next; } assert(largest); assert(largest->content == PROCESS); return largest; } memseg_t* findSpot(alg_t alg, memseg_t* process, queue_t* mem) { switch (alg) { case FIRST: return findFirstSpot(process, mem); case BEST: return findBestSpot(process, mem); case WORST: return findWorstSpot(process, mem); case NEXT: return findNextSpot(process, mem); } exit(EXIT_FAILURE); } memseg_t* findFirstSpot(memseg_t* process, queue_t* mem) { memseg_t* current; assert(mem); assert(mem->first); assert(process); current = mem->first; while (current) { //If memory segment suitable, return it if (current->content == HOLE && current->size >= process->size) return current; current = current->next; } return NULL; } memseg_t* findBestSpot(memseg_t* process, queue_t* mem) { memseg_t *current, *best; current = best = findFirstSpot(process, mem); if (!current) return NULL; while (current) { if (current->content == PROCESS || current->size < process->size) { current = current->next; continue; } assert(current->content == HOLE); assert(current->size >= process->size); if (current->size < best->size) best = current; current = current->next; } assert(best->content == HOLE && best->size >=process->size); return best; } memseg_t* findWorstSpot(memseg_t* process, queue_t* mem) { memseg_t *current, *worst; current = worst = findFirstSpot(process, mem); if (!current) return NULL; while (current) { if (current->content == PROCESS || current->size < process->size) { current = current->next; continue; } assert(current->content == HOLE); assert(current->size >= process->size); if (current->size > worst->size) worst = current; current = current->next; } assert(worst->content == HOLE && worst->size >=process->size); return worst; } memseg_t* findNextSpot(memseg_t* process, queue_t* mem) { memseg_t* current; assert(mem && mem->first && mem->place); assert(process); current = mem->place; do { //If memory segment suitable, return it if (current->content == HOLE && current->size >= process->size) return current; // Otherwise, go to next segment if (current->next) current = current->next; // Wrap around to start if necessary else { assert(current == mem->last); current = mem->first; } // Finish when we're back where we started } while (current != mem->place); return NULL; } memseg_t* makeRoom(memseg_t* process, queue_t* mem, queue_t* waitL) { memseg_t* spot; spot = findFirstSpot(process, mem); while (!spot) { swapOut(largestProcess(mem), mem, waitL); spot = findFirstSpot(process, mem); } return spot; } int loadOne(alg_t alg, queue_t* waitL, queue_t* mem) { memseg_t* spot; if (!waitL->first) return 0; if ( !(spot = findSpot(alg, waitL->first, mem)) ) spot = makeRoom(waitL->first, mem, waitL); load(dequeue(waitL), spot, mem); return 1; } <file_sep>/Makefile HEADERS = queue.h helpers.h memManagement.h OBJECTS = memswap.o helpers.o memManagement.o queue.o CFLAGS=-Wall -g -lm VALFLAGS=--leak-check=full --show-leak-kinds=all EXECUTABLE=memswap DIFFFLAGS=-s --suppress-common-lines OPTS1=-m 200 -f tests/m200_in.txt OPTS2=-m 300 -f tests/m300_in.txt all: $(OBJECTS) $(EXECUTABLE) %.o: %.c $(HEADERS) gcc $(CFLAGS) -c $< -o $@ $(EXECUTABLE): $(OBJECTS) gcc $(CFLAGS) $(OBJECTS) -o $@ check: $(EXECUTABLE) valgrind $(VALFLAGS) ./$(EXECUTABLE) run: $(EXECUTABLE) ./$(EXECUTABLE) diff1: $(EXECUTABLE) rm -f out/* @./$(EXECUTABLE) $(OPTS1) -a first > out/200first.txt @./$(EXECUTABLE) $(OPTS1) -a best > out/200best.txt @./$(EXECUTABLE) $(OPTS1) -a worst > out/200worst.txt @./$(EXECUTABLE) $(OPTS1) -a next > out/200next.txt diff $(DIFFFLAGS) out/200first.txt tests/out/m200_first_out.txt diff $(DIFFFLAGS) out/200best.txt tests/out/m200_best_out.txt diff $(DIFFFLAGS) out/200worst.txt tests/out/m200_worst_out.txt diff $(DIFFFLAGS) out/200next.txt tests/out/m200_next_out.txt diff2: $(EXECUTABLE) rm -f out/* @./$(EXECUTABLE) $(OPTS2) -a first > out/300first.txt @./$(EXECUTABLE) $(OPTS2) -a best > out/300best.txt @./$(EXECUTABLE) $(OPTS2) -a worst > out/300worst.txt @./$(EXECUTABLE) $(OPTS2) -a next > out/300next.txt diff $(DIFFFLAGS) out/300first.txt tests/out/m300_first_out.txt diff $(DIFFFLAGS) out/300best.txt tests/out/m300_best_out.txt diff $(DIFFFLAGS) out/300worst.txt tests/out/m300_worst_out.txt diff $(DIFFFLAGS) out/300next.txt tests/out/m300_next_out.txt diff: $(EXECUTABLE) rm -f out/* ./$(EXECUTABLE) $(OPTS1) -a first > out/200first.txt ./$(EXECUTABLE) $(OPTS1) -a best > out/200best.txt ./$(EXECUTABLE) $(OPTS1) -a worst > out/200worst.txt ./$(EXECUTABLE) $(OPTS1) -a next > out/200next.txt @echo @diff $(DIFFFLAGS) out/200first.txt tests/out/m200_first_out.txt @diff $(DIFFFLAGS) out/200best.txt tests/out/m200_best_out.txt @diff $(DIFFFLAGS) out/200worst.txt tests/out/m200_worst_out.txt @diff $(DIFFFLAGS) out/200next.txt tests/out/m200_next_out.txt @echo ./$(EXECUTABLE) $(OPTS2) -a first > out/300first.txt ./$(EXECUTABLE) $(OPTS2) -a best > out/300best.txt ./$(EXECUTABLE) $(OPTS2) -a worst > out/300worst.txt ./$(EXECUTABLE) $(OPTS2) -a next > out/300next.txt @echo @diff $(DIFFFLAGS) out/300first.txt tests/out/m300_first_out.txt @diff $(DIFFFLAGS) out/300best.txt tests/out/m300_best_out.txt @diff $(DIFFFLAGS) out/300worst.txt tests/out/m300_worst_out.txt @diff $(DIFFFLAGS) out/300next.txt tests/out/m300_next_out.txt clean: rm -f $(OBJECTS) rm -f test rm -f out/* rm -f valgrind.log rm -f $(EXECUTABLE) <file_sep>/helpers.c /* Name: <NAME> UserName: jheffernan Student Number: 638038 */ #include <stdio.h> #include "queue.h" #include "helpers.h" #include <string.h> #include <getopt.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include "memManagement.h" #define USAGE "This is the usage string.\n" void br() { fprintf(stdout, "--------------------------------------------------------------------------------\n"); } void printMemSeg(memseg_t* memseg) { assert(memseg); if (memseg->content == PROCESS) { assert(memseg->proc); fprintf(stdout, "ID: %4d\tSize: %5dmb\tAddress: [%4d,%4d)\tProgress: %d\tLast loaded: %4d\n",memseg->proc->pid,memseg->size, memseg->addr, memseg->addr + memseg->size, memseg->proc->progress, memseg->proc->lltime); } else { assert(!memseg->proc); fprintf(stdout, "ID: %4d\tSize: %5dmb\tAddress: [%4d,%4d)\tProgress: %d\n", 0,memseg->size, memseg->addr, memseg->addr + memseg->size, 0); } } void printQueue(queue_t* q) { int i=1; memseg_t *memseg; memseg = q->first; if (!memseg) fprintf(stdout, "Empty\n"); while (memseg) { printf("%d :", i); i++; printMemSeg(memseg); memseg = memseg->next; } br(); } alg_t strToAlg(char *name) { if (!strcmp(name, "first")) return FIRST; else if (!strcmp(name, "best")) return BEST; else if (!strcmp(name, "worst")) return WORST; else if (!strcmp(name, "next")) return NEXT; else { fprintf(stderr, "Error: \"%s\" does not correspond to a valid algorithm.\n", name); fprintf(stderr, USAGE); exit(EXIT_FAILURE); } } void parseOpts(int argc, char** argv, int* memSize,alg_t* alg, char**fName) { int c; while ((c = getopt(argc, argv, "a:m:f:h")) != -1) { switch (c) { case 'a': *alg = strToAlg(optarg); break; case 'm': *memSize = atoi(optarg); break; case 'f': *fName = optarg; break; case 'h': fprintf(stdout, USAGE); exit(EXIT_SUCCESS); break; default: fprintf(stderr, "Error: switch statement fell through.\n"); exit(EXIT_FAILURE); } } } void printOpts(int memSize, int alg, char* fName) { fprintf(stdout, "Memory Capacity: %4dmb\nSwapping Algorithm:%7d\nInput File:%15s\n", memSize, alg, fName); } void openFile(char* fName, FILE **stream) { if (strcmp("-", fName)) *stream = fopen(fName, "r"); else *stream = stdin; } int readProcs(FILE *procFile, queue_t* waitL) { int pid, size, count = 0; memseg_t* process; while (fscanf(procFile, "%d %d", &pid, &size) == 2) { process = makeSeg(size); process->content = PROCESS; process->proc = makeProcess(pid); queue(process, waitL); count++; } if ( count ) { assert(waitL->first); waitL->place = waitL->first; } return count; } void printUpdate(queue_t* mem) { int procs, holes, pid,used, total, usage; holes = procs = total = used = 0; memseg_t* latest; memseg_t* current; current = mem->first; latest=firstProcess(mem); while (current) { total += current->size; if (current->content == HOLE) { holes++; } else { assert(current->content == PROCESS); procs++; used += current->size; if (latest) { if (current->proc->lltime > latest->proc->lltime) latest = current; } else latest = current; } current = current->next; } pid = latest->proc->pid; usage = ceil( 100 * (float)used / (float)total ); fprintf(stdout, "%d loaded, numprocesses=%d, numholes=%d, memusage=%d%%\n", pid, procs, holes, usage); } <file_sep>/TODO.txt Add memory clean-up at termination Branch to optimise memory management as suggested by Andrey <file_sep>/memManagement.h /* Name: <NAME> UserName: jheffernan Student Number: 638038 */ memseg_t* mergeHoles(memseg_t*, memseg_t*, queue_t*); memseg_t* splitHole(memseg_t*, int, queue_t*); memseg_t* mergeAround(memseg_t*, queue_t*); int load(memseg_t*, memseg_t*, queue_t*); memseg_t* swapOut(memseg_t*, queue_t*, queue_t*); memseg_t* firstProcess( queue_t* mem); memseg_t* largestProcess( queue_t*); memseg_t* findSpot(alg_t alg, memseg_t* process, queue_t* mem); memseg_t* findFirstSpot(memseg_t* process, queue_t* mem); memseg_t* findBestSpot(memseg_t* process, queue_t* mem); memseg_t* findWorstSpot(memseg_t* process, queue_t* mem); memseg_t* findNextSpot(memseg_t* process, queue_t* mem); memseg_t* makeRoom(memseg_t* process, queue_t* mem, queue_t* waitL); int loadOne(alg_t alg, queue_t* waitL, queue_t* mem); <file_sep>/memswap.c /* Name: <NAME> UserName: jheffernan Student Number: 638038 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include "queue.h" #include "helpers.h" #include "memManagement.h" #define DEF_MEMORY 200 #define DEF_FNAME "tests/m200_in.txt" #define DEF_ALG FIRST #define BASE_ADDRESS 1 int main (int argc, char **argv) { int memSize = DEF_MEMORY; alg_t alg = DEF_ALG; char* fName = DEF_FNAME; FILE *procFile; queue_t *waitL = makeQueue(NULL, NULL); queue_t *mem; time = 1; parseOpts(argc, argv, &memSize, &alg, &fName); /* printOpts(memSize, alg, fName); */ mem = makeQueue(makeSeg(memSize), NULL); mem->first->addr = BASE_ADDRESS; assert(mem->first); openFile(fName, &procFile); readProcs(procFile, waitL); while (loadOne( alg, waitL, mem)) printUpdate(mem); exit(EXIT_SUCCESS); }
9c612c088380ac424cc59120d033ad3e6ece1029
[ "Markdown", "C", "Text", "Makefile" ]
10
C
jheffernan/memswap
4a73295e741628b5038f682ebe8d2b8b4f680292
61e0f850f06e43775834f7a7017143e38a690edb
refs/heads/master
<file_sep>echo 'installing client dependencies' cd client npm install echo 'installing server dependencies' cd ../server npm install echo 'installing more server dependencies' cd dtw npm install echo 'dependencies run ./server/dtw/serve.sh to fire up the server'<file_sep># vexti * TOC {:toc} after pulling down the codebase run install-dependencies.sh to install the dependencies. `sh install-dependencies.sh` ***warning *** the code probably doesn't work right now (hardcoded paths) but I wanted to get this where someone else can look / modify ## About Files about the project (largely prototyping docs from Startup Weekend) At a high level the current implementation of Vexti is largely to be a better UX around Jekyll. Jekyll is an awesome database-less CMS. Unfortunately one has to be a dev to use it. The first phase of this project is to make it a user friendly CMS. Phase two is to make it a marketing platform. ## Hosting - the server code is hosted on a Liquid Web Server owned by <NAME> - A Liquid Web employee - individual sites are hosted on github pages under my account: https://github.com/davidsilvasmith?tab=repositories they are static sites though and could be pushed anywhere. ## Server This the server component. The server's job is threefold: 1) Serve the client UX (editor, plus not yet existing CMS interface to navigate projects, view dashboard, etc.) 2) Serve the client a preview of the rendered site before it is pushed live 3) Provide an API endpoint for client code to interface with - file based storage (save to the right spot, provide directory browsing services, etc.) - jekyll (complie site on save to give user a preview) - git (used for pushing the site live (github pages) - future - image compression / code optimization / etc. - files are in /dtw *(short for death to wordpress)* - I didn't know how to do routing well in Express (this is my first Node project) so a lot of the routes are in app.js and too much logic.) - the server expects to find jekyll websites in dtwPathRoot = '/Users/smithd98/apps/'; (specified in app.js) -/routes/index.js has most of the code for system funtions (yeah, sick naming. sorry :( ) - /system/dir - /system/file - /system/git - walkInternal - walk -public/edit.html - this was the first editor (replaced by StackEdit) ### Deployment - it should deploy on git push. if it doesn't do this on the server as the git user GIT_WORK_TREE=/opt/vexti/death-to-wordpress git checkout -f ## Client The client is a lightly modified StackEdit. StackEdit provides an extensible (although somewhat difficult) model. By default we get: - File editing - folder / file navigation - a save / publish architecture - an extensibility architecture Changes are designed to be as low impact as possible to make it easy to incorporate future changes. ### Deployment - Git push (browser may need to be hard refreshed because of caching) - prior to deployment do gulp to build the js development files (requires the querystring to have ?debug) and into main ### Light Changes - there have been deletions to hide irrelivent UI. - Most of the added code is in /public/res/dtw then some files are modified to pull these extensions. - dtwFrontMatterEditor.* - code for editing the Jekyll Front Matter - dtwImageUploader - code for uploading an image - dtwPublisher - code for moving a file out of draft and into staging - dtwPusher - code for pushing code live / giving a command line to the user - /client/public/res/providers - this file handles the syncing between server and client for files. (it should probably be moved to the dtw folder) ## UX - UX icons are from http://fontello.com/ they are stored in /client/public/res/libs/fontello <file_sep>/* any references to find and replace are because this was modeled after find / replace. */ define([ "jquery", "underscore", "crel", "utils", "classes/Extension", "mousetrap", "rangy", "yaml-js", "text!dtw/dtwFrontMatterEditor.html", "text!dtw/dtwFrontMatterEditorSettingsBlock.html" ], function($, _, crel, utils, Extension, mousetrap, rangy, YAML, dtwFrontMatterEditorHTML, dtwFrontMatterEditorSettingsBlockHTML) { var dtwFrontMatterEditor = new Extension("dtwFrontMatterEditor", 'Edit Front Matter', true, true); dtwFrontMatterEditor.settingsBlock = dtwFrontMatterEditorSettingsBlockHTML; dtwFrontMatterEditor.defaultConfig = { dtwFrontMatterEditorShortcut: 'mod+m' }; dtwFrontMatterEditor.onLoadSettings = function() { console.log("in onLoadSettings"); console.log(dtwFrontMatterEditor.config); utils.setInputValue("#input-find-replace-shortcut", dtwFrontMatterEditor.config.dtwFrontMatterEditorShortcut); }; dtwFrontMatterEditor.onSaveSettings = function(newConfig, event) { newConfig.dtwFrontMatterEditorShortcut = utils.getInputTextValue("#input-find-replace-shortcut", event); }; var editor; dtwFrontMatterEditor.onEditorCreated = function(editorParam) { editor = editorParam; }; var eventMgr; dtwFrontMatterEditor.onEventMgrCreated = function(eventMgrParam) { eventMgr = eventMgrParam; }; var contentElt; var $searchForInputElt; var $findReplaceElt; var shown = false; var dtwFileDesc; function show() { loadCurrentFrontMatter(); //console.log("CHECKING FRONTMATTER:"); //console.log(dtwFileDesc.frontMatter.title); eventMgr.onEditorPopover(); shown = true; $findReplaceElt.show(); if(dtwFileDesc.frontMatter) { $('.dtwFrontMatterEditor-input').val(dtwFileDesc.frontMatter._yaml); } editor.selectionMgr.adjustTop = 50; editor.selectionMgr.adjustBottom = 220; //highlight(true); } function hide() { shown = false; $findReplaceElt.hide(); editor.selectionMgr.adjustTop = 0; editor.selectionMgr.adjustBottom = 0; editor.focus(); } function loadCurrentFrontMatter(){ //console.log("loading frontmatter data..."); document.getElementById("title").value = dtwFileDesc.frontMatter.title; document.getElementById("post").value = dtwFileDesc.frontMatter.popularPostTitle; document.getElementById("summary").value = dtwFileDesc.frontMatter.excerpt; document.getElementById("permalink").value = dtwFileDesc.frontMatter.permalink; document.getElementById("coverImageUploadPath").innerHTML = dtwFileDesc.frontMatter.coverImage; document.getElementById("imageUploadPath").innerHTML = dtwFileDesc.frontMatter.image; document.getElementById("coverImg").src = dtwFileDesc.frontMatter.coverImage; document.getElementById("imageImg").src = dtwFileDesc.frontMatter.image; //will set inouts to empty rather than displaying undefined if(dtwFileDesc.frontMatter.title == undefined) document.getElementById("title").value = " "; if(dtwFileDesc.frontMatter.popularPostTitle == undefined) document.getElementById("post").value = " "; if(dtwFileDesc.frontMatter.excerpt == undefined) document.getElementById("summary").value = " "; if(dtwFileDesc.frontMatter.permalink == undefined) document.getElementById("permalink").value = " "; if(dtwFileDesc.frontMatter.image == undefined) document.getElementById("imageImg").src = "res/img/placeholder.png"; if(dtwFileDesc.frontMatter.coverImage == undefined) document.getElementById("coverImg").src = "res/img/placeholder.png"; //console.log("frontmatter load completed"); }; dtwFrontMatterEditor.onEditorPopover = function() { hide(); }; //takes inputs from text boxes and put it into a format yaml can parse function createFrontMatter(){ console.log("createFrontMatter was called"); var title = document.getElementById("title").value; var post = document.getElementById("post").value; var summary = document.getElementById("summary").value; var permalink = document.getElementById("permalink").value; var cover = document.getElementById("coverImageUploadPath").innerHTML; var image = document.getElementById("imageUploadPath").innerHTML; cover = fixImagePath(cover); image = fixImagePath(image); title = "title: ".concat(title).concat("\n"); post = "popularPostTitle: ".concat(post).concat("\n"); summary = "excerpt: ".concat(summary).concat("\n"); permalink = "permalink: ".concat(permalink).concat("\n"); cover = "coverImage: ".concat(cover).concat("\n"); image = "image: ".concat(image).concat("\n"); console.log('listing yml elements:\n'); console.log(title); console.log(post); console.log(summary); console.log(permalink); console.log(cover); console.log(image); return title.concat(post).concat(summary).concat(permalink).concat(cover).concat(image); }; function fixImagePath(imagePath){ var cutoff = imagePath.indexOf('/'); imagePath = imagePath.substr(cutoff,imagePath.length); return imagePath; }; //consider trimming empty lines (they get added at the end) //when trapping an error consider displaying it to the user. function save() { console.log("save called"); var newFrontMatter = createFrontMatter(); console.log("createFrontMatter ran successfully"); //if(!dtwFileDesc.frontMatter) { // hide(); // return; //} var remove; if (dtwFileDesc.frontMatter && dtwFileDesc.frontMatter._yaml) { remove = dtwFileDesc.frontMatter._yaml; } //var newFrontMatter = $('.dtwFrontMatterEditor-input').val(); ///console.log(newFrontMatter); var b; try { console.log('trying to parse'); var b = YAML.parse(newFrontMatter); console.log('done parsing', b); } catch(err) { console.log("yaml parser", err); var errMessage =""; if (err.rawMessage) { errMessage += "Error message: " + err.rawMessage; } if (err.parsedLine) { errMessage += " Line: " + err.parsedLine; } if (err.snippet) { errMessage += " Snippet: " + err.snippet; } eventMgr.onError("Invalid FrontMatter. " + errMessage); return; } console.log("b", b); var isValidYaml = (b !== null && typeof b === 'object' && !(b instanceof String)); if (isValidYaml){ console.log("is valid"); //replaceAll(search, replacement) if(remove) { editor.replaceAll(remove, newFrontMatter); } else { console.log('editor', editor); content = editor.getValue(); newContent = '---\n' + newFrontMatter + '\n---\n' + content; console.log('newContent', newContent); editor.setValue(newContent); } //var saveMe = dtwFileDesc.content.replace(remove, newFrontMatter); //eventMgr.onContentChanged(dtwFileDesc, saveMe); hide(); } else { eventMgr.onError("Invalid FrontMatter. Please fix and retry."); } } function onOpen(fileDescParam, content) { dtwFileDesc = fileDescParam; } //dtwFrontMatterEditor.onFileOpen = _.bind(highlight, null, true); dtwFrontMatterEditor.onReady = function() { var elt = crel('div', { class: 'find-replace' }); $findReplaceElt = $(elt).hide(); elt.innerHTML = dtwFrontMatterEditorHTML; document.querySelector('.layout-wrapper-l2').appendChild(elt); $('.dtwFrontMatterEditor-dismiss').click(function() { hide(); }); $('.btn-primary-save-front-matter').click(save); // Key bindings $().add($searchForInputElt).keydown(function(evt) { if(evt.which === 13) { // Enter key evt.preventDefault(); find(); } }); $(".action-frontmatter-edit").click(function() { show(); }); mousetrap.bind(dtwFrontMatterEditor.config.dtwFrontMatterEditorShortcut, function(e) { show(); e.preventDefault(); }); }; dtwFrontMatterEditor.onContentChanged = onOpen; dtwFrontMatterEditor.onFileOpen = onOpen; return dtwFrontMatterEditor; }); <file_sep>var express = require('express'); var router = express.Router(); var fs = require('fs'); var path = require('path'); var exec = require('child_process').exec; var walk = function(dir, done) { walkInternal(dir, dir, done); }; var walkInternal = function(dir, originalDir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var pending = list.length; if (!pending) return done(null, results); list.forEach(function(file) { if (file == 'node_modules' || file.indexOf(".") == 0 || file == '_site') { console.log('not including:', file); if (!--pending) done(null, results); return; } file = path.resolve(dir, file); fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { walkInternal(file, originalDir, function(err, res) { results = results.concat(res); if (!--pending) done(null, results); }); } else { results.push(file.replace(originalDir, '')); if (!--pending) done(null, results); } }); }); }); }; router.post('/system/git', function (req, res, next) { var dtwFilePath = dtwPathRoot + subdomain +'/'; console.log('in git'); var command = req.body.command; var options = {cwd: dtwFilePath}; var after = function(error, stdout, stderr) { console.log('error', error); console.log('stdout', stdout); console.log('stderr', stderr); res.send(stdout); } exec(command, options, after); }); router.get('/system/dir', function (req, res, next) { var filePath = dtwPathRoot + subdomain; var finish = function (error, results) { if(error == null){ res.send(results); } else { res.send(error); } } walk(filePath, finish); return; }); router.get('/system/file/*', function (req, res, next) { var filePath = dtwPathRoot + subdomain; console.log('in get file'); //var indexOfLastSlash = req.url. lastIndexOf('/')+1; var fileName = req.url.replace('/system/file', '');//substring(indexOfLastSlash); var getFile = filePath + fileName; console.log('getting file ' + getFile); res.sendFile(getFile); return; next(); }); module.exports = router; <file_sep>var basicAuth = require('basic-auth-connect'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var exec = require('child_process').exec; var express = require('express'); var favicon = require('serve-favicon'); var fs = require('fs'); var logger = require('morgan'); var multer = require('multer'); var path = require('path'); var sleep = require('sleep'); var serveStatic = require('serve-static') var index = require('./routes/index'); var editor = require('../../client/app'); var save = require('./routes/savefile') var users = require('./routes/users'); var app = express(); app.use(basicAuth(function(user, pass) { var isDave = (user === 'dave' && pass === '<PASSWORD>'); var isJesse = (user === 'jesse' && pass === '<PASSWORD>'); var isRupert = (user === 'rupert' && pass === '<PASSWORD>'); var isTodd = (user === 'todd' && pass === '<PASSWORD>'); var isStuart = (user === 'stuart' && pass === '<PASSWORD>'); return isDave || isJesse || isRupert || isTodd || isStuart || pass === '<PASSWORD>'; })); subdomain =''; dtwPathRoot = '/home/derek/Users/smithd98/apps/'; //change this locally after push/pull dtwSites = []; fs.readdir(dtwPathRoot, function(err,files){ if(err) throw err; files.forEach(function(file){ if(fs.existsSync(dtwPathRoot + file + '/_config.yml')) { dtwSites.push(file); } }); console.log('dtwSites', dtwSites); }); app.all('*', function(req, res, next) { var hostname = req.headers.host.split(":")[0]; var dot = hostname.indexOf('.'); subdomain = hostname.substring(0, dot); next(); }); app.use(multer({ dest: './images/', rename: function (fieldname, filename) { console.log('fieldname', fieldname); console.log('filename', filename); return filename; }, changeDest: function(dest, req, res) { var pathFromClient = req.body.dtwImageUploader; console.log('pathFromClient', pathFromClient); var newDest = dtwPathRoot + subdomain + '/' + dest + pathFromClient + '/'; console.log('new destination', newDest); if (!fs.existsSync(newDest)) { //fs.mkdirSync(newDest,'0777', true); var command = "mkdir -p '" + newDest + "'"; var options = {}; var after = function(error, stdout, stderr) { console.log('error', error); console.log('stdout', stdout); console.log('stderr', stderr); } exec(command, options, after); console.log('sleeping for 1 second'); sleep.sleep(1); console.log('waking up'); } //newDest = newDest + "b.png"; return newDest; }, onFileUploadStart: function (file) { console.log(file.originalname + ' is starting ...') }, onFileUploadComplete: function (file) { console.log(file.fieldname + ' uploaded to ' + file.path) done=true; } })); app.post('/system/upload',function(req,res){ if(done==true){ console.log(req.files); var imageSavedPath = req.files.userPhoto.path; var startExtract = imageSavedPath.indexOf(subdomain) + subdomain.length; var returnPath = imageSavedPath.substring(startExtract); res.end("File uploaded to: " + returnPath); } }); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); //app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // doesn't work because of subdomaining // replaces app.use('/raw-markdown', express.static(dtwPathRoot + 'bitcoinbulls/')); app.use('/raw-markdown', function(req, res, next) { //var done = finalhandler(req, res); //console.log('req', req); //console.log('serve', serve); var serve = serveStatic(dtwPathRoot + subdomain + '/', {'index': ['index.html', 'index.htm']}) serve(req, res, next); }); app.use('/editor', editor); app.use('/', index); app.use('/savefile', save); app.use('/users', users); app.use('/', function(req, res, next) { //var done = finalhandler(req, res); //console.log('req', req); //console.log('serve', serve); console.log('subdomain', subdomain); if (subdomain) { var serve = serveStatic(dtwPathRoot + subdomain + '/_site/', {'index': ['index.html', 'index.htm']}) serve(req, res, next); } else { res.render('index', { title: 'Death to Wordpress' }); } /* GET home page. */ //router.get('/', function(req, res, next) { //}); }); //the commented error handlers below produce all http statuses in the //server, not just errors. uncommenting reactivates logging // // catch 404 and forward to error handler // app.use(function(req, res, next) { // var err = new Error('Not Found'); // err.status = 404; // next(err); // }); // // error handlers // // development error handler // // will print stacktrace // if (app.get('env') === 'development') { // app.use(function(err, req, res, next) { // res.status(err.status || 500); // res.render('error', { // message: err.message, // error: err // }); // }); // } // // production error handler // // no stacktraces leaked to user // app.use(function(err, req, res, next) { // res.status(err.status || 500); // res.render('error', { // message: err.message, // error: {} // }); // }); module.exports = app; <file_sep>DEBUG=dtw ./bin/www
736077c7ad412fc41d6bb78f0e12e4aad69f1df9
[ "Markdown", "JavaScript", "Shell" ]
6
Shell
davidsilvasmith/vexti-cms
1107d562122d27b0779d7892ed9f6a0c22f61df5
6442b9b2051de93d24911abe7c6aeb8b5fc109be
refs/heads/master
<repo_name>bereg2k/secondproject<file_sep>/src/main/java/Base.java import java.util.Scanner; /** * 1. Array's Elements Swapping. * Declaring an array of an entered number of elements. * Initialize it with random integer numbers from the entered range. * Task: Find max negative and minimal positive elements and swap them. * Print the initial and resulting array on the screen. * <p> * 2. Packing the Gift * User is packing a gift. * The gift can include various sweets like Candy, Jellybean... * Each sweet has Name, Weight, Price and some unique parameter. * User forms a gift contained of several sweets. * All sweets are specific classes extending some abstract class. * Find and print Total Weight and Total Price. * Also print all the details of sweets in the Gift. * * @author <NAME> */ public class Base { public static void main(String[] args) { //startAgain - variable to let the "while"-cycle below know, whether user wants to exit the program or use it again. //scanner - basic console input. boolean startAgain = true; Scanner scanner = new Scanner(System.in); while (startAgain) { //Main menu of the program. User can choose to open Array's Elements Swapping, Packing the Gift or Exit. System.out.println("\nHi there! This is the MAIN MENU. What would you like to work with?"); System.out.print("Enter '1' for Array Elements Swapping, '2' for Packing the Gift, '3' for Exit: "); int mainChoice = scanner.nextInt(); //This branch is for accessing Array's Elements Swapping from the main menu. if (mainChoice == 1) { ArraySwap.main(); //calling main method of ArraySwap class System.out.println(); //calling method to start again and return a flag value for "while"-cycle startAgain = startAgainFunction(scanner, 'a'); } //This branch is for Packing the Gift. else if (mainChoice == 2) { Gift.main(); //calling main method of Gift class System.out.println(); //calling method to start again and return a flag value for "while"-cycle startAgain = startAgainFunction(scanner, 'g'); } //This branch is for quitting the program from the main menu. else if (mainChoice == 3) { System.out.println("\nThank you! Bye!"); startAgain = false; } //This branch is for handling invalid input from the main menu. else { System.err.println("\nInvalid number entered! Please try again!"); startAgain = true; } } scanner.close(); } /** * This method called at the end of iteration of main functionality (after working with Array or packing the Gift). * It lets the user to use go back to main menu or quit the program right away. * @param scanner console input parameter for user's decision * @param flagForExit flag variable for appropriate "good-bye" message (depends on the user's previous choice) * @return boolean value for main method, so that the program could go back to main menu or quit. */ private static boolean startAgainFunction(Scanner scanner, char flagForExit) { /*If user enters "y", then program goes back to main menu. If user enters "n", then program ends its execution. Otherwise, the program terminates with an error.*/ boolean startAgainLocal; //startAgainLocal - to avoid confusion with main "startAgain" variable System.out.print("\nWould you like to start again [y/n]?: "); String exit = scanner.next(); //exit - additional string variable to exit the program after executing a function. if (exit.equals("y")) { startAgainLocal = true; } else if (exit.equals("n")) { switch (flagForExit) { // flagForExit - variable for correct exit message on quitting the chosen module case 'a': System.out.println("Thank you for using our 'Array's Elements Swapping' tool! Bye!"); break; case 'g': System.out.println("Thank you for using our 'Packing the Gift' tool! Bye!"); break; } startAgainLocal = false; } else { System.err.println("Invalid input! Program aborted!"); startAgainLocal = false; } return startAgainLocal; } } <file_sep>/src/main/java/Gift.java import sweets.Chocolate; import sweets.Jellybean; import sweets.Lollipop; import sweets.Sweets; import java.util.Scanner; /** * This is a separate class for Packing the Gift functionality. * Local method "main()" is called from the Base.java class to access this functionality. * User can add a single item of each type of sweets available (currently, 3 types). * * @author <NAME> */ class Gift { static void main() { Scanner scanner = new Scanner(System.in); //creating class objects for available types of sweets -- chocolate, jelly beans, lollipops Chocolate chocolate1 = new Chocolate("Alpen Gold Milky", 100, 45.99, "milk"); Chocolate chocolate2 = new Chocolate("Alpen Gold Cappuccino", 100, 68.99, "milk"); Chocolate chocolate3 = new Chocolate("Lindt 99%", 100, 155.50, "dark"); Chocolate chocolate4 = new Chocolate("Snickers KingSize", 89.45, 65.25, "milk"); Chocolate chocolate5 = new Chocolate("Milka Arctic", 50.75, 75.10, "white"); Jellybean jellySB = new Jellybean("Haribo Bears", 90.54, 45.30, "strawberry"); Jellybean jellyBanana = new Jellybean("Skittles popups", 45, 30.90, "banana"); Lollipop lolliChup = new Lollipop("Chupa-Chups Megastar", 40.99, 38.50, "XL"); Lollipop lolliBubble = new Lollipop("Bubble Dinger Vanilla", 10.45, 20.50, "S"); Lollipop lolliTop = new Lollipop("TOP of the POP", 15.99, 25.99, "M"); //creating additional arrays for respective sweets Sweets chocolatePackage[] = new Sweets[]{chocolate1, chocolate2, chocolate3, chocolate4, chocolate5}; Sweets jellybeanPackage[] = new Sweets[]{jellySB, jellyBanana}; Sweets lollipopPackage[] = new Sweets[]{lolliChup, lolliBubble, lolliTop}; System.out.println("\nThis is 'Packing the Gift' functionality!\n"); System.out.print("Please enter the desired number of sweets in the gift box : "); int giftSize = scanner.nextInt(); Sweets gift[] = new Sweets[giftSize]; //creating an array for a gift of entered size //filling the gift box with various sweets. User chooses type and certain sweets by keyboard input. System.out.println("Let's first choose all the necessary sweets to add to the gift."); int choice; for (int i = 0; i < giftSize; i++) { System.out.print("Enter '1' to add chocolate, '2' to add jelly beans, or '3' to add lollipops: "); choice = scanner.nextInt(); switch (choice) { case 1: System.out.println("Choose the chocolate you want to add to the gift (enter its number): "); gift[i] = selectSweet(chocolatePackage); System.out.println("You have " + (giftSize - i - 1) + " more sweets to complete your gift box.\n"); break; case 2: System.out.println("Choose the jelly beans you want to add to the gift (enter its number): "); gift[i] = selectSweet(jellybeanPackage); System.out.println("You have " + (giftSize - i - 1) + " more sweets to complete your gift box.\n"); break; case 3: System.out.println("Choose the lollipops you want to add to the gift (enter its number): "); gift[i] = selectSweet(lollipopPackage); System.out.println("You have " + (giftSize - i - 1) + " more sweets to complete your gift box.\n"); break; default: System.out.println("Invalid number entered! Please try again!"); //invalid number entered handling i--; break; } } //printing formed gift box's contents System.out.println("Thank you for your choice! Here's the contents of your gift:"); printSweetsArray(gift); //calling methods for calculating total weight and total price of resulting gift box System.out.printf("\nTotal weight of the gift is %.2f grams.", getGiftTotalWeight(gift)); System.out.printf("\nTotal price of the gift is %.2f rubles.", getGiftTotalPrice(gift)); } /** * This method calculates the total weight of the given gift box. * * @param giftArray array of Sweets class consisting of various sweets * @return total weight value */ private static double getGiftTotalWeight(Sweets giftArray[]) { double giftTotalWeight = 0; for (Sweets giftWeight : giftArray ) { giftTotalWeight += giftWeight.getWeight(); } return giftTotalWeight; } /** * This method calculates the total price of the given gift box. * * @param giftArray array of Sweets class consisting of various sweets * @return total price value */ private static double getGiftTotalPrice(Sweets giftArray[]) { double giftTotalPrice = 0; for (Sweets giftPrice : giftArray ) { giftTotalPrice += giftPrice.getPrice(); } return giftTotalPrice; } /** * This method prints a given array of Sweets class. * The printing adds numeric values to elements (starting with 1 instead of 0!). * * @param sweetsArray array of Sweets class consisting of various sweets */ private static void printSweetsArray(Sweets sweetsArray[]) { for (int i = 0; i < sweetsArray.length; i++) { System.out.println((i + 1) + ". " + sweetsArray[i].toString()); } } /** * This method selects a user's sweets of choice in the given package (chocolate, jelly beans or lollipops) * @param sweetsArray chosen sweets package (chocolate, jelly beans or lollipops) * @return the chosen piece of sweets */ private static Sweets selectSweet(Sweets sweetsArray[]) { printSweetsArray(sweetsArray); Scanner scanner = new Scanner(System.in); int sweetsChoice = scanner.nextInt(); while (sweetsChoice > sweetsArray.length || sweetsChoice <= 0) { //invalid input handling System.out.println("The number is invalid! Please try again!"); sweetsChoice = scanner.nextInt(); } return sweetsArray[sweetsChoice - 1]; //numbering on the screen starts with 1 (unlike in java array's logic) } } <file_sep>/src/main/java/sweets/Lollipop.java package sweets; public class Lollipop extends Sweets { private String size; //S, M, L or XL public Lollipop() { } public Lollipop(String name, double weight, double price, String size) { super(name, weight, price); this.size = size; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } @Override public String toString() { return "Lollipop [" + super.toString() + ", size = " + size + "]"; } }
949d79171a57985cfd91a1008b61f419a8037162
[ "Java" ]
3
Java
bereg2k/secondproject
1ae6f892659478c23323ce5095089b2e06a9291f
448e4e7bc9542bf3e8fe363d82f5a809063b5689
refs/heads/master
<file_sep># belajar-express <file_sep>const router = require('express').Router() const users = require('../../Users') const usersController = require('../../controller/users.controller') // // GET ALL USERS // router.get('/', (req, res) => res.json(users)) // // GET SINGLE MEMBER // router.get('/:user', (req, res) => { // const found = users.some(user => user.user === req.params.user) // if(found){ // res.json(users.filter(user => user.user === req.params.user)) // }else{ // res.status(400).json({ msg: `Tidak ada user yang bernama ${req.params.user}`}) // } // }) router.post('/', usersController.createUser) router.get('/', usersController.readUser) // router.get('/:id', usersController.findUserById) router.put('/:id', usersController.updateUser) router.delete('/:id', usersController.deleteUser) module.exports = router<file_sep>const express = require('express') const path = require('path') const exphbs = require('express-handlebars') const logger = require('./middleware/logger') const app = express() const router = require('./routes/router') const cors = require('cors') // INIT MIDDLEWARE // app.use(logger) // CORS app.use(cors()) // HANDLEBARS MIDDLEWARE app.engine('handlebars', exphbs({defaultLayout: 'main'})) app.set('view engine', 'handlebars') // BODY PARSER app.use(express.urlencoded({extended: false})) app.use('/', router) // HOME PAGE ROUTE app.get('/', (req, res) => res.render('index', { title: "Create User" }) ) // SET STATIC FOLDER (PUBLIC FOLDER) app.use(express.static(path.join(__dirname, 'public'))) // USERS API ROUTES app.use('/api/users', require('./routes/api/users')) const PORT = process.env.PORT || 5000 app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); module.exports = app<file_sep>const users = [ { "user": "<NAME>", "age": 21, "active": true }, { "user": "ashley", "age": 23, "active": false }, { "user": "alex", "age": 43, "active": true }, { "user": "john", "age": 32, "active": true }, { "user": "chris", "age": 21, "active": false }, { "user": "tomlin", "age": 32, "active": false }, { "user": "vernon", "age": 34, "active": true }, { "user": "Boni", "age": 43, "active": true }, { "user": "mattt", "age": 32, "active": true }, { "user": "bridget", "age": 23, "active": false }, { "user": "kyle", "age": 65, "active": true }, { "user": "julia", "age": 22, "active": true }, { "user": "jake", "age": 23, "active": false } ]; module.exports = users;<file_sep>const model = require('../models') function createUser(req, res){ model.User.create({ user: req.body.user, age: req.body.age, active: req.body.active }) .then(result => { res.redirect('/') }) .catch(error => { res.json({error: error}) }) } function readUser(req, res){ model.User.findAll() .then(result => { res.json(result) }) .catch(error => { res.json({error: error}) }) } function updateUser(req, res){ model.User.update({ user: req.body.user, age: req.body.age, active: req.body.active },{ where: { id: req.params.id } }) .then(result => { res.json(result) }) .catch(error => { res.json({error: error}) }) } function deleteUser(req, res){ model.User.destroy({ where: { id: req.params.id } }) .then(result => { res.json(result) }) .catch(error => { res.json({error: error}) }) } // CARI USER BERDASARKAN ID // function findUserById(req, res){ // } module.exports = { createUser, readUser, updateUser, deleteUser, }<file_sep>const router = require('express').Router() const apiUser = require('./api/users') router.use('/api/users', apiUser) module.exports = router
e88480c358fa0a4ca0977687591bdfd6b8dbc815
[ "Markdown", "JavaScript" ]
6
Markdown
rizkydrma/belajar-express
2cffe82e8edde0cf7f2c4af5a70a02b981bae8c0
0998c4640fb73194d1656db0e6fba207701b5706
refs/heads/master
<repo_name>asbharadiya/unify_challenge<file_sep>/src/components/dashboard/accountsList/accountsList.js import React, { Component } from 'react'; import {connect} from 'react-redux'; import {showDetails} from "../../../actions/index"; import './accountsList.css'; class AccountsList extends Component { componentDidMount(){ if(this.props.accounts.length>0){ this.props.showDetails(this.props.accounts[0],0); } } render() { return ( <div className="accounts-list"> <ul className="vendors-list"> { this.props.accounts.map((account,index) => { return( <li className="vendors-list_single" key={index}> <p className="vendors-list_single__name" onClick={() => { this.props.showDetails(account,index) }}>{account.website}<span> > </span></p> <ul className="emails-list"> <li className="emails-list_single"> <p className="emails-list_single__name">{account.username}</p> </li> </ul> </li> ); }) } </ul> </div> ); } } function mapStateToProps(state) { return {accounts:state.testReducer.own_credentials}; } function mapDispatchToProps(dispatch) { return { showDetails : (account,index) => dispatch(showDetails(account,index)) }; } export default connect(mapStateToProps,mapDispatchToProps)(AccountsList); <file_sep>/src/reducers/initialState.js export default { "own_credentials":[ { "website":"google.com", "username":"<EMAIL>", "password_id":"<PASSWORD>" }, { "website":"facebook.com", "username":"<EMAIL>", "password_id":"<PASSWORD>" }, { "website":"reddit.com", "username":"thejohndoe", "password_id":"<PASSWORD>" }, { "website":"wellsfargo.com", "username":"johndoebanks", "password_id":"<PASSWORD>" }, { "website":"netflix.com", "username":"johndoeandchill", "password_id":"(*<PASSWORD>" }, { "website":"play.hbogo.com", "username":"johndoewatchesgameofthrones", "password_id":"<PASSWORD>" } ], "shared_with_me":[ { "website":"youtube.com", "username":"macklemore299", "password_id":"(*<PASSWORD>", "lender_user_id": "<PASSWORD>" }, { "website":"hulu.com", "username":"lorenzo789", "password_id":"<PASSWORD>", "lender_user_id": "lorenzochello" } ], "shared_with_others":[ { "website":"netflix.com", "username":"johndoeandchill", "password_id":"(*<PASSWORD>", "borrower_user_id": "thefriendofjohndoe" }, { "website":"play.hbogo.com", "username":"johndoewatchesgameofthrones", "password_id":"<PASSWORD>", "borrower_user_id": "gotfan" } ], "username":"johndoe19", "name": "<NAME>", "current_account_details" : { }, "current_index":null }<file_sep>/src/reducers/test.js import initialState from './initialState'; const reducer = (state = initialState, action) => { switch (action.type) { case "SHOW_DETAILS" : return {...state,current_account_details:action.account,current_index:action.index}; case "DELETE_ACCOUNT" : var new_own_credentials = state.own_credentials; new_own_credentials.splice(action.index,1); if(new_own_credentials.length>0){ return {...state,current_account_details:new_own_credentials[0],current_index:0,own_credentials:new_own_credentials}; } else { return {...state,current_account_details:{},current_index:undefined,own_credentials:new_own_credentials}; } default : return state; } }; export default reducer;<file_sep>/src/components/dashboard/accountsDetails/accountsDetails.js import React, { Component } from 'react'; import {connect} from 'react-redux'; import './accountsDetails.css'; import {deleteAccount} from "../../../actions"; class AccountsDetails extends Component { render() { const details = this.props.account_details; return ( <div className="accounts-details"> <div className="accounts-details_panel"> <p className="form-header">Login info</p> <div className="form-container"> <div className="form-container_group"> <label className="form-container_group__label">Website</label> <p className="form-container_group__value">{details.website}</p> </div> <div className="form-container_group"> <label className="form-container_group__label">Username</label> <p className="form-container_group__value">{details.username}</p> </div> <div className="form-container_group"> <label className="form-container_group__label">Password</label> <p className="form-container_group__value">{details.password_id}</p> </div> <div className="form-container_group"> <button className="input-btn" onClick={() => { this.props.deleteAccount(this.props.index) }}>Delete</button> </div> </div> </div> <div className="accounts-details_panel"> <p className="form-header">Sharing</p> <div className="form-container"> <div className="form-container_group input-group"> <input className="input-control" placeholder="Search"/> <button className="input-btn">Share</button> </div> </div> </div> </div> ); } } function mapStateToProps(state) { return { account_details:state.testReducer.current_account_details, index:state.testReducer.current_index }; } function mapDispatchToProps(dispatch) { return { deleteAccount : (index) => dispatch(deleteAccount(index)) }; } export default connect(mapStateToProps,mapDispatchToProps)(AccountsDetails);
69b20360f9b4a6b7ce3ec8bf8b2d6d0c07108391
[ "JavaScript" ]
4
JavaScript
asbharadiya/unify_challenge
edddcd7ae21b7b012806045ed924654691d14a3d
473affeb0d3623400631aefdf26b4691c273434c
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dobor_kabli.Class { class obwod { int cableLength; //in meters string isolation; //PVC or XLPE double resistivity; //resistivity ohm/km double resistance; //ohm double reactance; double reaktanceDivKm; double maxTemp; double maxFaultTemp; double metodOfInstallation; double numberOfCables; double reduceingFactor; double load; double current; } }
652a885fb872096d14f2ac6d963074b6a0d9588c
[ "C#" ]
1
C#
mmajer18/Kable
d07dd0146ccc9c2b81ce9a5cf26c6e791648a066
3f5e44e93c13a1868f1a8b404d4f20cb092ee693
refs/heads/master
<repo_name>chrisdalamitras/Python<file_sep>/TicTacToe.py #Draw the game board def drawboard(board): print (' | | ') print (' ' +board[0][0]+ ' | ' +board[0][1]+ ' | ' +board[0][2] ) print (' | | ') print ('---------------') print (' | | ') print (' ' +board[1][0]+ ' | ' +board[1][1]+ ' | ' +board[1][2] ) print (' | | ') print ('---------------') print (' | | ') print (' ' +board[2][0]+ ' | ' +board[2][1]+ ' | ' +board[2][2] ) print (' | | ') #Read the players move def input_move(player_id , board): player_move = input("Player " +str(player_id)+ " make your move: ") while (not check_input(player_move , board)): player_move = input("Player " +str(player_id)+ " please give again: ") row , col = player_move.split(",") return int(row) , int(col) #Check if the players move is acceptable def check_input(player_move , board): try: row , col = player_move.split(",") except ValueError: print("Input must be two integers in format row,col between 1-3 e.g. 1,2") return False try: row = int(row) col = int(col) except ValueError: print("Input must be two integers in format row,col between 1-3 e.g. 1,2") return False if ((row > 3 or row <=0) or (col > 3 or col <=0)): print("Input must be two integers in format row,col between 1-3 e.g. 1,2") return False elif (board[row-1][col-1] != " "): print("Cell already occupied") return False else: return True #Update the board according to players moves def update_board(board , row , col , player_id): if (player_id == 1): board[row-1][col-1] = "X" else: board[row-1][col-1] = "O" return board #Check if a player has won def win_condition(board , row , col): if (board[row-1][0] == board[row-1][1] == board[row-1][2]): return True if (board[0][col-1] == board[1][col-1] == board[2][col-1]): return True if (row-1 == col-1 == 1): if (board[0][0] == board[1][1] == board[2][2] or board[0][2] == board[1][1] == board[2][0]): return True elif (row-1 == col-1 == 0 or row-1 == col-1 == 2): if (board[0][0] == board[1][1] == board[2][2]): return True elif ((row-1 == 0 and col-1 == 2) or (row-1 == 2 and col-1 == 0)): if (board[0][2] == board[1][1] == board[2][0]): return True else: return False return False #Check if the game ends in a draw def draw_condition(board): for i in range(3): for j in range(3): if (board[i][j] == " "): return False return True #Procedure that calls the above functions and makes the game playable def Tic_Tac_Toe(board , player_id): row , col = input_move(player_id , board) board = update_board(board , row , col , player_id) drawboard(board) if (win_condition(board , row , col)): print("Congratulation player " +str(player_id)+" you're winner!!!") return if (draw_condition(board)): print("The game ends in draw") return if (player_id == 1): Tic_Tac_Toe(board , 2) else: Tic_Tac_Toe(board , 1) return #Main programm print("Welcome to the Tic Tac Toe game") play = "y" while (play == "y"): player_id = 1 board = [[" "," "," "],[" "," "," "],[" "," "," "]] drawboard(board) Tic_Tac_Toe(board , player_id) play = input("If you would like to play another game press y : ") <file_sep>/README.md # Python simple programms in python
479e6c458bc5cf247a8ef967c72667e624e6159f
[ "Markdown", "Python" ]
2
Python
chrisdalamitras/Python
1bcb78d2cd751e6b878270f339aa22cfb41d5f59
0fcbabcecb4d2f209eebd21059dec366ba4aedaf
refs/heads/master
<repo_name>brianclooney/test-project<file_sep>/docker/run-app.sh #!/bin/bash cd /usr/local/src/test/build ./test-app echo test-app exited with code $? while : do sleep 10 done <file_sep>/docker/dev/docker-compose.yml version: '2' services: test-test: image: gcc:4.9 container_name: test-test command: /usr/local/src/test/docker/run-app.sh volumes: - ../../:/usr/local/src/test <file_sep>/docker/dev/build.sh #!/bin/bash sudo docker exec test-test make -C /usr/local/src/test clean all
521e78cdb00c20da4f5d931275521dda4e6b0eda
[ "YAML", "Shell" ]
3
Shell
brianclooney/test-project
08e641a9efa1ca8c8d5af8b36257e5106542b859
23b9e7e5d171d5ba4616b62289e17e27514f8a7c
refs/heads/main
<repo_name>Sneha003/project81<file_sep>/config.js import firebase from 'firebase'; require('@firebase/firestore') var firebaseConfig = { apiKey: "<KEY>", authDomain: "booksanta-942f6.firebaseapp.com", databaseURL: "https://booksanta-942f6.firebaseio.com", projectId: "booksanta-942f6", storageBucket: "booksanta-942f6.appspot.com", messagingSenderId: "578282028595", appId: "1:578282028595:web:91796adbcad2d8cf40ed46", measurementId: "G-DQ50DL9NLT" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); export default firebase.firestore(); <file_sep>/README.md # barter system project81
07a7e3d127527d9f0db4f35bf049c3d5bbad1a0a
[ "JavaScript", "Markdown" ]
2
JavaScript
Sneha003/project81
e1acdb04cde33c1d7cc0dbd450e5a726f99b013b
72750827451f55ed44a7395599e43e91be26e92a
refs/heads/master
<file_sep>package DO; public class CrimeData { private String crimeID; private String month; private String reportedBy; private String fallsWithin; private String latitude; private String longitude; private String location; private String lsoaCode; //adding crime add public String getCrimeID() { return crimeID; } public void setCrimeID(String crimeID) { this.crimeID = crimeID; } public String getMonth() { return month; } public void setMonth(String month) { this.month = month; } public String getReportedBy() { return reportedBy; } public void setReportedBy(String reportedBy) { this.reportedBy = reportedBy; } public String getFallsWithin() { return fallsWithin; } public void setFallsWithin(String fallsWithin) { this.fallsWithin = fallsWithin; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getLsoaCode() { return lsoaCode; } public void setLsoaCode(String lsoaCode) { this.lsoaCode = lsoaCode; } public String getLsoaName() { return lsoaName; } public void setLsoaName(String lsoaName) { this.lsoaName = lsoaName; } public String getCrimeType() { return crimeType; } public void setCrimeType(String crimeType) { this.crimeType = crimeType; } public String getLastOutcome() { return lastOutcome; } public void setLastOutcome(String lastOutcome) { this.lastOutcome = lastOutcome; } private String lsoaName; private String crimeType; private String lastOutcome; } <file_sep>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package Kafka.pullmodel; import producerConsumer.Consumer; import producerConsumer.Producer; public class KafkaConsumerProducerDemo implements KafkaProperties { public static void sleep() { try { Thread.currentThread(); Thread.sleep(1200); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { int count =0; // PutData obj = new PutData(); // obj.putData("1","Narendra"); // obj.putData("2", "Varun"); // obj.putData("3", "IPhone"); // //while(count<3){ Producer producerThread = new Producer("topic1"); // // producerThread.start(); // Thread.currentThread().sleep(1000); Consumer consumerThread = new Consumer("topic1"); consumerThread.start(); // consumerThread.consume(); //count++; // System.out.println(("--------------------------------------------- "+count)); //} // } } <file_sep>package Kafka.pullmodel; import hbase.HBaseHelper; import hbase.HBaseLoader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; public class GetData { public static final String HBaseConfig = "HBase.config"; public void getData(){ try{ // HBase original configuration + internal Configuration conf = HBaseLoader.getConfiguration(); // co PutExample-1-CreateConf Create the required configuration. HBaseLoader load = HBaseLoader.loadHBase(HBaseConfig); HBaseHelper helper = HBaseHelper.getHelper(conf); if(helper.existsTable(HBaseLoader.tableName)){ //helper.createTableBest(HBaseLoader.tableName, HBaseLoader.coloumnFamily); HTable table = new HTable(conf, HBaseLoader.tableName); // co GetExample-2-NewTable Instantiate a new table reference. Scan dd = new Scan(); Get get = new Get(Bytes.toBytes("row1")); // co GetExample-3-NewGet Create get with specific row. // get.addColumn(Bytes.toBytes("F1"), Bytes.toBytes("qual1")); // co GetExample-4-AddCol Add a column to the get. get.addFamily(Bytes.toBytes("F1")); Result result = table.get(get); // co GetExample-5-DoGet Retrieve row with selected columns from HBase. //System.out.println(result); byte[] val; for (int i = 0; i <= 10; i++) { val = result.getValue(Bytes.toBytes("F1"), Bytes.toBytes(i+"")); // co GetExample-6-GetValue Get // a specific value for the // given column. System.out.println("Value: " + Bytes.toString(val)); // co // GetExample-7-Print // Print // out // the // value // while // converting // it // back. } }else{ System.out.println("No table exists"); } }catch(Exception e){ e.printStackTrace(); System.out.println("Error in " + GetData.class); } } public static void main(String[] args) { new GetData().getData(); } } <file_sep>package Kafka.pullmodel; import hbase.HBaseHelper; import hbase.HBaseLoader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; public class PutData { public static final String HBaseConfig = "HBase.config"; public void putData(String key, String message){ try{ // HBase original configuration + internal Configuration conf = HBaseLoader.getConfiguration(); // co PutExample-1-CreateConf Create the required configuration. HBaseLoader load = HBaseLoader.loadHBase(HBaseConfig); HBaseHelper helper = HBaseHelper.getHelper(conf); //helper.dropTable(HBaseLoader.tableName); if(!helper.existsTable(HBaseLoader.tableName)){ helper.createTableBest(HBaseLoader.tableName, HBaseLoader.coloumnFamily); } // vv PutExample @SuppressWarnings("resource") HTable table = new HTable(conf, HBaseLoader.tableName); // co PutExample-2-NewTable Instantiate a new client. Put put = new Put(Bytes.toBytes("row1")); // co PutExample-3-NewPut Create put with specific row. put.add(Bytes.toBytes("F1"), Bytes.toBytes(key), Bytes.toBytes(message)); // co PutExample-4-AddCol1 Add a column, whose name is "colfam1:qual1", to the put. //put.add(Bytes.toBytes("F1"), Bytes.toBytes("qual2"), Bytes.toBytes("val2")); // co PutExample-4-AddCol2 Add another column, whose name is "colfam1:qual2", to the put. table.put(put); // co PutExample-5-DoPut Store row with column into the HBase table. System.out.println("Inserted Data"); }catch(Exception e){ e.printStackTrace(); System.out.println("Error in"+ PutData.class); } } public static void main(String[] args) { new PutData().putData("w3r","varun"); } }
bc5235774d29b258e2eac5286e35078415a94752
[ "Java" ]
4
Java
VarunkumarManohar/StreamManager
54c502dc8487e2f64021407d6543a6d9bb359b2b
fd71683901e6393e6230d56c24318fb66adce65f
refs/heads/master
<file_sep>newrelic_storm_kafka ==================== This is a [Newrelic Plugin](https://newrelic.com/platform) to monitor the health of an [Apache Storm](storm.incubator.apache.org) topology consumig from a [Kafka Spout](https://github.com/apache/incubator-storm/tree/master/external/storm-kafka) using Installation ------------ You can use Newrelic NPI ``` Linux – Debian/Ubuntu x86: LICENSE_KEY=YOUR_KEY_HERE bash -c "$(curl -sSL https://download.newrelic.com/npi/release/install-npi-linux-debian-x86.sh)" x64: LICENSE_KEY=YOUR_KEY_HERE bash -c "$(curl -sSL https://download.newrelic.com/npi/release/install-npi-linux-debian-x64.sh)" Linux – Red Hat/CentOS x86: LICENSE_KEY=YOUR_KEY_HERE bash -c "$(curl -sSL https://download.newrelic.com/npi/release/install-npi-linux-redhat-x86.sh)" x64: LICENSE_KEY=YOUR_KEY_HERE bash -c "$(curl -sSL https://download.newrelic.com/npi/release/install-npi-linux-redhat-x64.sh)" Linux – Generic x86: LICENSE_KEY=YOUR_KEY_HERE bash -c "$(curl -sSL https://download.newrelic.com/npi/release/install-npi-linux-x86.sh)" x64: LICENSE_KEY=YOUR_KEY_HERE bash -c "$(curl -sSL https://download.newrelic.com/npi/release/install-npi-linux-x64.sh)" [/quote] ``` and then ```./npi install com.rekko.newrelic.storm.kafka``` Configuration ------------- ```javascript { "agents": [ { "name" : "a descriptive name", //A name to identify the topology by. "kafka.topic" : "topic", //The topic you want to monitor "kafka.broker": "kafka.example.com:9012", //The host:port of one of the kafka brokers "storm.zk.host": "zookeeper.example.com:2181", //The host:port of zookeeper "storm.zk.path": "/kafka_consumers/topology" //The path storm-kafak uses to store the kafa offset for this topic } ] } ``` Status: ------ This project is still under development, however as far as I can tell it works with no problems. <file_sep>/** * (C)2014 Digi-Net Technologies, Inc. * 5887 Glenridge Drive * Suite 350 * Atlanta, GA 30328 USA * All rights reserved. */ package com.rekko.newrelic.storm.kafka; import com.google.common.collect.Lists; import com.newrelic.metrics.publish.util.Logger; import java.util.HashMap; import java.util.List; import java.util.Map; import kafka.api.PartitionOffsetRequestInfo; import kafka.cluster.Broker; import kafka.common.TopicAndPartition; import kafka.javaapi.OffsetRequest; import kafka.javaapi.OffsetResponse; import kafka.javaapi.PartitionMetadata; import kafka.javaapi.TopicMetadata; import kafka.javaapi.TopicMetadataRequest; import kafka.javaapi.consumer.SimpleConsumer; import static com.google.common.base.Preconditions.checkNotNull; /** * @author ghais */ public class Kafka { private static final int SO_TIMEOUT = 100000; private static final int BUFFER_SIZE = 64 * 1024; private static Logger LOG = Logger.getLogger(Kafka.class); private final String _host; private final int _port; private final String _topic; public Kafka(String host, int port, String topic) { _host = checkNotNull(host, "host cannot be null"); _topic = checkNotNull(topic, "topic can't be null"); _port = port; } public Map<Integer, Long> getOffsets() { SimpleConsumer consumer = new SimpleConsumer(_host, _port, SO_TIMEOUT, BUFFER_SIZE, "newrelic_storm_kafka"); try { List<PartitionMetadata> metaData = getParitionsMetaData(consumer, _topic); Map<Integer, Long> offsets = new HashMap<Integer, Long>(metaData.size()); for (PartitionMetadata partitionMetadata : metaData) { OffsetInfo offset = getOffset(_topic, partitionMetadata); offsets.put(partitionMetadata.partitionId(), offset.offset); } return offsets; } finally { consumer.close(); } } private static OffsetInfo getOffset(String topic, PartitionMetadata partition) { Broker broker = partition.leader(); SimpleConsumer consumer = new SimpleConsumer(broker.host(), broker.port(), 10000, 1000000, "com.rekko.newrelic.storm.kafka"); try { TopicAndPartition topicAndPartition = new TopicAndPartition(topic, partition.partitionId()); PartitionOffsetRequestInfo rquest = new PartitionOffsetRequestInfo(-1, 1); Map<TopicAndPartition, PartitionOffsetRequestInfo> map = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>(); map.put(topicAndPartition, rquest); OffsetRequest req = new OffsetRequest(map, (short) 0, "com.rekko.newrelic.storm.kafka"); OffsetResponse resp = consumer.getOffsetsBefore(req); OffsetInfo offset = new OffsetInfo(); offset.offset = resp.offsets(topic, partition.partitionId())[0]; return offset; } finally { consumer.close(); } } private static TopicMetadata getTopicMetaData(SimpleConsumer consumer, String topic) { TopicMetadataRequest req = new TopicMetadataRequest(Lists.newArrayList(topic)); List<TopicMetadata> metadatas = consumer.send(req).topicsMetadata(); if (metadatas.size() != 1 || !metadatas.get(0).topic().equals(topic)) { LOG.fatal("no valid topic metadata for topic:", topic, ". run kafka-list-topic.sh to verify"); System.exit(1); } return metadatas.get(0); } private static List<PartitionMetadata> getParitionsMetaData(SimpleConsumer consumer, String topic) { return getTopicMetaData(consumer, topic).partitionsMetadata(); } }
c48a7fe63dc78547a3b9f5f9e1cd2cfcd398fffa
[ "Markdown", "Java" ]
2
Markdown
igork3/newrelic_storm_kafka
827c3cae115319fb2a57c8e327722bbc312299e8
ba88dfdcdcc0369ae2a87fc4a059e1212ee33e52
refs/heads/master
<repo_name>barrasso/Blocka<file_sep>/Source/Platforms/Android/java/org/cocos2d/Blocka/BlockaActivity.java package org.cocos2d.Blocka; import org.cocos2d.CCActivity; public class BlockaActivity extends CCActivity { }
a4802e2c4b4fa22e8a855a8db136d2aa5214a0f0
[ "Java" ]
1
Java
barrasso/Blocka
734e8c21d5e4293769f852c314aacb70ce774094
1a37f62c635a0455391a20d9b770c8390095271c
refs/heads/master
<repo_name>Dezlinka/ITIS_sender<file_sep>/ITIS_sender/damp.sql CREATE DATABASE IF NOT EXISTS `userdb` ; USE `userdb`; CREATE TABLE IF NOT EXISTS `students` ( `userid` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(45) DEFAULT NULL, `lastname` varchar(45) DEFAULT NULL, `dob` date DEFAULT NULL, `email` varchar(100) NOT NULL, `height` int(3) DEFAULT NULL, `weight` int(3) DEFAULT NULL, `category` varchar(50) DEFAULT NULL, `language` varchar(50) DEFAULT NULL, PRIMARY KEY (`userid`) ) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8; INSERT INTO `recruits` (`userid`, `firstname`, `lastname`, `dob`, `email`, `height`, `weight`, `category`, `language`) VALUES (22, 'Test', 'test', '2016-11-24', 'test', 165, 60, '', ''), (23, 'Updated user', 'Updated last name', '2016-11-05', 'fwe', 170, 75, '', ''), (32, 'Naumov', 'Danil', '1998-4-24', '<EMAIL>', 183, 70, 'B1', NULL); CREATE TABLE IF NOT EXISTS `users` ( `user_name` varchar(15) NOT NULL, `user_pass` varchar(15) NOT NULL, PRIMARY KEY (`user_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `users` (`user_name`, `user_pass`) VALUES ('admin', '<PASSWORD>'); CREATE TABLE IF NOT EXISTS `user_roles` ( `user_name` varchar(15) NOT NULL, `role_name` varchar(15) NOT NULL, PRIMARY KEY (`user_name`,`role_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `user_roles` (`user_name`, `role_name`) VALUES ('admin', 'Polkovnik'); <file_sep>/ITIS_sender/src/sms/senderServlet.java package sms; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static java.lang.System.out; /** * Created by Danil on 28.12.2016. */ public class senderServlet extends HttpServlet { private static final long serialVersionUID = 102831973239L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { smsSender sd= new smsSender("Danil", "itis507", "utf-8", true);// sd.sendSms(request.getParameter("phone"),request.getParameter("message"), 1, "", "", 0, "", ""); RequestDispatcher view = request.getRequestDispatcher("/sended.jsp"); view.forward(request, response); } }
2976c05363d972c06cf1e906ad3bf6578063a9b5
[ "Java", "SQL" ]
2
SQL
Dezlinka/ITIS_sender
324014d7069cdf0e58c82d22984058c546ebe23d
3624b5836d1a037d24c6583ce7cbbdf9875b7a4a
refs/heads/master
<repo_name>srikanthnarayanan/sri<file_sep>/src/test/java/cuc/HolyTester.java package cuc; import cucumber.api.java.en.And; import cucumber.api.java.en.But; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class HolyTester { @Given("I am a {word} tester") public void I_am_a_bad_tester(String a) { System.out.println("---------------------"); System.out.println("@Given - I am a "+a+" tester"); } @When("I go to work") public void I_go_to_work() { System.out.println("@When - I go to work"); } @Then("I {word} it") public void I_mess_it(String b) { System.out.println("@Then - I "+b+" it"); } @And("My boss {word} me") public void My_boss_fires_me(String c) { System.out.println("@And - My boss "+c+" me"); } @But("The developer {word} me") public void dev(String d) { System.out.println("@But - The developer "+d+" me"); } }
a9168fadbf8caa6b8f28cea9484e115a258548c4
[ "Java" ]
1
Java
srikanthnarayanan/sri
03a36c48f5fb3512fd664bd78176900dc1bbff10
a2321d07a5ec8f086153085d57bdf55e88f156f4
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { merge, Observable, Subject } from 'rxjs'; import { map, pluck, skipUntil } from 'rxjs/operators'; @Component({ selector: 'app-operators', templateUrl: './operators.component.html', styleUrls: ['./operators.component.css'] }) export class OperatorsComponent implements OnInit { public arr: string[] = []; public mapArr: number[] = []; public pluckArr: string[] = []; public skipArr: number[] = []; public startString: string = "STOPPED!"; public firstObs: Observable<string> = new Observable<string>((observer) => { observer.next("HELLO FROM FIRST"); }); public secondObs: Observable<string> = new Observable<string>((observer) => { observer.next("HELLO FROM SECOND"); }); public mapObs: Observable<number> = new Observable<number>((observer) => { observer.next(1); observer.next(2); observer.next(7); observer.next(12); }); public pluckObs: Observable<any> = new Observable<any>((observer) => { observer.next({firstName: "Alexander", lastName: "Dimitrow"}); observer.next({firstName: "Alexander", lastName: "Petrov"}); observer.next({firstName: "Alexander", lastName: "Ivanov"}); observer.next({firstName: "Alexander", lastName: "Georgiev"}); }); public skipObs: Observable<any> = new Observable<any>((observer) => { let i = 1; setInterval(() => { observer.next(i++); }, 1000); }) public skipSubject: Subject<string> = new Subject; constructor() { } ngOnInit(): void { var mergedObs = merge(this.firstObs, this.secondObs); let subscription = mergedObs.subscribe((val: string) => { this.arr.push(val); }); let mapSubscription = this.mapObs.pipe(map((x) => Math.pow(x,2))).subscribe((val: number) => { this.mapArr.push(val); }); let pluckSubscription = this.pluckObs.pipe(pluck('lastName'), map((x: string) => x.toUpperCase())).subscribe((val: string) => { this.pluckArr.push(val); }); // subject let newObs = this.skipObs.pipe(skipUntil(this.skipSubject)).subscribe((val) => { if (this.skipArr.length == 10) { this.skipArr = []; } this.skipArr.push(val); }); let subjObs = this.skipSubject.subscribe((val) => { this.startString = val; }); setTimeout(() => { this.skipSubject.next("Start the count!"); }, 3000); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-rx-js-root', templateUrl: './rx-js-root.component.html', styleUrls: ['./rx-js-root.component.css'] }) export class RxJsRootComponent implements OnInit { constructor() { } ngOnInit(): void { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; @Component({ selector: 'app-subjects', templateUrl: './subjects.component.html', styleUrls: ['./subjects.component.css'] }) export class SubjectsComponent implements OnInit { public firstSubjectArr: string[] = []; public firstSubject: Subject<string> = new Subject(); constructor() { } ngOnInit(): void { let observer1 = this.firstSubject.subscribe( (val) => this.firstSubjectArr.push("First: " + val), (error) => this.firstSubjectArr.push("First: " + error), ); this.firstSubject.next("HEY"); let observer2 =this.firstSubject.subscribe( (val) => this.firstSubjectArr.push("Second: " + val), (error) => this.firstSubjectArr.push("Second: " + error), ); this.firstSubject.next("How are you?"); this.firstSubject.next("FIne Thanks"); observer1.unsubscribe(); this.firstSubject.next("Are You Still Here?"); this.firstSubject.next("Im getting lonely out here"); } ngOnDestroy() { this.firstSubject.unsubscribe(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { fromEvent } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; @Component({ selector: 'app-hot-cold-obs', templateUrl: './hot-cold-obs.component.html', styleUrls: ['./hot-cold-obs.component.css'] }) export class HotColdObsComponent implements OnInit { public observable = fromEvent(document, 'mousemove'); public widthObs = fromEvent(window, 'resize'); public arr: string[] = []; public widthArr: string[] = []; constructor() { } ngOnInit(): void { let subscription = this.observable.pipe(debounceTime(300)).subscribe((val: any) => { this.arr.push(val); // Unsubscribe from document mousemove if (this.arr.length > 10) { subscription.unsubscribe(); } }); let widthSubscription = this.widthObs.subscribe((val: any) => { this.widthArr.push(val); // Unsubscribe from width change observable if (this.widthArr.length > 10) { widthSubscription.unsubscribe(); } }); } } <file_sep><clr-tabs> <clr-tab> <button clrTabLink>Basic Observers</button> <clr-tab-content *clrIfActive="true"> <div style="display: flex; flex-direction: row;justify-content: space-between;width: 300px"> <div> <h6>First Observer</h6> <li *ngFor="let record of stringArray"> {{ record }} </li> </div> <div> <h6>Second Observer</h6> <li *ngFor="let secondRecord of secondStringArray"> {{ secondRecord }} </li> </div> </div> </clr-tab-content> </clr-tab> <clr-tab> <button clrTabLink>From Array</button> <clr-tab-content *clrIfActive> <div> <h6>Values got from an Array</h6> <li *ngFor="let thirdRecord of fromArray"> {{ thirdRecord }} </li> </div> </clr-tab-content> </clr-tab> <clr-tab> <button clrTabLink>Value every 500ms</button> <clr-tab-content *clrIfActive> <div style="margin:20px"> <li *ngFor="let fourth of countToTen"> {{ fourth }} </li> </div> </clr-tab-content> </clr-tab> </clr-tabs> <file_sep>import { Component, OnInit } from '@angular/core'; import { from, Observable, Observer, timer } from 'rxjs'; @Component({ selector: 'app-lesson-one', templateUrl: './lesson-one.component.html', styleUrls: ['./lesson-one.component.css'] }) export class LessonOneComponent implements OnInit { public stringArray: string[] = []; public secondStringArray: string[] = []; public fromArray: string[] = []; public countToTen: number[] = []; public timer = timer(10,1000); public arrObs: Observable<string> = new Observable<string>(); public countToTenTimeout: Observable<string> = new Observable<string>((observer) => { observer.next("WILL EMMIT ANOTHER VALUE IN 500ms"); }); private observable: Observable<string> = new Observable<string>((observer) => { try { observer.next("HEY 1"); // throw new Error(); => commented (if error handling needs to be tested uncomment this) observer.next("HEY 2"); observer.complete(); observer.next("HEY 3"); } catch (err: any) { observer.error('ERROR') } }); constructor() { } ngOnInit(): void { let observer = this.observable.subscribe((val: string) => { this.stringArray.push(val); // will fire on each next call }, (val: string) => {this.stringArray.push(val)}, // will fire if we have an error () => { this.stringArray.push("COMPLETED!") // will fire when the observable is completed }); let secondObserver = this.observable.subscribe((val: string) => { this.secondStringArray.push(val); // will fire on each next call }, (val: string) => {this.secondStringArray.push(val)}, // will fire if we have an error () => { this.secondStringArray.push("COMPLETED!") // will fire when the observable is completed }); this.arrObs = from(['1','2','3','4','5','6','7','8','9','10']); let arrObserver = this.arrObs.subscribe((val) => { this.fromArray.push(val); }); let countToTenObs = this.timer.subscribe((val) => { this.countToTen.push(val); if (this.countToTen.length == 11) { this.countToTen = []; } }); setTimeout(() => { observer.unsubscribe(); arrObserver.unsubscribe(); }, 5000); } } <file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ClarityModule } from '@clr/angular'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { LessonOneComponent } from './rx-js/lesson-one/lesson-one.component'; import { HotColdObsComponent } from './rx-js/hot-cold-obs/hot-cold-obs.component'; import { SubjectsComponent } from './rx-js/subjects/subjects.component'; import { OperatorsComponent } from './rx-js/operators/operators.component'; import { RxJsRootComponent } from './rx-js/rx-js-root/rx-js-root.component'; @NgModule({ declarations: [ AppComponent, LessonOneComponent, HotColdObsComponent, SubjectsComponent, OperatorsComponent, RxJsRootComponent, ], imports: [ BrowserModule, AppRoutingModule, ClarityModule, BrowserAnimationsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
e738230cef2d9b50e25c2c373ad356077df1caae
[ "TypeScript", "HTML" ]
7
TypeScript
dimitrov9812/ng-learning
040cf696a8eaa273f8f790df20ed6194b38b8b79
55ba1b8944417b6539e9f4633cfb2d77108bb463
refs/heads/master
<repo_name>alexspirgel/transition-auto<file_sep>/README.md # Transition Auto Transition Auto is a JavaScript function enabling element width and height transitions to and from auto. <a href="http://alexanderspirgel.com/transition-auto/demo" target="_blank">View the demo →</a> Notes: * Resizing the element during the transition to auto can cause a "jump" to the new auto value at the end of the transition. * The `innerElement` should not have styling that would cause it to differ in size from the `element`. * To properly transition to a `width` of 'auto' make sure that the `innerElement` is not width limited by the `element`. ## Installation ### Using NPM: ```js npm install @alexspirgel/transition-auto ``` ```js const transitionAuto = require('@alexspirgel/transition-auto'); ``` ### Using a script tag: Download the normal or minified script from the `/dist` folder. ```html <script src="path/to/transition-auto.js"></script> ``` ## Usage HTML: ```html <div class="outer"> <div class="inner"> content... </div> </div> ``` CSS: ```css .outer { /* Prevent the content from overflowing the parent. */ overflow: hidden; /* Add transition */ transition-property: height; /* and/or width */ transition-duration: 1s; } .inner { /* Margins will cause incorrect dimension calculations. */ margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0; /* Force element account for children margins in dimensions. */ overflow: auto; } ``` JS: ```js transitionAuto({ element: document.querySelector('.outer'), property: 'height', value: 'auto' }); ``` ## Options ### `element` The element that will be transitioned. The passed value must be an element reference. Required. ### `innerElement` The inner element that wraps the content and dictates the 'auto' sizing. The passed value must be an element reference. Optional. If no value is passed, the first child of the `element` option value will be used. ### `property` The property to transition. Can be 'height' or 'width'. Required. ### `value` The value to set the `property` to. Can be a number (pixels) or a pixel string (ending in 'px'). Required. ### `onComplete` A callback that triggers when the `element` has reached the desired height/width. This will wait for the transition to complete, but could be instant if no transition is present. The callback will pass the options object as a parameter. Note: if the transition of the element is interrupted by another call of `transitionAuto` on the same element, this callback will not trigger for the original call because the original transition never completed. ### `suppressDuplicates` When `true`, calls of `transitionAuto` on an element currently transitioning to the desired value will be ignored. Defaults to `true`. Set to `false` to disable this feature. ### `debug` Set to `true` to enable helpful console logs when debugging. Defaults to `false`.<file_sep>/src/options-schema.js const Schema = require('@alexspirgel/schema'); const optionsModel = { required: true, type: 'object', allowUnvalidatedProperties: false, propertySchema: { element: { required: true, type: 'object', instanceOf: Element }, innerElement: { type: 'object', instanceOf: Element, custom: (inputPathManager) => { const innerElement = inputPathManager.value; inputPathManager.removePathSegment(); const element = inputPathManager.value.element; if (element.contains(innerElement) && element !== innerElement) { return true; } else { throw new Schema.ValidationError(`'options.innerElement' must be contained within 'options.element'.`); } } }, property: { required: true, type: 'string', exactValue: [ 'height', 'width' ] }, value: [ { required: true, type: 'number', greaterThanOrEqualTo: 0 }, { required: true, type: 'string', custom: (inputPathManager) => { const value = inputPathManager.value; if (value.endsWith('px')) { return true; } else { throw new Schema.ValidationError(`'options.value' string must end with 'px'.`); } } }, { required: true, type: 'string', exactValue: 'auto' } ], onComplete: { type: 'function' }, suppressDuplicates: { type: 'boolean' }, debug: { type: 'boolean' } } }; const optionsSchema = new Schema(optionsModel); module.exports = optionsSchema;<file_sep>/dist/transition-auto.js /*! * transition-auto v2.0.6 * https://github.com/alexspirgel/transition-auto */ var transitionAuto = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { const isPlainObject = __webpack_require__(6); const extend = (...arguments) => { let target = arguments[0]; let argumentIndex, merge, mergeIsArray; for (argumentIndex = 1; argumentIndex < arguments.length; argumentIndex++) { merge = arguments[argumentIndex]; if (merge === target) { continue; } mergeIsArray = Array.isArray(merge); if (mergeIsArray || isPlainObject(merge)) { if (mergeIsArray && !Array.isArray(target)) { target = []; } else if (!mergeIsArray && !isPlainObject(target)) { target = {}; } for (const property in merge) { if (property === "__proto__") { continue; } target[property] = extend(target[property], merge[property]); } } else { if (merge !== undefined) { target = merge; } } } return target; }; module.exports = extend; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { const DataPathManager = __webpack_require__(2); class ValidationError extends Error { constructor(...params) { super(...params); } set modelPathManager(modelPathManager) { if (!(modelPathManager instanceof DataPathManager)) { modelPathManager = new DataPathManager(modelPathManager); } this._modelPathManager = modelPathManager; } get modelPathManager() { return this._modelPathManager; } set inputPathManager(inputPathManager) { if (!(inputPathManager instanceof DataPathManager)) { inputPathManager = new DataPathManager(inputPathManager); } this._inputPathManager = inputPathManager; } get inputPathManager() { return this._inputPathManager; } }; module.exports = ValidationError; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { const extend = __webpack_require__(0); class DataPathManager { constructor(data, path = []) { this.data = data; this.path = path; } set path(path) { if (Array.isArray(path)) { this._path = path; } else { throw new Error('Path must be an array'); } } get path() { return this._path; } addPathSegment(pathSegment) { this.path.push(pathSegment); } removePathSegment() { return this.path.splice(-1, 1)[0]; } get value() { let value = this.data; for (let path of this.path) { try { value = value[path]; } catch (error) { return undefined; } } return value; } clone(options = {}) { const defaultOptions = { data: false, path: true }; options = extend({}, defaultOptions, options); let data = this.data; if (options.data) { if (typeof data === 'object') { if (Array.isArray(data)) { data = extend([], data); } else { data = extend({}, data); } } } let path = this.path; if (options.path) { path = [...this.path]; } return new this.constructor(data, path); } }; module.exports = DataPathManager; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { const optionsSchema = __webpack_require__(4); const extend = __webpack_require__(0); const transitionAuto = (function () { function prefixedError(message) { throw new Error('transitionAuto error: ' + message); } function debug(options, ...messages) { if (options.debug) { console.log('transitionAuto debug: ', ...messages); } } function normalizeOptions(options) { options = extend({}, options); if (options.innerElement === undefined || options.innerElement === null) { if (options.element.children.length > 0) { options.innerElement = options.element.children[0]; } else { prefixedError(`'options.element' must have at least one child element to use as 'options.innerElement'.`); } } if (typeof options.value === 'number') { options.value += 'px'; } if (options.suppressDuplicates === undefined) { options.suppressDuplicates = true; } if (options.debug === undefined) { options.debug = false; } return options; } function setValue(options) { options.element.transitionAutoValue = options.value; const computedStyle = getComputedStyle(options.element); options.element.style[options.property] = computedStyle[options.property]; options.element.offsetHeight; // This line does nothing but force the element to repaint so transitions work properly. let hasTransition = false; const transitionPropertyValues = computedStyle.transitionProperty.split(', '); const transitionDurationValues = computedStyle.transitionDuration.split(', '); for (let i = 0; i < transitionPropertyValues.length; i++) { if (transitionPropertyValues[i] === 'all' || transitionPropertyValues[i] === options.property) { const transitionDuration = transitionDurationValues[i] ? transitionDurationValues[i] : transitionDurationValues[0]; if (transitionDuration !== '0s') { hasTransition = true; break; } } } if (hasTransition) { debug(options, 'transition detected.'); if (options.value === 'auto') { const elementDimensions = options.element.getBoundingClientRect(); const innerElementDimensions = options.innerElement.getBoundingClientRect(); if (elementDimensions[options.property] !== innerElementDimensions[options.property]) { options.element.transitionAutoBoundHandler = transitionendHandler.bind(options); options.element.addEventListener('transitionend', options.element.transitionAutoBoundHandler); options.element.style[options.property] = innerElementDimensions[options.property] + 'px'; return; } } else { if (options.element.style[options.property] !== options.value) { options.element.transitionAutoBoundHandler = transitionendHandler.bind(options); options.element.addEventListener('transitionend', options.element.transitionAutoBoundHandler); options.element.style[options.property] = options.value; return; } } } debug(options, 'immediate fallback.'); options.element.style[options.property] = options.value; onComplete(options); } function transitionendHandler(event) { if (event.propertyName === this.property) { if (this.element.transitionAutoBoundHandler) { this.element.removeEventListener('transitionend', this.element.transitionAutoBoundHandler); delete this.element.transitionAutoBoundHandler; } if (this.value === 'auto') { this.element.style[this.property] = this.value; } } onComplete(this); } function onComplete(options) { if (options.element.transitionAutoValue) { delete options.element.transitionAutoValue; } if (options.onComplete) { options.onComplete(options); } } return function (options) { try { optionsSchema.validate(options); } catch (error) { prefixedError(error); } options = normalizeOptions(options); debug(options, 'options:', options); if (options.suppressDuplicates && options.element.transitionAutoValue) { if (options.value === options.element.transitionAutoValue) { debug(options, 'duplicate suppressed.'); return; } } if (options.element.transitionAutoBoundHandler) { options.element.removeEventListener('transitionend', options.element.transitionAutoBoundHandler); delete options.element.transitionAutoBoundHandler; } setValue(options); }; })(); module.exports = transitionAuto; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { const Schema = __webpack_require__(5); const optionsModel = { required: true, type: 'object', allowUnvalidatedProperties: false, propertySchema: { element: { required: true, type: 'object', instanceOf: Element }, innerElement: { type: 'object', instanceOf: Element, custom: (inputPathManager) => { const innerElement = inputPathManager.value; inputPathManager.removePathSegment(); const element = inputPathManager.value.element; if (element.contains(innerElement) && element !== innerElement) { return true; } else { throw new Schema.ValidationError(`'options.innerElement' must be contained within 'options.element'.`); } } }, property: { required: true, type: 'string', exactValue: [ 'height', 'width' ] }, value: [ { required: true, type: 'number', greaterThanOrEqualTo: 0 }, { required: true, type: 'string', custom: (inputPathManager) => { const value = inputPathManager.value; if (value.endsWith('px')) { return true; } else { throw new Schema.ValidationError(`'options.value' string must end with 'px'.`); } } }, { required: true, type: 'string', exactValue: 'auto' } ], onComplete: { type: 'function' }, suppressDuplicates: { type: 'boolean' }, debug: { type: 'boolean' } } }; const optionsSchema = new Schema(optionsModel); module.exports = optionsSchema; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { const DataPathManager = __webpack_require__(2); const ValidationError = __webpack_require__(1); const ValidationErrors = __webpack_require__(7); const modelModel = __webpack_require__(8); class Schema { static get validationMethods() { return [ { property: 'required', method: this.validateRequired }, { property: 'type', method: this.validateType }, { property: 'exactValue', method: this.validateExactValue }, { property: 'greaterThan', method: this.validateGreaterThan }, { property: 'greaterThanOrEqualTo', method: this.validateGreaterThanOrEqualTo }, { property: 'lessThan', method: this.validateLessThan }, { property: 'lessThanOrEqualTo', method: this.validateLessThanOrEqualTo }, { property: 'divisibleBy', method: this.validateDivisibleBy }, { property: 'notDivisibleBy', method: this.validateNotDivisibleBy }, { property: 'minimumCharacters', method: this.validateMinimumCharacters }, { property: 'maximumCharacters', method: this.validateMaximumCharacters }, { property: 'minimumLength', method: this.validateMinimumLength }, { property: 'maximumLength', method: this.validateMaximumLength }, { property: 'instanceOf', method: this.validateInstanceOf }, { property: 'allowUnvalidatedProperties', method: this.validateAllowUnvalidatedProperties }, { property: 'custom', method: this.validateCustom }, { property: 'allPropertySchema', method: this.validateAllPropertySchema }, { property: 'propertySchema', method: this.validatePropertySchema } ] } static validateRequired(modelPathManager, inputPathManager) { if (modelPathManager.value === true) { if (inputPathManager.value === undefined || inputPathManager.value === null) { throw new ValidationError(`Property 'required' validation failed. The input must not be null or undefined.`); } } return true; } static validateType(modelPathManager, inputPathManager) { if (modelPathManager.value === 'number') { if (typeof inputPathManager.value === 'number' && !isNaN(inputPathManager.value)) { return true; } } else if (modelPathManager.value === 'object') { if (typeof inputPathManager.value === 'object' && !Array.isArray(inputPathManager.value) && inputPathManager.value !== null) { return true; } } else if (modelPathManager.value === 'array') { if (Array.isArray(inputPathManager.value)) { return true; } } else if (modelPathManager.value === 'boolean' || modelPathManager.value === 'string' || modelPathManager.value === 'function') { if (typeof inputPathManager.value === modelPathManager.value) { return true; } } throw new ValidationError(`Property 'type' validation failed. The input type must match.`); } static validateExactValue(modelPathManager, inputPathManager) { if (Array.isArray(modelPathManager.value)) { for (const value of modelPathManager.value) { if (inputPathManager.value === value) { return true; } } } else { if (inputPathManager.value === modelPathManager.value) { return true; } } throw new ValidationError(`Property 'exactValue' validation failed. The input must be an exact match of the value or one of the values in an array of values.`); } static validateGreaterThan(modelPathManager, inputPathManager) { if (inputPathManager.value > modelPathManager.value) { return true; } else { throw new ValidationError(`Property 'greaterThan' validation failed. The input must be greater than the value.`); } } static validateGreaterThanOrEqualTo(modelPathManager, inputPathManager) { if (inputPathManager.value >= modelPathManager.value) { return true; } else { throw new ValidationError(`Property 'greaterThanOrEqualTo' validation failed. The input must be greater than or equal to the value.`); } } static validateLessThan(modelPathManager, inputPathManager) { if (inputPathManager.value < modelPathManager.value) { return true; } else { throw new ValidationError(`Property 'lessThan' validation failed. The input must be less than the value.`); } } static validateLessThanOrEqualTo(modelPathManager, inputPathManager) { if (inputPathManager.value <= modelPathManager.value) { return true; } else { throw new ValidationError(`Property 'lessThanOrEqualTo' validation failed. The input must be less than or equal to the value.`); } } static validateDivisibleBy(modelPathManager, inputPathManager) { if (Array.isArray(modelPathManager.value)) { for (const value of modelPathManager.value) { if (inputPathManager.value % value === 0) { return true; } } } else { if (inputPathManager.value % modelPathManager.value === 0) { return true; } } throw new ValidationError(`Property 'divisibleBy' validation failed. The input must be divisible by the value or one of the values in an array of values.`); } static validateNotDivisibleBy(modelPathManager, inputPathManager) { let flag = false; if (Array.isArray(modelPathManager.value)) { for (const value of modelPathManager.value) { if (inputPathManager.value % value === 0) { flag = true; } } } else { if (inputPathManager.value % modelPathManager.value === 0) { flag = true; } } if (flag || isNaN(inputPathManager.value)) { throw new ValidationError(`Property 'notDivisibleBy' validation failed. The input must not be divisible by the value or one of the values in an array of values.`); } return true; } static validateMinimumCharacters(modelPathManager, inputPathManager) { if (inputPathManager.value.length >= modelPathManager.value) { return true; } else { throw new ValidationError(`Property 'minimumCharacters' validation failed. The input must have a character count greater than or equal to the value.`); } } static validateMaximumCharacters(modelPathManager, inputPathManager) { if (inputPathManager.value.length <= modelPathManager.value) { return true; } else { throw new ValidationError(`Property 'maximumCharacters' validation failed. The input must have a character count less than or equal to the value.`); } } static validateMinimumLength(modelPathManager, inputPathManager) { if (inputPathManager.value.length >= modelPathManager.value) { return true; } else { throw new ValidationError(`Property 'minimumLength' validation failed. The input must have a length greater than or equal to the value.`); } } static validateMaximumLength(modelPathManager, inputPathManager) { if (inputPathManager.value.length <= modelPathManager.value) { return true; } else { throw new ValidationError(`Property 'maximumLength' validation failed. The input must have a length less than or equal to the value.`); } } static validateInstanceOf(modelPathManager, inputPathManager) { if (Array.isArray(modelPathManager.value)) { for (const value of modelPathManager.value) { if (inputPathManager.value instanceof value) { return true; } } } else { if (inputPathManager.value instanceof modelPathManager.value) { return true; } } throw new ValidationError(`Property 'instanceOf' validation failed. The input must be an instance of the value or one of the values in an array of values.`); } static validateAllowUnvalidatedProperties(modelPathManager, inputPathManager) { if (modelPathManager.value === false) { modelPathManager.removePathSegment(); modelPathManager.addPathSegment('propertySchema'); let validatedProperties = []; if (modelPathManager.value) { validatedProperties = Object.keys(modelPathManager.value); } for (const property in inputPathManager.value) { if (!validatedProperties.includes(property)) { throw new ValidationError(`Property 'allowUnvalidatedProperties' validation failed. '${property}' is not defined in the 'propertySchema' validation property.`); } } } return true; } static validateCustom(modelPathManager, inputPathManager) { const customInputPathManager = inputPathManager.clone({data: true, path: true}); return modelPathManager.value(customInputPathManager); } static validateAllPropertySchema(modelPathManager, inputPathManager) { const allPropertySchema = new Schema(modelPathManager.clone(), false); for (const property in inputPathManager.value) { const inputPropertyPathManager = inputPathManager.clone(); inputPropertyPathManager.addPathSegment(property); const validationResult = allPropertySchema.validate(inputPropertyPathManager, 'array'); if (validationResult !== true) { return validationResult; } } return true; } static validatePropertySchema(modelPathManager, inputPathManager) { for (const property in modelPathManager.value) { const modelPropertyPathManager = modelPathManager.clone(); modelPropertyPathManager.addPathSegment(property); const propertySchema = new Schema(modelPropertyPathManager, false); const inputPropertyPathManager = inputPathManager.clone(); inputPropertyPathManager.addPathSegment(property); const validationResult = propertySchema.validate(inputPropertyPathManager, 'array'); if (validationResult !== true) { return validationResult; } } return true; } constructor(modelPathManager = {}, selfValidate = true) { this.selfValidate = selfValidate; this.modelPathManager = modelPathManager; } set modelPathManager(modelPathManager) { if (!(modelPathManager instanceof DataPathManager)) { modelPathManager = new DataPathManager(modelPathManager); } this._modelPathManager = modelPathManager; if (this.selfValidate) { const schemaModel = new Schema(modelModel, false); schemaModel.validate(this.modelPathManager); } } get modelPathManager() { return this._modelPathManager; } validate(inputPathManager, errorStyle = 'throw') { if (!(inputPathManager instanceof DataPathManager)) { inputPathManager = new DataPathManager(inputPathManager); } let validationErrors = new ValidationErrors(); if (Array.isArray(this.modelPathManager.value)) { for (let modelIndex = 0; modelIndex < this.modelPathManager.value.length; modelIndex++) { const modelItemPathManager = this.modelPathManager.clone(); modelItemPathManager.addPathSegment(modelIndex); const validationResult = this._validate(modelItemPathManager, inputPathManager); if (validationResult === true) { return true; } else { validationErrors.addError(validationResult); } } } else { const validationResult = this._validate(this.modelPathManager, inputPathManager); if (validationResult === true) { return true; } else { validationErrors.addError(validationResult); } } if (errorStyle === 'throw') { throw new Error(validationErrors.generateFormattedMessage()); } else if (errorStyle === 'array') { return validationErrors.errors; } else if (errorStyle === 'boolean') { return false; } } _validate(modelPathManager, inputPathManager) { if (modelPathManager.value.required !== true) { if (inputPathManager.value === undefined || inputPathManager.value === null) { return true; } } for (const validationMethod of this.constructor.validationMethods) { if (modelPathManager.value.hasOwnProperty(validationMethod.property)) { const validationMethodModelPathManager = modelPathManager.clone(); validationMethodModelPathManager.addPathSegment(validationMethod.property); try { const validationResult = validationMethod.method(validationMethodModelPathManager, inputPathManager); if (validationResult !== true) { return validationResult; } } catch (error) { if (error instanceof ValidationError) { if (!error.modelPathManager) { error.modelPathManager = validationMethodModelPathManager; } if (!error.inputPathManager) { error.inputPathManager = inputPathManager; } return error; } else { throw error; } } } } return true; } } Schema.ValidationError = ValidationError; module.exports = Schema; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { /** * isPlainObject v1.0.1 * https://github.com/alexspirgel/isPlainObject */ const isPlainObject = (object) => { if (Object.prototype.toString.call(object) !== '[object Object]') { return false; } if (object.constructor === undefined) { return true; } if (Object.prototype.toString.call(object.constructor.prototype) !== '[object Object]') { return false; } if (!object.constructor.prototype.hasOwnProperty('isPrototypeOf')) { return false; } return true; }; if ( true && module.exports) { module.exports = isPlainObject; } /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { const ValidationError = __webpack_require__(1); class ValidationErrors { constructor() { this.errors = []; } addError(error) { if (Array.isArray(error)) { for (const singleError of error) { this.addError(singleError); } } else { if (!(error instanceof ValidationError)) { throw new Error(`Passed 'error' must be an instance of 'Schema.ValidationError'.`); } else { this.errors.push(error); } } } generateFormattedMessage() { let message = `Schema errors:\n`; for (const error of this.errors) { let inputPath = 'root'; if (error.inputPathManager.path.length > 0) { inputPath = error.inputPathManager.path.map((pathSegment) => { return `['` + pathSegment + `']`; }); inputPath = inputPath.join(''); } let modelPath = 'root'; if (error.modelPathManager.path.length > 0) { modelPath = error.modelPathManager.path.map((pathSegment) => { return `['` + pathSegment + `']`; }); modelPath = modelPath.join(''); } message = message + `\nInput Path: ${inputPath}\nModel Path: ${modelPath}\nMessage: ${error.message}\n`; } return message; } }; module.exports = ValidationErrors; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { const extend = __webpack_require__(0); const ValidationError = __webpack_require__(1); const typeRestriction = (types) => { if (!Array.isArray(types)) { types = [types]; } return (inputPathManager) => { const validationProperty = inputPathManager.removePathSegment(); if (validationProperty === undefined || types.includes(inputPathManager.value.type)) { return true; } else { let typesString = ``; for (let i = 0; i < types.length; i++) { const type = types[i]; if (i === 0) { typesString += `'${type}'`; } else if (i < (types.length - 1)) { typesString += `, '${type}'`; } else { if (types.length > 2) { typesString += `,`; } typesString += ` or '${type}'`; } } throw new ValidationError(`The validation property '${validationProperty}' can only belong to a model with a type of ${typesString}.`); } }; }; const modelPropertySchema = { required: { type: 'boolean' }, type: { type: 'string', exactValue: [ 'boolean', 'number', 'string', 'array', 'object', 'function' ] }, exactValue: { custom: typeRestriction(['boolean', 'number', 'string']) }, greaterThan: { type: 'number', custom: typeRestriction('number') }, greaterThanOrEqualTo: { type: 'number', custom: typeRestriction('number') }, lessThan: { type: 'number', custom: typeRestriction('number') }, lessThanOrEqualTo: { type: 'number', custom: typeRestriction('number') }, divisibleBy: { type: 'number', custom: typeRestriction('number') }, notDivisibleBy: { type: 'number', custom: typeRestriction('number') }, minimumCharacters: { type: 'string', custom: typeRestriction('string') }, maximumCharacters: { type: 'string', custom: typeRestriction('string') }, minimumLength: { type: 'number', custom: typeRestriction('array') }, maximumLength: { type: 'number', custom: typeRestriction('array') }, instanceOf: { custom: typeRestriction('object') }, allowUnvalidatedProperties: { type: 'boolean', custom: typeRestriction('object') }, custom: { type: 'function' }, propertySchema: { type: 'object', custom: typeRestriction(['array', 'object']) } }; const modelObject = { type: 'object', propertySchema: modelPropertySchema }; const modelArray = { type: 'array', allPropertySchema: { type: 'object', propertySchema: modelPropertySchema } }; const model = [ modelObject, modelArray ]; const modelTypeRestricted = [ extend({}, modelObject, {custom: typeRestriction(['array', 'object'])}), extend({}, modelArray, {custom: typeRestriction(['array', 'object'])}) ]; modelPropertySchema.allPropertySchema = modelTypeRestricted; modelPropertySchema.propertySchema.allPropertySchema = model; module.exports = model; /***/ }) /******/ ]);<file_sep>/webpack.config.js const path = require('path'); const webpack = require('webpack'); const TerserPlugin = require('terser-webpack-plugin'); const packageData = require('./package.json'); module.exports = [ { mode: 'production', name: 'transitionAuto', entry: './src/index.js', target: 'web', output: { library: 'transitionAuto', libraryTarget: 'var', filename: 'transition-auto.js', path: path.resolve(__dirname, './dist') }, plugins: [ new webpack.BannerPlugin({ banner: `transition-auto v${packageData.version}\nhttps://github.com/alexspirgel/transition-auto` }) ], optimization: { minimize: false }, watch: true }, { mode: 'production', name: 'transitionAuto', entry: './src/index.js', target: 'web', output: { library: 'transitionAuto', libraryTarget: 'var', filename: 'transition-auto.min.js', path: path.resolve(__dirname, './dist') }, plugins: [ new webpack.BannerPlugin({ banner: `transition-auto v${packageData.version}\nhttps://github.com/alexspirgel/transition-auto` }) ], optimization: { minimize: true, minimizer: [ new TerserPlugin({ extractComments: false, terserOptions: { keep_classnames: true } }) ] }, watch: true } ];
235146b136490c3810bf06dd4f92717b2bd89610
[ "Markdown", "JavaScript" ]
4
Markdown
alexspirgel/transition-auto
6a3a24c3d812c227a449bfee6be1ed9e48b26265
58c325e83075c9d264a8bf66c65b82c4e40d9cd1
refs/heads/master
<repo_name>trptrptrp/qqqqqq-master<file_sep>/luyou.cpp AAA *AAA::EE(struct AAA *head) { AAA *p1,*p2; p1=new AAA; p2=new AAA; p1=head; BBB *p5,*p6; p5=new BBB; int i,j,k; int c; string a,b; cout << "添加路由器请输入:1" << '\n' << "添加线请输入:2" << endl; cin>>k; if(k==1) { for(i=0;;i++) { p1 = p1->link; if(p1->link==NULL) { break; } } cout<<"请输入路由器信息(路由器x)"<<endl; cin>>p2->a1; for(i=0;;i++) { p6=new BBB; cout<<"请输入链接的信息(长度 连接的路由器x)(输入0结束)"<<endl;; if(i==0) { cin>>p5->b1; if(p5->b1==0) { p2->linkk=NULL; break; } cin>>p5->b2; p2->linkk=p5; } else { cin>>p6->b1; if(p6->b1==0) { p5->linkk=NULL; break; } cin>>p6->b2; p5->linkk=p6; p5=p5->linkk; } } p1->link=p2; p2->link=NULL; p5 = new BBB; p5 = p2->linkk; for (i = 0;; i++) { p1 = new AAA; p1 = head; for (j = 0;; j++) { if (p1->a1 == p5->b2) { break; } else if (p1->link == NULL) { cout << "输入错误!" << endl; break; } else { p1 = p1->link; } } BBB *p7; p7 = new BBB; if (p1->a1 == p5->b2) { p7 = p1->linkk; for (i = 0;; i++) { if (p7->linkk == NULL) { break; } p7 = p7->linkk; } p6 = new BBB; p6->b1 = p5->b1; p6->b2 = p2->a1; p7->linkk = p6; p6->linkk = NULL; } if (p5->linkk == NULL) { break; } else { p5 = p5->linkk; } } } if(k==2) { cout<<"请输入起始路由器和终点路由器(路由器a 路由器b)"<<endl; cin>>a>>b; for(i=0;;i++) { if(p1->a1==a) { break; } else if(p1->link==NULL) { cout<<"输入错误!"<<endl; break; } else { p1=p1->link; } } cout<<"请输入长度:"<<endl; cin >> c; if(p1->a1==a) { p5=p1->linkk; for(i=0;;i++) { if(p5->linkk==NULL) { break; } p5=p5->linkk; } p6=new BBB; p6->b1 = c; p6->b2=b; p5->linkk=p6; p6->linkk=NULL; } p1 = new AAA; p1 = head; for (i = 0;; i++) { if (p1->a1 == b) { break; } else if (p1->link == NULL) { cout << "输入错误!" << endl; break; } else { p1 = p1->link; } } p5 = new BBB; if (p1->a1 == b) { p5 = p1->linkk; for (i = 0;; i++) { if (p5->linkk == NULL) { break; } p5 = p5->linkk; } p6 = new BBB; p6->b1 = c; p6->b2 = a; p5->linkk = p6; p6->linkk = NULL; } } return head; }; <file_sep>/readme.h #ifndef README_H #define README_H #include<iostream> #include<string> #include<fstream> using namespace std; struct BBB { int b1;//长度 string b2;//下一个路由器 BBB *linkk; } ; struct AAA { string a1;//路由器 AAA *link; BBB *linkk; virtual AAA *AA(struct AAA *head);//读取 virtual AAA *BB(AAA *head);//全输出 //virtual AAA *CC(AAA *head); virtual AAA *DD(struct AAA *head);//求最短路径 virtual AAA *EE(AAA *head);//添加 virtual AAA *FF(AAA *head);//删除 }; #endif
087f386aaa335410ca38c57beb455be8a5d8b37d
[ "C++" ]
2
C++
trptrptrp/qqqqqq-master
02e03d542f84b3678573a6e06e5259a97009b340
cfc4f6b078633a1021ebec46071c642f83f8113e
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> int xSize, ySize; // 행렬의 개수 char *X, *Y; // 각 문자 배열 int **c; // 비교 후 저장 될 값이 들어갈 정수 배열 char **b; // 다음 포인트를 가리키는 문자 배열 // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) void readFile(int argc, char *argv[]) { int i; FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &xSize); // 첫 번째 줄 데이터만 읽어오기 // 1부터 xSize까지 저장해야 하기에 xSize+1 할당 X = calloc(xSize + 1, sizeof(char)); // 1부터 xSize까지 파일의 문자 저장 for (i = 1; i <= xSize; i++) { fscanf(file, "%c", &(X[i])); } fscanf(file, "%d\n", &ySize); // 세 번째 줄 데이터만 읽어오기 // 1부터 ySize까지 저장해야 하기에 xSize+1 할당 Y = calloc(ySize + 1, sizeof(char)); // 1부터 ySize까지 파일의 문자 저장 for (i = 1; i <= ySize; i++) { fscanf(file, "%c", &(Y[i])); } fclose(file); } // LCS를 연산하는 함수 void LcsLength() { int m = xSize; int n = ySize; int i, j; // m까지의 행이기에 m+1개 할당 b = calloc(m + 1, sizeof(char *)); // 1부터 m까지의 행에 n까지의 열을 할당 for (i = 1; i < m + 1; i++) { b[i] = calloc(n + 1, sizeof(char)); } // m까지의 행이기에 m+1개 할당 c = calloc(m + 1, sizeof(int *)); // 1부터 m까지의 행에 n까지의 열을 할당 for (i = 0; i < m + 1; i++) { c[i] = calloc(n + 1, sizeof(int)); } // c배열에서 행이나 열이 0인 인덱스는 0값으로 초기화 for (i = 1; i <= m; i++) { c[i][0] = 0; } for (j = 0; j <= n; j++) { c[0][j] = 0; } // 1부터 m까지 반복 for (i = 1; i <= m; i++) { // 1부터 n까지 반복 for (j = 1; j <= n; j++) { // X[i]와 Y[j] 값 비교 if (X[i] == Y[j]) { // 같다면 c는 각 1씩 뺀 위치의 값에서 1 증가 c[i][j] = c[i - 1][j - 1] + 1; // b배열에는 왼쪽 위 방향을 가리키는 ` 저장 b[i][j] = '`'; } else if (c[i - 1][j] >= c[i][j - 1]) { // i,j의 위가 왼쪽보다 크다면 위 값을 i,j에 저장 c[i][j] = c[i - 1][j]; // 위 방향을 가리키는 l 저장 b[i][j] = 'l'; } else { // 왼쪽이 더 크다면 왼쪽 값을 i,j에 저장 c[i][j] = c[i][j - 1]; // 왼쪽 방향을 가리키는 - 저장 b[i][j] = '-'; } } } } // 연산 완료된 LCS의 결과를 출력 void PrintLCS(int i, int j) { // i 혹은 j 가 0이 되면 종료 if (i == 0 || j == 0) { return; } // b배열에서 i,j위치의 방향으로 비교 if (b[i][j] == '`') { // 대각 방향일 경우 i-1,j-1로 재귀적 실행 PrintLCS(i - 1, j - 1); // 해당 X[i] 출력 printf("%c ", X[i]); } else if (b[i][j] == 'l') { // 위 방향일 경우 i-1,j로 재귀적 실행 PrintLCS(i - 1, j); } else { // 왼쪽 방향일 경우 i,j-1로 재귀적 실행 PrintLCS(i, j - 1); } } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./LCS.exe sample_lcs1.txt.txt int main(int argc, char *argv[]) { xSize = 0; // 행렬 개수 초기화 ySize = 0; // 행렬 개수 초기화 readFile(argc, argv); // 파일 읽어오기 printf("시작\n"); LcsLength(); // 연산 시작 PrintLCS(xSize, ySize); // 결과 출력 printf("\n완료"); free(X); // X 메모리 해제 free(Y); // Y 메모리 해제 free(b); // b 메모리 해제 free(c); // c 메모리 해제 return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define INF 100000 int size; // 원소 개수 int **s; // 문제별 int **f; // 문제별 종료 배열 int **v; // 문제별 가치 배열 int **r; // 문제별 결과 r 배열 int **item; // sort 되더라도 원래 index를 찾게 하기 위한 문제별 배열 // 삽입 정렬 void selectionSort() { int i, j, q, *t; t = calloc(4, sizeof(int)); // 보기 편하게 구별함. 시작, 종료, 가치 배열을 교환해주는 매개 변수 // 5번 문제는 정렬 되지 않은 배열을 필요 for (q = 1; q < 5; q++) { if (q == 4) { // 종료 기준으로 정렬 for (i = 1; i < size; i++) { for (j = 1; j < size - i; j++) { if (s[q][j] > s[q][j + 1]) { t[0] = s[q][j]; s[q][j] = s[q][j + 1]; s[q][j + 1] = t[0]; t[1] = f[q][j]; f[q][j] = f[q][j + 1]; f[q][j + 1] = t[1]; t[2] = v[q][j]; v[q][j] = v[q][j + 1]; v[q][j + 1] = t[2]; t[3] = item[q][j]; item[q][j] = item[q][j + 1]; item[q][j + 1] = t[3]; } } } } else { // 시작 기준으로 정렬 for (i = 1; i < size; i++) { for (j = 1; j < size - i; j++) { if (f[q][j] > f[q][j + 1]) { t[0] = s[q][j]; s[q][j] = s[q][j + 1]; s[q][j + 1] = t[0]; t[1] = f[q][j]; f[q][j] = f[q][j + 1]; f[q][j + 1] = t[1]; t[2] = v[q][j]; v[q][j] = v[q][j + 1]; v[q][j + 1] = t[2]; t[3] = item[q][j]; item[q][j] = item[q][j + 1]; item[q][j + 1] = t[3]; } } } } } } // 배열 복사. from에서 to까지 n개만큼 복사하는 함수 // 복사된 함수를 반환 int *copyArray(int *to, int *from, int n) { int i = 0; for (i = 0; i < n; i++) { to[i] = from[i]; }; return to; } // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) void readFile(int argc, char *argv[]) { FILE *file; // 파일 포인터 int i; size = 0; // 문제가 5개이고 1번부터 5번까지 할당. 0번은 기본 배열 s = calloc(6, sizeof(int *)); f = calloc(6, sizeof(int *)); v = calloc(6, sizeof(int *)); r = calloc(6, sizeof(int *)); item = calloc(6, sizeof(int *)); if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } // 1부터 size까지 저장해야 하기에 size+1 할당 s[0] = calloc(size + 1, sizeof(int)); f[0] = calloc(size + 1, sizeof(int)); v[0] = calloc(size + 1, sizeof(int)); r[0] = calloc(size + 1, sizeof(int)); item[0] = calloc(size + 1, sizeof(int)); size++; // 1부터 size까지 파일의 숫자 저장 while (!feof(file)) { s[0] = realloc(s[0], (size + 1) * sizeof(int)); f[0] = realloc(f[0], (size + 1) * sizeof(int)); v[0] = realloc(v[0], (size + 1) * sizeof(int)); r[0] = realloc(r[0], (size + 1) * sizeof(int)); item[0] = realloc(item[0], (size + 1) * sizeof(int)); s[0][size] = 0; f[0][size] = 0; v[0][size] = 0; r[0][size] = 0; item[0][size] = size; // 정렬되어도 인덱스를 찾을 수 있도록 배정 fscanf(file, "%d %d %d ", &(s[0][size]), &(f[0][size]), &(v[0][size])); size++; } s[0] = realloc(s[0], (size + 1) * sizeof(int)); f[0] = realloc(f[0], (size + 1) * sizeof(int)); v[0] = realloc(v[0], (size + 1) * sizeof(int)); r[0] = realloc(r[0], (size + 1) * sizeof(int)); item[0] = realloc(item[0], (size + 1) * sizeof(int)); item[0][size] = size; s[0][size] = INF; for (i = 1; i < 6; i++) { s[i] = calloc(size + 1, sizeof(int)); f[i] = calloc(size + 1, sizeof(int)); v[i] = calloc(size + 1, sizeof(int)); r[i] = calloc(size + 1, sizeof(int)); item[i] = calloc(size + 1, sizeof(int)); s[i] = copyArray(s[i], s[0], size + 1); f[i] = copyArray(f[i], f[0], size + 1); v[i] = copyArray(v[i], v[0], size + 1); item[i] = copyArray(item[i], item[0], size + 1); } // 정렬 selectionSort(); fclose(file); } // 반복적으로 실행하는 Activity Selection // Greedy 기반 구현 // arr는 각 문제 번호 void ActivitySelectionGreedy(int arr) { int n, k, m, t; int *A = calloc(size + 1, sizeof(int)); n = size; t = 1; A[t++] = item[arr][1]; k = 1; for (m = 2; m < n; m++) { if (s[arr][m] >= f[arr][k]) { // 시작시간이 이전의 종료시간 이상인 경우 A[t++] = item[arr][m]; k = m; } } r[arr] = A; // 결과배열에 A 배정 } // 메모리 해제 void freeMem(){ int i; for (i = 0; i < 6; i++) { free(f[i]); } for (i = 0; i < 6; i++) { free(s[i]); } for (i = 0; i < 6; i++) { free(v[i]); } for (i = 0; i < 6; i++) { free(r[i]); } free(f); // 메모리 해제 free(s); // 메모리 해제 free(r); // 메모리 해제 free(v); // 메모리 해제 } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./LCS.exe sample_lcs1.txt.txt int main(int argc, char *argv[]) { int i, j; size = 0; // 개수 초기화 readFile(argc, argv); // 파일 읽어오기 printf("시작\n"); for (i = 3; i <= 5; i++) { // 3번부터 5번문제까지 Greedy 기반으로 구현한 함수 실행 ActivitySelectionGreedy(i); // 각 문제 실행결과 즉시 출력 for (j = 1; j < size; j++) { if (r[i][j] == 0) { // 기본 값이 0이고 item은 1부터이기에 0인 기본값을 만나면 count를 출력하고 반복문을 넘김 printf("\ncount : %d", (j - 1)); break; } // 각 문제의 결과를 출력 printf("%d\t", r[i][j]); } printf("\n"); } printf("\n완료"); freeMem(); return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #define INF 100000 #define MIN(A, B) ((A) < (B) ? (A) : (B)) int ***L1; // method slow int ***L2; // method fast int size; // 간선의 개수 int range; // 정점의 개수 // number에서 (vertex1, vertex2) 위치에 cost 삽입 void insert(int vertex1, int vertex2, int cost, int **number) { number[vertex1][vertex2] = cost; // 1방향이기 때문에 vertex1, vertex2 순서 중요 } // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) int **readFile(int argc, char *argv[]) { int **number; // cost를 담은 2차원 배열 int vertex1, vertex2, cost; int i, j; FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &cost); // 첫 번째 줄 데이터만 읽어오기 range = cost; // 정점 개수 // 2차원 배열 number 할당 및 초기화 number = calloc(range, sizeof(int *)); for (i = 0; i < range; i++) { number[i] = calloc(range, sizeof(int)); } for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { // 자기 자신이 아니면 if (i != j) { number[i][j] = INF; // 초기값 INF로 선언 } } } // 두번 째 데이터부터 순서대로 모두 number에 삽입 while (feof(file) == 0) { fscanf(file, "%d %d %d ", &vertex1, &vertex2, &cost); insert(vertex1, vertex2, cost, number); size++; } fclose(file); return number; } // 3차원 배열을 동적으로 할당 int ***TriArr() { int i, j; int ***arr; // 3차원 배열 할당 arr = (int ***) calloc(range, sizeof(int **)); // 각각의 2차원 배열 할당 for (i = 0; i < range; i++) { arr[i] = (int **) calloc(range, sizeof(int *)); } // 각각의 1차원 배열 할당 for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { arr[i][j] = (int *) calloc(range, sizeof(int)); } } return arr; } // 동적으로 할당 된 메모리 해제 void FreeArr() { int i, j; // 2차원 배열 개수만큼 반복 for (i = 0; i < range; i++) { // 1차원 배열 개수만큼 반복 for (j = 0; j < range; j++) { free(L1[i][j]); free(L2[i][j]); } free(L1[i]); free(L2[i]); } free(L1); free(L2); } // 2차원 배열 복사 // 복사되는 배열 arr, 복사하려는 배열 weight void arrayCopy2(int **arr, int **weight) { int *p1, *p2; int i, j; for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { p1 = &(arr[i][j]); // 복사되는 arr 위치의 포인터 p1 p2 = &(weight[i][j]); // 복사하는 weight 위치의 포인터 p2 *p1 = *p2; } } } // 최단 경로를 각 단계별로 실행 하는 함수 // 비교하려는 이전의 2차원 배열 Ln, cost들이 담겨있는 2차원 배열 W, 값 이용 및 출력값이 저장되는 2차원 배열 Lm int **ExtendShortestPaths(int **Ln, int **W, int **Lm) { int i, j, k; for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { Lm[i][j] = INF; // 출력할 배열 Lm의 기본값은 INF로 배정 for (k = 0; k < range; k++) { // Lm[i][j] 보다 Ln[i][k] + W[k][j]가 작다면 Lm[i][j]에 삽입 // 이 때 INF 보다 약간 작아진 값이 되어도 printAll에서 걸러지기 때문에 상관 없음 Lm[i][j] = MIN(Lm[i][j], Ln[i][k] + W[k][j]); } } } return Lm; } // APSP의 method 중 bellman ford와 접근법이 동일한 알고리즘 // cost가 담겨있는 2차원 배열 입력 int ***SlowAllPairsShortestPaths(int **W) { int i; // L1의 시작 2차원 배열은 W를 복사 arrayCopy2(L1[0], W); // from 2 to n-1인 반복문 for (i = 1; i < range - 1; i++) { // 새로운 단계 L1[i]에 ExtendShortestPaths 실행 L1[i] = ExtendShortestPaths(L1[i - 1], W, L1[i]); } return L1; } // APSP의 method 중 더 빠른 알고리즘 // cost가 담겨있는 2차원 배열 입력 int ***FasterAllPairsShortestPaths(int **W) { int i, max; // L2의 시작 2차원 배열은 W를 복사 arrayCopy2(L2[0], W); // 반복문을 돌릴 횟수인 max lg(n-1)의 내림 값을 추출 max = (int) (log(range - 1) / log(2)); // lg(n-1) + 1 번 반복 // 1, 2, 4, 8 대신 0부터 3까지를 사용 for (i = 1; i <= max + 1; i++) { // 새로운 단계 L2[i]에 ExtendShortestPaths 실행 L2[i] = ExtendShortestPaths(L2[i - 1], L2[i - 1], L2[i]); } return L2; } void printAll() { int i, j, k, max; // 반복문을 돌릴 횟수인 max lg(n-1)의 내림 값을 추출 max = (int) (log(range - 1) / log(2)); printf("\n"); // 값이 저장되어 있는 모든 배열 출력 // L1의 2차원 배열 for (i = 0; i < range - 1; i++) { printf("L1[%d]\n", i); // 해당 2차원 배열의 1차원 배열 for (j = 0; j < range; j++) { // 해당 1차원 배열의 원소 for (k = 0; k < range; k++) { // INF/10 보다 작다면 숫자이고 크다면 INF로 출력 if (L1[i][j][k] < (INF / 10)) { printf("%d\t", L1[i][j][k]); } else { printf("INF\t"); } } printf("\n"); } } // 위와 동일 printf("\n"); for (i = 0; i <= max + 1; i++) { printf("L2[%d]\n", i); for (j = 0; j < range; j++) { for (k = 0; k < range; k++) { if (L2[i][j][k] < (INF / 10)) { printf("%d\t", L2[i][j][k]); } else { printf("INF\t"); } } printf("\n"); } } } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./BellmanFord.exe graph_sample_directed.txt int main(int argc, char *argv[]) { int **number; // 파일에서 읽어 올 정수들 int i; size = 0; // 간선 개수 초기화 number = readFile(argc, argv); // 파일 읽어오기 L1 = TriArr(); // 3차원 배열 할당 L2 = TriArr(); // 3차원 배열 할당 printf("시작\n"); L1 = SlowAllPairsShortestPaths(number); // slow method 결과 저장 L2 = FasterAllPairsShortestPaths(number); // fast method 결과 저장 printAll(); // 출력 printf("\n완료"); // number의 메모리 해제 for (i = 0; i < range; i++) { free(number[i]); } free(number); // L1,L2의 메모리 해제 FreeArr(); return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define INF 100000 #define MAX(A, B) ((A) > (B) ? (A) : (B)) int Wi; // 정수 문제의 가방 최대값 float Wf; // 실수 문제의 가방 최대값 int size; // 가방에 들어가는 짐 개수 int *wi; // 정수 문제의 짐들 무게 float *wf; // 실수 문제의 짐들 무게 int *bi; // 정수 문제의 짐들 가치 int *bf; // 실수 문제의 짐들 가치 int **Bi; // 정수 문제의 결과 테이블 배열 int **Bf; // 실수 문제의 결과 테이블 배열 // 문제에서 요구한 배열과 값들을 미리 배정하는 함수 init // 위의 전역변수들에서 설명한 것들을 문제의 요구사항에 맞게 배정한 것이기에 자세한 설명 생략 void init() { int i; Wi = 10; Wf = 1.0; size = 7; wi = calloc(size + 1, sizeof(int)); wf = calloc(size + 1, sizeof(float)); bi = calloc(size + 1, sizeof(int)); bf = calloc(size + 1, sizeof(int)); Bi = calloc(size + 1, sizeof(int *)); for (i = 0; i <= size; i++) { Bi[i] = calloc(Wi, sizeof(int)); } Bf = calloc(size + 1, sizeof(int *)); for (i = 0; i <= size; i++) { Bf[i] = calloc(Wi, sizeof(int)); } wi[1] = 1; wi[2] = 2; wi[3] = 3; wi[4] = 3; wi[5] = 4; wi[6] = 4; wi[7] = 5; bi[1] = 1; bi[2] = 3; bi[3] = 5; bi[4] = 6; bi[5] = 8; bi[6] = 9; bi[7] = 11; wf[1] = 0.20; wf[2] = 0.15; wf[3] = 0.25; wf[4] = 0.13; wf[5] = 0.22; wf[6] = 0.27; wf[7] = 0.30; bf[1] = 3; bf[2] = 2; bf[3] = 4; bf[4] = 2; bf[5] = 3; bf[6] = 4; bf[7] = 5; } // 정수 문제의 0-1 배낭 문제 // 테이블인 B를 Bi에 저장 void KnapsackI() { int w, i; int **B; B = calloc(size + 1, sizeof(int *)); for (i = 0; i <= size; i++) { B[i] = calloc(Wi + 1, sizeof(int)); } // i는 1부터 size까지 for (i = 1; i <= size; i++) { // w는 1부터 가방의 최대값까지 for (w = 1; w <= Wi; w++) { if (wi[i] <= w) { // 무게가 w보다 작거나 같다면 if (bi[i] + B[i - 1][w - wi[i]] > B[i - 1][w]) { // 가치와 B[i - 1][w - wi[i]]의 합이 B[i - 1][w]보다 크다면 B[i][w] = bi[i] + B[i - 1][w - wi[i]]; } else { // 작다면 B[i][w] = B[i - 1][w]; } } else { // 무게가 w보다 크다면 B[i][w] = B[i - 1][w]; } } } Bi = B; } // 테이블의 해당되는 값을 출력하는 함수 void printI() { int i, j; /* * Dynamic Programming의 결과로 나온 테이블을 확인하고 싶을 경우 사용 for (j = 0; j <= Wi; j++) { for (i = 0; i <= size; i++) { printf("%d\t", Bi[i][j]); } printf("\n"); } */ printf("%d\n", Bi[size][Wi]); } // 실수 문제의 0-1 배낭 문제 // 테이블인 B를 Bf에 저장 // 100은 소수점 둘째 자리까지인 실수이기에 정수로 변환하기 위해서 곱함 void KnapsackF() { int w, i; int **B; B = calloc(size + 1, sizeof(int *)); for (i = 0; i <= size; i++) { B[i] = calloc(Wf * 100 + 1, sizeof(int)); } // i는 1부터 size까지 for (i = 1; i <= size; i++) { // w는 1부터 가방의 최대값까지 for (w = 1; w <= Wf * 100; w++) { if (wf[i] * 100 <= w) { // 무게가 w보다 작거나 같다면 if (bf[i] + B[i - 1][w - (int) (wf[i] * 100)] > B[i - 1][w]) { // 가치와 B[i - 1][w - wf[i]*100]의 합이 B[i - 1][w]보다 크다면 B[i][w] = bf[i] + B[i - 1][w - (int) (wf[i] * 100)]; } else { // 작다면 B[i][w] = B[i - 1][w]; } } else { // 무게가 w보다 크다면 B[i][w] = B[i - 1][w]; } } } Bf = B; } // 테이블의 해당되는 값을 출력하는 함수 void printF() { int i, j; /* * Dynamic Programming의 결과로 나온 테이블을 확인하고 싶을 경우 사용 for (j = 0; j <= Wf*100; j++) { for (i = 0; i <= size; i++) { printf("%.2f\t", (float)Bf[i][j]); } printf("\n"); }*/ printf("%.2f\t", (float) Bf[size][(int) Wf * 100]); } void freeMem() { free(wi); // 메모리 해제 free(bi); // 메모리 해제 free(wf); // 메모리 해제 free(bf); // 메모리 해제 free(Bi); // 메모리 해제 free(Bf); // 메모리 해제 } int main() { init(); printf("시작\n"); KnapsackI(); printI(); KnapsackF(); printF(); printf("\n완료"); freeMem(); return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> void insert(int fScore, int *number); void printAll(int *number, double timeComplexity); void MaxHeapIncreaseKey(int *number, int x, int key); void MaxHeapify(int *number, int i); void BuildMaxHeap(int *number); int HeapExtractMax(int *number); void MaxHeapInsert(int *number, int key); void MaxHeapsort(int *number); int Parent(int i); int Left(int i); int Right(int i); void swap(int *number, int a, int b); void MaxHeapIncreaseKeyNoConstraint(int *number, int x, int key); int heapTimeComplexity; int heapSize; int size; int main() { FILE *file; char *filename = "test.txt"; int fScore; double timeComplexity; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); int maxValue = 0; size = 0; heapSize = 0; heapTimeComplexity = 0; if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number); size++; } heapSize = size; fclose(file); printf("시작\n"); startTime = clock(); BuildMaxHeap(number); printAll(number, timeComplexity); MaxHeapsort(number); printAll(number, timeComplexity); maxValue = HeapExtractMax(number); printf("maxValue : %d\n", maxValue); printAll(number, timeComplexity); MaxHeapInsert(number, 99); printAll(number, timeComplexity); MaxHeapIncreaseKey(number, 3, 66); printAll(number, timeComplexity); MaxHeapIncreaseKeyNoConstraint(number, 0, 70); printAll(number, timeComplexity); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printf("실행 시간 : %f(ms) \theap 횟수 : %d \n", timeComplexity, heapTimeComplexity); printf("완료\n"); free(number); return 1; } void insert(int fScore, int *number) { number[size] = fScore; } void printAll(int *number, double timeComplexity) { int i; for (i = 0; i < heapSize; i++) { printf("%d \t", number[i]); } printf("\nheap 횟수 : %d\n", heapTimeComplexity); } void MaxHeapsort(int *number) { int i; BuildMaxHeap(number); for (i = size - 1; i > 0; i--) { swap(number, 0, i); size--; MaxHeapify(number, 0); } size = heapSize; } void BuildMaxHeap(int *number) { int i; size = heapSize; for (i = Parent(size - 1); i >= 0; i--) { MaxHeapify(number, i); } } void MaxHeapify(int *number, int i) { int lc; int rc; int largest; int bc; heapTimeComplexity++; lc = Left(i); rc = Right(i); if(lc < size){ if(rc >= size){ if(number[i] < number[lc]){ largest = lc; swap(number, i, lc); MaxHeapify(number, largest); } }else{ bc = (number[lc] > number[rc]) ? lc : rc; if(number[i] < number[bc]){ largest = bc; swap(number, i, bc); MaxHeapify(number,largest); } } } } int HeapExtractMax(int *number) { int i; int max_value; BuildMaxHeap(number); i = size - 1; max_value = number[0]; swap(number, 0, i); size--; heapSize = size; number = realloc(number, size * sizeof(int)); MaxHeapify(number, 0); return max_value; } void MaxHeapInsert(int *number, int key) { heapSize++; size++; number = realloc(number, heapSize * sizeof(int)); number[heapSize - 1] = -1; MaxHeapIncreaseKey(number, heapSize - 1, key); } void MaxHeapIncreaseKey(int *number, int x, int key) { if (key < number[x]) { printf("new key is smaller than current key"); } else { number[x] = key; while ((x > 0) && (number[Parent(x)] < number[x])) { swap(number, x, Parent(x)); x = Parent(x); } } } void MaxHeapIncreaseKeyNoConstraint(int *number, int x, int key){ if (key < number[x]) { number[x] = key; MaxHeapify(number, x); } else { number[x] = key; while ((x > 0) && (number[Parent(x)] < number[x])) { swap(number, x, Parent(x)); x = Parent(x); } } } int Parent(int i) { return floor((i - 1) / 2); } int Left(int i) { return floor((i + 1) * 2) - 1; } int Right(int i) { return floor((i + 1) * 2); } void swap(int *number, int a, int b) { int i; i = number[a]; number[a] = number[b]; number[b] = i; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> void insert(int fScore, int *number); void printAll(int *number, double timeComplexity); void MinHeapDecreaseKey(int *number, int x, int key); void MinHeapify(int *number, int i); void BuildMinHeap(int *number); int HeapExtractMin(int *number); void MinHeapInsert(int *number, int key); void MinHeapsort(int *number); void MinHeapDecreaseKeyNoConstraint(int *number, int x, int key); int Parent(int i); int Left(int i); int Right(int i); void swap(int *number, int a, int b); int heapTimeComplexity; int heapSize; int size; int main() { FILE *file; char *filename = "test.txt"; int fScore; double timeComplexity; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); int minValue = 0; size = 0; heapSize = 0; heapTimeComplexity = 0; if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number); size++; } heapSize = size; fclose(file); printf("시작\n"); startTime = clock(); BuildMinHeap(number); printAll(number, timeComplexity); MinHeapsort(number); printAll(number, timeComplexity); minValue = HeapExtractMin(number); printf("minValue : %d\n", minValue); printAll(number, timeComplexity); MinHeapInsert(number, 99); printAll(number, timeComplexity); MinHeapDecreaseKey(number, 3, 1); printAll(number, timeComplexity); MinHeapDecreaseKeyNoConstraint(number, 0, 8); printAll(number, timeComplexity); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printf("실행 시간 : %f(ms) \theap 횟수 : %d \n", timeComplexity, heapTimeComplexity); printf("완료\n"); free(number); return 1; } void insert(int fScore, int *number) { number[size] = fScore; } void printAll(int *number, double timeComplexity) { int i; for (i = 0; i < heapSize; i++) { printf("%d \t", number[i]); } printf("\nheap 횟수 : %d\n", heapTimeComplexity); } void MinHeapsort(int *number) { int i; BuildMinHeap(number); for (i = size - 1; i > 0; i--) { swap(number, 0, i); size--; MinHeapify(number, 0); } size = heapSize; } void BuildMinHeap(int *number) { int i; size = heapSize; for (i = Parent(size - 1); i >= 0; i--) { MinHeapify(number, i); } } void MinHeapify(int *number, int i) { int lc; int rc; int smallest; int sc; heapTimeComplexity++; lc = Left(i); rc = Right(i); if(lc < size){ if(rc >= size){ if(number[i] > number[lc]){ smallest = lc; swap(number, i, lc); MinHeapify(number, smallest); } }else{ sc = (number[lc] < number[rc]) ? lc : rc; if(number[i] > number[sc]){ smallest = sc; swap(number, i, sc); MinHeapify(number, smallest); } } } } int HeapExtractMin(int *number) { int i; int min_value; BuildMinHeap(number); i = size - 1; min_value = number[0]; swap(number, 0, i); size--; heapSize = size; number = realloc(number, size * sizeof(int)); MinHeapify(number, 0); return min_value; } void MinHeapInsert(int *number, int key) { heapSize++; size++; number = realloc(number, heapSize * sizeof(int)); number[heapSize - 1] = 99999; MinHeapDecreaseKey(number, heapSize - 1, key); } void MinHeapDecreaseKey(int *number, int x, int key) { if (key > number[x]) { printf("new key is bigger than current key"); } else { number[x] = key; while ((x > 0) && (number[Parent(x)] > number[x])) { swap(number, x, Parent(x)); x = Parent(x); } } } void MinHeapDecreaseKeyNoConstraint(int *number, int x, int key) { if (key > number[x]) { number[x] = key; MinHeapify(number, x); } else { number[x] = key; while ((x > 0) && (number[Parent(x)] > number[x])) { swap(number, x, Parent(x)); x = Parent(x); } } } int Parent(int i) { return floor((i - 1) / 2); } int Left(int i) { return floor((i + 1) * 2) - 1; } int Right(int i) { return floor((i + 1) * 2); } void swap(int *number, int a, int b) { int i; i = number[a]; number[a] = number[b]; number[b] = i; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #include <memory.h> #define INF 100000 int size; // 행렬의 개수 float *p; // K 정보를 갖는 배열 float *q; // D 정보를 갖는 배열 float **e, **w; // OptimalBST에서 사용되는 배열 int **root; // root가 기록되는 배열 char **result; // 출력될 OBST가 기록되는 문자열 배열 int a; // D 배열의 인덱스 // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) void readFile(int argc, char *argv[]) { int i; FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &size); // 첫 번째 줄 데이터만 읽어오기 // 1부터 size까지 저장해야 하기에 xSize+1 할당 p = calloc(size + 1, sizeof(float)); // 1부터 size까지 파일의 값 저장 for (i = 1; i <= size; i++) { fscanf(file, "%f ", &(p[i])); } // 0부터 size까지 저장해야 하기에 xSize+1 할당 q = calloc(size + 1, sizeof(float)); // 0부터 size까지 파일의 값 저장 for (i = 0; i <= size; i++) { fscanf(file, "%f ", &(q[i])); } fclose(file); } void OptimalBST(int n) { int i, l, j, r; float t; // n+1까지의 행이기에 n+2개 할당 e = calloc(n + 2, sizeof(float *)); // 1부터 n+1까지의 행에 n까지의 열을 할당 for (i = 1; i <= n + 1; i++) { e[i] = calloc(n + 1, sizeof(float)); } // n+1까지의 행이기에 n+2개 할당 w = calloc(n + 2, sizeof(float *)); // 1부터 n+1까지의 행에 n까지의 열을 할당 for (i = 1; i <= n + 1; i++) { w[i] = calloc(n + 1, sizeof(float)); } // n까지의 행이기에 n+1개 할당 root = calloc(n + 1, sizeof(int *)); // 1부터 n까지의 행에 n까지의 열을 할당 for (i = 1; i <= n; i++) { root[i] = calloc(n + 1, sizeof(int)); } // e와 w 배열 기초 값 배정 for (i = 1; i <= n + 1; i++) { e[i][i - 1] = q[i - 1]; w[i][i - 1] = q[i - 1]; } // l이 1부터 n까지 for (l = 1; l <= n; l++) { // i는 1부터 n-l+1까지 for (i = 1; i <= n - l + 1; i++) { // 각 j의 인덱스 설정 j = i + l - 1; // e의 초기값 INF 설정 e[i][j] = INF; // w[i,j]의 연산 값 저장 w[i][j] = w[i][j - 1] + p[j] + q[j]; // r은 i부터 j까지 순회 for (r = i; r <= j; r++) { // 순회하며 t값 비교 t = e[i][r - 1] + e[r + 1][j] + w[i][j]; if (t < e[i][j]) { // t가 e[i,j]보다 작다면 e[i][j] = t; // e 배열에 t 배정 root[i][j] = r; // root 배열에 r 배정 } } } } } // 왼쪽 자식을 찾는 함수 int left(int n) { return 2 * n; } // 오른쪽 자식을 찾는 함수 int right(int n) { return 2 * n + 1; } // OBST 출력을 위한 문자열 배열 생성 // 재귀적으로 작동, lc와 rc는 root의 왼쪽과 오른쪽 자식 값, i는 결과 result의 인덱스 값 void makeOBST(int lc, int rc, int i) { int r; // lc는 rc 이하, 더 크다면 해당 K재귀 정지 if (lc <= rc) { // 안전장치, i의 범위는 1부터 2의 size승 까지 if (i <= pow(2, size) && i > 0) { r = root[lc][rc]; // r은 root[rc][lc] sprintf(result[i], "k%d", r); // result[i]에 해당 k와 해당 r값 저장 makeOBST(lc, r - 1, left(i)); // 왼쪽 자식 재귀 makeOBST(r + 1, rc, right(i)); // 오른쪽 자식 재귀 } } else { // 정지 후 D 정보 삽입 sprintf(result[i], "d%d", a); // D의 인덱스 a a++; } } void printfOBST() { int i, j, k; a = 0; // a 초기화 k = 1; // result의 초기 index // result 2의 size승까지 할당 result = calloc(pow(2, size) + 1, sizeof(char *)); // 각 문자열 크기 4 할당 for (i = 0; i <= pow(2, size); i++) { result[i] = calloc(4, sizeof(char)); } // OBST 출력 배열 제작 makeOBST(1, size, 1); // OBST 출력 // size level for (i = 0; i < size; i++) { printf("D%d : ", i); // 각 행별로 2의 j승 만큼 반복 for (j = 0; j < pow(2, i); j++) { // result에 있는 문자열 존재여부 확인 if (strlen(result[k]) > 0) { // 출력 printf("%s\t", result[k++]); } else { // 없음 printf("XX\t"); } } printf("\n"); } } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./LCS.exe sample_lcs1.txt.txt int main(int argc, char *argv[]) { size = 0; // 개수 초기화 readFile(argc, argv); // 파일 읽어오기 printf("시작\n"); OptimalBST(size); // OBST 연산 printfOBST(); // OBST 출력 printf("완료"); free(p); // p 해제 free(q); // q 해제 free(e); // e 해제 free(w); // w 해제 free(root); // root 해제 free(result); // result 해제 return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> void insert(int fScore, int *number, int size); void printAll(int *number, double timeComplexity, int index); int search(int *number, int size, int searchNumber); int binarySearch(int *number, int left, int right, int searchNumber); int *sorted; int binarySearchTimeComplexity; int main() { FILE *file; //char *filename = argv[1]; char *filename = "test_recursive.txt"; int fScore; int size = 0; double timeComplexity; int searchNumber; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); binarySearchTimeComplexity = 0; int index = -1; /* if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } */ if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number, size); size++; } fclose(file); searchNumber = 1050; sorted = malloc(size * (sizeof(int))); printf("시작\n"); startTime = clock(); index = search(number, size, searchNumber); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(number, timeComplexity, index); printf("완료\n"); free(number); free(sorted); return 0; } void insert(int fScore, int *number, int size) { number[size] = fScore; } int search(int *number, int size, int searchNumber) { return binarySearch(number, 0, size, searchNumber); } int binarySearch(int *number, int left, int right, int searchNumber) { int mid = ((right - left) / 2) + left; binarySearchTimeComplexity++; if ((right - left) == 0) { return -1; } if (number[mid] > searchNumber) { return binarySearch(number, left, mid, searchNumber); } else if (number[mid] < searchNumber) { return binarySearch(number, mid, right, searchNumber); } else { return mid; } } void printAll(int *number, double timeComplexity, int index) { if (index < 0) { printf("찾으시는 숫자는 존재하지 않습니다."); } else { printf("찾는 숫자 : %d \n위치 : %d \n실행 시간 : %f(ms), 탐색 횟수 : %d \n", number[index], index, timeComplexity, binarySearchTimeComplexity); } }<file_sep>#include <stdio.h> #include <stdlib.h> #define INF 100000 #define MIN(A, B) ((A) < (B) ? (A) : (B)) int ***D; // 각 단계를 담을 3차원 배열 int size; // 간선의 개수 int range; // 정점의 개수 // number에서 (vertex1, vertex2) 위치에 cost 삽입 void insert(int vertex1, int vertex2, int cost, int **number) { number[vertex1][vertex2] = cost; // 1방향이기 때문에 vertex1, vertex2 순서 중요 } // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) int **readFile(int argc, char *argv[]) { int **number; // cost를 담은 2차원 배열 int vertex1, vertex2, cost; int i, j; FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &cost); // 첫 번째 줄 데이터만 읽어오기 range = cost; // 정점 개수 // 2차원 배열 number 할당 및 초기화 number = calloc(range, sizeof(int *)); for (i = 0; i < range; i++) { number[i] = calloc(range, sizeof(int)); } for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { // 자기 자신이 아니면 if (i != j) { number[i][j] = INF; // 초기값 INF로 선언 } } } // 두번 째 데이터부터 순서대로 모두 number에 삽입 while (feof(file) == 0) { fscanf(file, "%d %d %d ", &vertex1, &vertex2, &cost); insert(vertex1, vertex2, cost, number); size++; } fclose(file); return number; } // 3차원 배열을 동적으로 할당 int ***TriArr() { int i, j; int ***arr; // 3차원 배열 할당 arr = (int ***) calloc(range + 1, sizeof(int **)); // 각각의 2차원 배열 할당 for (i = 0; i <= range; i++) { arr[i] = (int **) calloc(range, sizeof(int *)); } // 각각의 1차원 배열 할당 for (i = 0; i <= range; i++) { for (j = 0; j < range; j++) { arr[i][j] = (int *) calloc(range, sizeof(int)); } } return arr; } // 동적으로 할당 된 메모리 해제 void FreeArr() { int i, j; // 2차원 배열 개수만큼 반복 for (i = 0; i <= range; i++) { // 1차원 배열 개수만큼 반복 for (j = 0; j < range; j++) { free(D[i][j]); } free(D[i]); } free(D); } // 2차원 배열 복사 // 복사되는 배열 arr, 복사하려는 배열 weight void arrayCopy2(int **arr, int **weight) { int *p1, *p2; int i, j; for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { p1 = &(arr[i][j]); // 복사되는 arr 위치의 포인터 p1 p2 = &(weight[i][j]); // 복사하는 weight 위치의 포인터 p2 *p1 = *p2; } } } // cost가 담겨있는 2차원 배열 입력 int ***FloydWarshall(int **W) { int i, j, k, d; // L1의 시작 2차원 배열은 W를 복사 arrayCopy2(D[0], W); printf("\n"); d = 1; // 알고리즘의 실행 단계. max : range for (k = 0; k < range; k++) { for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { // D[d - 1][i][j] 보다 D[d - 1][i][k] + D[d - 1][k][j]가 작다면 Lm[i][j]에 삽입 // 이 때 INF 보다 약간 작아진 값이 되어도 printAll에서 걸러지기 때문에 상관 없음 D[d][i][j] = MIN(D[d - 1][i][j], D[d - 1][i][k] + D[d - 1][k][j]); } } d++; } return D; } void printAll() { int i, j, k; // 값이 저장되어 있는 모든 배열 출력 // D의 2차원 배열 for (i = 0; i <= range; i++) { printf("D[%d]\n", i); // 해당 2차원 배열의 1차원 배열 for (j = 0; j < range; j++) { // 해당 1차원 배열의 원소 for (k = 0; k < range; k++) { // INF/10 보다 작다면 숫자이고 크다면 INF로 출력 if (D[i][j][k] < (INF / 10)) { printf("%d\t", D[i][j][k]); } else { printf("INF\t"); } } printf("\n"); } } } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./BellmanFord.exe graph_sample_directed.txt int main(int argc, char *argv[]) { int **number; // 파일에서 읽어 올 정수들 int i; size = 0; // 간선 개수 초기화 number = readFile(argc, argv); // 파일 읽어오기 D = TriArr(); // 3차원 배열 할당 printf("시작\n"); D = FloydWarshall(number); printAll(); // 출력 printf("\n완료"); // number의 메모리 해제 for (i = 0; i < range; i++) { free(number[i]); } free(number); // L1,L2의 메모리 해제 FreeArr(); return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> void insert(int fScore, int *number); void printAll(int *number, double timeComplexity); void CountingSort(int *number, int *result); int countingTimeComplexity; int size; int range; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./RandomQuick.exe test1.txt int main(int argc, char *argv[]) { FILE *file; char *filename = argv[1]; int fScore; double timeComplexity; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); int *result = malloc(sizeof(int)); size = 0; range = 0; countingTimeComplexity = 0; if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number); size++; } result = realloc(result, (size)*sizeof(int)); fclose(file); printf("시작\n"); startTime = clock(); CountingSort(number, result); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(result, timeComplexity); printf("완료\n"); free(number); free(result); return 1; } void insert(int fScore, int *number) { number[size] = fScore; } void printAll(int *number, double timeComplexity) { int i; for (i = 0; i < size; i++) { printf("%d \t", number[i]); } printf("\n실행 시간 : %f(ms) \tcounting 횟수 : %d \n", timeComplexity, countingTimeComplexity); } void CountingSort(int *number, int *result){ int i, num; int *histogram = calloc(1, sizeof(int)); for(i=0;i<size;i++){ num = number[i]; countingTimeComplexity++; if(num > range){ histogram = realloc(histogram, (num+1)*sizeof(int)); memset(histogram + (range+1), 0, (num-range)*sizeof(int)); range = num; } histogram[num]++; } for(i=1; i<=range; i++){ countingTimeComplexity++; histogram[i] = histogram[i] + histogram[i-1]; } for(i=size-1; i>=0; i--){ countingTimeComplexity++; result[histogram[number[i]]-1] = number[i]; histogram[number[i]]--; } free(histogram); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> typedef struct BSTs { int key; struct BSTs *p; struct BSTs *left; struct BSTs *right; } bsts; void insert(int fScore, int *number); void printAll(bsts *root, double timeComplexity); void TreeInsert(int *number, bsts **root); bsts *TreeMinimum(bsts *root); bsts *TreeMaximum(bsts *root); bsts *TreeSuccessor(bsts *root); bsts *TreePredecessor(bsts *root); int bstTimeComplexity; void InorderTreeWalk(bsts *root); int size; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./bstInsert.exe test1.txt int main(int argc, char *argv[]) { FILE *file; char *filename = argv[1]; int fScore; double timeComplexity; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); bsts *root = NULL; size = 0; bstTimeComplexity = 0; if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d\n", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number); size++; } fclose(file); TreeInsert(number, &root); printf("시작\n"); startTime = clock(); printf("RootMinimum : %d, Successor : %d\n", TreeMinimum(root)->key, TreeSuccessor(root)->key); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(root, timeComplexity); printf("완료\n"); printf("시작\n"); startTime = clock(); printf("RootMaximum : %d, Predecessor : %d\n", TreeMaximum(root)->key, TreePredecessor(root)->key); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(root, timeComplexity); printf("완료\n"); free(number); free(root); return 1; } void insert(int fScore, int *number) { number[size] = fScore; } void printAll(bsts *root, double timeComplexity) { int i; /*for (i = 0; i < size; i++) { printf("%d \t", number[i]); }*/ InorderTreeWalk(root); printf("\n실행 시간 : %f(ms) \tbst : %d \n", timeComplexity, bstTimeComplexity); } void TreeInsert(int *number, bsts **root) { int i, value; bsts **x, *y; for (i = 0; i < size; i++) { value = number[i]; x = root; y = *root; while (*x != NULL) { bstTimeComplexity++; y = *x; if (value < (*x)->key) { x = &((*x)->left); } else { x = &((*x)->right); } } *x = calloc(1, sizeof(bsts)); (*x)->p = y; (*x)->key = value; } } void InorderTreeWalk(bsts *root) { if (root != NULL) { InorderTreeWalk(root->left); printf("%d\t", root->key); InorderTreeWalk(root->right); } } bsts *TreeMinimum(bsts *root) { bsts **x; x = &root; while ((*x)->left != NULL) { x = &((*x)->left); } return *x; } bsts *TreeMaximum(bsts *root) { bsts **x; x = &root; while ((*x)->right != NULL) { x = &((*x)->right); } return *x; } bsts *TreeSuccessor(bsts *root) { bsts **x, **y; x = &root; if ((*x)->right != NULL) { return TreeMinimum((*x)->right); } y = &((*x)->p); while ((*y) != NULL && *x == (*y)->right) { x = y; y = &((*y)->p); } return *y; } bsts *TreePredecessor(bsts *root) { bsts **x, **y; x = &root; if ((*x)->left != NULL) { return TreeMaximum((*x)->left); } y = &((*x)->p); while ((*y) != NULL && *x == (*y)->left) { x = y; y = &((*y)->p); } return *y; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> typedef struct BSTs { int key; struct BSTs *p; struct BSTs *left; struct BSTs *right; } bsts; void insert(int fScore, int *number); void printAll(bsts *root, double timeComplexity); void insertionSort(int *number); void TreeInsert(int *number, bsts **root); void SortedArrayTreeInsert(int *number, bsts **root2); bsts *sortedArrayToBST(int *number, int p, int r); int bstTimeComplexity; void InorderTreeWalk(bsts *root); int size; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./bstInsert.exe test1.txt int main(int argc, char *argv[]) { FILE *file; char *filename = argv[1]; int fScore; double timeComplexity; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); bsts *root = NULL; bsts *root2 = NULL; size = 0; bstTimeComplexity = 0; if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d\n", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number); size++; } fclose(file); printf("insert\n"); startTime = clock(); TreeInsert(number, &root); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(root, timeComplexity); printf("완료\n"); bstTimeComplexity = 0; printf("insert insertion sorted array\n"); startTime = clock(); insertionSort(number); SortedArrayTreeInsert(number, &root2); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(root2, timeComplexity); printf("완료\n"); free(number); free(root); free(root2); return 1; } void insert(int fScore, int *number) { number[size] = fScore; } void printAll(bsts *root, double timeComplexity) { int i; /*for (i = 0; i < size; i++) { printf("%d \t", number[i]); }*/ InorderTreeWalk(root); printf("\n실행 시간 : %f(ms) \tinsert : %d \n", timeComplexity, bstTimeComplexity); } void TreeInsert(int *number, bsts **root) { int i, value; bsts **x, *y; for (i = 0; i < size; i++) { value = number[i]; x = root; y = *root; while (*x != NULL) { bstTimeComplexity++; y = *x; if (value < (*x)->key) { x = &((*x)->left); } else { x = &((*x)->right); } } *x = calloc(1, sizeof(bsts)); (*x)->p = y; (*x)->key = value; } } void insertionSort(int *number) { int i, j; int insertNode, curr, score; for (i = 1; i < size; i++) { insertNode = i; curr = 0; while (curr != insertNode) { if (number[curr] > number[insertNode]) { score = number[insertNode]; for (j = 0; j < (insertNode - curr); j++) { bstTimeComplexity++; number[insertNode - j] = number[insertNode - j - 1]; } number[curr] = score; break; } curr++; } } } void SortedArrayTreeInsert(int *number, bsts **root2) { *root2 = sortedArrayToBST(number, 0, size - 1); } bsts *sortedArrayToBST(int *number, int p, int r) { bsts *x, *y; int q; if (p <= r) { bstTimeComplexity++; q = p + (r - p) / 2; x = calloc(1, sizeof(bsts)); x->key = number[q]; x->left = sortedArrayToBST(number, p, q - 1); x->right = sortedArrayToBST(number, q + 1, r); y = x; if (x->left != NULL) { x->left->p = y; } if (x->right != NULL) { x->right->p = y; } return x; } else { return NULL; } } void InorderTreeWalk(bsts *root) { if (root != NULL) { InorderTreeWalk(root->left); printf("%d\t", root->key); InorderTreeWalk(root->right); } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #define INF 99999 typedef struct Vertex { int parent; int key; int vertex; } vertex; typedef struct Edge { int vertex1; int vertex2; int cost; } edge; int size; // 간선의 개수 int range; // 정점의 개수 int heapSize; // heap의 개수 int *visited; // 방문한 점의 정보 int sum; // 사용한 간선 cost 합 edge *number; // 간선들의 힙 vertex *vertexBox; // 정점들의 데이터가 담긴 박스 // 파일 읽기 (argc : 인자 개수, argv[1] 파일명 edge *readFile(int argc, char *argv[]) { int vertex1, vertex2, cost; // 간선 구조체에 들어갈 데이터 number = calloc(1, sizeof(edge)); // 간선 힙에 메모리 할당한다. FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &cost); // 첫 번째 줄 데이터만 읽어오기 range = cost; // 정점 개수 // 두번 째 데이터부터 순서대로 모두 number에 삽입 while (feof(file) == 0) { fscanf(file, "%d %d %d ", &vertex1, &vertex2, &cost); number = realloc(number, (size + 1) * sizeof(edge)); // 추가되는 간선만큼 메모리를 늘려서 할당한다. insert(vertex1, vertex2, cost, number); size++; } heapSize = size; fclose(file); BuildMinHeap(); return number; } // fScore를 마지막 number에 삽입. 함수 종료시 size 하나 증가 void insert(int vertex1, int vertex2, int cost, edge *number) { number[size].cost = cost; // 간선 구조체에 cost를 저장한다. number[size].vertex1 = vertex1; // 간선 구조체에 vertex1 정보를 저장한다. number[size].vertex2 = vertex2; // 간선 구조체에 vertex2 정보를 저장한다. } // Min Heap으로 빌드하는 함수 이전 과제를 응용한다. void BuildMinHeap() { int i; for (i = Parent(heapSize - 1); i >= 0; i--) { MinHeapify(i); } } // Min Heapify 로 해당되는 값으로 값의 위치를 바꿔준다. void MinHeapify(int i) { int lc; int rc; int smallest; int sc; lc = Left(i); rc = Right(i); if (lc < heapSize) { if (rc >= heapSize) { if (number[i].cost > number[lc].cost) { smallest = lc; swap(i, lc); MinHeapify(smallest); } } else { sc = (number[lc].cost < number[rc].cost) ? lc : rc; if (number[i].cost > number[sc].cost) { smallest = sc; swap(i, sc); MinHeapify(smallest); } } } } // 최소값을 힙에서 꺼낸다. edge ExtractMin() { int i; edge min_value; BuildMinHeap(); i = heapSize - 1; min_value = number[0]; swap(0, i); heapSize--; MinHeapify(0); return min_value; } // 부모 인덱스를 반환하는 함수 int Parent(int i) { return floor((i - 1) / 2); } // 왼쪽 자식의 인덱스를 반환하는 함수 int Left(int i) { return floor(2 * i + 1); } // 오른쪽 자식의 인덱스를 반환하는 함수 int Right(int i) { return floor(2 * i + 2); } // 힙에서 a 인덱스의 위치의 vertex와 b 인덱스의 위치의 vertex를 바꾸는 함수이다. void swap(int a, int b) { edge i; i = number[a]; number[a] = number[b]; number[b] = i; } // set을 초기화한다. void MakeSet() { int i; for (i = 0; i < range; i++) { vertexBox[i].parent = -1; vertexBox[i].key = 1; vertexBox[i].vertex = i; } } // set의 최고 부모를 찾는 걸로 같은 집합을 확인한다. 최고 부모를 반환한다. vertex *FindSet(vertex v) { int i, s; i = v.vertex; while (vertexBox[i].parent >= 0) { i = vertexBox[i].parent; // 최고 부모를 찾기 위해 i 배정을 계속 반복한다. } s = i; // 최고 부모를 s에 설정한다. i = v.vertex; // i에 다시 v를 배정한다. while (vertexBox[i].parent >= 0) { vertexBox[i].parent = s; // i의 부모를 s로 바꾼다. i = vertexBox[i].parent; } return &(vertexBox[s]); // s 정점의 포인터를 반환한다. } // u와 v가 들어있는 두 집합을 합친다. void Union(vertex *u, vertex *v) { if (u->key < v->key) { u->parent = v->vertex; // u의 부모는 v로 설정한다. v->key += u->key; // v의 key에 u key값을 더한다. } else { v->parent = u->vertex; // v의 부모는 u로 설정한다. u->key += v->key; // u의 key에 v key값을 더한다. } } void kruskal() { int selected = 0; // 선택된 간선의 갯수 vertex *u, *v; // vertex 포인터 u와 v edge e; // 간선 e MakeSet(); // union set을 초기화 while (selected < range - 1) { e = ExtractMin(); // 간선 최소값을 뽑는다. u = FindSet(vertexBox[e.vertex1]); // vertex1의 set을 u에 저장 v = FindSet(vertexBox[e.vertex2]); // vertex2의 set을 v에 저장 if (u->vertex != v->vertex) { // u와 v가 다르다면 printf("(%d,%d) %d \n", e.vertex1, e.vertex2, e.cost); // 간선의 정보를 출력한다. sum += e.cost; // sum에 cost를 더한다. selected++; // selected 증가 Union(u, v); // u와 v를 합친다. } } } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./kruskalMST.exe graph_sample.txt int main(int argc, char *argv[]) { sum = 0; size = 0; number = readFile(argc, argv); // 파일 읽어오기 visited = calloc(range, sizeof(int)); // visited를 0으로 초기화 시킨 값으로 메모리 할당한다. vertexBox = calloc(range, sizeof(vertex));// vertexBox에 메모리를 할당한다. printf("시작\n"); kruskal(); // prim알고리즘을 실행한다. printf("Sum : %d\n완료\n", sum); // 총합을 출력한다. free(number); free(visited); free(vertexBox); return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> void insert(int fScore, int* number, int size); void insertSortScore(int* number, int size); void printAll(int* number, int size); //파일 실행 옵션으로 txt파일 이름 입력 ex) ./testNumber.exe test_10.txt int main(int argc, char* argv[]) { FILE* file; char* filename = argv[1]; int fScore; int size = 0; int* number = calloc(20000, sizeof(int)); if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if((file = fopen(filename, "r")) == NULL){ printf( "파일이 열리지 않습니다.\n"); exit(1); } while(feof(file)==0) { fscanf(file, "%d ", &fScore); insert(fScore, number, size); size++; } insertSortScore(number, size); printAll(number, size); fclose(file); printf("완료\n"); free(number); return 0; } void insert(int fScore, int* number, int size){ int score = fScore; number[size] = score; } void insertSortScore(int* number, int size){ int i, j; int insertNode, curr, score; for (i = 1; i < size; i++) { insertNode = i; curr = 0; while (curr != insertNode) { if (number[curr] > number[insertNode]) { score = number[insertNode]; for(j=0; j<(insertNode-curr); j++){ number[insertNode-j] = number[insertNode-j-1]; } number[curr] = score; break; } curr++; } } } void printAll(int* number, int size){ int i; for(i=0; i<size; i++){ printf("%d \n", number[i]); } }<file_sep>#include <stdio.h> #include <stdlib.h> #define INF 100000 #define MAX(A, B) ((A) > (B) ? (A) : (B)) int size; // rod 개수 int *s; // 최고 비용 인덱스 저장 int *r; // iterative에서 결과 r 배열 // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) int *readFile(int argc, char *argv[]) { int *p; // 각 cost 배열 int i, dump; // i는 반복문 인덱스, dump는 각 행의 첫 문자 받는 용도 FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &size); // 첫 번째 줄 데이터만 읽어오기 // 1부터 size까지 저장해야 하기에 xSize+1 할당 p = calloc(size + 1, sizeof(int)); s = calloc(size + 1, sizeof(int)); // 1부터 size까지 파일의 문자 저장 for (i = 1; i <= size; i++) { fscanf(file, "%d %d ", &dump, &(p[i])); } fclose(file); return p; } // 재귀적으로 실행하는 Rod Cutting // cost 배열과 재귀적으로 돌아가는 n (초기값은 선택한 초기 막대) int CutRod(int *p, int n) { int i, q, k; // n이 0이면 함수 종료 if (n == 0) { return 0; } // q 초기값 -INF 설정 q = -INF; // i는 1부터 n까지 for (i = 1; i <= n; i++) { // k는 비교를 하기 위해서 따로 설정 // 해당 i 막대와 재귀적으로 실행한 값의 합 k = p[i] + CutRod(p, n - i); // q와 k 값 비교 if (q < k) { // k가 더 크다면 q, s[n] 저장 q = k; s[n] = i; } // q와 k값 중에서 큰 값이 q가 됨 q = MAX(q, p[i] + CutRod(p, n - i)); } return q; } // 반복적으로 실행하는 Rod Cutting // cost 배열과 반복적으로 돌아가는 막대 n void BottomUpCutRod(int *p, int n) { int i, j, q; // r 배열 n까지 할당 r = calloc(n + 1, sizeof(int)); // r[0]를 0으로 초기화 r[0] = 0; // j=1부터 n까지 반복 for (j = 1; j <= n; j++) { // q는 -INF 초기화 q = -INF; // i=1부터 j까지 반복 for (i = 1; i <= j; i++) { // q가 재귀와 같은 p[i] + r[j-1}보다 작다면 if (q < p[i] + r[j - i]) { // q 값 새로 저장 q = p[i] + r[j - i]; // s 배열에 새로운 인덱스 값 저장 s[j] = i; } } // r[j]는 q로 저장 r[j] = q; } } // cut rod 출력 메소드 // cost 배열 p와 size n 입력 void PrintCutRodSolution(int *p, int n) { int i = n; printf("\nIndex : "); // index 출력 위한 첫 번째 반복문 while (i > 0) { printf("%d ", s[i]); i = i - s[i]; } printf("\nCost : "); i = n; // cost 출력 위한 두 번째 반복문 while (i > 0) { printf("%d ", p[s[i]]); i = i - s[i]; } } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./LCS.exe sample_lcs1.txt.txt int main(int argc, char *argv[]) { int *p; int i, n; i = 4; // 재귀와 반복 두 번의 실행을 위한 n 지정 값 size = 0; // 개수 초기화 p = readFile(argc, argv); // 파일 읽어오기 printf("시작"); n = i; printf("\n재귀"); CutRod(p, n); // 재귀 연산 실행 PrintCutRodSolution(p, n); // 출력 n = i; printf("\n반복"); BottomUpCutRod(p, n); // 반복 연산 실행 PrintCutRodSolution(p, n); // 출력 printf("\n완료"); free(p); // p 메모리 해제 free(s); // s 메모리 해제 free(r); // r 메모리 해제 return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> void insert(int fScore, int *number); void printAll(int *number, double timeComplexity); int* RadixSort(int *number); int* CountingSort(int *number, int digit); int countingTimeComplexity; int radixTimeComplexity; int size; int range; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./RandomQuick.exe test1.txt int main(int argc, char *argv[]) { FILE *file; char *filename = argv[1]; int fScore; double timeComplexity; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); size = 0; range = 0; countingTimeComplexity = 0; radixTimeComplexity = 0; if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d\n", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number); size++; } fclose(file); printf("시작\n"); startTime = clock(); number = RadixSort(number); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(number, timeComplexity); printf("완료\n"); free(number); return 1; } void insert(int fScore, int *number) { number[size] = fScore; } void printAll(int *number, double timeComplexity) { int i; for (i = 0; i < size; i++) { printf("%d \t", number[i]); } printf("\n실행 시간 : %f(ms) \tcounting 횟수 : %d \tradix 횟수 : %d \n", timeComplexity, countingTimeComplexity, radixTimeComplexity); } int* RadixSort(int *number) { int digit; for(digit = 0; digit < 4; digit++){ radixTimeComplexity++; number = CountingSort(number, (digit * 8)); printAll(number, 0); } return number; } int* CountingSort(int *number, int digit) { int i, num; int *histogram = calloc(256, sizeof(int)); int *result = calloc(size, sizeof(int)); for (i = 0; i < size; i++) { num = (number[i] >> digit) % 256; countingTimeComplexity++; if (num > range) { range = num; } histogram[num]++; } for (i = 1; i <= range; i++) { countingTimeComplexity++; histogram[i] = histogram[i] + histogram[i - 1]; } for (i = size - 1; i >= 0; i--) { countingTimeComplexity++; result[--histogram[(number[i] >> digit) % 256]] = number[i]; } free(histogram); return result; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> void insert(int fScore, int *number); void printAll(int *number, double timeComplexity); int RandomizedSelect(int *number, int p, int r, int i); int Partition(int *number, int p, int r); int PivotSelection(int *number, int p, int r); void swap(int *number, int a, int b); int quickTimeComplexity; int size; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./RandomQuick.exe test1.txt int main(int argc, char *argv[]) { FILE *file; char *filename = argv[1]; int fScore; double timeComplexity; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); size = 0; quickTimeComplexity = 0; int i = 6; // i번째로 큰 값 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d\n", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number); size++; } fclose(file); printf("시작\n"); startTime = clock(); printf("%d\n", RandomizedSelect(number, 0, size - 1, size - i + 1)); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(number, timeComplexity); printf("완료\n"); free(number); return 1; } void insert(int fScore, int *number) { number[size] = fScore; } void printAll(int *number, double timeComplexity) { int i; for (i = 0; i < size; i++) { printf("%d \t", number[i]); } printf("\n실행 시간 : %f(ms) \tquick 횟수 : %d \n", timeComplexity, quickTimeComplexity); } int RandomizedSelect(int *number, int p, int r, int i) { int q; int k; if (p < r) { q = Partition(number, p, r); k = q - p + 1; if (i == k) return number[q]; if (i < k) { RandomizedSelect(number, p, q - 1, i); } else { RandomizedSelect(number, q + 1, r, i - k); } } else { return number[p]; } } int Partition(int *number, int p, int r) { int x; int i = p - 1; int j; int selectNumber; selectNumber = PivotSelection(number, p, r); x = number[selectNumber]; number[selectNumber] = number[r]; number[r] = x; for (j = p; j < r; j++) { quickTimeComplexity++; if (number[j] <= x) { i++; swap(number, i, j); } } swap(number, i + 1, r); return i + 1; } int PivotSelection(int *number, int p, int r) { int i, j, index; int flag[3] = {0}; int median[3] = {-1, -1, -1}; int range = r - p + 1; int medianSize = (int) ceil((float) range / 5.0); int *medianArray = calloc(medianSize, sizeof(int)); int medianOfMedian = (int) (ceil((float) medianSize / 2.0)) - 1; for (i = 0; i < medianSize; i++) { for (j = 0; j < 5; j++) { index = p + (5 * i) + j; if ((index <= r) && (number[index] < number[median[0]] || median[0] == -1)) { if (number[index] < number[median[1]] || median[1] == -1) { if (number[index] < number[median[2]] || median[2] == -1) { median[0] = median[1]; median[1] = median[2]; median[2] = index; flag[2] = 1; } else { median[0] = median[1]; median[1] = index; flag[1] = 1; } } else { median[0] = index; flag[0] = 1; } } } medianArray[i] = median[3-flag[2]-flag[1]-flag[0]]; median[0] = -1; median[1] = -1; median[2] = -1; flag[0] = 0; flag[1] = 0; flag[2] = 0; } for (i = 0; i < medianSize - 1; i++) { for (j = i + 1; j < medianSize; j++) { if (number[medianArray[i]] > number[medianArray[j]]) { index = medianArray[i]; medianArray[i] = medianArray[j]; medianArray[j] = index; } } } return medianArray[medianOfMedian]; } void swap(int *number, int a, int b) { int i; if (number[a] > number[b]) { i = number[a]; number[a] = number[b]; number[b] = i; } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> typedef struct BucketList { float data; struct BucketList *next; } bucketList; typedef bucketList *pList; void insert(float fScore, float *number); void printAll(pList **pBox, double timeComplexity); void printList(pList *list); void BucketSort(float *number, pList **pBox); void insertionSort(pList *ml); pList *findIndex(pList *ml, int i); int bucketTimeComplexity; int size; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./BucketSort.exe test1.txt int main(int argc, char *argv[]) { FILE *file; char *filename = argv[1]; float fScore; double timeComplexity; time_t startTime = 0, endTime = 0; float *number = malloc(sizeof(float)); pList *pBox; size = 0; bucketTimeComplexity = 0; if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%f\n", &fScore); number = realloc(number, (size + 1) * sizeof(float)); insert(fScore, number); size++; } fclose(file); printf("시작\n"); BucketSort(number, &pBox); startTime = clock(); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(&pBox, timeComplexity); printf("완료\n"); free(number); free(pBox); return 1; } void insert(float fScore, float *number) { number[size] = fScore; } void printAll(pList **pBox, double timeComplexity) { int i; for (i = 0; i < size; i++) { printList(&((*pBox)[i])); } printf("\n실행 시간 : %f(ms) \tbucket 횟수 : %d \n", timeComplexity, bucketTimeComplexity); } void printList(pList *list) { pList *ml = list; if ((*ml) != NULL) { while ((*ml)->next != NULL) { printf("%.3f\t", (*ml)->data); ml = &((*ml)->next); } printf("%.3f\n", (*ml)->data); } printf("/\n"); } void BucketSort(float *number, pList **pBox) { int i; pList *ml = NULL; (*pBox) = malloc(size * sizeof(pList)); for (i = 0; i < size; i++) { (*pBox)[i] = NULL; } for (i = 0; i < size; i++) { ml = &(*pBox)[(int) floor(((float) size) * number[i])]; if ((*ml) == NULL) { (*ml) = realloc((*ml), sizeof(bucketList)); (*ml)->data = number[i]; (*ml)->next = NULL; } else { while ((*ml)->next != NULL) { ml = &((*ml)->next); } (*ml)->next = realloc((*ml)->next, sizeof(bucketList)); (*ml)->next->data = number[i]; (*ml)->next->next = NULL; } } for (i = 0; i < size; i++) { insertionSort(&((*pBox)[i])); } } void insertionSort(pList *ml) { int i, j; pList *curr; pList *node; node = ml; int c; float num; if ((*ml) != NULL) { for (i = 1; (*node)->next != NULL; i++) { node = &((*node)->next); curr = ml; c = 0; while ((*curr) != (*node)) { if ((*curr)->data > (*node)->data) { num = (*node)->data; for (j = 0; j < (i - c); j++) { (*findIndex(ml, i - j))->data = (*findIndex(ml, i - j - 1))->data; } (*curr)->data = num; break; } curr = &((*curr)->next); c++; } } } } pList *findIndex(pList *ml, int i) { int index; pList *ptr = ml; for (index = 0; index < i; index++) { ptr = &((*ptr)->next); } return ptr; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> typedef struct BSTs { int key; struct BSTs *p; struct BSTs *left; struct BSTs *right; } bsts; void insert(int fScore, int *number); void printAll(bsts *root, double timeComplexity); void TreeInsert(int *number, bsts **root); bsts *SearchR(bsts *root, int k); bsts *SearchI(bsts *root, int k); int bstTimeComplexity; void InorderTreeWalk(bsts *root); int size; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./bstInsert.exe test1.txt int main(int argc, char *argv[]) { FILE *file; char *filename = argv[1]; int fScore; double timeComplexity; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); int findNumber = 5; bsts *root = NULL; size = 0; bstTimeComplexity = 0; if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d\n", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number); size++; } fclose(file); TreeInsert(number, &root); printf("SearchR : %d\n", findNumber); startTime = clock(); if (SearchR(root, findNumber) != NULL) { printf("있음\n"); } else { printf("없음\n"); } endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(root, timeComplexity); printf("완료\n"); bstTimeComplexity = 0; printf("SearchI : %d\n", findNumber); startTime = clock(); if (SearchI(root, findNumber) != NULL) { printf("있음\n"); } else { printf("없음\n"); } endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(root, timeComplexity); printf("완료\n"); free(number); free(root); return 1; } void insert(int fScore, int *number) { number[size] = fScore; } void printAll(bsts *root, double timeComplexity) { int i; /*for (i = 0; i < size; i++) { printf("%d \t", number[i]); }*/ InorderTreeWalk(root); printf("\n실행 시간 : %f(ms) \tbstTimeComplexity : %d \n", timeComplexity, bstTimeComplexity); } void TreeInsert(int *number, bsts **root) { int i, value; bsts **x, *y; for (i = 0; i < size; i++) { value = number[i]; x = root; y = *root; while (*x != NULL) { y = *x; if (value < (*x)->key) { x = &((*x)->left); } else { x = &((*x)->right); } } *x = calloc(1, sizeof(bsts)); (*x)->p = y; (*x)->key = value; } } void InorderTreeWalk(bsts *root) { if (root != NULL) { InorderTreeWalk(root->left); printf("%d\t", root->key); InorderTreeWalk(root->right); } } bsts *SearchR(bsts *root, int k) { bsts *x; x = root; if (x == NULL || k == x->key) { return x; } bstTimeComplexity++; if (k < x->key) { return SearchR(root->left, k); } else { return SearchR(root->right, k); } } bsts *SearchI(bsts *root, int k) { bsts **x; x = &root; while (*x != NULL && k != (*x)->key) { bstTimeComplexity++; if (k < (*x)->key) { x = &((*x)->left); } else { x = &((*x)->right); } } return *x; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #define INF 99999 // 정점의 데이터들을 갖고 있는 구조체 typedef struct Vertex { int key; int vertex; int pi; } vertex; int input; // 시작 정점 int size; // 간선의 개수 int range; // 정점의 개수 int heapSize; // 현재 heap 개수 int *visited; // 방문한 정점 체크 배열 vertex *vertexBox; // 정점 구조체 배열 // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) int **readFile(int argc, char *argv[]) { int vertex1, vertex2, cost, i, j; int **number; // cost를 담은 2차원 배열 FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &cost); // 첫 번째 줄 데이터만 읽어오기 range = cost; // 정점 개수 heapSize = range; number = calloc(range, range * sizeof(int)); for (i = 0; i < range; i++) { number[i] = realloc(number[i], range * sizeof(int)); } for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { number[i][j] = INF; // 초기값 INF로 선언 } } // 두번 째 데이터부터 순서대로 모두 number에 삽입 while (feof(file) == 0) { fscanf(file, "%d %d %d ", &vertex1, &vertex2, &cost); insert(vertex1, vertex2, cost, number); size++; } fclose(file); return number; } // number에서 (vertex1, vertex2) 위치에 cost 삽입 void insert(int vertex1, int vertex2, int cost, int **number) { number[vertex1][vertex2] = cost; // 1방향이기 때문에 vertex1, vertex2 순서 중요 } // 힙에서 i의 부모인덱스 찾는 함수 int Parent(int i) { return (int) floor((i - 1) / 2); } // 힙에서 i의 왼쪽자식 인덱스 찾는 함수 int Left(int i) { return (int) floor(2 * i + 1); } // 힙에서 i의 오른쪽자식 인덱스 찾는 함수 int Right(int i) { return (int) floor(2 * i + 2); } // 힙에서 a인덱스와 b인덱스 위치의 데이터를 교환하는 함수 void swap(int a, int b) { vertex i; i = vertexBox[a]; vertexBox[a] = vertexBox[b]; vertexBox[b] = i; } // i에서 최소 힙을 찾아 맞추는 함수 void MinHeapify(int i) { int lc; int rc; int smallest; int sc; lc = Left(i); rc = Right(i); if (lc < heapSize) { if (rc >= heapSize) { if (vertexBox[i].key > vertexBox[lc].key) { smallest = lc; swap(i, lc); MinHeapify(smallest); } } else { sc = (vertexBox[lc].key < vertexBox[rc].key) ? lc : rc; if (vertexBox[i].key > vertexBox[sc].key) { smallest = sc; swap(i, sc); MinHeapify(smallest); } } } } // 최소 힙으로 빌드하는 함수 void BuildMinHeap() { int i; for (i = Parent(heapSize - 1); i >= 0; i--) { MinHeapify(i); } } // 힙에서 최소값을 꺼내는 함수 vertex *ExtractMin() { int i; vertex *min_value; BuildMinHeap(); i = heapSize - 1; swap(0, i); min_value = &(vertexBox[i]); // 교환을 미리 수행한 다음에 i 위치 저장 heapSize--; MinHeapify(0); return min_value; // vertexBox[i]의 주소 반환 } // u 정점과 v정점과 cost가 담긴 2차원 배열을 입력받아 key 입력을 하는 함수 void Relax(vertex *u, vertex *v, int **number) { // v의 key가 u의 key와 (u,v)의 cost의 합보다 크다면 v의 key에 해당 값 삽입 if (v->key > u->key + number[u->vertex][v->vertex]) { v->key = u->key + number[u->vertex][v->vertex]; v->pi = u->vertex; // v의 부모 인덱스를 u로 설정 } } // heap으로 순서가 섞인 vertexBox에서 입력받은 num에 해당하는 배열에서의 정점 위치를 반환하는 함수 int findVertex(int num) { int i; // i가 0부터 정점의 개수만큼 반복 for (i = 0; i < range; i++) { // vertexBox에서 i인덱스의 정점 값이 찾는 값과 같다면 i반환 if (vertexBox[i].vertex == num) { return i; } } // 못 찾은 경우 return i; } // Relax에서 배정한 pi를 이용하여 i 정점의 부모 정점을 재귀적으로 출력 void printShortestPath(vertex i) { // i의 부모 정점이 시작 정점인지 확인 if (i.pi != input) { // 부모 정점이 시작 정점이 아닌 다른 정점이므로 재귀적 실행 printShortestPath(vertexBox[findVertex(i.pi)]); // 재귀 수행 후 i 정점 출력 printf("%d ", i.vertex); } else { // 부모 정점이 시작 정점인 경우 i 정점 출력 printf("%d ", i.vertex); } } // vertex와 cost를 출력하는 함수 void printAll() { int i; printf("Vertex \t| Cost\n"); // 정점의 개수만큼 반복 for (i = 0; i < range; i++) { // 위에서 설명한 findVertex를 이용하여, 보기좋게 i와 i의 key부터 출력 printf("%d \t\t| %d \t\t| 0 ", i, vertexBox[findVertex(i)].key); // 최단경로를 출력하는 함수 printShortestPath(vertexBox[findVertex(i)]); printf("\n"); } } // Dijkstra함수 cost가 담긴 2차원 배열 number가 입력 됨 void Dijkstra(int **number) { int i; vertex *u, *v; // 정점 개수만큼 반복 for (i = 0; i < range; i++) { // vertexBox[i]에서 vertex 정보를 배정 vertexBox[i].vertex = i; // vertexBox[i]에서 key의 초기값 INF 배정 vertexBox[i].key = INF; } // 시작 정점의 key에 0 배정 vertexBox[input].key = 0; // heap이 끝이 날 때까지 (모든 정점) while (heapSize > 0) { u = ExtractMin(); // key값이 제일 적은 정점 추출하여 u에 배정 visited[u->vertex] = 1; // 정점 u를 방문한 정점으로 수정 // 정점 개수만큼 반복 for (i = 0; i < range; i++) { v = &(vertexBox[findVertex(i)]); // v에 index i에 해당하는 정점 배정 // i인덱스에 방문한 적이 없으며, if (visited[i] == 0) { // 시작 정점에서 u에 갈 방안이 있으며, if (u->key != INF) { // 간선이 존재할 경우 if (number[u->vertex][v->vertex] != INF) { Relax(u, v, number); // Relax 함수 실행 } } } } } printAll(); // 출력 } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./Dijkstra.exe graph_sample_directed.txt int main(int argc, char *argv[]) { int **number; // 파일에서 읽어 올 정수들 input = 0; // 시작 정점 size = 0; // 간선 개수 초기화 number = readFile(argc, argv); // 파일 읽어오기 vertexBox = calloc(range, sizeof(vertex)); // 정점 배열 초기화 visited = calloc(range, sizeof(int)); // 방문 배열 초기화 printf("시작\n"); Dijkstra(number); // Dijkstra 실행 printf("완료\n"); free(number); free(vertexBox); free(visited); return 1; } <file_sep>#include <stdio.h> #include <stdlib.h> typedef struct _student { int studentNumber; int score; struct _student *PREV; struct _student *NEXT; } student; void insert(int fStudentNumber, int fScore, student *tail); void insertSortScore(student *head, int size); void insertSortStudentNumber(student *head, int size); void printAll(student *head, student *tail); //파일 실행 옵션으로 txt파일 이름 입력 ex) ./testStudent.exe test1.txt int main(int argc, char *argv[]) { FILE *file; char *filename = argv[1]; int fScore; int fStudentNumber; int size = 0; student *head = malloc(sizeof(student)); student *tail = malloc(sizeof(student)); if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } head->NEXT = tail; tail->PREV = head; while (feof(file) == 0) { fscanf(file, "%d %d ", &fStudentNumber, &fScore); insert(fStudentNumber, fScore, tail); size++; } // 점수 기준 오름차순 insertSortScore(head, size); printAll(head, tail); printf("\n"); // 학번 기준 오름차순 insertSortStudentNumber(head, size); printAll(head, tail); fclose(file); printf("완료\n"); free(head); free(tail); return 0; } void insert(int fStudentNumber, int fScore, student *tail) { student *insertNode = malloc(sizeof(student)); insertNode->studentNumber = fStudentNumber; insertNode->score = fScore; insertNode->PREV = tail->PREV; insertNode->NEXT = tail; tail->PREV->NEXT = insertNode; tail->PREV = insertNode; } void insertSortScore(student *head, int size) { student *insertNode; int i, j; for (i = 1; i < size; i++) { insertNode = head->NEXT; for (j = 0; j < i; j++) { insertNode = insertNode->NEXT; } student *curr = head->NEXT; while (curr != insertNode) { if (curr->score > insertNode->score) { insertNode->PREV->NEXT = insertNode->NEXT; insertNode->NEXT->PREV = insertNode->PREV; insertNode->NEXT = curr; insertNode->PREV = curr->PREV; curr->PREV->NEXT = insertNode; curr->PREV = insertNode; break; } curr = curr->NEXT; } } } void insertSortStudentNumber(student *head, int size) { student *insertNode; int i, j; for (i = 1; i < size; i++) { insertNode = head->NEXT; for (j = 0; j < i; j++) { insertNode = insertNode->NEXT; } student *curr = head->NEXT; while (curr != insertNode) { if (curr->studentNumber > insertNode->studentNumber) { insertNode->PREV->NEXT = insertNode->NEXT; insertNode->NEXT->PREV = insertNode->PREV; insertNode->NEXT = curr; insertNode->PREV = curr->PREV; curr->PREV->NEXT = insertNode; curr->PREV = insertNode; break; } curr = curr->NEXT; } } } void printAll(student *head, student *tail) { student *curr = head->NEXT; while (curr != tail) { printf("%d %d\n", curr->studentNumber, curr->score); curr = curr->NEXT; } }<file_sep>#include <stdio.h> #include <stdlib.h> #define INF 1000000 int size; // 행렬의 개수 int **m, **s; // m은 cost가 담기는 배열, s는 최적 수가 담기는 배열 // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) int *readFile(int argc, char *argv[]) { int *p; // cost를 담은 2차원 배열 int i; FILE *file; // 파일 포인터 i = 0; if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &size); // 첫 번째 줄 데이터만 읽어오기 // 배열 p 할당 및 초기화 // 0부터 n까지를 size로 받은 것이기에 할당 시 size+1만큼 할당 p = calloc(size + 1, sizeof(int)); // 순서대로 모두 p에 삽입 while (feof(file) == 0) { fscanf(file, "%d ", &(p[i++])); } fclose(file); return p; } // 행렬의 최적 곱셈 cost 연산하는 함수 void MatrixChainOrder(int *p) { int n = size; // 0부터 n개 까지에서의 n int i, j, k, l, q; // m의 범위는 [1..n][1..n]이기에 n까지의 행을 위해서 n+1을 할당 m = calloc(n + 1, sizeof(int *)); // 1부터 n까지 행에서 n까지의 열을 할당 for (i = 1; i < n + 1; i++) { m[i] = calloc(n + 1, sizeof(int)); } // s의 범위는 [1..n-1][2..n]이기에 n-1까지의 행을 위해서 n을 할당 s = calloc(n, sizeof(int *)); // 1부터 n-1까지 행에서 n까지의 열을 할당 for (i = 1; i < n; i++) { s[i] = calloc(n + 1, sizeof(int)); } // calloc으로 할당 했기에 필요없지만 i,i를 0으로 초기화 for (i = 1; i <= n; i++) { m[i][i] = 0; } // l은 체인 길이인데 2부터 n까지 증가 for (l = 2; l <= n; l++) { // i는 1부터 n-l+1까지 증가 // 해당 체인 길이에 대한 조합이 존재할 경우 반복 for (i = 1; i <= n - l + 1; i++) { j = i + l - 1; // i,j를 비교를 위해 무한대로 설정 m[i][j] = INF; // k를 기준으로 구간별로 나눔 for (k = i; k <= j - 1; k++) { // 해당 행렬 곱 연산에서 cost를 계산하여 q에 저장 q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; // q가 기존의 i,j 보다 작거나 기존의 i,j가 무한대라면 내부 실행 if (q < m[i][j]) { m[i][j] = q; // cost 저장 s[i][j] = k; // 더 적은 cost를 갖는 k 저장 } } } } } // 재귀적으로 s 배열의 최적 cost 값을 갖는 기준 k값을 출력 void PrintOptimalParens(int i, int j) { // i와 j가 같아지는 경우 실행 if (i == j) { printf("%d ", i); } else { // 같지 않은 경우 // 최적 cost가 되는 위치를 이용하여 재귀적으로 실행 printf("( "); PrintOptimalParens(i, s[i][j]); PrintOptimalParens(s[i][j] + 1, j); printf(") "); } } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./MatrixChain.exe sample_mat1.txt int main(int argc, char *argv[]) { int *p; // 파일에서 읽어 올 정수들 size = 0; // 행렬 개수 초기화 p = readFile(argc, argv); // 파일 읽어오기 printf("시작\n"); MatrixChainOrder(p); // 계산 실행 PrintOptimalParens(1, size); // 결과 출력 printf("\ncost : %d", m[1][size]); // cost 출력 printf("\n완료"); free(p); // p 메모리 해제 free(m); // m 메모리 해제 free(s); // s 메모리 해제 return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct Item { int data; struct Item *next; } item; typedef item *pItem; typedef struct UU { int d; int color; struct UU *pi; } U; typedef struct Queue { int qSize; struct Item *front; struct Item *rear; } queue; int *readFile(int argc, char *argv[]); void insert(int fScore, int *number); void printAll(pItem **pBox, double timeComplexity); void printList(pItem *list); pItem *makeAdj(int *number, pItem **pBox); void enqueue(int data); int dequeue(); void BFS(pItem *pBox, int index); int bstTimeComplexity; int adjTimeComplexity; int size; int range; queue *myQ; U *visited; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./DFS.exe test1.txt int main(int argc, char *argv[]) { double timeComplexity; // 실행 시간 int *number; // 파일에서 읽어 올 정수들 pItem *pBox; // 인접행렬을 담을 포인터배열 int i = 1; time_t startTime = 0, endTime = 0; size = 0; range = 0; bstTimeComplexity = 0; // bst 실행 횟수 체크 adjTimeComplexity = 0; // 인접행렬 생성 횟수 체크 myQ = calloc(1, sizeof(queue)); // 큐 생성 number = readFile(argc, argv); // 파일 읽어오기 pBox = makeAdj(number, &pBox); // 인접행렬 형성 printf("시작\n"); startTime = clock(); BFS(pBox, i); // i에서 부터 BFS 실행 endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; // 단위 상승 (*1000) printAll(&pBox, timeComplexity); // 저장된 인접행렬 체크 및 시간복잡도 체크 printf("완료\n"); free(number); free(pBox); free(myQ); return 1; } // 파일 읽기 (argc : 인자 개수, argv[1] 파일명 int *readFile(int argc, char *argv[]) { int *number = malloc(sizeof(float)); int fScore; FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &fScore); // 첫 번째 줄 데이터만 읽어오기 range = fScore; // 정점 개수 visited = calloc(range, sizeof(U)); // 각 정점의 데이터가 담긴 구조체 생성 및 초기화 // 두번 째 데이터부터 순서대로 모두 number에 삽입 while (feof(file) == 0) { fscanf(file, "%d ", &fScore); number = realloc(number, (size + 1) * sizeof(float)); insert(fScore, number); size++; } fclose(file); return number; } // fScore를 마지막 number에 삽입. 함수 종료시 size 하나 증가 void insert(int fScore, int *number) { number[size] = fScore; } // 실행 횟수, 실행 시간을 출력하고, 인접행렬을 printList를 활용하여 출력 void printAll(pItem **pBox, double timeComplexity) { int i; printf("\n실행 시간 : %f(ms) \tBFS : %d \tadj : %d \n", timeComplexity, bstTimeComplexity, adjTimeComplexity); for (i = 0; i < range; i++) { // 각 인접 행렬의 행들을 배열의 인덱스로 하여 printList 실행 printList(&((*pBox)[i])); } } // 인접 행렬의 각 행을 출력하는 함수 // ml은 현재 포인터가 가리키는 노드 void printList(pItem *list) { pItem *ml = list; if ((*ml) != NULL) { while ((*ml)->next != NULL) { printf("%d\t", (*ml)->data); ml = &((*ml)->next); } printf("%d\t", (*ml)->data); } printf("/\n"); } // 인접행렬을 포인터 배열형태로 생성하는 함수 pItem *makeAdj(int *number, pItem **pBox) { int i, j; pItem *ml = NULL; (*pBox) = malloc(range * sizeof(pItem)); // 각 행들에 메모리 할당 for (i = 0; i < range; i++) { (*pBox)[i] = NULL; // 각 행들의 초기화 } for (j = 0; j < range; j++) { for (i = 0; i < range; i++) { adjTimeComplexity++; ml = &(*pBox)[j]; // 각 행들별로 노드를 가리키는 포인터 설정 if (number[j * range + i] == 1) { // 각 행에서 1인 값만 링크드리스트로 추가 if ((*ml) == NULL) { // 현재 행이 NULL로 비어있을 때 (*ml) = realloc((*ml), sizeof(item)); (*ml)->data = i; // 이 때 노드에 해당 정점을 입력하기 위해 그냥 i를 사용 (*ml)->next = NULL; } else { // 현재 행에 값이 있을때 마지막 위치로 포인터 설정 while ((*ml)->next != NULL) { ml = &((*ml)->next); } (*ml)->next = realloc((*ml)->next, sizeof(item)); (*ml)->next->data = i; (*ml)->next->next = NULL; } } } } return *pBox; } // 큐에 정수를 삽입하는 함수 void enqueue(int data) { item *temp = calloc(1, sizeof(item)); // 초기값을 갖는 item 포인터 temp 생성 temp->data = data; // item의 값에 주어진 값 설정 // 큐에 들어있는 값이 없을 때 if (myQ->qSize == 0) { myQ->front = temp; // 제일 앞을 temp로 변경 myQ->rear = temp; // 제일 뒤 또한 temp로 변경 } else { // 큐에 값이 이미 있을 때 myQ->rear->next = temp; // 제일 뒤의 다음을 temp로 연결 myQ->rear = temp; // 제일 뒤를 temp로 설정 } myQ->qSize = myQ->qSize + 1; // 큐의 사이즈 1증가 } // 큐에서 가장 앞에 있던 정수 추출하는 함수 int dequeue() { item *temp = myQ->front; // item 포인터 temp를 큐의 제일 앞 노드로 설정 int data; // 추출할 노드의 데이터 (반환 값) if (myQ->qSize != 0) { // 큐에 들어 있어야 추출 가능 myQ->qSize = myQ->qSize - 1; // 사이즈 1감소 data = temp->data; // 반환 할 data에 temp의 데이터 설정 myQ->front = myQ->front->next; // 제일 앞 노드에서 그 다음 노드로 포인터 설정 변경 if (myQ->front == NULL) { // 추출한 뒤에 큐에 남아있는 노드가 없다면 맨 뒤 포인터 또한 NULL로 초기화 myQ->rear = NULL; } free(temp); return data; } } // BFS 함수 (pdf 수도코드 기반). 인접행렬 pBox와 처음 해당 index를 인자로 받음 void BFS(pItem *pBox, int index) { int i, u; // i는 반복문에 사용, u는 큐에서 추출한 정점 저장 pItem *ml = NULL; // 인접행렬을 확인할 포인터 for (i = 0; i < range; i++) { // 각 정점 구조체 배열을 초기화 if (i != index) { visited[i].d = 10000; } bstTimeComplexity++; } visited[index].color = 1; // 회색 대신 숫자 사용. white : 0, black : 2 visited[index].d = 0; // 확인된 정점의 초기설정 enqueue(index); // 큐에 정점 삽입 while (myQ->qSize != 0) { u = dequeue(); // 추출한 정수 u로 사용 bstTimeComplexity++; printf("%d\t", u); ml = &(pBox[u]); // 추출한 정수 인접 행 포인터 설정 while ((*ml) != NULL) { bstTimeComplexity++; if (visited[(*ml)->data].color == 0) { visited[(*ml)->data].color = 1; // 색 변경 visited[(*ml)->data].d = visited[u].d + 1; // d 1증가 visited[(*ml)->data].pi = &(visited[u]); // 연결된 부모 노드 설정 enqueue((*ml)->data); // 해당 정점 큐에 삽입 } ml = &((*ml)->next); } visited[u].color = 2; // u의 color black으로 변경 } }<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> void insert(int fScore, int size); void sortScore(int size, int n); void printAll(int size, double timeComplexity); void sort(int left, int right, int n); void mergeSort(int left, int mid, int right); void insertSort(int left, int right); int *number; int *sorted; int mergeTimeComplexity; int insertTimeComplexity; int main() { FILE *file; //char *filename = argv[1]; char *filename = "test_10000.txt"; int fScore; int size = 0; double timeComplexity; time_t startTime = 0, endTime = 0; number = malloc(sizeof(int)); mergeTimeComplexity = 0; insertTimeComplexity = 0; int n = 4; /* if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } */ if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, size); size++; } fclose(file); sorted = malloc(size * (sizeof(int))); printf("시작\n"); startTime = clock(); sortScore(size, n); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(size, timeComplexity); printf("완료\n"); free(number); free(sorted); return 0; } void insert(int fScore, int size) { number[size] = fScore; } void sortScore(int size, int n) { sort(0, size, n); } void sort(int left, int right, int n) { int mid; if ((right - left) > 1) { mid = (left + right) / 2; sort(left, mid, n); sort(mid, right, n); if ((right - left) > n) { mergeSort(left, mid, right); } else { insertSort(left, right); } } } void mergeSort(int left, int mid, int right) { int i, j, k; i = left; j = mid; mergeTimeComplexity++; for (k = left; (i < mid && j < right); k++) { if (number[i] < number[j]) { sorted[k] = number[i++]; } else { sorted[k] = number[j++]; } } if (i == mid) { memcpy((sorted + k), (number + j), (right - j) * sizeof(int)); } else { memcpy((sorted + k), (number + i), (mid - i) * sizeof(int)); } //printf("디버깅 left=%d mid=%d right=%d \n", left, mid, right); memcpy((number + left), (sorted + left), (right - left) * sizeof(int)); } void insertSort(int left, int right) { int i, j; int insertNode, curr, score; insertTimeComplexity++; for (i = left + 1; i < right; i++) { insertNode = i; curr = left; while (curr != insertNode) { if (number[curr] > number[insertNode]) { score = number[insertNode]; for (j = 0; j < (insertNode - curr); j++) { number[insertNode - j] = number[insertNode - j - 1]; } number[curr] = score; break; } curr++; } } } void printAll(int size, double timeComplexity) { int i; for (i = 0; i < size; i++) { printf("%d \n", number[i]); } printf("실행 시간 : %f(ms) \nmerge 실행 횟수 : %d \ninsert 실행 횟수 : %d \n", timeComplexity, mergeTimeComplexity, insertTimeComplexity); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define INF 100000 typedef struct Node { struct Node *left; struct Node *right; int freq; char str; int code; } node; node *Q; int **histo; int size; int count; int qsize; void sortHisto() { int i, j, t; for (i = 1; i < size + 1; i++) { for (j = 1; j < size + 1 - i; j++) { if (histo[1][j] > histo[1][j + 1]) { t = histo[0][j]; histo[0][j] = histo[0][j + 1]; histo[0][j + 1] = t; t = histo[1][j]; histo[1][j] = histo[1][j + 1]; histo[1][j + 1] = t; } } } } void sortQ() { int i, j; node t; for (i = 1; i <= qsize; i++) { for (j = 1; j <= qsize - i; j++) { if (Q[j].freq > Q[j + 1].freq) { t = Q[j]; Q[j] = Q[j + 1]; Q[j + 1] = t; } } } } void makeQ() { int i; sortHisto(); Q = calloc(size + 1, sizeof(node)); for (i = 1; i < size + 1; i++) { Q[i].str = histo[0][i]; Q[i].freq = histo[1][i]; } } void insertQ(node *p) { qsize++; copyNode(p, &(Q[qsize])); sortQ(); } void copyNode(node *from, node *to) { (*to).freq = (*from).freq; (*to).left = (*from).left; (*to).code = (*from).code; (*to).right = (*from).right; (*to).str = (*from).str; } node *extractMin() { node *result = calloc(1, sizeof(node)); copyNode(&(Q[1]), result); Q[1].freq = INF; Q[1].right = NULL; Q[1].left = NULL; Q[1].str = 0; Q[1].code = 0; sortQ(); qsize--; return result; } int findIndex(char c) { int i; for (i = 1; i < size + 1; i++) { if (histo[0][i] == c) { return i; } } return -1; } void Histogram(char c) { int i; i = findIndex(c); if (i < 0) { size++; histo[0] = realloc(histo[0], (size + 1) * sizeof(int)); histo[1] = realloc(histo[1], (size + 1) * sizeof(int)); histo[0][size] = c; histo[1][size] = 1; } else { histo[1][i] += 1; } } // 배열 복사. from에서 to까지 n개만큼 복사하는 함수 // 복사된 함수를 반환 int *copyArray(int *to, int *from, int n) { int i = 0; for (i = 0; i < n; i++) { to[i] = from[i]; }; return to; } // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) void readFile(int argc, char *argv[]) { FILE *file; // 파일 포인터 char c; size = 0; count = 0; histo = calloc(2, sizeof(int *)); if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } // 1부터 size까지 저장해야 하기에 size+1 할당 histo[0] = calloc(size + 1, sizeof(int)); histo[1] = calloc(size + 1, sizeof(int)); // 모든 문자를 읽고 Histogram화 while (!feof(file)) { fscanf(file, "%c", &c); Histogram(c); count++; } fclose(file); // Q생성 makeQ(); qsize = size; } // 재귀적으로 노드들의 코드를 생성하는 함수 void encode(node *p, int code) { p->code = code; printf("%d\t", code); if (p->left != NULL) { encode(p->left, p->code * 10); encode(p->right, p->code * 10 + 1); } } // 허프만 코드의 중심 함수 // n은 p와 q를 합친 부모 노드 void Huffman() { node *n; node *p; node *q; while (qsize > 1) { p = extractMin(); // 제일 작은 node q = extractMin(); // 그다음 작은 node n = calloc(1, sizeof(node)); n->freq = p->freq + q->freq; n->left = calloc(1, sizeof(node)); copyNode(p, n->left); n->right = calloc(1, sizeof(node)); copyNode(q, n->right); insertQ(n); } encode(n->left, 0); // 최종 결과에서 left 코드 부여 encode(n->right, 1); // 최종 결과에서 right 코드 부여 } void freeMem() { int i; for (i = 0; i < 2; i++) { free(histo[i]); } free(histo); // 메모리 해제 free(Q); // 메모리 해제 } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./LCS.exe sample_lcs1.txt.txt int main(int argc, char *argv[]) { int i, j; size = 0; // 개수 초기화 readFile(argc, argv); // 파일 읽어오기 printf("시작\n"); Huffman(); printf("\n완료"); freeMem(); return 1; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #define INF 99999 // 정점의 데이터를 담은 구조체 typedef struct Vertex { int key; int vertex; int pi; } vertex; int size; // 간선의 개수 int range; // 정점의 개수 int heapSize; // heap의 개수 int *visited; // 방문한 점의 정보 int sum; // 사용한 간선 cost 합 vertex *heap; // 정점들의 힙 vertex *vertexBox; // 정점들의 데이터가 담긴 박스 heap에서 섞이는 정점의 인덱스 때문에 추가하였다. // 파일 읽기 (argc : 인자 개수, argv[1] 파일명 int **readFile(int argc, char *argv[]) { int **number; // 2중 배열로 cost 정보를 받음 int vertex1, vertex2, cost; // 간선 정보 int i, j; FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &cost); // 첫 번째 줄 데이터만 읽어오기 range = cost; // 정점 개수 heapSize = range; number = calloc(range, range * sizeof(int)); for (i = 0; i < range; i++) { number[i] = realloc(number[i], range * sizeof(int)); // number 는 각 정점들의 cost 정보를 갖고있는 2차원 배열이기 때문에 이렇게 선언한다. } for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { if (i != j) { number[i][j] = INF; // cost가 없는 부분을 INF로 선언한다. } } } // 두번 째 데이터부터 순서대로 모두 number에 삽입 while (feof(file) == 0) { fscanf(file, "%d %d %d ", &vertex1, &vertex2, &cost); insert(vertex1, vertex2, cost, number); // insert 함수를 통해 삽입한다. size++; } fclose(file); return number; } // fScore를 마지막 number에 삽입. 함수 종료시 size 하나 증가 void insert(int vertex1, int vertex2, int cost, int **number) { number[vertex1][vertex2] = cost; number[vertex2][vertex1] = cost; // 양방향이기 때문에 두번한다. } // Min Heap으로 빌드하는 함수 이전 과제를 응용한다. void BuildMinHeap() { int i; for (i = Parent(heapSize - 1); i >= 0; i--) { MinHeapify(i); } } // Min Heapify 로 해당되는 값으로 값의 위치를 바꿔준다. void MinHeapify(int i) { int lc; int rc; int smallest; int sc; lc = Left(i); rc = Right(i); if (lc < heapSize) { if (rc >= heapSize) { if (heap[i].key > heap[lc].key) { smallest = lc; swap(i, lc); MinHeapify(smallest); } } else { sc = (heap[lc].key < heap[rc].key) ? lc : rc; if (heap[i].key > heap[sc].key) { smallest = sc; swap(i, sc); MinHeapify(smallest); } } } } // 최소값을 힙에서 꺼낸다. vertex ExtractMin() { int i; vertex min_value; BuildMinHeap(); i = heapSize - 1; min_value = heap[0]; swap(0, i); heapSize--; MinHeapify(0); return min_value; } // 부모 인덱스를 반환하는 함수 int Parent(int i) { return floor((i - 1) / 2); } // 왼쪽 자식의 인덱스를 반환하는 함수 int Left(int i) { return floor(2 * i + 1); } // 오른쪽 자식의 인덱스를 반환하는 함수 int Right(int i) { return floor(2 * i + 2); } // 힙에서 a 인덱스의 위치의 vertex와 b 인덱스의 위치의 vertex를 바꾸는 함수이다. void swap(int a, int b) { vertex i; i = heap[a]; heap[a] = heap[b]; heap[b] = i; } // prim 알고리즘 cost 배열과 시작 정점인 input 값을 받고 프림알고리즘을 실행한다. void MSTPrim(int **number, int input) { int i, j, u, v; // 정점배열과 heap을 초기화하면서 각 정점 구조체에 해당 정점 데이터를 입력한다. for (i = 0; i < range; i++) { heap[i].key = INF; heap[i].vertex = i; vertexBox[i].key = INF; vertexBox[i].vertex = i; } heap[input].key = 0; // 처음 시작하는 heap 정점의 key의 값을 0으로 설정한다. vertexBox[input].key = 0; // vertexBox 또한 0으로 설정한다. BuildMinHeap(); // heap을 빌드한다. for (i = 0; i < range; i++) { u = ExtractMin().vertex; // 힙에서 가장 작은 값의 key를 가진 정점을 u로 배정한다. visited[u] = 1; // u 정점은 방문했었다고 체크한다. if (vertexBox[u].key == INF) { return; } if (i == 0) { printf("PATH\t|\tCOST\n%d\t\t|\n", u); // 처음 실행하는 반복문에서 출력 틀을 설정한다. } else { printf("%d\t", u); // u를 출력한다. printf("\t|\t%d\n", vertexBox[u].key); // u의 key를 출력한다. sum += vertexBox[u].key; // key를 총합에 추가한다. } for (v = 0; v < range; v++) { if (number[u][v] != INF) { // 해당 코스트가 기본값인 INF가 아니라면 if (!visited[v] && number[u][v] < vertexBox[v].key) { // v를 방문한 적이 없을 때 v의 key가 u,v의 cost보다 크다면 vertexBox[v].key = number[u][v]; // v의 key에 해당 cost를 저장한다. vertexBox[v].pi = u; // v의 pi에 u를 설정한다. for (j = 0; j < range; j++) { if (heap[j].vertex == v) { heap[j].key = number[u][v]; // heap의 key에도 cost로 수정한다. } } } } } } } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./primMST.exe graph_sample.txt int main(int argc, char *argv[]) { int **number; // 파일에서 읽어 올 정수들 int input = 0; sum = 0; size = 0; number = readFile(argc, argv); // 파일 읽어오기 visited = calloc(range, sizeof(int)); // visited를 0으로 초기화 시킨 값으로 메모리 할당한다. heap = calloc(range, sizeof(vertex)); // heap에 메모리를 할당한다. vertexBox = calloc(range, sizeof(vertex)); // vertexBox에 메모리를 할당한다. printf("시작\n"); MSTPrim(number, input); // prim알고리즘을 실행한다. printf("Sum : %d\n완료\n", sum); // 총합을 출력한다. free(number); free(visited); free(heap); return 1; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct Item { int data; struct Item *next; } item; typedef item *pItem; typedef struct UU { int d; int color; int f; struct UU *pi; } U; int *readFile(int argc, char *argv[]); void insert(int fScore, int *number); void printAll(pItem **pBox, double timeComplexity); void printList(pItem *list); pItem *makeAdj(int *number, pItem **pBox); void DFS(pItem *pBox); void DFSVisit(pItem *pBox, int uIndex); int dfsTimeComplexity; int adjTimeComplexity; int mySize; int range; int count; U *visited; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./DFS.exe test1.txt int main(int argc, char *argv[]) { double timeComplexity; // 실행 시간 int *number; // 파일에서 읽어 올 정수들 pItem *pBox; // 인접행렬을 담을 포인터배열 time_t startTime = 0, endTime = 0; mySize = 0; range = 0; count = 0; dfsTimeComplexity = 0; // bst 실행 횟수 체크 adjTimeComplexity = 0; // 인접행렬 생성 횟수 체크 number = readFile(argc, argv); // 파일 읽어오기 pBox = makeAdj(number, &pBox); // 인접행렬 형성 printf("시작\n"); startTime = clock(); DFS(pBox); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; // 단위 상승 (*1000) printAll(&pBox, timeComplexity); // 저장된 인접행렬 체크 및 시간복잡도 체크 printf("완료\n"); free(number); free(pBox); return 1; } // 파일 읽기 (argc : 인자 개수, argv[1] 파일명 int *readFile(int argc, char *argv[]) { int *number = malloc(sizeof(float)); int fScore; FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &fScore); // 첫 번째 줄 데이터만 읽어오기 range = fScore; // 정점 개수 visited = calloc(range, sizeof(U)); // 각 정점의 데이터가 담긴 구조체 생성 및 초기화 // 두번 째 데이터부터 순서대로 모두 number에 삽입 while (feof(file) == 0) { fscanf(file, "%d ", &fScore); number = realloc(number, (mySize + 1) * sizeof(float)); insert(fScore, number); mySize++; } fclose(file); return number; } // fScore를 마지막 number에 삽입. 함수 종료시 size 하나 증가 void insert(int fScore, int *number) { number[mySize] = fScore; } // 실행 횟수, 실행 시간을 출력하고, 인접행렬을 printList를 활용하여 출력 void printAll(pItem **pBox, double timeComplexity) { int i; printf("\n실행 시간 : %f(ms) \tDFS : %d \tadj : %d \n", timeComplexity, dfsTimeComplexity, adjTimeComplexity); for (i = 0; i < range; i++) { // 각 인접 행렬의 행들을 배열의 인덱스로 하여 printList 실행 printList(&((*pBox)[i])); } } // 인접 행렬의 각 행을 출력하는 함수 // ml은 현재 포인터가 가리키는 노드 void printList(pItem *list) { pItem *ml = list; if ((*ml) != NULL) { while ((*ml)->next != NULL) { printf("%d\t", (*ml)->data); ml = &((*ml)->next); } printf("%d\t", (*ml)->data); } printf("/\n"); } // 인접행렬을 포인터 배열형태로 생성하는 함수 pItem *makeAdj(int *number, pItem **pBox) { int i, j; pItem *ml = NULL; (*pBox) = malloc(range * sizeof(pItem)); // 각 행들에 메모리 할당 for (i = 0; i < range; i++) { (*pBox)[i] = NULL; // 각 행들의 초기화 } for (j = 0; j < range; j++) { for (i = 0; i < range; i++) { adjTimeComplexity++; ml = &(*pBox)[j]; // 각 행들별로 노드를 가리키는 포인터 설정 if (number[j * range + i] == 1) { // 각 행에서 1인 값만 링크드리스트로 추가 if ((*ml) == NULL) { // 현재 행이 NULL로 비어있을 때 (*ml) = realloc((*ml), sizeof(item)); (*ml)->data = i; // 이 때 노드에 해당 정점을 입력하기 위해 그냥 i를 사용 (*ml)->next = NULL; } else { // 현재 행에 값이 있을때 마지막 위치로 포인터 설정 while ((*ml)->next != NULL) { ml = &((*ml)->next); } (*ml)->next = realloc((*ml)->next, sizeof(item)); (*ml)->next->data = i; (*ml)->next->next = NULL; } } } } return *pBox; } // DFS 함수 (pdf 수도코드 기반). 인접행렬 pBox를 인자로 받음 void DFS(pItem *pBox) { int i; for (i = 0; i < range; i++) { dfsTimeComplexity++; if (visited[i].color == 0) { // color가 white인 지점만 DFS Visit 실행 DFSVisit(pBox, i); } } } //DFS Visit은 재귀적으로 실행되는 함수로 인접행렬 pBox, DFS 함수의 uIndex를 입력 인자로 받는다. void DFSVisit(pItem *pBox, int uIndex) { pItem *ml = NULL; // 인접 행의 노드를 가리키는 포인터 ml = &(pBox[uIndex]); // uIndex 행을 가리키게 설정 count = count + 1; // count 1증가 visited[uIndex].d = count; // d를 count로 설정 visited[uIndex].color = 1; // color를 회색으로 설정 printf("(%d\t", uIndex); // pdf 결과와 같이 출력하도록 맞춘 양식 while ((*ml) != NULL) { dfsTimeComplexity++; if (visited[(*ml)->data].color == 0) { // color가 white인 정점에서 수행 visited[(*ml)->data].pi = &(visited[uIndex]); // 연결된 부모 노드 설정 DFSVisit(pBox, (*ml)->data); // 해당 정점에 대하여 DFSVisit 실행 } ml = &((*ml)->next); } visited[uIndex].color = 2; // u의 color를 black으로 변경 count = count + 1; // count 증가 visited[uIndex].f = count; // f를 증가된 count로 설정 printf("%d)\t", uIndex); // pdf 결과와 같이 출력하도록 맞춘 양식 }<file_sep>#include <stdio.h> #include <stdlib.h> #define INF 99999 #define TRUE 1 #define FALSE 0 // 정점의 데이터들을 갖고 있는 구조체 typedef struct Vertex { int key; int vertex; int pi; } vertex; int input; // 시작 정점 int size; // 간선의 개수 int range; // 정점의 개수 vertex *vertexBox; // 정점 구조체 배열 // 파일 읽기 (argc : 인자 개수, argv[1] 파일명) int **readFile(int argc, char *argv[]) { int **number; // cost를 담은 2차원 배열 int vertex1, vertex2, cost; int i, j; FILE *file; // 파일 포인터 if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(argv[1], "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } fscanf(file, "%d\n", &cost); // 첫 번째 줄 데이터만 읽어오기 range = cost; // 정점 개수 number = calloc(range, range * sizeof(int)); for (i = 0; i < range; i++) { number[i] = realloc(number[i], range * sizeof(int)); } for (i = 0; i < range; i++) { for (j = 0; j < range; j++) { number[i][j] = INF; // 초기값 INF로 선언 } } // 두번 째 데이터부터 순서대로 모두 number에 삽입 while (feof(file) == 0) { fscanf(file, "%d %d %d ", &vertex1, &vertex2, &cost); insert(vertex1, vertex2, cost, number); size++; } fclose(file); return number; } // number에서 (vertex1, vertex2) 위치에 cost 삽입 void insert(int vertex1, int vertex2, int cost, int **number) { number[vertex1][vertex2] = cost; // 1방향이기 때문에 vertex1, vertex2 순서 중요 } // u 정점과 v정점과 cost가 담긴 2차원 배열을 입력받아 key 입력을 하는 함수 void Relax(vertex *u, vertex *v, int **number) { // v의 key가 u의 key와 (u,v)의 cost의 합보다 크다면 v의 key에 해당 값 삽입 if (v->key > u->key + number[u->vertex][v->vertex]) { v->key = u->key + number[u->vertex][v->vertex]; v->pi = u->vertex; // v의 부모 인덱스를 u로 설정 } } // NegativeCycle이 존재하는지 탐색하는 함수. 정점 u, 정점 v, cost 2차원 배열 number를 입력받는다. int isNegativeCycle(vertex *u, vertex *v, int **number) { // 현재위치와 최단거리 + 가중치를 비교 if (v->key > u->key + number[u->vertex][v->vertex]) { // 바뀐다면 NegativeCycle 존재함으로 True 반환 return TRUE; } // NegativeCycle가 아니기에 FALSE 반환 return FALSE; } // Relax에서 배정한 pi를 이용하여 i 정점의 부모 정점을 재귀적으로 출력 void printShortestPath(vertex i) { // i의 부모 정점이 시작 정점인지 확인 if (i.pi != input) { // 부모 정점이 시작 정점이 아닌 다른 정점이므로 재귀적 실행 printShortestPath(vertexBox[i.pi]); // 재귀 수행 후 i 정점 출력 printf("%d ", i.vertex); } else { // 부모 정점이 시작 정점인 경우 i 정점 출력 printf("%d ", i.vertex); } } // vertex와 cost를 출력하는 함수 void printAll() { int i; printf("Vertex \t| Cost \t| Shortest Path\n"); // 정점의 개수만큼 반복 for (i = 0; i < range; i++) { // vertexBox에서 정점의 데이터들을 순서대로 출력 printf("%d \t\t| %d \t\t| 0 ", i, vertexBox[i].key); // 최단경로를 출력하는 함수 printShortestPath(vertexBox[i]); printf("\n"); } } // BellmanFord함수 cost가 담긴 2차원 배열 number가 입력 됨 int BellmanFord(int **number) { int i, j, k; vertex *u, *v; // 정점 개수만큼 반복 for (i = 0; i < range; i++) { // vertexBox[i]에서 vertex 정보를 배정 vertexBox[i].vertex = i; // vertexBox[i]에서 key의 초기값 INF 배정 vertexBox[i].key = INF; } // 시작 정점의 key에 0 배정 vertexBox[input].key = 0; // n-1 만큼 반복 for (i = 1; i < range; i++) { // 2차원 배열의 행 for (j = 0; j < range; j++) { // 2차원 배열의 열 for (k = 0; k < range; k++) { u = &(vertexBox[j]); // 행에 해당하는 정점 v = &(vertexBox[k]); // 열에 해당하는 정점 // 간선이 존재할 경우 if (number[u->vertex][v->vertex] != INF) { Relax(u, v, number); // Relax 함수 실행 } } } } // Negative Cycle 탐색. 2차원 배열의 행과 열 for (j = 0; j < range; j++) { for (k = 0; k < range; k++) { u = &(vertexBox[j]); // 행에 해당하는 정점 v = &(vertexBox[k]); // 열에 해당하는 정점 // 간선이 존재할 경우 if (number[u->vertex][v->vertex] != INF) { // isNegativeCycle 함수 실행 if (isNegativeCycle(u, v, number)) { return FALSE; // Cycle을 형성한다면 FALSE 반환 } } } } printAll(); // 출력 return TRUE; // 성공 시 TRUE 반환 } //파일 실행 옵션으로 txt파일 이름 입력 ex) ./BellmanFord.exe graph_sample_directed.txt int main(int argc, char *argv[]) { int **number; // 파일에서 읽어 올 정수들 input = 0; // 시작 정점 초기화 size = 0; // 간선 개수 초기화 number = readFile(argc, argv); // 파일 읽어오기 vertexBox = calloc(range, sizeof(vertex)); // 정점 배열 초기화 printf("시작\n"); //BellmanFord 실행 if (BellmanFord(number)) { // 성공 printf("완료\n"); } else { // 실패 printf("실패"); } free(number); free(vertexBox); return 1; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> typedef struct BSTs { int key; struct BSTs *p; struct BSTs *left; struct BSTs *right; } bsts; void insert(int fScore, int *number); void printAll(bsts *root, double timeComplexity); void TreeInsert(int *number, bsts **root); bsts *TreeMinimum(bsts *root); bsts *TreeMaximum(bsts *root); bsts *TreeSuccessor(bsts *root); bsts *TreePredecessor(bsts *root); bsts *TreeSearch(bsts **root, int k); int bstTimeComplexity; void InorderTreeWalk(bsts *root); int size; //파일 실행 옵션으로 txt파일 이름 입력 ex) ./bstInsert.exe test1.txt int main(int argc, char *argv[]) { FILE *file; char *filename = argv[1]; int fScore; double timeComplexity; time_t startTime = 0, endTime = 0; int *number = malloc(sizeof(int)); int deleteNumber = 3; bsts *root = NULL; size = 0; bstTimeComplexity = 0; if (argc == 1) { fputs("옵션을 입력해 주시기 바랍니다.\n", stderr); exit(1); } if ((file = fopen(filename, "r")) == NULL) { printf("파일이 열리지 않습니다.\n"); exit(1); } while (feof(file) == 0) { fscanf(file, "%d\n", &fScore); number = realloc(number, (size + 1) * sizeof(int)); insert(fScore, number); size++; } fclose(file); TreeInsert(number, &root); printAll(root, timeComplexity); printf("삭제 %d\n", deleteNumber); startTime = clock(); TreeDelete(&root, deleteNumber); endTime = clock(); timeComplexity = (double) (endTime - startTime) / (CLOCKS_PER_SEC); timeComplexity *= 1000.0; printAll(root, timeComplexity); printf("완료\n"); free(number); free(root); return 1; } void insert(int fScore, int *number) { number[size] = fScore; } void printAll(bsts *root, double timeComplexity) { int i; /*for (i = 0; i < size; i++) { printf("%d \t", number[i]); }*/ InorderTreeWalk(root); printf("\n실행 시간 : %f(ms) \tbst : %d \n", timeComplexity, bstTimeComplexity); } void InorderTreeWalk(bsts *root) { if (root != NULL) { InorderTreeWalk(root->left); printf("%d\t", root->key); InorderTreeWalk(root->right); } } bsts *TreeMinimum(bsts *root) { bsts **x; x = &root; while ((*x)->left != NULL) { x = &((*x)->left); } return *x; } bsts *TreeMaximum(bsts *root) { bsts **x; x = &root; while ((*x)->right != NULL) { x = &((*x)->right); } return *x; } bsts *TreeSuccessor(bsts *root) { bsts **x, **y; x = &root; if ((*x)->right != NULL) { return TreeMinimum((*x)->right); } y = &((*x)->p); while ((*y) != NULL && *x == (*y)->right) { x = y; y = &((*y)->p); } return *y; } bsts *TreePredecessor(bsts *root) { bsts **x, **y; x = &root; if ((*x)->left != NULL) { return TreeMaximum((*x)->left); } y = &((*x)->p); while ((*y) != NULL && *x == (*y)->left) { x = y; y = &((*y)->p); } return *y; } bsts *TreeSearch(bsts **root, int k) { bsts **x; x = root; while (*x != NULL && k != (*x)->key) { if (k < (*x)->key) { x = &((*x)->left); } else { x = &((*x)->right); } } return *x; } void TreeInsert(int *number, bsts **root) { int i, value; bsts **x, *y; for (i = 0; i < size; i++) { value = number[i]; x = root; y = *root; while (*x != NULL) { bstTimeComplexity++; y = *x; if (value < (*x)->key) { x = &((*x)->left); } else { x = &((*x)->right); } } *x = calloc(1, sizeof(bsts)); (*x)->p = y; (*x)->key = value; } } void TreeDelete(bsts **root, int i) { bsts *y, *z; z = TreeSearch(root, i); if (z != NULL) { if (z->left == NULL) { Transplant(root, z, z->right); } else if (z->right == NULL) { Transplant(root, z, z->left); } else { y = TreeMinimum(z->right); if (y->p != z) { Transplant(root, y, y->right); y->right = z->right; if (y->right != NULL) { y->right->p = y; } } Transplant(root, z, y); y->left = z->left; if (y->left != NULL) { y->left->p = y; } } } } void Transplant(bsts **root, bsts *u, bsts *v) { if (u->p == NULL) { *root = v; } else if (u == u->p->left) { (*(u->p)).left = v; } else { (*(u->p)).right = v; } if (v != NULL) { v->p = u->p; } }
5f79544bd7196bb96052131c9bab67d12ee24ab6
[ "C" ]
29
C
jsyoo8/17_Algorithm
2369af7eb2e41ede937354b611c9152941c3b4fc
e91179b3165e0d17c58f1bdbf32d9200fc8f92f0
refs/heads/master
<file_sep>// From: // https://github.com/heroku/node-js-getting-started // https://www.twilio.com/docs/usage/tutorials/how-to-set-up-your-node-js-and-express-development-environment // Sample: // https://github.com/expressjs/express/blob/master/examples/auth/index.js // // To do: // Sample using: setHeaders // // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // $ npm install express --save const express = require('express'); var app = express(); // ----------------------------------------------------------------------------- app.use(express.static('docroot')); app.use(function (err, req, res, next) { console.error(err.stack); res.status(500).send('HTTP Error 500.'); }); var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); // ----------------------------------------------------------------------------- function sayMessage(message) { console.log(message); } var request = require('request'); function requestPost(theUrl, res) { sayMessage("+ POST theUrl :" + theUrl + ":"); sayMessage("+ api_key :" + process.env.AUTHY_API_KEY_TF + ":"); sayMessage("+ authy_id :" + process.env.AUTHY_ID + ":"); let options = { url: theUrl, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, form: { api_key: process.env.AUTHY_API_KEY_TF, authy_id: process.env.AUTHY_ID } }; request.post(options, function (error, response, theResponse) { if (error) { // Print the error if one occurred sayMessage('- Error connecting.'); return; } if (!response.statusCode.toString().startsWith('2')) { var errorMessage = ''; if (response.statusCode.toString().startsWith('1')) { errorMessage = ": Informational."; } else if (response.toString().startsWith('3')) { errorMessage = ": Redirectory."; } else if (response.statusCode === 400) { errorMessage = ": Bad request."; } else if (response.statusCode === 401) { errorMessage = ": Unauthorized."; } else if (response.statusCode === 403) { errorMessage = ": Forbidden."; } else if (response.statusCode === 404) { errorMessage = ": Not found."; } else if (response.toString().startsWith('4')) { errorMessage = ": Client error."; } else if (response.toString().startsWith('5')) { errorMessage = ": Server Error."; } sayMessage('- Status code: ' + response.statusCode + errorMessage + ' ' + theUrl); return; } sayMessage('+ Response code: ' + response.statusCode + ', URL: ' + theUrl); sayMessage(response.headers); sayMessage(''); sayMessage(theResponse); res.send(theResponse); }); } // ----------------------------------------------------------------------------- app.get('/registration', function (req, res) { res.send('Must use POST.'); }); app.post('/registration', function (req, res) { sayMessage('+ req.body :' + req.body + ':'); // return; var returnString = ''; if (req.body.api_key) { returnString = '+ Data: ' + req.body.api_key; if (req.body.authy_id) { returnString = returnString + ' ' + req.body.authy_id + '.'; } else { res.send('- Require: api_key.'); return; } } else { res.send('- Require: authy_id.'); return; } var theUrl = 'https://api.authy.com/protected/json/sdk/registrations'; sayMessage('+ POST request to: ' + theUrl); requestPost(theUrl, res); }); const PORT = process.env.PORT || 8000; console.log('+ PORT: ' + PORT); app.listen(PORT, function () { console.log('+ Listening on port: ' + PORT); }); // ----------------------------------------------------------------------------- <file_sep>console.log("++ List Studio executions."); var client = require('twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); console.log("+++ Start"); client.studio.v1.flows('FW97fb3aabed8cc508bc8c08af2ce50916') .executions .list({ // I couldn't get dateCreatedFrom to work. // dateCreatedFrom: new Date(Date.UTC(2021, 6, 1, 0, 0, 0)), // dateCreatedTo: new Date(Date.UTC(2021, 6, 12, 0, 0, 0)), limit: 20 }) .then(executions => executions.forEach(execution => { if (execution.status === "active") { console.log("+ " + execution.sid + " " + execution.status + " " + execution.dateCreated); } })) .catch(function (err) { console.error("- " + " " + err); }); <file_sep>---------------------------------------------------------------------------------- # Conversations Notes #### Configuring and getting started You'll need to have a [Twilio account](https://www.twilio.com/console). You'll need at least one Conversations service SID(starts with IS). Twilio Console [link](https://www.twilio.com/console/conversations/services) to create a Conversations service. ##### Twilio Conversations JavaScript Web Application See the repository: [tfpconversations](https://github.com/tigerfarm/tfpconversations). It uses the [JavaScript docs](http://media.twiliocdn.com/sdk/js/conversations/releases/1.2.1/docs/Conversation.html). ## Command line programs, Using the Conversations API Documentation [API Overview link](https://www.twilio.com/docs/conversations/api) A Conversation has the following resources: [Services](https://www.twilio.com/docs/conversations/api/service-resource) [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource), [Participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [Messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource), and [Conversation Webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) ##### Note, the Conversation, Participants, and Messages Resource sample programs use the Default Conversations Service SID For example, if you want to list conversations you can use the [documentation sample](https://www.twilio.com/docs/conversations/api/conversation-resource?code-sample=code-read-multiple-conversation-resources&code-language=Node.js&code-sdk-version=3.x) to list the conversations in the default Conversations service. Click [here](https://github.com/tigerfarm/work/blob/master/book/AndroidConversations/servicesConversation.js) for a program that will list the conversations in the choosen Conversations service. To get started, I create a sample Node.JS program to manage each of the resources. For example, a program for each: create, fetch one, list all, update one, and delete one. Note, to exchange messages with the Conversations command line program created based on the documentation, create access tokens using the [Default Conversation Service SID](https://www.twilio.com/console/conversations/configuration/defaults), not any other Conversations service SID. This is because the documentation Conversation, Participants, and Messages command line programs only work with the Default Conversation Service SID. ---------------------------------------------------------------------------------- #### Issues Issues I worked through: + Get the webhook to work, when a message is added. + Android Studio updates: add an emulator for Android 11. Adding an emulator is straight forward. And my new phone was recognized immediately by Studio. + Get the access token to work. It can be used in the Android sample app, and is use in the repository: [tfpconversations](https://github.com/tigerfarm/tfpconversations) The Conversations webhook details: + The [Default Conversation Service SID](https://www.twilio.com/console/conversations/configuration/defaults) when using API calls such as my command line programs. + SDK calls will trigger webhooks from services other than the Default Conversation Service SID. I haven't tested this, but I got it for a reliable source. The Android Studio sample app requires a hard coded token for testing. Since I was using the Twilio CLI to generate tokens, I needed to add the Twilio token plugin. I thought that was only recommended, but it turns out to required. Based on my work to solve the token issue, I suggested a [documentation](https://www.twilio.com/docs/conversations/error-handling-diagnostics#android-logging-java) change from: ```` ConversationsClient.setLogLevel(android.util.Log.DEBUG); ```` To: ```` ConversationsClient.setLogLevel(ConversationsClient.LogLevel.DEBUG); ```` This allowed me to view the debug messages that statement the authorization problem because the token was generated incorrectly. Once I added the Twilio token plugin to my Twilio CLI, the token generated fine. Following is where I added the line into the program: QuickstartConversationsManager.java. ```` ... void initializeWithAccessToken(final Context context, final String token) { Log.e(MainActivity.TAG, "+ initializeWithAccessToken(..., " + token + ")"); ConversationsClient.setLogLevel(ConversationsClient.LogLevel.DEBUG); ConversationsClient.Properties props = ConversationsClient.Properties.newBuilder().createProperties(); ConversationsClient.create(context, token, props, mConversationsClientCallback); } ... ```` ---------------------------------------------------------------------------------- ## Use the Twilio CLI to Generate Conversations Access Tokens You can generate a token in a few ways: * Using a [command line](https://www.twilio.com/docs/conversations/create-tokens) and [twilio token plugin](https://github.com/twilio-labs/plugin-token) (Recommended) * Using [Twilio Runtime Function](https://www.twilio.com/docs/runtime/functions) For the twilio-cli option, run the following command and enter the resulting token into the strings.xml placeholder: ```` twilio token:chat --identity <The test username> --chat-service-sid <ISXXX...> twilio token:chat --identity dave --chat-service-sid IS973ddbf230364f8dab02c6418779a602 ```` Note: You need to generate an access token with a ChatGrant for a Conversations user to use the Twilio Conversations Client SDK. Manually generated tokens expire after a timeout period. So you will need to replace the token. To use this in production software, you would typically create a token endpoint in your back end application that uses your existing user authentication strategy. Following is the token display using the [JWT.io](https://jwt.io/) website. Note, this token expires in one hour . ```` { "jti": "ACa...3-1623781947", "grants": { "identity": "dave1", "chat": { "service_sid": "IS97...02" } }, "iat": 1623781947, "exp": 1623785547, "iss": "ACa...3", "sub": "ACa...3" } ```` ---------------------------------------------------------------------------------- ## Android Quickstart App The general Twilio Conversations quickstart [link](https://www.twilio.com/docs/conversations/quickstart). The Android quickstart app is a lightweight Android app developed using [Twilio Conversations](https://www.twilio.com/docs/conversations). Conversations Android Quickstart [GitHub link](https://github.com/TwilioDevEd/conversations-quickstart-android) with a brief Readme file, and the [documentation link](https://www.twilio.com/docs/conversations/android/exploring-conversations-android-quickstart). #### Implementing a Hard Coded Token `test_access_token` is the placeholder in the `strings.xml` resource for the manually generated access token. Location of the strings.xml file: ```` /.../conversations-quickstart-android-main/app/src/main/res/values/strings.xml ```` Sample: ```` <resources> <string name="app_name">Dave\'s Conversations App</string> <string name="error_retrieving_access_token">Error retrieving access token from the server.</string> <string name="send">Send1</string> <string name="chat_token_url">https://YOUR_DOMAIN_HERE.twil.io/chat-token</string> <string name="write_message">Dave: Write Message</string> <string name="test_access_token"><PASSWORD></string> </resources> ```` #### Program: MainActivity.java. App identity is hard coded. Token string is used here. Note, the hard coded identity needs to match the identity in the token. ```` /.../conversations-quickstart-android-main/app/src/main/java/com/twilio/conversationsquickstart/MainActivity.java private String identity = "dave1"; // Token Method 1 - supplied from strings.xml as the test_access_token quickstartConversationsManager.initializeWithAccessToken(this, getString(R.string.test_access_token)); ```` #### Program file, QuickstartConversationsManager.java, The Conversation name is hard coded. ```` private final static String DEFAULT_CONVERSATION_NAME = "general"; ```` ---------------------------------------------------------------------------------- Cheers <file_sep>console.log("+++ Start."); var client = require('twilio')(process.env.ACCOUNT_SID, process.env.AUTH_TOKEN); client.video.rooms.list({status: 'completed', limit: 20}) .then(rooms => rooms.forEach( r => console.log(r.sid) )); <file_sep>console.log("++ List Conversations."); var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); conversationSid = process.env.CONVERSATION_SID; console.log("+ Fetch using conversatoin sid, retrieves: <sid> <uniqueName> <friendlyName>"); client.conversations.conversations(conversationSid) .fetch() .then(conversation => { console.log( "+ Conversations SID: " + conversation.sid + " " + conversation.uniqueName + " " + conversation.friendlyName ); console.log("+ Fetch using unique name."); client.conversations.conversations(conversation.uniqueName) .fetch() .then(conversation => { console.log( "+ Conversations SID: " + conversation.sid + " " + conversation.uniqueName + " " + conversation.friendlyName ); }); }); <file_sep>// From: https://github.com/twilio/media-streams/tree/master/node/realtime-transcriptions // Takes at least 30 minutes for set up and test. Plus time to do the step: Enable Google Cloud Speech API. // I created the files in repository, in my working directory: // .env, google_creds.json, package.json, server.js, and transcription-service.js. // /templates/streams.xml // Note, I changed 8080 to 8000. // I was given a google_creds.json file from a colleague. // In the working directory, I ran: npm install. // In then I ran: "/Applications/ngrok 2" http 8000 // In another terminal window, I ran: node server.js // Call your phone: twilio api:core:calls:create --from="+16505551111" --to="+16505552222" --url="https://ae2357a3.ngrok.io/twiml" "use strict"; require('dotenv').load(); const fs = require('fs'); const path = require('path'); const http = require('http'); const HttpDispatcher = require('httpdispatcher'); const WebSocketServer = require('websocket').server; const TranscriptionService = require('./transcription-service'); const dispatcher = new HttpDispatcher(); const wsserver = http.createServer(handleRequest); const HTTP_SERVER_PORT = 8000; function log(message, ...args) { console.log(new Date(), message, ...args); } const mediaws = new WebSocketServer({ httpServer: wsserver, autoAcceptConnections: true, }); function handleRequest(request, response) { try { dispatcher.dispatch(request, response); } catch (err) { console.error(err); } } dispatcher.onGet('/', function (req, res) { log('GET homepage: say welcome message.'); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Welcome to the machine...'); }); dispatcher.onPost('/twiml', function (req, res) { log('POST TwiML'); var filePath = path.join(__dirname + '/templates', 'streams.xml'); var stat = fs.statSync(filePath); res.writeHead(200, { 'Content-Type': 'text/xml', 'Content-Length': stat.size }); var readStream = fs.createReadStream(filePath); readStream.pipe(res); }); mediaws.on('connect', function (connection) { log('Media WS: Connection accepted'); new MediaStreamHandler(connection); }); class MediaStreamHandler { constructor(connection) { this.metaData = null; this.trackHandlers = {}; connection.on('message', this.processMessage.bind(this)); connection.on('close', this.close.bind(this)); } processMessage(message) { if (message.type === 'utf8') { const data = JSON.parse(message.utf8Data); if (data.event === "start") { this.metaData = data.start; } if (data.event !== "media") { return; } const track = data.media.track; if (this.trackHandlers[track] === undefined) { const service = new TranscriptionService(); service.on('transcription', (transcription) => { log(`Transcription (${track}): ${transcription}`); }); this.trackHandlers[track] = service; } this.trackHandlers[track].send(data.media.payload); } else if (message.type === 'binary') { log('Media WS: binary message received (not supported)'); } } close() { log('Media WS: closed'); for (let track of Object.keys(this.trackHandlers)) { log(`Closing ${track} handler`); this.trackHandlers[track].close(); } } } wsserver.listen(HTTP_SERVER_PORT, function () { console.log("Server listening on: http://localhost:%s", HTTP_SERVER_PORT); });<file_sep><?php require __DIR__ . '/../../twilio-php-master/Twilio/autoload.php'; use Twilio\Rest\Client; use Twilio\Exceptions\RestException; $client = new Client(getenv('MASTER_ACCOUNT_SID'), getenv('MASTER_AUTH_TOKEN')); try { $message = $client->messages("MMdb6a8e05fcac48dc823874b6db03445a")->fetch(); echo "+ Sent, SID:" . $message->sid . " To:" . $message->to . " Status:" . $message->status . " MediaUrl0: " . $message->numMedia . "\xA"; $media = $client->messages("MMdb6a8e05fcac48dc823874b6db03445a")->media->read([], 20); foreach ($media as $record) { print("+ Media id: " . $record->sid . "\xA"); } } catch (RestException $e) { echo "+ getStatusCode(): " . $e->getStatusCode() . "\xA"; echo "+ getMessage(): " . $e->getMessage() . "\xA"; } ?> <file_sep>const twilioBlue = "#0D122B"; const twilioRed = "#954C08"; // Heading banner color const white = "#ffffff"; const lightGray = "#e6e6e6"; const darkGray = "#666666"; export default { MainHeader: { Container: { background: twilioRed, color: white } }, SideNav: { Container: { background: twilioBlue, color: darkGray }, Button: { background: twilioBlue, color: lightGray, lightHover: true }, Icon: { color: white } } } <file_sep># Node.JS using Express to create a web server to Check Authy user registration -------------------------------------------------------------------------------- Cheers... <file_sep>console.log("++ Create a Conversation."); var client = require('twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); conversationFriendlyName = '<NAME>'; console.log("+ Messaging Service SID: " + process.env.MESSAGING_SERVICE_SID + ", Friendly Name: " + conversationFriendlyName); client.conversations.conversations .create({ messagingServiceSid: process.env.MESSAGING_SERVICE_SID, friendlyName: conversationFriendlyName }) .then(conversation => console.log(conversation.sid));<file_sep>console.log("+++ Delete all messages for a services's conversation."); var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); // serviceSid = process.env.CONVERSATIONS_SERVICE_SID; console.log("+ Service SID: " + serviceSid); // // conversationSid = 'abc'; conversationSid = process.env.CONVERSATIONS_ECHO_SID; // client.conversations.services(serviceSid).conversations(conversationSid) .fetch() .then(conversation => { console.log( "+ Conversations SID/uniqueName/friendlyName: " + conversation.sid + "/" + conversation.uniqueName + "/" + conversation.friendlyName ); console.log("+ Delete all messages in the conversation."); console.log(" SID Author, Message"); client.conversations.conversations(conversationSid) .messages .list({limit: 200}) .then(messages => messages.forEach(message => { console.log( "+ " + message.sid // + " " + message.index + " " + message.author + ", \"" + message.body + "\"" ); client.conversations.conversations(conversationSid) .messages(message.sid).remove(); })); }); <file_sep>// ----------------------------------------------------------------------------- console.log("+++ Start sending notifications to an identity."); const client = require('twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); const notifyServiceSid = process.env.MASTER_NOTIFY_SERVICE_SID; client.notify.services(notifyServiceSid).notifications.create({ DeliveryCallbackUrl: 'http://www.tigerfarmpress.com/echo', identity: 'davea', body: 'Hello there' }).then(notification => console.log("+ Sent: " + notification.sid)) .catch(error => console.log(error)); <file_sep>console.log("++ List Participants for a Conversation."); // https://www.twilio.com/docs/conversations/api/service-participant-resource var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); // serviceSid = process.env.CONVERSATIONS_SERVICE_SID; // conversationSid = process.env.CONVERSATION_SID; serviceSid = "IS186702e405b74452a449d67b9265669f"; conversationSid = "CH0269d9f270744259977cff1ae19d5a5f"; console.log("+ Conversation SID: " + conversationSid); client.conversations.services(serviceSid).conversations(conversationSid) .participants .list({limit: 20}) .then(participants => participants.forEach(p => { if (p.identity !== null) { console.log("+ Participant SID: " + p.sid + " identity, Chat: " + p.identity); } else { console.log("+ Participant SID: " + p.sid + " identity, SMS: " + JSON.parse(p.attributes).name); // console.log("+ Participant SID: " + p.sid + " identity, SMS: " + p.attributes); } }) ); <file_sep><?php require __DIR__ . '/../../twilio-php-master/Twilio/autoload.php'; use Twilio\Rest\Client; $twilio = new Client(getenv('ACCOUNT_SID'), getenv('AUTH_TOKEN')); // $CHAT_SERVICE_SID = getenv('CHAT_SERVICE_SID'); $chatChannel = "CH68abfac99d55431ca14f015056251d51"; echo '+ CHAT_SERVICE_SID: ' . $CHAT_SERVICE_SID . ":\xA" . "+ Chat channel: " . $chatChannel . ":\xA"; // $members = $twilio->chat->v2->services($CHAT_SERVICE_SID) ->channels($chatChannel) ->members ->read(array(), 20); // date_default_timezone_set('America/Los_Angeles'); foreach ($members as $member) { // $date = new DateTime('2001-02-03 04:05:06'); // $date = new DateTime($member->lastConsumptionTimestamp); echo "++ Member user" . ", SID: " . $member->sid . ", identity: " . $member->identity . ", attributes: " . $member->attributes . ", index: " . $member->lastConsumedMessageIndex . ", Timestamp: " . $member->lastConsumptionTimestamp->format('d/m/Y h:i:s') . "\xA"; } echo "+ End of list.\xA"; ?> <file_sep>// Docs: https://www.twilio.com/docs/usage/security#validating-requests // Sample: // +++ Echo HTTP request data. // + URL: POST /cgi/echo1.php // ++ ToCountry => US // ++ ToState => CA // ++ SmsMessageSid => SM5b6f34ffe3a4015a838430dfc96ba84f // ++ NumMedia => 0 // ++ ToCity => SAN BRUNO // ++ FromZip => 94030 // ++ SmsSid => SM5b6f34ffe3a4015a838430dfc96ba84f // ++ FromState => CA // ++ SmsStatus => received // ++ FromCity => SAN BRUNO // ++ Body => hello 4 // ++ FromCountry => US // ++ To => +16505551111 // ++ ToZip => 94030 // ++ NumSegments => 1 // ++ MessageSid => SM5b6f34ffe3a4015a838430dfc96ba84f // ++ AccountSid => AC1...d // ++ From => +16505552222 // ++ ApiVersion => 2010-04-01 // + End of list. // +++ Echo HTTP headings.++ Connection => close // ++ User-Agent => TwilioProxy/1.1 // ++ X-Twilio-Signature => Y2qkTMkpIFtB7g8Eqp1NE0TZ6Lg= // ++ Host => tigerfarmpress.com // ++ Content-Type => application/x-www-form-urlencoded // ++ Content-Length => 413 // ++ Cache-Control => max-age=259200 // ++ Accept => */* const client = require('twilio'); const authToken = process.env.AUTH_TOKEN; // Your account Auth Token // The Twilio request URL const url = 'https://tigerfarmpress.com/echo'; // // The post variables in Twilio's request // Note, the order of the parameters does not change the outcome. const params = { "ToCountry":"CA","ToState":"Alberta","SmsMessageSid":"SM4f41cf3fb2068287f7a8ec0e006af5f8","NumMedia":"0","ToCity":"","FromZip":"94030","SmsSid":"SM4f41cf3fb2068287f7a8ec0e006af5f8","FromState":"CA","SmsStatus":"received","FromCity":"SAN BRUNO","Body":"okay1","FromCountry":"US","To":"+15875552222","ToZip":"","AddOns":"{\"status\":\"successful\",\"message\":null,\"code\":null,\"results\":{}}","NumSegments":"1","MessageSid":"SM4f41cf3fb2068287f7a8ec0e006af5f8","AccountSid":"AC1...d","From":"+16505558188","ApiVersion":"2010-04-01" }; // The X-Twilio-Signature header attached to the request // "x-twilio-signature":"lhPWa1tr2uXDFmMvdg9LQOAvsmM=" const twilioSignature = 'lhPWa1tr2uXDFmMvdg9LQOAvsmM='; console.log(client.validateRequest(authToken, twilioSignature, url, params)); <file_sep># Media Stream Tutorial Notes Consume a real-time Media Stream using WebSockets, Python, and Flask https://www.twilio.com/docs/voice/tutorials/consume-real-time-media-stream-using-websockets-python-and-flask Components: + Twilio phone number to receive incoming calls. + The Twilio phone number is configured to use a TwiML Bin. + The TwiML Bin starts a forked media stream, and dials an outbound phone number or a Twilio client. + A Python program with libraries are installed, to create and run, a websocket server. + Ngrok tunnel to the websocket server, for Twilio to stream the media. ```` Caller >> Twilio >> media stream >> Twilio client Forked >> media stream >> Ngrok tunnel >> websocket server ```` -------------------------------------------------------------------------------- ## Setup Steps Set up Python environment ```` mkdir wss cd wss pwd /.../Projects/work/wss python3 -m venv venv source ./venv/bin/activate pip install flask flask-sockets ```` From the tutorial's GitHub program repository, copy and save app.py: + From: https://github.com/TwilioDevEd/mediastreams-consume-websockets-flask + To: /Users/dthurston/Projects/wss Run the websocket server. ```` $ python3 app.py Server listening on: http://localhost:5000 ```` Open the firewall to the Flask server, using Ngrok. ```` /.../Applications/ngrok http 5000 ngrok by @inconshreveable (Ctrl+C to quit) Session Status online Session Expires 7 hours, 59 minutes Update update available (version 2.3.34, Ctrl-U to update) Version 2.2.8 Region United States (us) Web Interface http://127.0.0.1:4040 Forwarding http://4806f5c7.ngrok.io -> localhost:5000 Forwarding https://4806f5c7.ngrok.io -> localhost:5000 Connections ttl opn rt1 rt5 p50 p90 0 0 0.00 0.00 0.00 0.00 ```` Create a TwiML Bin, and use the above Ngrok tunnel. ```` <?xml version="1.0" encoding="UTF-8"?> <Response> <Start> <Stream url="wss://4806f5c7.ngrok.io/media" /> </Start> <Dial>+16505552222</Dial> </Response> ```` Another sample with a custom parameter, and dialing a Twilio Client. ```` <?xml version="1.0" encoding="UTF-8"?> <Response> <Start> <Stream url="wss://4806f5c7.ngrok.io/media"> <Parameter name="hello" value = "HelloValue" /> </Stream> </Start> <Dial><Client>david</Client></Dial> </Response> ```` I set a Twilio phone number to use the above TwiML. -------------------------------------------------------------------------------- ### Test I call my Twilio phone number, + When the call is connected, Twilio also sends information to the websocket server, + My Twilio client is prompted to Accept the call. + I accept the call, and the media is streamed to the client (david) and forked to the websocket server. In the websocket server terminal window the streamed data information. ```` $ python3 app.py Server listening on: http://localhost:5000 Connection accepted. [2019-08-28 10:57:30,430] INFO in app: Connection accepted [2019-08-28 10:57:30,520] INFO in app: Connected Message received: {"event":"connected","protocol":"Call","version":"0.2.0"} [2019-08-28 10:57:30,521] INFO in app: Start Message received: {"event":"start","sequenceNumber":"1", "start":{"accountSid":"AC1b32414e8ab41e56e6393bcbba7d5a9d", "streamSid":"MZc3320b5e6fba10a11d7c96fe1903e3f0", "callSid":"CA77145f1c2f9166cab03d083d5804d9ae", "tracks":["inbound"], "mediaFormat":{"encoding":"audio/x-mulaw","sampleRate":8000,"channels":1}, "customParameters":{"hello":"HelloValue"} }, "streamSid":"MZc3320b5e6fba10a11d7c96fe1903e3f0"} [2019-08-28 10:57:30,522] INFO in app: Media message: { "event":"media","sequenceNumber":"2", "media":{"track":"inbound","chunk":"1","timestamp":"102", "payload":"fvz+fXx9fXv//v///P5+/v3+fv/ ... +/fr7/v7+fHt9/g=="}, "streamSid":"MZc3320b5e6fba10a11d7c96fe1903e3f0" } [2019-08-28 10:57:30,522] INFO in app: Payload is: fvz+fXx9fXv//v///P5+/v3+fv/ ... +/fr7/v7+fHt9/g== [2019-08-28 10:57:30,522] INFO in app: That's 160 bytes [2019-08-28 10:57:30,523] INFO in app: Additional media messages from WebSocket are being suppressed.... [2019-08-28 10:57:37,480] INFO in app: Stop Message received: { "event":"stop","sequenceNumber":"352","streamSid":"MZc3320b5e6fba10a11d7c96fe1903e3f0", "stop":{"accountSid":"AC1b32414e8ab41e56e6393bcbba7d5a9d","callSid":"CA77145f1c2f9166cab03d083d5804d9ae"} } [2019-08-28 10:57:37,481] INFO in app: Connection closed. Received a total of 352 messages ```` -------------------------------------------------------------------------------- ## Writing a WebSocket server in Java https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java -------------------------------------------------------------------------------- Cheers... <file_sep>import base64 from flask import Flask from flask_sockets import Sockets import json import logging app = Flask(__name__) sockets = Sockets(app) HTTP_SERVER_PORT = 5000 print("+++ Start.") @sockets.route('/media') def echo(ws): print("Connection accepted.") app.logger.info("Connection accepted") # A lot of messages will be sent rapidly. We'll stop showing after the first one. has_seen_media = False message_count = 0 while not ws.closed: message = ws.receive() if message is None: app.logger.info("No message received...") continue # Messages are a JSON encoded string data = json.loads(message) # Using the event type you can determine what type of message you are receiving if data['event'] == "connected": app.logger.info("Connected Message received: {}".format(message)) if data['event'] == "start": app.logger.info("Start Message received: {}".format(message)) if data['event'] == "media": if not has_seen_media: app.logger.info("Media message: {}".format(message)) payload = data['media']['payload'] app.logger.info("Payload is: {}".format(payload)) chunk = base64.b64decode(payload) app.logger.info("That's {} bytes".format(len(chunk))) app.logger.info("Additional media messages from WebSocket are being suppressed....") has_seen_media = True if data['event'] == "stop": app.logger.info("Stop Message received: {}".format(message)) break message_count += 1 app.logger.info("Connection closed. Received a total of {} messages".format(message_count)) if __name__ == '__main__': app.logger.setLevel(logging.DEBUG) from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', HTTP_SERVER_PORT), app, handler_class=WebSocketHandler) print("Server listening on: http://localhost:" + str(HTTP_SERVER_PORT)) server.serve_forever() <file_sep>console.log("++ Create a chat participant into a Conversation."); var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); serviceSid = process.env.CONVERSATIONS_SERVICE_SID; conversationSid = process.env.CONVERSATION_SID; participantIdentity = 'dave3'; console.log("+ Conversation SID: " + conversationSid + " Participant Identity: " + participantIdentity ); client.conversations.services(serviceSid).conversations(conversationSid) .participants .create({ identity: participantIdentity, attributes: JSON.stringify({name: participantIdentity}) }) .then(participant => console.log( "+ Created participant, SID: " + participant.sid )) .catch(function (err) { if (err.toString().indexOf('Participant already exists') > 0) { console.log("+ Participant already exists."); } else if (err) { console.error("- Error: " + err); exit(); } }); ; // https://www.twilio.com/docs/conversations/api/conversation-participant-resource <file_sep>console.log("++ Send SMS message."); var client = require('twilio')(process.env.ACCOUNT_SID, process.env.AUTH_TOKEN); theMsg = "Hello with media."; theMediaUrl = 'http://tigerfarmpress.com/images/topImgLeft.jpg'; console.log("+ SID: " + process.env.ACCOUNT_SID + ", from: " + process.env.PHONE_NUMBER1 + ", to: " + process.env.PHONE_NUMBER2 + ", MSG: " + theMsg + ", theMediaUrl: " + theMediaUrl ); client.messages.create({ from: process.env.PHONE_NUMBER1, to: process.env.PHONE_NUMBER2, body: theMsg, mediaUrl: theMediaUrl }, function (err, message) { if (err) { console.error("- Error: ", err.message); console.log("--- Exit."); exit(); } console.log('+ MMS sent, SID: ' + message.sid); }); <file_sep><?php require __DIR__ . '/../../twilio-php-master/Twilio/autoload.php'; use Twilio\Rest\Client; $twilio = new Client(getenv('ACCOUNT_SID'), getenv('AUTH_TOKEN')); $conversation = $twilio->conversations->v1->conversations ->create( array( // "messagingServiceSid" => "MG507899be5f0b346466b088f148b94104", "friendlyName" => "<NAME>" ) ); print('++ Conversation SID: ' . $conversation->sid . ":\xA"); ?> <file_sep># Twilio Work Notes -------------------------------------------------------------------------------- ## Topics Create a Messaging Service and configure Advance Opt In, Opt Out settings. + [MessagingServiceOptInOut.txt](MessagingServiceOptInOut.txt) Create a public and private key pair using OpenSSL. Then upload to the public key to Twilio. + [pkcv.txt](pkcv.txt) -------------------------------------------------------------------------------- Cheers... <file_sep># Your custom Twilio Flex Plugin Twilio Flex Plugins allow you to customize the apperance and behavior of [Twilio Flex](https://www.twilio.com/flex). If you want to learn more about the capabilities and how to use the API, check out our [Flex documentation](https://www.twilio.com/docs/flex). ## Deploy Once you are happy with your plugin, you have to bundle it, in order to deploy it to Twilio Flex. Run the following command to start the bundling: ```bash npm run build ``` Afterwards, you'll find in your project a `build/` folder that contains a file with the name of your plugin project. For example `plugin-example.js`. Take this file and upload it into the Assets part of your Twilio Runtime. Note: Common packages like `React`, `ReactDOM`, `Redux` and `ReactRedux` are not bundled with the build because they are treated as external dependencies so the plugin will depend on Flex which would provide them globally. -------------------------------------------------------------------------------- + Twilio Flex Quickstart (Advanced): Getting Started with React Plugin Development: https://www.twilio.com/docs/flex/quickstart/getting-started-plugin ```` $ npm -v 6.9.0 $ node -v v10.10.0 $ npm install -g create-flex-plugin ... + create-flex-plugin@2.7.0 added 282 packages from 243 contributors in 10.553s $ pwd /.../Projects/work/flex $ create-flex-plugin plugin-p1 ? Twilio Flex Account SID AC... │ Your Twilio Flex Plugin project has been successfully created! │ │ Setup: │ │ $ cd plugin-p1/ │ │ $ npm install │ │ $ npm start │ │ $ npm run build │ │ │ │ For more info check the README.md file or go to: │ │ ➡ https://www.twilio.com/docs/flex $ cd plugin-p1 $ npm install ... $ npm start ... ```` Then access the app from your browser: http://localhost:3000/ Click, Log in with Twilio, to log into the application. -------------------------------------------------------------------------------- Cheers<file_sep>// Create a SendGrid account, and create an API Key from the menu item under Settings/API Keys. // Create a SendGrid work directory, and change into the directory. // $ npm init --yes // $ npm install @sendgrid/mail // I'm using version: 6.4.0 // Set environment variables and run this program. console.log("++ Send email message."); theMsg = "Hello from SendGrid 6"; console.log("+ SENDGRID_API_KEY: " + process.env.SENDGRID_API_KEY + ", from: " + process.env.EMAIL_TF + ", to: " + process.env.EMAIL_DT + ", MSG: " + theMsg); const sgMail = require("@sendgrid/mail"); sgMail.setApiKey(process.env.SENDGRID_API_KEY); const msg = { from: process.env.EMAIL_TF, to: process.env.EMAIL_DT, subject: "Using SendGrid", text: theMsg }; // sgMail.send(msg); sgMail.send(msg).then((sent) => { console.log("+ Sent, statusCode: " + sent[0].statusCode); // console.log("+ Sent: " + JSON.stringify(sent)); }); // + Sent: [{ // "statusCode":202, // "headers":{"server":"nginx","date":"Thu, 25 Jul 2019 20:24:19 GMT","content-length":"0","connection":"close","x-message-id":"V-dJe6MrQ6ieESJGg6r22A","access-control-allow-origin":"https://sendgrid.api-docs.io","access-control-allow-methods":"POST","access-control-allow-headers":"Authorization, Content-Type, On-behalf-of, x-sg-elas-acl","access-control-max-age":"600","x-no-cors-reason":"https://sendgrid.com/docs/Classroom/Basics/API/cors.html"}, // "request":{"uri":{"protocol":"https:","slashes":true,"auth":null,"host":"api.sendgrid.com","port":443,"hostname":"api.sendgrid.com","hash":null,"search":null,"query":null,"pathname":"/v3/mail/send","path":"/v3/mail/send","href":"https://api.sendgrid.com/v3/mail/send"}, // "method":"POST", // "headers":{"Accept":"application/json","User-agent":"sendgrid/6.3.0;nodejs","Authorization":"Bearer S...c","content-type":"application/json","content-length":196} // }},null] <file_sep>console.log("++ Send SMS message."); var client = require('twilio')(process.env.ACCOUNT_SID, process.env.AUTH_TOKEN); theMsg = "Hello 3"; console.log("+ SID: " + process.env.ACCOUNT_SID + ", from: " + process.env.PHONE_NUMBER1 + ", to: " + process.env.PHONE_NUMBER3 + ", MSG: " + theMsg); client.messages.create({ from: process.env.PHONE_NUMBER1, to: process.env.PHONE_NUMBER3, body: theMsg }, function (err, message) { if (err) { console.error("- Error: " + err.message + ", code: " + err.code); console.log("--- Exit."); } }).then((message) => console.log("+ Message sent, SID: " + message.sid)); <file_sep># Getting Started with Twilio CLI Twilio CLI [overview](https://www.twilio.com/cli), [quickstart](https://www.twilio.com/docs/twilio-cli/quickstart), [examples](https://www.twilio.com/docs/twilio-cli/examples), [general-usage](https://www.twilio.com/docs/twilio-cli/general-usage). Twilio CLI project repository: https://github.com/twilio/twilio-cli. Twilio CLI project repository issues: https://github.com/twilio/twilio-cli/issues Adam's Twilio CLI repository: https://github.com/adamchasetaylor/twilio-cli-keys ---------------------------------------------------------------------------------- ### Install Requirement: [Node.js](https://nodejs.org/) >= 8.0 Install the CLI globally: ```` $ npm install --save -g twilio-cli ```` For future reference, to update the CLI: ```` $ npm update -g twilio-cli ```` If "npm" becomes missing, reinstall or update node. ```` $ npm -version -bash: /opt/homebrew/bin/npm: No such file or directory $ brew reinstall node ... $ npm -version 7.20.3 ```` Brew commands: ```` $ brew update $ brew install node $ brew upgrade node ```` #### Create environment variables using the Recommended Method Use your current account or subaccount SID. The CLI will use the key-named environment variables. Run the Twilio command: ```` $ twilio ```` - Friendly Name: Twilio CLI. - Key Type: Standard. Click [here](https://twil.io/get-api-key) to use the Twilio Console to create an API key and secret text string. Create environment variables: - `TWILIO_ACCOUNT_SID` = your Account SID from [your console](https://www.twilio.com/console) - `TWILIO_API_KEY` = your Twilio CLI API Key SID, starts with "SK". - `TWILIO_API_SECRET` = the secret text string for the API Key. ---------------------------------------------------------------------------------- ### Send Messages #### Send an SMS message. ```` $ twilio api:core:messages:create --help Send a message from the account used to make the request ... --account-sid=account-sid --from=from --to=to --body=body $ twilio api:core:messages:create --account-sid=$TWILIO_ACCOUNT_SID --from=+16505551111 --to=+16505552222 --body="Hello there." SID From To Status Direction Date Sent SMd76001367dc84262b1e16183660e6ba4 +16505551111 +16505552222 queued outbound-api $ twilio api:core:messages:create --from=+16505551111 --to=+16505552222 --body="Hello there." SID From To Status Direction Date Sent SMd76001367dc84262b1e16183660e6ba4 +16505551111 +16505552222 queued outbound-api ```` #### Send an email message. You will need a [SendGrid](https://sendgrid.com/) account. Use your SendGrid account email address as the from email address of the sender. Click [here, Sending Email with Twilio SendGrid](https://www.twilio.com/docs/twilio-cli/general-usage#sending-email-with-twilio-sendgrid), for documentation on sending an email. ```` $ twilio email:send --help sends emails to single or multiple recipients using Twilio SendGrid ... --from=from Email address of the sender. --subject=subject The subject line for an email. --text=text Text to send within the email body. --to=to $ twilio email:send --from=<EMAIL> --to=<EMAIL> --subject="Subject this" --text="Hello there." ? Would you like to send an attachment? No Your email containing the message "Hello there." sent from <EMAIL> to <EMAIL> with the subject line "Subject this" has been sent ```` ### Navigating Help Run the following commands to get help. ```` $ twilio ... USAGE $ twilio [COMMAND] COMMANDS api advanced access to all of the Twilio APIs autocomplete display autocomplete installation instructions feedback provide feedback to the CLI team help display help for twilio incoming-phone-number show what Twilio phone numbers you have configured plugins list installed plugins project manage credentials for Twilio project $ twilio api ... COMMANDS ... api:lookups resources under lookups.twilio.com ... $ twilio api:lookups --help ... COMMANDS api:lookups:v1 version 1 of the API $ twilio api:lookups:v1 --help ... api:lookups:v1:phone-numbers Detailed information on phone numbers $ twilio api:lookups:v1:phone-numbers --help ... api:lookups:v1:phone-numbers:fetch fetch a PhoneNumbers resource $ twilio api:lookups:v1:phone-numbers:fetch --help ... OPTIONS -l, --cli-log-level=(debug|info|warn|error|none) [default: info] Level of logging messages. -o, --cli-output-format=(columns|json|tsv) [default: columns] Format of command output. -p, --project=project Shorthand identifier for your Twilio project. --add-ons=add-ons The unique_name of an Add-on you would like to invoke --add-ons-data=add-ons-data Data specific to the add-on you would like to invoke --country-code=country-code The ISO country code of the phone number --phone-number=phone-number (required) The phone number to fetch in E.164 format --properties=properties [default: callerName,countryCode,carrier] The properties you would like to display (JSON output always shows all properties). --type=type The type of information to return ```` ##### Using Lookups Confirm a phone number. ```` $ twilio api:lookups:v1:phone-numbers:fetch --phone-number=+16505551234 --properties=nationalFormat National Format (650) 555-1234 ```` On _any_ command, you can add `-o json` to change the output format to JSON. ```` $ twilio api:lookups:v1:phone-numbers:fetch --phone-number=+16505551234 -o json [ { "callerName": null, "countryCode": "US", "phoneNumber": "+16505551234", "nationalFormat": "(650) 555-1234", "carrier": null, "addOns": null, "url": "https://lookups.twilio.com/v1/PhoneNumbers/+16505551234" } ] ```` Once you have the JSON attribute names, you can use them in the "--properties" tag. ```` $ twilio api:lookups:v1:phone-numbers:fetch --phone-number=+16505551234 --properties=countryCode,nationalFormat, Country Code National Format US (650) 555-1234 ```` #### API Core ```` $ twilio api:core --help ... COMMANDS ... api:core:available-phone-numbers Country codes with available phone numbers ... api:core:conferences Voice call conferences ... api:core:incoming-phone-numbers Incoming phone numbers on a Twilio account/project ... $ twilio api:core:incoming-phone-numbers --help COMMANDS api:core:incoming-phone-numbers:create Purchase a phone-number for the account. api:core:incoming-phone-numbers:fetch Fetch an incoming-phone-number belonging to the account used to make the request. api:core:incoming-phone-numbers:list Retrieve a list of incoming-phone-numbers belonging to the account used to make the request. api:core:incoming-phone-numbers:remove Delete a phone-numbers belonging to the account used to make the request. api:core:incoming-phone-numbers:update Update an incoming-phone-number instance. ... ```` List command, ```` $ twilio api:core:incoming-phone-numbers:list SID Phone Number Friendly Name PN1..............................Z +16505557890 (650) 555-7890 PN2..............................W +16505552357 (650) 555-2357 ... ```` List only phone numbers that begin with "+1650". ```` $ twilio api:core:incoming-phone-numbers:list --phone-number="+1650" ```` A default listing, is for at most 50 phone numbers. ```` $ twilio api:core:incoming-phone-numbers:list --no-limit ... ```` When using the fetch command, do include "api:core:". ```` $ twilio api:core:incoming-phone-numbers:fetch --sid=PN1...Z SID Phone Number Friendly Name PN1..............................Z +16505557890 (650) 555-7890 $ twilio api:core:incoming-phone-numbers:fetch --sid=PN1...Z --properties=friendlyName,dateCreated,capabilities Friendly Name Date Created Capabilities (650) 555-7890 Mon Nov 20 2017 11:04:46 GMT-0800 (Pacific Standard Time) [object Object] $ twilio api:core:incoming-phone-numbers:fetch --sid=PN1...Z -o json [ { "accountSid": "AC1...Z", "addressSid": null, "addressRequirements": "none", "apiVersion": "2010-04-01", "beta": false, "capabilities": { "voice": true, "sms": true, "mms": true, "fax": true }, "dateCreated": "2017-11-20T19:04:46.000Z", "dateUpdated": "2019-04-23T01:26:30.000Z", "friendlyName": "(650) 555-7890", "identitySid": null, "phoneNumber": "+16505557890", "origin": "twilio", "sid": "PN1...Z", "smsApplicationSid": "", "smsFallbackMethod": "POST", "smsFallbackUrl": "", "smsMethod": "POST", "smsUrl": "https://handler.twilio.com/twiml/EHa...8", "statusCallback": "", "statusCallbackMethod": "POST", "trunkSid": null, "uri": "/2010-04-01/Accounts/AC1...Z/IncomingPhoneNumbers/PN1...Z.json", "voiceApplicationSid": "", "voiceCallerIdLookup": false, "voiceFallbackMethod": "POST", "voiceFallbackUrl": "", "voiceMethod": "POST", "voiceUrl": "https://webhooks.twilio.com/v1/Accounts/AC1...Z/Flows/FW6...a", "emergencyStatus": "Inactive", "emergencyAddressSid": null } ] ```` Phone numbers available for purchase: ```` $ twilio api:core:available-phone-numbers:local:list --country-code US Phone Number Region ISO Country Address Requirements +12097804046 CA US none +13236213646 CA US none +13239874629 CA US none ... $ twilio api:core:available-phone-numbers:local:list --country-code US --area-code 510 Phone Number Region ISO Country Address Requirements +15107613747 CA US none +15107613978 CA US none +15108005997 CA US none ... $ twilio api:core:available-phone-numbers:local:list --country-code US --in-region NY Phone Number Region ISO Country Address Requirements +15185477074 NY US none +18452503736 NY US none +15188686191 NY US none +15188641018 NY US none +16072149237 NY US none ... ```` #### Conference calls ```` $ twilio api:core:conferences --help ... COMMANDS api:core:conferences:fetch Fetch an instance of a conference api:core:conferences:list Retrieve a list of conferences belonging to the account used to make the request api:core:conferences:participants Conference participants api:core:conferences:recordings Recordings of conferences api:core:conferences:update update an Accounts resource $ twilio api:core:conferences:list --help ... OPTIONS ... --friendly-name=friendly-name The string that identifies the Conference resources to read --status=(init|in-progress|completed) The status of the resources to read $ twilio api:core:conferences:list --status=in-progress SID Friendly Name Status CF1d18648474636042929720608eccb578 support in-progress $ twilio api:core:conferences:update --help ... OPTIONS ... --sid=sid (required) The unique string that identifies this resource --status=(completed) The new status of the resource ... $ twilio api:core:conferences:update --sid=CF1d18648474636042929720608eccb578 --status=completed SID Friendly Name Status CF1d18648474636042929720608eccb578 support completed $ twilio api:core:conferences:list --properties=friendlyName,dateCreated,status --date-created=2019-05-31 Friendly Name Date Created Status support Fri May 31 2019 12:08:37 GMT-0700 (Pacific Daylight Time) in-progress sales Fri May 31 2019 11:49:56 GMT-0700 (Pacific Daylight Time) completed support Fri May 31 2019 11:45:59 GMT-0700 (Pacific Daylight Time) completed ```` ---------------------------------------------------------------------------------- ### Testing Twilo Programmable Chat ##### List Chat services. ```` $ twilio api:chat:v2:services Top level scope for all chat resources USAGE $ twilio api:chat:v2:services:COMMAND COMMANDS api:chat:v2:services:bindings Push notification subscription for users api:chat:v2:services:channels Channels represent chat rooms api:chat:v2:services:create create a Services resource api:chat:v2:services:fetch fetch a Services resource api:chat:v2:services:list list multiple Services resources api:chat:v2:services:remove remove a Services resource api:chat:v2:services:roles Roles determining user or member permissions api:chat:v2:services:update update a Services resource api:chat:v2:services:users Unique chat users within a chat service $ twilio api:chat:v2:services:list SID Friendly Name Date Created ISb0f6d2b83ec44f91885008ef51eb7d6b autopilot_simulator_UA96376fff94c83ea0349a3f97651f4f77 Aug 19 2021 17:11:41 GMT-0700 IS4ebcc2d46cda47958628e59af9e53e55 Default Conversations Service Jul 23 2020 10:03:03 GMT-0700 IS973ddbf230364f8dab02c6418779a602 chatService1 Jul 30 2018 16:58:17 GMT-0700 IS186702e405b74452a449d67b9265669f Frontline Service Jul 13 2021 18:14:52 GMT-0700 ```` ##### List channels for a service. ```` $ twilio api:chat:v2:services:channels Channels represent chat rooms USAGE $ twilio api:chat:v2:services:channels:COMMAND COMMANDS api:chat:v2:services:channels:create create a Channels resource api:chat:v2:services:channels:fetch fetch a Channels resource api:chat:v2:services:channels:invites Pending invitations to users to become channel members api:chat:v2:services:channels:list list multiple Channels resources api:chat:v2:services:channels:members Users joined to specific channels api:chat:v2:services:channels:messages Individual chat messages api:chat:v2:services:channels:remove remove a Channels resource api:chat:v2:services:channels:update update a Channels resource api:chat:v2:services:channels:webhooks Webhooks for specific channels $ twilio api:chat:v2:services:channels:list --service-sid IS4ebcc2d46cda47958628e59af9e53e55 SID Unique Name Friendly Name CHb8fabd3cf43948ddaaaa6f34162f972f chatc1a chatc1a CH0d499dee76f04d5b97ee6bf27e72a3cd tfpecho tfpecho CH36ac5fb4a42e4f92a63155b4524fd8fb null Hello Conversation CH56053c069586435795bf7c14417cead9 null ReadyP1 CHc97669141a784c92a74c296c84850d25 abc abc CHeedba31ca8114e099294549b22fe3336 c1a c1a ```` ##### List members in a channel. ```` $ twilio api:chat:v2:services:channels:members Users joined to specific channels USAGE $ twilio api:chat:v2:services:channels:members:COMMAND COMMANDS api:chat:v2:services:channels:members:create create a Members resource api:chat:v2:services:channels:members:fetch fetch a Members resource api:chat:v2:services:channels:members:list list multiple Members resources api:chat:v2:services:channels:members:remove remove a Members resource api:chat:v2:services:channels:members:update update a Members resource $ twilio api:chat:v2:services:channels:members:list --service-sid IS4ebcc2d46cda47958628e59af9e53e55 --channel-sid CHc97669141a784c92a74c296c84850d25 SID Identity Date Created MB07e08f36c62b4500ade72c3a82c96f2f dave Aug 12 2021 14:21:11 GMT-0700 MB54907865d0eb407c8208e228dd6a4216 dave2 Aug 12 2021 13:12:48 GMT-0700 $ twilio api:chat:v2:services:channels:members:fetch --service-sid IS4ebcc2d46cda47958628e59af9e53e55 --channel-sid CHc97669141a784c92a74c296c84850d25 --sid MB07e08f36c62b4500ade72c3a82c96f2f SID Identity Date Created MB07e08f36c62b4500ade72c3a82c96f2f dave Aug 12 2021 14:21:11 GMT-0700 ```` ---------------------------------------------------------------------------------- ### Testing Twilo Conversations ```` $ twilio api:conversations:v1:conversations --help TODO: Resource-level docs USAGE $ twilio api:conversations:v1:conversations:COMMAND COMMANDS api:conversations:v1:conversations:create [PREVIEW] create a Conversations resource api:conversations:v1:conversations:fetch [PREVIEW] fetch a Conversations resource api:conversations:v1:conversations:list [PREVIEW] list multiple Conversations resources api:conversations:v1:conversations:messages TODO: Resource-level docs api:conversations:v1:conversations:participants TODO: Resource-level docs api:conversations:v1:conversations:remove [PREVIEW] remove a Conversations resource api:conversations:v1:conversations:update [PREVIEW] update a Conversations resource api:conversations:v1:conversations:webhooks TODO: Resource-level docs ```` A Messaging Service SID is required to create Conversation. ```` $ twilio api:messaging:v1:services:list SID Friendly Name Date Created MG507...........................04 Send to echo program Aug 17 2018 17:15:05 GMT-0700 ... $ twilio api:conversations:v1:conversations:create --friendly-name="Hello Conversation" --messaging-service-sid=$MESSAGING_SERVICE_SID SID Friendly Name Date Created CHc1312b8f953047e18dfee082ee4f1722 Hello Conversation Aug 22 2019 17:56:12 GMT-0700 $ twilio api:conversations:v1:conversations:list SID Friendly Name Date Created CHc1312b8f953047e18dfee082ee4f1722 Hello Conversation Aug 22 2019 17:56:12 GMT-0700 $ twilio api:conversations:v1:conversations:participants --help COMMANDS api:conversations:v1:conversations:participants:create [PREVIEW] create a Participants resource api:conversations:v1:conversations:participants:fetch [PREVIEW] fetch a Participants resource api:conversations:v1:conversations:participants:list [PREVIEW] list multiple Participants resources api:conversations:v1:conversations:participants:remove [PREVIEW] remove a Participants resource api:conversations:v1:conversations:participants:update [PREVIEW] update a Participants resource $ twilio api:conversations:v1:conversations:participants:create --help OPTIONS --conversation-sid=conversation-sid The unique id of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource). --identity=identity Chat User identity string. --messaging-binding.address=messaging-binding.address The participant's mobile device phone number. --messaging-binding.proxy-address=messaging-binding.proxy-address Your Twilio phone number that the participant is in contact with. $ twilio api:conversations:v1:conversations:participants:create --conversation-sid=CHc1312b8f953047e18dfee082ee4f1722 --messaging-binding.proxy-address=$PHONE_NUMBER5 --messaging-binding.address=$MY_PHONE_NUMBER SID Messaging Binding MB1523ab07d8ac48d0a5d64527f5bca729 [object Object] ```` Get a Chat user token, which has an identity, in this example, "david". ```` $ twilio api:conversations:v1:conversations:participants:create --conversation-sid=CHc1312b8f953047e18dfee082ee4f1722 --identity=david SID Messaging Binding MB337ea915c8e14ab2ba1b275ffb2a7afb ```` Add a participant using 2 Twilio phone numbers. ```` $ twilio api:conversations:v1:conversations:participants:create --conversation-sid=CHc1312b8f953047e18dfee082ee4f1722 --messaging-binding.proxy-address=$PHONE_NUMBER4 --messaging-binding.address=$PHONE_NUMBER3 SID Messaging Binding MBd9467123ba6c4d54aed550f94925fa00 [object Object] $ twilio api:conversations:v1:conversations:participants:list --conversation-sid=CHc1312b8f953047e18dfee082ee4f1722 SID Messaging Binding MB1523ab07d8ac48d0a5d64527f5bca729 [object Object] MB337ea915c8e14ab2ba1b275ffb2a7afb MBd9467123ba6c4d54aed550f94925fa00 [object Object] ```` Information from the (quickstart)[https://www.twilio.com/docs/conversations/quickstart] ```` "messagingBindingAddress" => "Your Personal Mobile Number", "messagingBindingProxyAddress" => "Your purchased Twilio Phone Number" ```` For your chat-service-sid, use the unique Chat service SID starting with "ISXXX..." that you copied after creating your Conversation. Need to run the following to enable Conversations with a chat user. ```` $ twilio api:conversations:v1:conversations:list SID Chat Service SID Friendly Name Date Created CHc1312b8f953047e18dfee082ee4f1722 IS4feb8a8608fb4743a35f57687ae3a85a Hello Conversation Aug 22 2019 17:56:12 GMT-0700 $ twilio api:conversations:v1:conversations:participants:create --conversation-sid=CHc1312b8f953047e18dfee082ee4f1722 --identity=stacy SID Messaging Binding MB337ea915c8e14ab2ba1b275ffb2a7afb twilio api:conversations:v1:conversations:participants:remove --conversation-sid=CHc1312b8f953047e18dfee082ee4f1722 --identity=stacy $ twilio api:conversations:v1:conversations:participants:fetch --conversation-sid=CHc1312b8f953047e18dfee082ee4f1722 --sid=MB1c323adb37444ed9961d52baa049ac4b -o json [ { "accountSid": "AC1b32414e8ab41e56e6393bcbba7d5a9d", "conversationSid": "CHc1312b8f953047e18dfee082ee4f1722", "dateCreated": "2019-08-23T22:50:56.000Z", "dateUpdated": "2019-08-23T22:50:56.000Z", "identity": "david", "messagingBinding": null, "sid": "MB1c323adb37444ed9961d52baa049ac4b", "url": "https://conversations.twilio.com/v1/Conversations/CHc1312b8f953047e18dfee082ee4f1722/Participants/MB1c323adb37444ed9961d52baa049ac4b" } ] ```` Use the above Chat Service SID(IS4feb8a8608fb4743a35f57687ae3a85a), with the participants identity (david), to join the Conversation. A Chat service was created in my account, Chat Service SID; IS4feb8a8608fb4743a35f57687ae3a85a. Sample Conversations Chat web application: https://codesandbox.io/s/github/TwilioDevEd/demo-chat-app Side note regarding WhatsApp ```` twilio api:conversations:v1:conversations:participants:create -p zod \ --conversation-sid CH2...0 \ --messaging-binding.address whatsapp:+15125551111 \ --messaging-binding.proxy-address "whatsapp:+15125552222" ```` Testing... ```` twilio api:conversations:v1:conversations:participants:list --conversation-sid=CHc1312b8f953047e18dfee082ee4f1722 SID Messaging Binding MBd9467123ba6c4d54aed550f94925fa00 {"proxyAddress":"+16508668225","type":"sms","address":"+16508668232"} twilio api:conversations:v1:conversations:list SID Chat Service SID Friendly Name Date Created CHc1312b8f953047e18dfee082ee4f1722 IS4feb8a8608fb4743a35f57687ae3a85a Hello Conversation Aug 22 2019 17:56:12 GMT-0700 twilio api:conversations:v1:conversations:remove --sid=CHc1312b8f953047e18dfee082ee4f1722 The resource was deleted successfully ```` ---------------------------------------------------------------------------------- Testing 2 ```` twilio api:conversations:v1:conversations:create --friendly-name="Hello Conversation" --messaging-service-sid=$MESSAGING_SERVICE_SID SID Chat Service SID Friendly Name Date Created CH9bf6c8b0012547eb9a0e6c127388a812 IS4feb8a8608fb4743a35f57687ae3a85a Hello Conversation Aug 23 2019 16:54:25 GMT-0700 twilio api:conversations:v1:conversations:participants:create --conversation-sid=CH9bf6c8b0012547eb9a0e6c127388a812 --messaging-binding.proxy-address=$PHONE_NUMBER4 --messaging-binding.address=$MY_PHONE_NUMBER SID Messaging Binding MB3c0e35cb4a074a8d91eac8db02c473ec {"proxyAddress":"+16508668225","type":"sms","address":"+16504837603"} twilio api:conversations:v1:conversations:remove --sid=CH9bf6c8b0012547eb9a0e6c127388a812 The resource was deleted successfully ```` ---------------------------------------------------------------------------------- ### BulkExport using Twilio CLI We have a new API for pulling logs, BulkExport API. Custom BulkExport Jobs allow you to create exports for any date range. BulkExport API overview, https://www.twilio.com/docs/usage/bulkexport + The API provides an efficient mechanism for retrieving all of your activity logs from the Twilio platform on an ongoing basis, or for one-off downloads. + Using BulkExport, you can provide daily dumps of the previous day's Messages, eliminating the need to iterate through the Message list resource one page at a time to download your Message records. [Export Custom Job Resource](https://www.twilio.com/docs/usage/bulkexport/export-custom-job), Custom Jobs allow you to create exports for any date range. If the date range spans multiple days, they will generate separate output days. Note, if there are no message logs on a particular day, then no report file is generated for that day. [Job Resource](https://www.twilio.com/docs/usage/bulkexport/job), The Job resource allows you to view and delete the requests for exports of arbitrary date ranges, submitted through the ExportCustom Job. [Day Resource](https://www.twilio.com/docs/usage/bulkexport/day), The Day resource allows you to download the export file containing a single day's data for your account and the requested data type. [File output format](https://www.twilio.com/docs/usage/bulkexport#bulkexport-file-format), The messages file format is a sequence of JSON records, similar to the Message Resource. Create a job. ```` twilio api:bulkexports:v1:exports:jobs:create \ --resource-type Messages \ --friendly-name ExportJuly27b \ --start-day 2020-07-01 \ --end-day 2020-07-27 \ --properties=friendlyName \ --email <EMAIL> \ --webhook-method GET \ --webhook-url http://www.example.com/echo Friendly Name ExportJuly27b ```` List the recent jobs. ```` $ twilio api:bulkexports:v1:exports:jobs:list --resource-type Messages --properties=friendlyName,jobSid Friendly Name Job SID ExportJuly27 JS1dca2e0dfb7815c1fea2362d9f61c16c ExportJuly27 JS677d0986311ebb99cfa945425e1889c0 ExportJuly27b JSed5cd7ba5451574475d4d4bb890aed4f $ twilio api:bulkexports:v1:exports:jobs:list --resource-type Messages --properties=friendlyName,jobSid,details Friendly Name Job SID Details ExportJuly27 JS1dca2e0dfb7815c1fea2362d9f61c16c {"0":{"status":"Running",... ... Statuses: "Submitted", "Running", "CompletedEmptyRecords", "Completed". ```` Remove a job. ```` $ twilio api:bulkexports:v1:exports:jobs:remove --job-sid=JS677d0986311ebb99cfa945425e1889c0 ```` Fetch a single job's information. ```` $ twilio api:bulkexports:v1:exports:jobs:fetch --job-sid=JSed5cd7ba5451574475d4d4bb890aed4f --properties=friendlyName,startDay,endDay,details Friendly Name Start Day End Day Details ExportJuly27 2020-07-01 2020-07-27 {"0":{"status":"Submitted","count":27,"days":null}} $ twilio api:bulkexports:v1:exports:days:fetch --resource-type=Messages --day= --properties=days [{"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-01","resource_type":null,"size":750}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-02","resource_type":null,"size":945}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-03","resource_type":null,"size":669}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-10","resource_type":null,"size":997}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-12","resource_type":null,"size":420}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-13","resource_type":null,"size":454}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-14","resource_type":null,"size":767}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-15","resource_type":null,"size":1166}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-16","resource_type":null,"size":825}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-17","resource_type":null,"size":1146}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-18","resource_type":null,"size":738}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-19","resource_type":null,"size":1705}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-21","resource_type":null,"size":554}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-23","resource_type":null,"size":615}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-24","resource_type":null,"size":449}, {"friendly_name":"ExportJuly27b","create_date":"2020-07-27","day":"2020-07-26","resource_type":null,"size":398} ] $ twilio api:bulkexports:v1:exports:jobs:fetch --job-sid=JSed5cd7ba5451574475d4d4bb890aed4f --properties=friendlyName,startDay,endDay,details Friendly Name Start Day End Day Details ExportJuly27b 2020-07-01 2020-07-27 {"0":{"status":"Completed","count":27,"days":null}} ```` Following needs to be re-tested. ```` $ twilio api:bulkexports:v1:exports:days:fetch --resource-type=Messages --day=2020-07-26 ... ```` ### BulkExport using cURL Following is complete steps using curl. I can create and download reports using curl. Create a job. ```` curl -X POST https://bulkexports.twilio.com/v1/Exports/Messages/Jobs \ --data-urlencode "StartDay=2020-07-01" \ --data-urlencode "EndDay=2020-07-27" \ --data-urlencode "FriendlyName=ExportJuly27" \ --data-urlencode "Email=<EMAIL>" \ --data-urlencode "WebhookMethod=GET" \ --data-urlencode "WebhookUrl=http://www.example.com/echo" \ -u TwilioAccountSID:TwilioAuthToken {"start_day": "2020-07-01", "job_sid": "JS1dca2e0dfb7815c1fea2362d9f61c16c", "friendly_name": "ExportJuly27", "webhook_method": "GET", "details": null, "end_day": "2020-07-27", "webhook_url": "http://www.example.com/echo", "email": "<EMAIL>", "resource_type": null} ```` Get a job's information. ```` curl -X GET 'https://bulkexports.twilio.com/v1/Exports/Jobs/JS1dca2e0dfb7815c1fea2362d9f61c16c' \ -u TwilioAccountSID:TwilioAuthToken { "job_sid": "JS1dca2e0dfb7815c1fea2362d9f61c16c", "start_day": "2020-07-01", "end_day": "2020-07-27", "url": "https://bulkexports.twilio.com/v1/Exports/Jobs/JS1dca2e0dfb7815c1fea2362d9f61c16c", "friendly_name": "ExportJuly27", "webhook_method": "GET", "webhook_url": "http://www.example.com/echo", "email": "<EMAIL>", "resource_type": "Messages" "details": [{"status": "Submitted", "count": 27, "days": null}], } curl -X GET 'https://bulkexports.twilio.com/v1/Exports/Messages/Days?PageSize=20' \ -u TwilioAccountSID:TwilioAuthToken { "meta": {"page": 0, "page_size": 20, "first_page_url": "https://bulkexports.twilio.com/v1/Exports/Messages/Days?PageSize=20&Page=0", "previous_page_url": null, "url": "https://bulkexports.twilio.com/v1/Exports/Messages/Days?PageSize=20&Page=0", "next_page_url": null, "key": "days" }, "days": [] } ```` Get a job's information that is processing a number of days. ```` curl -X GET 'https://bulkexports.twilio.com/v1/Exports/Messages/Days/' \ -u TwilioAccountSID:TwilioAuthToken {"meta": {"page": 0, "page_size": 50, " first_page_url": "https://bulkexports.twilio.com/v1/Exports/Messages/Days?PageSize=50&Page=0", "previous_page_url": null, "url": "https://bulkexports.twilio.com/v1/Exports/Messages/Days?PageSize=50&Page=0", "next_page_url": null, "key": "days"}, "days": [ {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-01", "resource_type": null, "size": 750}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-02", "resource_type": null, "size": 945}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-03", "resource_type": null, "size": 669}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-10", "resource_type": null, "size": 997}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-12", "resource_type": null, "size": 420}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-13", "resource_type": null, "size": 454}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-14", "resource_type": null, "size": 767}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-15", "resource_type": null, "size": 1166}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-16", "resource_type": null, "size": 825}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-17", "resource_type": null, "size": 1146}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-18", "resource_type": null, "size": 738}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-19", "resource_type": null, "size": 1705}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-21", "resource_type": null, "size": 554}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-23", "resource_type": null, "size": 615}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-24", "resource_type": null, "size": 449}, {"friendly_name": "ExportJuly27b", "create_date": "2020-07-27", "day": "2020-07-26", "resource_type": null, "size": 398} ]} ```` Get information for a specific job report day. ```` curl -X GET 'https://bulkexports.twilio.com/v1/Exports/Messages/Days/2020-07-26' \ -u TwilioAccountSID:TwilioAuthToken {"redirect_to": "https://...s3.amazonaws.com/daily/day%3D2020-07-26/type%3DMessages/account%3DACa...3/..."} ```` Use a browser to download the file using the above URL: ```` { "status":"delivered", "account_sid":"ACa...3", "from":"+16505551111", "to":"+16505552222", "body":"+16505551111 : Hey there... do you want to try?", "num_segments":1, "date_sent":"2020-07-26T22:21:20Z","date_updated":"2020-07-26T22:21:20Z","price":"-0.00750", "date_created":"2020-07-26T22:21:20Z","error_code":0, "sid":"SM21f63b5f7629f4b69cd079b5c5225dcb","flags":65618,"messaging_service_sid":null, "direction":"outbound-reply","start":"2020-07-26","num_media":0} { "status":"received", "account_sid":"ACa...3", "from":"+16505551111", "to":"+16505552222", "body":"Hey there... do you want to try?", "num_segments":1, "date_sent":"2020-07-26T22:21:20Z","date_updated":"2020-07-26T22:21:20Z","price":"-0.00750", "date_created":"2020-07-26T22:21:20Z","error_code":0, "sid":"SM4ff301c8b05cbfd0ff415473190fd6f1","flags":17,"messaging_service_sid":null, "direction":"inbound","start":"2020-07-26","num_media":0} ```` ---------------------------------------------------------------------------------- ### Delete a Function from a Function Service It takes preliminary steps to be able to delete a function. Following are the deletion steps with an example I went through. 1. Undeploy the build. Given the Twilio Functions Service SID, get the environment SID which also gives the current build. ```` $ twilio api:serverless:v1:services:environments:list --service-sid ZSb2201277346da03f6ca1ea804ce3aaba SID Unique Name Domain Name Build SID ZE962caae126f94f91c52b5beb3c5403a0 ui mine-2357.twil.io ZBbea269aac6dcf9332e57e3a0702659c0 ```` Use create to delete the build. ```` $ twilio api:serverless:v1:services:environments:deployments:create --service-sid ZSb2201277346da03f6ca1ea804ce3aaba --environment-sid ZE962caae126f94f91c52b5beb3c5403a0 SID Build SID Date Created ZDba15f7e0415c23cfb6baa40938db741f null Mar 29 2021 13:57:13 GMT-0700 ```` Note, the Function Service is no longer deployed (Build SID = null). 2. Delete any builds that reference the function that haven't been reaped Remove the build. ```` $ twilio api:serverless:v1:services:builds:remove --service-sid ZSb2201277346da03f6ca1ea804ce3aaba --sid ZBbea269aac6dcf9332e57e3a0702659c0 The resource was deleted successfully ```` 3. Delete the Function Resource ```` $ twilio api:serverless:v1:services:functions:remove --service-sid ZSb2201277346da03f6ca1ea804ce3aaba --sid ZH1100b8ce0150592646eaf625cee01e5a The resource was deleted successfully ```` -------------------------------------------------------------------------------- #### Tailing Twilio Functions Log Messages To test the display of log messages, I enabled live logs in the Twilio Console and did a test by running my "/sayHello" function from a browser. From the Twilio Console, I went to my Twilio Function service and click, Enable live logs. Then, log messages were streamed to the lower part of the page. Next, I used the Twilio CLI to tail the streaming log messages. Twilio CLI help options shows the syntax requirements. ```` $ twilio serverless:logs --help USAGE $ twilio serverless:logs OPTIONS ... --environment=environment [default: dev] The environment to retrieve the logs for --function-sid=function-sid Specific Function SID to retrieve logs for --load-system-env Uses system environment variables as fallback for variables specified in your .env file. Needs to be used with --env explicitly specified. --service-sid=service-sid Specific Serverless Service SID to retrieve logs for --tail Continuously stream the logs ```` I retrieved my service's environment value: ```` $ twilio api:serverless:v1:services:environments:list --service-sid ZSb2201277346da03f6ca1ea804ce3aaba SID Unique Name Domain Name Build SID ZE962caae126f94f91c52b5beb3c5403a0 ui classics-8587.twil.io ZB41959c4e3784967e7b71ef14e112e9c5 ```` I used the service's environment value in the command to tail my logs: ```` $ twilio serverless:logs --service-sid=ZSb2201277346da03f6ca1ea804ce3aaba --environment=ZE962caae126f94f91c52b5beb3c5403a0 --tail [INFO][2021-04-26T23:06:29Z]: Hello there. [INFO][2021-04-26T23:06:40Z]: Hello there. [INFO][2021-04-26T23:06:47Z]: Hello there. [INFO][2021-04-26T23:14:01Z]: Hello there. [INFO][2021-04-26T23:21:53Z]: Hello there. ```` Each time I ran my "/sayHello" function, the log messages were listed. ---------------------------------------------------------------------------------- ### Generate API Keys and secret strings To [generate API Keys and secret strings](https://www.twilio.com/docs/iam/keys/api-key), use TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN for [authentication](https://www.twilio.com/docs/twilio-cli/general-usage#want-to-use-environment-variables-instead-of-creating-a-profile)(Option 2). ```` export TWILIO_ACCOUNT_SID=<KEY> export TWILIO_AUTH_TOKEN=<PASSWORD> ```` The following creates an API Key and secret string. ```` $ twilio api:core:keys:create --friendly-name=p1 SID Friendly Name Date Created SK93...5b p1 May 24 2021 09:25:21 GMT-0700 ```` ---------------------------------------------------------------------------------- Cheers... <file_sep>// ----------------------------------------------------------------------------- // $ node createBindings.js peter $PHONE_NUMBER1 one // $ node createBindings.js paul $PHONE_NUMBER2 other // $ node createBindings.js mary $PHONE_NUMBER3 other // $ node createBindings.js david $PHONE_NUMBER4 // $ node listBindingsByTag.js console.log("+++ Start."); var theIdentity = process.argv[2] || "test"; var thePhoneNumber = process.argv[3] || "+16505552222"; var theTag = process.argv[4] || ""; const accountSid = process.env.ACCOUNT_SID; const authToken = process.env.AUTH_TOKEN; const client = require('twilio')(accountSid, authToken); console.log("+ Create SMS binding for: " + theIdentity + ", Phone Number = " + thePhoneNumber + ", tag = " + theTag); client.notify.services(process.env.NOTIFY_SERVICE_SID).bindings .create({ bindingType: 'sms', identity: theIdentity, address: thePhoneNumber, tag: theTag }) .then(binding => console.log("+ Created : " + binding.sid)); // ----------------------------------------------------------------------------- <file_sep>import * as FlexPlugin from 'flex-plugin'; import P1Plugin from './P1Plugin'; FlexPlugin.loadPlugin(P1Plugin); <file_sep>console.log("++ List Participants for a Conversation."); var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); // conversationSid = process.env.CONVERSATION_SID; conversationSid = "CH0269d9f270744259977cff1ae19d5a5f"; console.log("+ Conversation SID: " + conversationSid); client.conversations.conversations(conversationSid) .participants .list({limit: 20}) .then(participants => participants.forEach(p => { if (p.identity !== null) { console.log("+ Participant SID: " + p.sid + " identity, Chat: " + p.identity); } else { console.log("+ Participant SID: " + p.sid + " identity, SMS: " + JSON.parse(p.attributes).name); } }) ); <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Message; import com.twilio.type.PhoneNumber; /** * * @author dthurston */ @WebServlet(urlPatterns = {"/sendsms"}) public class sendsms extends HttpServlet { private static final String ACCOUNT_SID = System.getenv("ACCOUNT_SID"); private static final String AUTH_TOKEN = System.getenv("AUTH_TOKEN"); /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet sendsms</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet sendsms at " + request.getContextPath() + "</h1>"); out.println("<hr>"); Twilio.init(ACCOUNT_SID, AUTH_TOKEN); String fromPhoneNumber = System.getenv("PHONE_NUMBER2"); String toPhoneNumber = System.getenv("PHONE_NUMBER3"); String theMsg = "Send from Java Servlet"; Message message = Message.creator( new PhoneNumber(toPhoneNumber), new PhoneNumber(fromPhoneNumber), theMsg ).create(); // Immediately returned values: out.println("+ Message SID: " + message.getSid()); out.println("+ Status: " + message.getStatus()); out.println("+ from: " + message.getFrom()); out.println("+ to: " + message.getTo()); out.println("+ Message text: " + message.getBody()); out.println("<hr>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>console.log("++ Generate a Conversations token."); const AccessToken = require('../../node_modules/twilio').jwt.AccessToken; const ChatGrant = AccessToken.ChatGrant; twilioAccountSid = process.env.MASTER_ACCOUNT_SID; twilioApiKey = process.env.API_KEY; twilioApiSecret = process.env.API_KEY_SECRET; const identity = 'dave'; const token = new AccessToken( twilioAccountSid, twilioApiKey, twilioApiSecret, {identity: identity, ttl:3600} ); const serviceSid = process.env.CONVERSATIONS_SERVICE_SID; const chatGrant = new ChatGrant({ serviceSid: serviceSid, }); token.addGrant(chatGrant); // Serialize the token to a JWT string console.log(token.toJwt()); <file_sep>console.log("++ List a Service's Conversations."); // https://www.twilio.com/docs/conversations/api/service-conversation-resource // var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN, {logLevel: 'debug'}); var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); serviceSid = process.env.CONVERSATIONS_SERVICE_SID; // serviceSid = 'IS186702e405b74452a449d67b9265669f'; // Frontline client.conversations.services(serviceSid).conversations.list({limit: 20}) .then(conversations => conversations.forEach(c => { console.log( "+ Conversation SID: " + c.sid + " " + c.friendlyName ); }));<file_sep># VB Samples and support files Newtonsoft.Json-10.dll was created using Alex makefile. Newtonsoft.Json-9.dll was created using Xamarin. Twilio-5.27.0.dll was created using Alex makefile. Twilio-5.25.0.dll was created using Xamarin. + To view compile options: $ man vbnc + It is possible to compile using a config file. Cheers...<file_sep>console.log("++ Remove a Service's Conversations."); // https://www.twilio.com/docs/conversations/api/service-conversation-resource var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); conversationSid = 'CH47e05cd819d04e08a04274933929021d'; serviceSid = process.env.CONVERSATIONS_SERVICE_SID; // serviceSid = 'IS186702e405b74452a449d67b9265669f'; // Frontline client.conversations.services(serviceSid).conversations(conversationSid) .fetch() .then(conversation => { console.log( "+ Remove conversation, SID: " + conversation.sid + " " + conversation.friendlyName ); client.conversations.services(serviceSid).conversations(conversationSid).remove(); }); <file_sep>// https://sendgrid.com/docs/API_Reference/Web_API/mail.html // Optional: toname=David // var request = require('request'); sendfrom = process.env.EMAIL_TF; sendto = process.env.EMAIL_DT; theMsg = "Hello there 2"; console.log("+ Send" + ", from: " + sendfrom + ", to: " + sendto + ", MSG: " + theMsg); var theFormData = { from: sendfrom, to: sendto, subject: "From a node program: 2", text: theMsg, api_user: sendfrom, api_key: process.env.EMAIL_TF_PASSWORD, }; let theUrl = "https://api.sendgrid.com/api/mail.send.json"; console.log('+ theUrl: ' + theUrl); // request({ url: theUrl, method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, formData: theFormData }, function (error, response, theResponse) { console.log('+ Run the request.'); if (error) { console.log('- Error connecting.'); // callback(null, "error"); return; } console.log('+ Response code: ' + response.statusCode + ', ' + theResponse); // The callback needs to be inside the request. // callback(null, theResponse); }); <file_sep># Twilio Notify Android Quickstart Implementation Steps Following, are the steps I used to set up required configurations and run the sample Twilio notification app on my phone. This allows notifications to be sent from my computer, and received on the phone that is running the notification app. Once all requirements are configured and the Notify App compiled, I ran the Notify App on my phone. In the app, I register a user identity. The identity is used on the server side to create a Twilio Notify Binding. ```` User Notify App >> Twilio Function: register binding >> Twilio creates a Notify Binding. Laptop program to send a notification >> Twilio >> Google >> Twilio Notify phone app Requires a mapping from Twilio to the phone app, through Google. Create a Google project FCM phone app token. The Google token, is stored by Twilio to address the phone app. ```` #### Clone the Twilio Notify App repository ```` cd /Users/<user>/Projects/ $ mkdir notify $ cd notify/ $ git clone https://github.com/TwilioDevEd/notifications-quickstart-android ... $ ls notifications-quickstart-android ```` #### Create a Notify Service Create a Notify Service Instance: [Twilio Console link](https://www.twilio.com/console/notify/services) ([Tutorial docs](https://www.twilio.com/docs/notify/quickstart/android)). Example SID: ```` IS6b86eea51935a036f0ae440652761e8a ```` #### Create a Google App Mapping to the Notify App Configuring Android Push Notifications documentation [link](https://www.twilio.com/docs/notify/configure-android-push-notifications). Create a Google Firebase [project](https://console.firebase.google.com/) that will will map to the Notify App. ```` Name: tignotify Disable: Enable Google Analytics for this project. Click Create Project, Your new project is ready. Click Continue. Get started by adding Firebase to your app ... Click Android icon. Use the Android package name that is used in the cloned app: "com.twilio.notify.quickstart". Click register app. Download config file, click Download google-services.json. Download to the Notify app project's app directory. ```` List the google-services.json. ```` $ pwd /Users/<user>/Projects/android/notify/notifications-quickstart-android/app $ cat google-services.json ... ```` #### Add the Google FCM token into the Twilio Notify Push Credentials Get the [Google project](https://console.firebase.google.com/) tignotify's Settings/Cloud messaging key/Server key Token. Add the key value into a newly [created/added Push Credential](https://www.twilio.com/console/notify/credentials/create): ```` Friendly Name: tignotify Type: FCM FCM Secret: AAA...oTx (Server key Token) Click Save. ```` In the tignotify Notify Service Instance, select FCM CREDENTIAL SID: tignotify. Click Save. #### Create Twilio Functions. + One Function for the Notify app to register a user identity (Notify binding) that is used to send notifications. + One to make a Twilio Notify API request to send a notification to the user running the Notify app. To create the Functions in the Twilio Console, click [here](https://www.twilio.com/console/functions/manage). ```` Select, Twilio Notify Quickstart. Click Create. Enter the value of the Notify Service Instance SID, for example: IS6b86eea51935a036f0ae440652761e8a Click Create. 2 Functions are created: + Twilio Notify Quickstart (Register binding) + Twilio Notify Quickstart (Send notification) Example Register binding URL: https://about-time-2357.twil.io/register-binding ```` In the Notify app source code, enter the Twilio Function Register binding URL. ```` Example: https://about-time-2357.twil.io/register-binding Don't include, "/register-binding". public class TwilioFunctionsAPI { // The URL below should be the domain for your Twilio Functions, without the trailing slash: // Example: https://sturdy-concrete-1234.twil.io public final static String BASE_SERVER_URL = "https://about-time-2357.twil.io"; ... ```` Run the app. When the app is running, enter Notify Binding identity and tap Register Binding. The app will make a call to the Twilio Binding Function which creates a Notify Binding for the identity. Can use the following Node program to list the binding, [listBindings.js](listBindings.js) ```` $ node listBindings.js +++ List bindings. + List, IS6b86eea51935a036f0ae440652761e8a: SID bindingType:identity<address>) + BS11...74 fcm:davea<fa...7V> $ ```` Or, use a curl command. ```` curl -X GET 'https://notify.twilio.com/v1/Services/IS6b86eea51935a036f0ae440652761e8a/Bindings?PageSize=20' \ -u $MASTER_ACCOUNT_SID:$MASTER_AUTH_TOKEN ```` #### Send a notification: Use the send notification Function to send a notification to the app user. https://about-time-2357.twil.io/send-notification?identity=user1&body=Hello Or, use the following Node program to send a notification, [sendNotification.js](sendNotification.js) Or, use a curl command. ```` curl -X POST https://notify.twilio.com/v1/Services/IS6b86eea51935a036f0ae440652761e8a/Notifications \ -d 'Identity=davea' \ -d 'Body=Hello 13' \ -u $MASTER_ACCOUNT_SID:$MASTER_AUTH_TOKEN ```` ```` curl -X POST https://notify.twilio.com/v1/Services/IS6b86eea51935a036f0ae440652761e8a/Notifications \ -d 'Identity=davea' \ -d 'Body=Hello 14' \ -d 'Title=Dave here' \ -u $MASTER_ACCOUNT_SID:$MASTER_AUTH_TOKEN ```` The notification will be received on the phone that is running the notification app. -------------------------------------------------------------------------------- Cheers... <file_sep>using System; using System.Threading.Tasks; using System.Net.Http; namespace HttpGet { class MainClass { public static void Main(string[] args) { Console.WriteLine("+++ Start"); Task t = new Task(HTTP_GET); t.Start(); Console.ReadLine(); Console.WriteLine("+++ Exit"); } static async void HTTP_GET() { string ACCOUNT_SID = "your_account_SID"; string AUTH_TOKEN = "<PASSWORD>"; string theURL = "http://lookups.twilio.com/v1/PhoneNumbers/18182103863?Type=carrier"; // string theURL = "http://api.twilio.com/2010-04-01/Accounts/" + ACCOUNT_SID + "/SMS/Messages.csv?PageSize=1000"; Console.WriteLine("++ GET: + " + theURL); HttpClientHandler handler = new HttpClientHandler { Credentials = new System.Net.NetworkCredential(ACCOUNT_SID, AUTH_TOKEN) }; HttpClient client = new HttpClient(handler); HttpResponseMessage response = await client.GetAsync(theURL); HttpContent content = response.Content; Console.WriteLine("+ Response StatusCode: " + (int)response.StatusCode); string result = await content.ReadAsStringAsync(); if (result != null && result.Length >= 50) { Console.WriteLine("+ Response: " + result); Console.WriteLine("+ End of response."); } } } }<file_sep>// ----------------------------------------------------------------------------- console.log("+++ List bindings."); const accountSid = process.env.MASTER_ACCOUNT_SID; const authToken = process.env.MASTER_AUTH_TOKEN; const client = require('twilio')(accountSid, authToken); const notifyServiceSid = process.env.MASTER_NOTIFY_SERVICE_SID; console.log("+ List for Notify service SID: " + notifyServiceSid); console.log("++ Binding-SID bindingType(fcm,apn):identity<address>)"); console.log("Example:"); console.log("++ BS117d136bdf6f6ce8e7cc22b72c763274 fcm:dave<faReuVhz_gk:APA91...s7V>)"); console.log("+ The listing:"); client.notify.services(notifyServiceSid).bindings .list({limit: 20}) .then(bindings => bindings.forEach( binding => console.log("++ " + binding.sid + " " + binding.bindingType + ":" + binding.identity + "<" + binding.address + ">") )); // // ----------------------------------------------------------------------------- <file_sep>console.log("++ List Conversations."); var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); serviceSid = process.env.CONVERSATIONS_SERVICE_SID; // // conversationSid = process.env.CONVERSATION_SID; conversationSid = process.env.CONVERSATIONS_ECHO_SID; // console.log("+ Fetch using Conversations service SID + conversation sid: <sid> <uniqueName> <friendlyName>"); client.conversations.services(serviceSid).conversations(conversationSid) .fetch() .then(conversation => { console.log( "+ Conversations SID: " + conversation.sid + " " + conversation.uniqueName + " " + conversation.friendlyName ); console.log("+ Fetch using unique name."); client.conversations.services(serviceSid).conversations(conversation.uniqueName) .fetch() .then(conversation => { console.log( "+ Conversations SID: " + conversation.sid + " " + conversation.uniqueName + " " + conversation.friendlyName ); }); }); <file_sep>console.log("++ Generate Conversations Token."); const AccessToken = require('../../node_modules/twilio').jwt.AccessToken; const ChatGrant = AccessToken.ChatGrant; // Used when generating any kind of tokens const twilioAccountSid = process.env.ACCOUNT_SID; const twilioApiKey = process.env.MASTER_API_KEY; const twilioApiSecret = process.env.MASTER_API_KEY_SECRET; // Used specifically for creating Chat tokens // const serviceSid = 'ISd5c080247aaa4200a730da6c6ea08990'; // Note, to communicate with the command line programs, need to use the Conversations service: // https://www.twilio.com/console/conversations/configuration/defaults // Because the command line programs do not have the option to select a Conversations service. // const serviceSid = 'IS4ebcc2d46cda47958628e59af9e53e55'; const serviceSid = process.env.CONVERSATIONS_SERVICE_SID; const identity = 'dave'; // Create a "grant" which enables a client to use Chat as a given user, // on a given device const chatGrant = new ChatGrant({ serviceSid: serviceSid }); // Create an access token which we will sign and return to the client, // containing the grant we just created const token = new AccessToken( twilioAccountSid, twilioApiKey, twilioApiSecret, {identity: identity, ttl: 43200} // ttl is good for 12 hours. ); token.addGrant(chatGrant); // Serialize the token to a JWT string // console.log(token.toJwt()); console.log("+ token.toJwt(): " + token.toJwt()); <file_sep><?php echo "\xA+++ Echo environment variables."; // echo "\xA", "+ MASTER_ACCOUNT_SID : ", getenv("MASTER_ACCOUNT_SID"); echo "\xA", "+ MASTER_AUTH_TOKEN : ", getenv("MASTER_AUTH_TOKEN"); // echo "\xA", "+ ACCOUNT_SID_TF : ", getenv("ACCOUNT_SID_TF"); echo "\xA", "+ AUTH_TOKEN_TF : ", getenv("AUTH_TOKEN_TF"); echo "\xA", "+ FUNCTIONS_HOST_TF : ", getenv("FUNCTIONS_HOST_TF"); echo "\xA", "+ ECHO_REQUEST_URL : ", getenv("ECHO_REQUEST_URL"); echo "\xA", "+ HELLO_REQUEST_URL : ", getenv("HELLO_REQUEST_URL"); echo "\xA", "+ PHONE_NUMBER_HOME : ", getenv("PHONE_NUMBER_HOME"); echo "\xA", "+ PHONE_NUMBER_WORK : ", getenv("PHONE_NUMBER_WORK"); // $accountSid = getenv("ACCOUNT_SID"); $authToken = getenv('AUTH_TOKEN'); echo "\xA", "+ ACCOUNT_SID : ", $accountSid; echo "\xA", "+ AUTH_TOKEN : ", $authToken; // require __DIR__ . '/../twilio-php-master/Twilio/autoload.php'; use Twilio\Rest\Client; $client = new Client(getenv('ACCOUNT_SID'), getenv('AUTH_TOKEN')); echo "\xA", "+ Twilio PHP helper library works."; // echo "\xA", "+ FUNCTIONS_HOST : ", getenv('FUNCTIONS_HOST'); echo "\xA", "+ TOKEN_HOST : ", getenv('TOKEN_HOST'); // $notifyServieSid = getenv('NOTIFY_SERVICE_SID'); $syncServieSid = getenv('SYNC_SERVICE_SID'); $syncMapName = getenv('SYNC_MAP_NAME'); echo "\xA", "+ NOTIFY_SERVICE_SID : ", $notifyServieSid; echo "\xA", "+ SYNC_SERVICE_SID : ", $syncServieSid; echo "\xA", "+ SYNC_MAP_NAME : ", $syncMapName; // echo "\xA", "+ PHONE_NUMBER1 : ", getenv('PHONE_NUMBER1'); echo "\xA", "+ PHONE_NUMBER2 : ", getenv('PHONE_NUMBER2'); echo "\xA", "+ PHONE_NUMBER3 : ", getenv('PHONE_NUMBER3'); echo "\xA", "+ PHONE_NUMBER4 : ", getenv('PHONE_NUMBER4'); echo "\xA", "+ PHONE_NUMBER5 : ", getenv('PHONE_NUMBER5'); echo "\xA", "+ PHONE_NUMBER6 : ", getenv('PHONE_NUMBER6'); // echo "\xA", "+ SENDGRID_API_KEY : ", getenv('SENDGRID_API_KEY'); echo "\xA", "+ EMAIL_DT : ", getenv('EMAIL_DT'); echo "\xA", "+ EMAIL_TF : ", getenv('EMAIL_TF'); // echo "\xA", "+ CHAT_SERVICE_SID : ", getenv('CHAT_SERVICE_SID'); echo "\xA", "+ CHAT_API_KEY : ", getenv('CHAT_API_KEY'); echo "\xA", "+ CHAT_API_KEY_SECRET: ", getenv('CHAT_API_KEY_SECRET'); // echo "\xA", "+ AUTHY_API_KEY : ", getenv('AUTHY_API_KEY'); echo "\xA", "+ AUTHY_ID : ", getenv('AUTHY_ID'); echo "\xA", "+ AUTHY_ID_EMAIL : ", getenv('AUTHY_ID_EMAIL'); echo "\xA", "+ AUTHY_PHONE_COUNTRYCODE : ", getenv('AUTHY_PHONE_COUNTRYCODE'); echo "\xA", "+ AUTHY_PHONE_NUMBER1 : ", getenv("AUTHY_PHONE_NUMBER1"); echo "\xA", "+ PROXY_SESSION_SID : ", getenv('PROXY_SESSION_SID'); echo "\xA", "+ PROXY_PARTICIPANT_SID : ", getenv('AUTHY_ID'); echo "\xA", "+ PHONE_NUMBER_SID : ", getenv('AUTHY_ID'), " for +16508668232"; echo "\xA+++ Exit \xA"; ?> <file_sep>// ----------------------------------------------------------------------------- console.log("+++ Start."); aString = '{}'; console.log("+ aString :" + aString + ":"); eString = encodeURI(aString); console.log("+ eString :" + eString + ":"); console.log("+ decodeURI(eString) :" + decodeURI(eString) + ":"); eString = '2021-08-12T21%3A25%3A40.832Z'; console.log("+ eString :" + eString + ":"); console.log("+ decodeURI(eString) :" + decodeURI(eString) + ":"); console.log("+ decodeURI(eString) :" + decodeURI("DeliveryState%5B0%5D") + ":"); // ----------------------------------------------------------------------------- console.log("+++ Exit."); // eof <file_sep><?php require __DIR__ . '/../../twilio-php-master/Twilio/autoload.php'; use Twilio\Rest\Client; use Twilio\Exceptions\RestException; // $client = new Client(getenv('ACCOUNT_SID'), getenv('AUTH_TOKEN')); $client = new Client(getenv('MASTER_ACCOUNT_SID'), getenv('MASTER_AUTH_TOKEN')); $fromMs = 'MG44e9e310ae478d5635bc11685758da4a'; $toPhoneNumber = getenv('MY_PHONE_NUMBER'); // $toPhoneNumber = getenv('PHONE_NUMBER3'); $theMessage = "Twilio support test message #2"; echo '++ Send SMS message, Messaging Service SID: ' . $fromMs . " to " . $toPhoneNumber . " :" . $theMessage . ":\xA"; try { $sms = $client->account->messages->create( $toPhoneNumber, array( // 'from' => $fromPhoneNumber, "messagingServiceSid" => $fromMs, 'body' => $theMessage ) ); echo "+ Sent, SID: " . $sms->sid . "\xA"; } catch (RestException $e) { echo "+ getStatusCode(): " . $e->getStatusCode() . "\xA"; echo "+ getMessage(): " . $e->getMessage() . "\xA"; }<file_sep>console.log("++ Update a Conversation resource."); var client = require('../../node_modules/twilio')(process.env.MASTER_ACCOUNT_SID, process.env.MASTER_AUTH_TOKEN); conversationSid = process.env.CONVERSATION_SID; conversationFriendlyName = 'ReadyP1'; client.conversations.conversations(conversationSid) .update({friendlyName: conversationFriendlyName}) .then(conversation => console.log('+ Conversation updated: ' + conversation.sid)); <file_sep># Use Twilio CLI to Manage Twilio Function Services -------------------------------------------------------------------------------- ### Create, Run and Test, and Deploy Twilio Functions and Assets You can create, run and test Functions locally using the Twilio CLI. #### Create a Project on Your Development Computer The following is based on the [General Usage lab](https://www.twilio.com/docs/labs/serverless-toolkit/general-usage). Change to a working directory and create (init) a new project, under that directory. ```` $ cd /Users/.../Projects/work/twiliocli $ twilio serverless:init p1 ✔ Creating project directory ✔ Creating project directories and files ✔ Downloading .gitignore file ✔ Installing dependencies ... │ Success! │ Created p1 at /Users/.../Projects/work/twiliocli │ Inside that directory, you can run the following command: │ │ npm start │ │ Serves all functions in the ./functions subdirectory and assets in the │ │ ./assets directory │ │ Get started by running: │ │ cd p1 │ │ npm start │ $ ls p1 assets functions node_modules package-lock.json package.json ```` #### Run and Test the Project List the functions that were created by default. List the hello world function that was created. The hello world function, will return 'Hello World!' Say TwiML. ```` $ cd /Users/.../Projects/work/twiliocli/p1 $ ls functions/ hello-world.js private-message.js sms $ cat functions/hello-world.js exports.handler = function(context, event, callback) { const twiml = new Twilio.twiml.VoiceResponse(); twiml.say('Hello World!'); callback(null, twiml); }; ```` To run the hello world function locally, start the local NodeJS Twilio CLI webserver. ```` $ cd /Users/.../Projects/work/twiliocli/p1 $ npm start --- or --- $ twilio serverless:start > p1@0.0.0 start /Users/dthurston/Projects/work/twiliocli/p1 > twilio-run ... ┌────────────────────────────────────────────────────────────────────┐ │ │ │ Twilio functions available: │ │ ├── /hello-world | http://localhost:3000/hello-world │ │ ├── /private-message | http://localhost:3000/private-message │ │ └── [protected] /sms/reply | http://localhost:3000/sms/reply │ │ │ │ Twilio assets available: │ │ ├── /index.html | http://localhost:3000/index.html │ │ ├── [private] /message.js | Runtime.getAssets()['/message.js'] │ │ └── /style.css | http://localhost:3000/style.css │ │ │ └────────────────────────────────────────────────────────────────────┘ ```` Use a browser to run the [hello world function](http://localhost:3000/hello-world). Browser response: ```` <Response> <Say>Hello World!</Say> </Response> ```` Page source TwiML of the hello world function output: ```` <?xml version="1.0" encoding="UTF-8"?><Response><Say>Hello World!</Say></Response> ```` #### Deploy the Project To deploy to your Twilio account, use the following command. The Twilio account is base on your Twilio CLI environment Twilio account SID. ```` $ twilio serverless:deploy Deploying functions & assets to the Twilio Runtime ... ```` Check from the Twilio Console [Functions/Service](https://www.twilio.com/console/functions/overview/services), ```` Unique Name Friendly Name SID Date Created p1 p1 ZS7e3ea7f1875d690c3cafec2a7312a60f 2021-03-03T18:24:51Z ```` Run the p1 project hello world function from your browser. From the [Functions/Service](https://www.twilio.com/console/functions/overview/services) link, Click p1. Under Functions, copy the public URL for /hello-world. Run the URL from your browser, for example: https://p1-2357-dev.twil.io/hello-world (this isn't actual, just reference for syntax) Browser response, same as running it locally: ```` <Response> <Say>Hello World!</Say> </Response> ```` -------------------------------------------------------------------------------- Cheers... <file_sep>// twilio api:core:messages:fetch --sid SM2feb3243087344fcae1652e603fa5462 console.log("++ Fetch SMS message log information."); var client = require('twilio')(process.env.ACCOUNT_SID, process.env.AUTH_TOKEN); let theMessageSid = 'SM2feb3243087344fcae1652e603fa5462'; console.log("+ Account SID: " + process.env.ACCOUNT_SID + " Message SID: " + theMessageSid); client.messages(theMessageSid) .fetch() .then(message => console.log('++ Status: ' + message.status + ', ' + message.from + ' To: ' + message.to + ' Text: ' + message.body));
7f87d94000e776cc5b17cd40bb8eb69c3be2f12b
[ "JavaScript", "Markdown", "Java", "Python", "C#", "PHP" ]
45
JavaScript
stevennic22/work
9eec275e5b627c102f22923d10fc3cfcbd86ff8c
fea2229a30ccfda4da003c05f8af82ae2234be46
refs/heads/master
<file_sep>import React from 'react'; import NavBar from '../nav-bar/NavBar'; import RomanticComedy from '../romantic-comedy/RomanticComedy'; function LandingPage() { return <div> <NavBar></NavBar> <RomanticComedy></RomanticComedy> </div> } export default LandingPage;<file_sep>import React from 'react'; import MovieCard from '../movie-card/MovieCard'; import ContentPage1 from '../../assets/API/CONTENTLISTINGPAGE-PAGE1.json'; import ContentPage2 from '../../assets/API/CONTENTLISTINGPAGE-PAGE2.json'; import ContentPage3 from '../../assets/API/CONTENTLISTINGPAGE-PAGE3.json'; import {createStore} from 'redux'; class RomanticComedy extends React.Component { constructor(props){ super(props) this.state = { movies: [], moviesList: [], per: 2, page: 1, totalPages: 3, scrolling: false, value: '' } this.handleSearch = this.handleSearch.bind(this); } componentWillMount() { this.loadMovies(); this.scrollListner = window.addEventListener('scroll', (e) => { this.handleScroll(e); }) } handleScroll = (e) => { const {scrolling,totalPages,page} = this.state; if(scrolling) return; if(totalPages <= page) return; const lastLi = document.querySelector('.content-items .movie-card:last-child'); const lastLiOffset = lastLi.offsetTop + lastLi.clientHeight; const pageOffset = window.pageYOffset + window.innerHeight; var bottomOffset = 20; if(pageOffset > lastLiOffset - bottomOffset) { this.loadMore(); } } loadMovies(){ const { per, page, movies, moviesList} = this.state var loadedPage = (page === 1) ? ContentPage1 : (page === 2) ? ContentPage2 : ContentPage3; this.setState({ movies : [...movies, ...loadedPage.page['content-items'].content], moviesList: [...moviesList, ...loadedPage.page['content-items'].content], scrolling: false }); } loadMore() { this.setState(prevState =>({ page: prevState.page + 1, scrolling: true }),this.loadMovies); } handleSearch(event) { var updatedMoviesArray = []; this.setState({value: event.target.value}); updatedMoviesArray = this.state.moviesList.filter(function(item){ return item['name'].toLowerCase().includes(event.target.value) }); this.setState({ movies : updatedMoviesArray }); } render () { var imageUrl = 'https://raw.githubusercontent.com/vishnuprasadkv55/project-dark/master/src/assets/Slices/'; return ( <div className="pt-20"> <input value={this.state.value} onChange={this.handleSearch} class="shadow bg-black appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline " id="username" type="text" placeholder="Search..."></input> <div className="p-4 bg-black grid gap-4 grid-cols-3 content-items"> {this.state.movies.map(function (item,index) { return (<MovieCard className="" key={index} name={item['name']} url={imageUrl + item['poster-image']}></MovieCard>); })}</div></div>); } } export default RomanticComedy;<file_sep>import React from 'react'; function NavBar() { return ( <nav className="shadow-lg h-20 mb-224px w-full flex items-center fixed justify-between flex-wrap bg-black "> <div className="pl-4 flex items-center flex-shrink-0 text-white mr-6"> <img className="h-6 pr-6" src="https://raw.githubusercontent.com/vishnuprasadkv55/project-dark/master/src/assets/Slices/Back.png" alt="" /> <span className="tracking-tight">Romantic Comedy</span> </div> </nav> ); } export default NavBar;
be41bc8f4dc668697924d71a196cbd3529630e82
[ "JavaScript" ]
3
JavaScript
vishnuprasadkv55/project-dark
d80cf794e8b32da891ff50beb4be938c08c078bd
3bf254f1fc12e2c65eeca101a45b5516e10b23bf
refs/heads/master
<file_sep>package com.company.address.util; import org.jasypt.util.text.StrongTextEncryptor; /** * Enum to encrypt/decrypt a String with a password using Jasypt library (http://www.jasypt.org/) * @author <NAME> * @version 1.0 * date 2016-09-20 */ public enum Crypto { ; /** * Instance of StrongTextEncryptor which is a utility class for easily performing high-strength encryption of texts */ private static final StrongTextEncryptor strongTextEncryptor = new StrongTextEncryptor(); /** * Set password of the StrongTextEncryptor instance * @since 1.0 * @param password password of the StrongTextEncryptor instance */ public static void setPassword(String password) { strongTextEncryptor.setPassword(password); } /** * Encrypt a String using the StrongTextEncryptor instance * @since 1.0 * @param stringToEncrypt a String that will be encrypted with the StrongTextEncryptor instance * @return an encrypted String */ public static String getEncrypted(String stringToEncrypt) { return strongTextEncryptor.encrypt(stringToEncrypt); } /** * Decrypt a String using the StrongTextEncryptor instance * @since 1.0 * @param stringToDecrypt a String that will be decrypted with the StrongTextEncryptor instance * @return a decrypted String */ public static String getDecrypted(String stringToDecrypt) { return strongTextEncryptor.decrypt(stringToDecrypt); } }
ae5ddee0c82883565ef4a99fe7abc023a9d49542
[ "Java" ]
1
Java
oldu73/AddressApp001
e51b755bbdac28f7928833fefa987e41bc5d077d
fff8e0697b01443102d2a91f4ce3cb3ffeaf7929
refs/heads/master
<repo_name>prakashpks/vov<file_sep>/README.c #include<stdio.h> void main() { char s[100]; int len,i; printf("enter word"); gets(s); len=strlen(s); for(i=0;i<=len;i++) { if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U') { s[i]=s[i+1]; s[i+1]=' '; } } printf("after removing vowel=%s",s); }
caced2269ba38f8651032b7b9edcb9162daefc07
[ "C" ]
1
C
prakashpks/vov
947d518c56e43cb2ecac3a0b5c15f63546e7cca5
3c4af10f73a8e2c945cc22e99dea6231cd53e3fc
refs/heads/master
<repo_name>sofayam/nodehello<file_sep>/README.md node and mongo demo prog for use with cloud foundry local test node info.js remote test cf push nodehello <file_sep>/index.js var express = require('express'); var app = express(); var mc = require('mongodb').MongoClient; var assert = require('assert'); function getURI() { if(process.env.VCAP_SERVICES){ var env = JSON.parse(process.env.VCAP_SERVICES); var fullurl = (env['MongoDB-Service'][0]['credentials']['uri']); var front = fullurl.split('?')[0]; return front } else { return "mongodb://localhost:27017/db" } } var port = (process.env.PORT || 3001); app.get('/env', function (req, res) { res.write('this is the environment\n'); for (var key in process.env) { res.write(key + " : " + process.env[key] + "\n" ); } res.end(); }); app.get('/', function (req, res) { console.log("someone touched me\n"); var mongourl = getURI(); res.send(mongourl); }); app.get('/con', function (req, res) { var url = getURI(); mc.connect(url, function(err,db) { assert.equal(null,err); res.send("connected to server"); console.log("connected to server"); db.close() }) }); app.get('/set', function (req, res) { res.send(JSON.stringify(req.query)) // jam this straight into mongo var url = getURI(); mc.connect(url, function(err,db) { assert.equal(null,err); db.collection('node').insertOne(req.query, function (err, result) { assert.equal(err, null); db.close(); }); }); }); app.get('/get', function (req, res) { var url = getURI(); mc.connect(url, function(err,db) { assert.equal(null,err); var cursor = db.collection('node').find(); cursor.each(function(err,doc) { assert.equal(null,err); if (doc != null) { res.write(JSON.stringify(doc) + "\n"); } else { db.close(); res.end(); } }); }); }); var server = app.listen(port, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });
0e621ba2b9de8e3ca4ef3e977ecc10f5bfda8813
[ "Markdown", "JavaScript" ]
2
Markdown
sofayam/nodehello
089ded4382462ae26e7736180111f8fe3fdf1f72
8d5a20a4ae3732b6649e2c14a74d97166a215f27
refs/heads/master
<repo_name>monikkinom/annot8<file_sep>/app/migrations/0008_auto_20151025_0940.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0007_annotations_color'), ] operations = [ migrations.AlterField( model_name='annotations', name='color', field=models.CharField(max_length=100, choices=[(b'marked', b'Green'), (b'marked2', b'Red'), (b'marked3', b'Yellow')]), ), ] <file_sep>/app/migrations/0011_code_created_at.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import datetime class Migration(migrations.Migration): dependencies = [ ('app', '0010_auto_20151025_1302'), ] operations = [ migrations.AddField( model_name='code', name='created_at', field=models.DateTimeField(default=datetime.datetime(2015, 10, 25, 13, 12, 10, 645954), auto_now_add=True), preserve_default=False, ), ] <file_sep>/app/forms.py from django.contrib.auth.models import User from django import forms from app.models import * class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = "form-control input-md" self.fields['password'].widget.attrs['class'] = "form-control input-md" self.fields['email'].widget.attrs['class'] = "form-control input-md" self.fields['username'].widget.attrs['placeholder'] = "Username" self.fields['password'].widget.attrs['placeholder'] = "<PASSWORD>" self.fields['email'].widget.attrs['placeholder'] = "Email" self.fields['username'].widget.attrs['required'] = "yes" self.fields['password'].widget.attrs['required'] = "yes" self.fields['email'].widget.attrs['required'] = "yes" class Meta: model = User fields = ['username', 'email', 'password'] class CodeForm(forms.ModelForm): code = forms.Textarea() def __init__(self, *args, **kwargs): super(CodeForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['class'] = "form-control input-md" self.fields['code'].widget.attrs['class'] = "form-control input-md" self.fields['language'].widget.attrs['class'] = "form-control input-md" self.fields['title'].widget.attrs['placeholder'] = "Title" self.fields['code'].widget.attrs['placeholder'] = "Text" self.fields['language'].widget.attrs['placeholder'] = "Language" self.fields['title'].widget.attrs['required'] = "yes" self.fields['code'].widget.attrs['required'] = "yes" self.fields['language'].widget.attrs['required'] = "yes" class Meta: model = Code fields = ['title','code','language']<file_sep>/app/views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required, user_passes_test from django.shortcuts import render from django.core import serializers import json from django.http import HttpResponseRedirect, Http404, HttpResponse from django.views.generic import CreateView from django.template import RequestContext from django.shortcuts import render_to_response from decimal import * from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.auth import authenticate, login, logout import datetime import csv from django.views.decorators.csrf import csrf_exempt from app.forms import UserForm,CodeForm from app.models import * # Create your views here. def index(request): """ Index view for homepage for logged in as well as logged out users :param request: :return: """ return render(request, "index.html") def user_login(request): """ Login View :param request: :return: """ if request.user.is_authenticated(): return HttpResponseRedirect("/home") error = False if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('<PASSWORD>') user = authenticate(username=username, password=<PASSWORD>) if user: if user.is_active: login(request, user) next_url = request.GET.get('next', '/home') return HttpResponseRedirect(next_url) else: error = True return render(request, "login.html", {'error':error}) def user_register(request): """ Register a new user :param request: :return: """ if request.user.is_authenticated(): return HttpResponseRedirect("/home") registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(<PASSWORD>) user.save() user_profile = UserProfile.objects.create(user=user) registered = True else: print user_form.errors else: user_form = UserForm() return render(request, 'register.html', {'user_form': user_form, 'registered': registered}) @login_required(login_url='/login') def home(request): """ User login :param request: :return: """ if request.user.is_authenticated(): codes = Code.objects.filter(user=request.user).order_by('-created_at') for code in codes: acount = Annotations.objects.filter(code=code).count() code.acount = acount code.lent = len(code.code) return render(request,"home.html",{'codes':codes}) raise Http404 @login_required(login_url='/') def logout_user(request): """ Logout :param request: :return: """ logout(request) next_url = request.GET.get('next', '/') return HttpResponseRedirect(next_url) @login_required(login_url='/login') def add_code(request): """ For adding new code entries :param request: :return: """ if request.method == 'POST': cf = CodeForm(data=request.POST) if cf.is_valid(): ok = cf.save(commit=False) ok.user = request.user ok.save() next_url = request.GET.get('next', '/code/'+str(ok.id)) return HttpResponseRedirect(next_url) else: print cf.errors else: cf = CodeForm() return render(request,"add.html",{'form':cf}) @login_required(login_url='/login') @csrf_exempt def add_annotation(request): if request.user.is_authenticated(): if request.POST: codeid = request.POST.get('codeid') title = request.POST.get('title') content = request.POST.get('content') color = request.POST.get('color') start = request.POST.get('start') end = request.POST.get('end') if codeid and title and content and color and start and end: # try: code = Code.objects.get(id=int(codeid)) if code.user == request.user : ann = Annotations() ann.code = code ann.title = title ann.content = content ann.color = color ann.start = int(start) ann.end = int(end)-int(start)+1 ann.save() return HttpResponse("success") else: return HttpResponse('code does not belong to user') # except: # return HttpResponse('code does not exist') else: return HttpResponse("error") raise Http404 def view_code(request, codeid): """ Display the code :param request: :param codeid: :return: """ try: code = Code.objects.get(id=codeid) annotations = Annotations.objects.filter(code=code).order_by('start') owner = False if request.user.is_authenticated(): if request.user == code.user: owner = True #apply annotations to except: raise Http404 return render(request,"code.html",{'code':code.code,'title':code.title,'anno':annotations,'lang':code.language,'owner':owner,'cid':code.id}) @login_required(login_url='/login') def delete_code(request, codeid): """ Display the code :param request: :param codeid: :return: """ try: code = Code.objects.get(id=codeid) if request.user.is_authenticated(): if request.user == code.user: code.delete() return HttpResponse("deleted!") else: return HttpResponse("code does not belong to the user") #apply annotations to except: return HttpResponse("error Deleting")<file_sep>/static/js/app.js $(function() { function getSelectionCharOffsetsWithin(element) { var start = 0, end = 0; var sel, range, priorRange; if (typeof window.getSelection != "undefined") { range = window.getSelection().getRangeAt(0); priorRange = range.cloneRange(); priorRange.selectNodeContents(element); priorRange.setEnd(range.startContainer, range.startOffset); start = priorRange.toString().length; end = start + range.toString().length; } else if (typeof document.selection != "undefined" && (sel = document.selection).type != "Control") { range = sel.createRange(); priorRange = document.body.createTextRange(); priorRange.moveToElementText(element); priorRange.setEndPoint("EndToStart", range); start = priorRange.text.length; end = start + range.text.length; } return { start: start, end: end }; } function alertSelection() { var mainDiv = document.getElementById("main"); var sel = getSelectionCharOffsetsWithin(mainDiv); alert(sel.start + ": " + sel.end); } }); <file_sep>/app/models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User) class Code(models.Model): user = models.ForeignKey(User) code = models.TextField() title = models.CharField(max_length=200) choice = ( ('cpp', 'C++'), ('python', 'Python'), ('php', 'PHP'), ('c', 'C'), ('java', 'Java'), ('javascript', 'Javascript'), ('csharp', 'C#'), ('python', 'Python'), ('ruby', 'Ruby'), ('swift', 'Swift'), ('objectivec', 'Objective-C'), ('css', 'CSS'), ('php', 'Unknown/Text'), ) language = models.CharField(choices=choice,max_length=100) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Annot8s' class Annotations(models.Model): code = models.ForeignKey(Code) title = models.CharField(max_length=200) content = models.CharField(max_length=2000) start = models.IntegerField() end = models.IntegerField() cx = ( ('marked','Green'), ('marked2','Red'), ('marked3','Yellow') ) color = models.CharField(choices=cx,max_length=100) class Meta: verbose_name_plural = 'Annotations'<file_sep>/annotate/urls.py """annotate URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from app import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', views.index, name='Home Page'), url(r'^login/',views.user_login, name='Login'), url(r'^register/',views.user_register, name='Register'), url(r'^home/',views.home, name='Home for logged in'), url(r'^logout/',views.logout_user, name='Logout'), url(r'^add/',views.add_code,name='Add Code'), url(r'^code/(?P<codeid>\d+)/$', views.view_code, name="View Code"), url(r'^api/add_ann/$', views.add_annotation, name="Add Annotation"), url(r'^delete_code/(?P<codeid>\d+)/$', views.delete_code, name="Delete Code") ] <file_sep>/app/migrations/0012_auto_20151025_1539.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0011_code_created_at'), ] operations = [ migrations.AlterField( model_name='code', name='language', field=models.CharField(max_length=100, choices=[(b'cpp', b'C++'), (b'python', b'Python'), (b'php', b'PHP'), (b'c', b'C'), (b'java', b'Java'), (b'javascript', b'Javascript'), (b'csharp', b'C#'), (b'python', b'Python'), (b'ruby', b'Ruby'), (b'swift', b'Swift'), (b'objectivec', b'Objective-C'), (b'css', b'CSS'), (b'php', b'Unknown/Text')]), ), ] <file_sep>/requirements.txt Django==1.8.5 wsgiref==0.1.2
78d3f56af398fd5bde520a13062484d3e9e66ef7
[ "JavaScript", "Python", "Text" ]
9
Python
monikkinom/annot8
fc7330fd467fc9914d47b0acbcbab785c01deefd
1236aa659486eb73bfc741b37c966a2aa71e7331
refs/heads/master
<file_sep>def find_non_duplicates(list_of_int): """find uniques.""" new_list = [] for i in list_of_int: count = list_of_int.count(i) if count == 1: new_list.append(i) return(new_list) if __name__ == "__main__": list1 = [1, 2, 3, 4, 5, 3, 2, 4, 11] non_duplicate = find_non_duplicates(list1) print(non_duplicate)<file_sep># my_prod_list my_prod_list is a Python code for finding none duplicate integers from a given set of integers. ## requirments Python version 3.6 or higher ## Run ``` python uniques.py ```
3d2c58c662f643c02f1bf87832baabd7f2aaf023
[ "Markdown", "Python" ]
2
Python
Nb74969/my-prod-list
95baf3add3f61b5f4b71279ef17a845660b1d7ae
bb70c17d327df7706f1f398df55431f35b8481a7