text
stringlengths
0
1.25M
meta
stringlengths
47
1.89k
/* * Copyright (C) 2021 FISCO BCOS. * SPDX-License-Identifier: Apache-2.0 * Licensed 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. * * @brief factory of vm * @file VMFactory.cpp * @author: xingqiangbai * @date: 2021-05-24 */ #include "VMFactory.h" #include "VMInstance.h" #include <BCOS_WASM.h> #include <evmc/loader.h> #include <evmone/evmone.h> #include <boost/program_options.hpp> namespace po = boost::program_options; namespace bcos { namespace executor { namespace { auto g_kind = VMKind::evmone; /// The pointer to VMInstance create function in DLL VMInstance VM. /// /// This variable is only written once when processing command line arguments, /// so access is thread-safe. evmc_create_fn g_evmcCreateFn; /// A helper type to build the tabled of VM implementations. /// /// More readable than std::tuple. /// Fields are not initialized to allow usage of construction with initializer lists {}. struct VMKindTableEntry { VMKind kind; const char* name; }; /// The table of available VM implementations. #if 0 VMKindTableEntry vmKindsTable[] = {{VMKind::BcosWasm, "bcos wasm"}, {VMKind::evmone, "evmone"}}; void setVMKind(const std::string& _name) { for (auto& entry : vmKindsTable) { // Try to find a match in the table of VMs. if (_name == entry.name) { g_kind = entry.kind; return; } } // If not match for predefined VM names, try loading it as an VMInstance DLL. evmc_loader_error_code ec; g_evmcCreateFn = evmc_load(_name.c_str(), &ec); switch (ec) { case EVMC_LOADER_SUCCESS: break; case EVMC_LOADER_CANNOT_OPEN: BOOST_THROW_EXCEPTION( po::validation_error(po::validation_error::invalid_option_value, "vm", _name, 1)); case EVMC_LOADER_SYMBOL_NOT_FOUND: BOOST_THROW_EXCEPTION(std::system_error(std::make_error_code(std::errc::invalid_seek), "loading " + _name + " failed: VMInstance create function not found")); default: BOOST_THROW_EXCEPTION( std::system_error(std::error_code(static_cast<int>(ec), std::generic_category()), "loading " + _name + " failed")); } g_kind = VMKind::DLL; } #endif } // namespace VMInstance VMFactory::create() { return create(g_kind); } VMInstance VMFactory::create(VMKind _kind) { switch (_kind) { case VMKind::BcosWasm: return VMInstance{evmc_create_bcoswasm()}; case VMKind::evmone: return VMInstance{evmc_create_evmone()}; case VMKind::DLL: return VMInstance{g_evmcCreateFn()}; default: return VMInstance{evmc_create_evmone()}; } } } // namespace executor } // namespace bcos
{"hexsha": "6bc8722fc3f6ce13670cf49595b3820fa8cd5931", "size": 3218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bcos-executor/src/vm/VMFactory.cpp", "max_stars_repo_name": "contropist/FISCO-BCOS", "max_stars_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bcos-executor/src/vm/VMFactory.cpp", "max_issues_repo_name": "contropist/FISCO-BCOS", "max_issues_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bcos-executor/src/vm/VMFactory.cpp", "max_forks_repo_name": "contropist/FISCO-BCOS", "max_forks_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9826086957, "max_line_length": 96, "alphanum_fraction": 0.6796146675, "num_tokens": 826}
# -*- coding: utf-8 -*- """ Created on Thu Mar 29 14:08:21 2018 @author: tih """ def run(input_nc, Inflow_Text_Files): ''' This functions add inflow to the runoff dataset before the channel routing. The inflow must be a text file with a certain format. The first line of this format are the latitude and longitude. Hereafter for each line the time (ordinal time) and the inflow (m3/month) seperated with one space is defined. See example below: [lat lon] 733042 156225.12 733073 32511321.2 733102 212315.25 733133 2313266.554 ''' # General modules import numpy as np # Water Accounting modules import wa.General.raster_conversions as RC import wa.Functions.Start.Area_converter as Area Runoff = RC.Open_nc_array(input_nc, Var = 'Runoff_M') # Open information and open the Runoff array geo_out, epsg, size_X, size_Y, size_Z, Time = RC.Open_nc_info(input_nc) # Calculate the surface area of every pixel dlat, dlon = Area.Calc_dlat_dlon(geo_out, size_X, size_Y) area_in_m2 = dlat * dlon for Inflow_Text_File in Inflow_Text_Files: # Open the inlet text data Inlet = np.genfromtxt(Inflow_Text_File, dtype=None, delimiter=" ") # Read out the coordinates Coord = Inlet[0,:] Lon_coord = Coord[0][1:] Lat_coord = Coord[1][:-1] # Search for the pixel lon_pix = int(np.ceil((float(Lon_coord) - geo_out[0])/geo_out[1])) lat_pix = int(np.ceil((float(Lat_coord) - geo_out[3])/geo_out[5])) # Add the value on top of the Runoff array for i in range(1, len(Inlet)): time = float(Inlet[i,0]) time_step = np.argwhere(np.logical_and(Time>=time,Time<=time)) if len(time_step) > 0: time_step_array = int(time_step[0][0]) value_m3_month = float(Inlet[i,1]) area_in_m2_pixel = area_in_m2[lat_pix, lon_pix] value_mm = (value_m3_month/area_in_m2_pixel) * 1000 Runoff[time_step_array,lat_pix, lon_pix] = Runoff[time_step_array,lat_pix, lon_pix] + value_mm return(Runoff)
{"hexsha": "0af20e8c3d82510abf1d06ff99f00a6c2fc81aaf", "size": 2195, "ext": "py", "lang": "Python", "max_stars_repo_path": "Models/SurfWAT/Part0_Add_Inlets.py", "max_stars_repo_name": "ali1100/wa", "max_stars_repo_head_hexsha": "700e5014533c45f38a245c3abdeacc537cb307bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-04-27T21:22:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-21T12:57:03.000Z", "max_issues_repo_path": "Models/SurfWAT/Part0_Add_Inlets.py", "max_issues_repo_name": "ali1100/wa", "max_issues_repo_head_hexsha": "700e5014533c45f38a245c3abdeacc537cb307bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-06-17T08:07:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-22T12:28:37.000Z", "max_forks_repo_path": "Models/SurfWAT/Part0_Add_Inlets.py", "max_forks_repo_name": "wateraccounting/wa", "max_forks_repo_head_hexsha": "29ed8e7eac732135678a5d171cd5e53a54c95313", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2016-10-24T13:24:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-03T17:42:22.000Z", "avg_line_length": 36.5833333333, "max_line_length": 133, "alphanum_fraction": 0.6369020501, "include": true, "reason": "import numpy", "num_tokens": 607}
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np try: from .pkg import rolex from .parse_datetime import any2datetime except: # pragma: no cover from convert2.pkg.rolex import rolex from convert2.parse_datetime import any2datetime class Anything2Date(object): """Parse anything to ``datetime.date``. The logic: - for int, it's the ``datetime.fromordinal(value)`` - for float, it's a invalid input - for str, try to parse ``date`` - for datetime type, it's the date part - for date type, it's itself """ def __call__(self, value): #--- None --- if value is None: return None try: if np.isnan(value): return None except: pass #--- int, long, np.int, np.int8, np.int16, np.int32, np.int64 --- try: if int(value) == value: try: return rolex.from_ordinal(value) except: raise ValueError("%r is not date parsable!" % value) except: pass #--- float, np.float, np.float16, np.float32, np.float64 --- if type(value).__name__.startswith("float"): raise ValueError("%r is not date parsable!" % value) #--- np.datetime64, pd.Timestamp --- # --- other type --- try: return any2datetime(value).date() except: raise ValueError("%r is not date parsable!" % value) any2date = Anything2Date()
{"hexsha": "dc0ec26e3f08d9c8ca2c1b0207e0ebc25e4301cf", "size": 1543, "ext": "py", "lang": "Python", "max_stars_repo_path": "convert2/parse_date.py", "max_stars_repo_name": "MacHu-GWU/convert2-project", "max_stars_repo_head_hexsha": "aad1837676b3702aa22f53f6462beb8c5c17d4e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "convert2/parse_date.py", "max_issues_repo_name": "MacHu-GWU/convert2-project", "max_issues_repo_head_hexsha": "aad1837676b3702aa22f53f6462beb8c5c17d4e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convert2/parse_date.py", "max_forks_repo_name": "MacHu-GWU/convert2-project", "max_forks_repo_head_hexsha": "aad1837676b3702aa22f53f6462beb8c5c17d4e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1525423729, "max_line_length": 73, "alphanum_fraction": 0.546338302, "include": true, "reason": "import numpy", "num_tokens": 363}
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # coding: utf-8 """ Author: Arnaud Ferré Mail: [email protected] Description: Training module for C-Norm method Licensed 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. """ ####################################################################################################### # Import modules & set up logging ####################################################################################################### from optparse import OptionParser import json import gzip from os.path import dirname, exists from os import makedirs import numpy import gensim from tensorflow.keras import layers, models, Model, Input, regularizers, optimizers, metrics, losses, initializers, backend from word2term import getSizeOfVST from onto import loadOnto, ontoToVec ####################################################################################################### # Utils ####################################################################################################### # Normalization of token embeddings: def normalizeEmbedding(vst_onlyTokens): for token in vst_onlyTokens.keys(): vst_onlyTokens[token] = vst_onlyTokens[token] / numpy.linalg.norm(vst_onlyTokens[token]) return vst_onlyTokens # CHoose with getMatricForCNN...? def prepare2D_data(vst_onlyTokens, dl_terms, dl_associations, vso, phraseMaxSize): #ToDo: Keep a constant size of the input matrix between train and prediction nbTerms = len(dl_terms.keys()) sizeVST = getSizeOfVST(vst_onlyTokens) sizeVSO = getSizeOfVST(vso) X_train = numpy.zeros((nbTerms, phraseMaxSize, sizeVST)) Y_train = numpy.zeros((nbTerms, 1, sizeVSO)) l_unkownTokens = list() l_uncompleteExpressions = list() for i, id_term in enumerate(dl_associations.keys()): # stderr.write('id_term = %s\n' % str(id_term)) # stderr.write('len(dl_associations[id_term]) = %d\n' % len(dl_associations[id_term])) for id_concept in dl_associations[id_term]: Y_train[i][0] = vso[id_concept] for j, token in enumerate(dl_terms[id_term]): if j < phraseMaxSize: if token in vst_onlyTokens.keys(): X_train[i][j] = vst_onlyTokens[token] else: l_unkownTokens.append(token) else: l_uncompleteExpressions.append(id_term) break # Because it' easier to keep only one concept per mention (mainly to calculate size of matrix). # ToDo: switch to object to include directly size with these structures. return X_train, Y_train, l_unkownTokens, l_uncompleteExpressions # def loadJSON(filename): if filename.endswith('.gz'): f = gzip.open(filename) else: # f = open(filename, encoding='utf-8') f = open(filename, "r", encoding="utf-8") result = json.load(f) f.close() return result; ####################################################################################################### # Concept-Normalization (C-Norm) ####################################################################################################### def CNorm(vst_onlyTokens, dl_terms, dl_associations, vso, nbEpochs=30, batchSize=64, l_numberOfFilters=[4000], l_filterSizes=[1], phraseMaxSize=15): # Preparing data for SLFNN and S-CNN components: dataSCNN, labels, l_unkownTokens, l_uncompleteExpressions = prepare2D_data(vst_onlyTokens, dl_terms, dl_associations, vso, phraseMaxSize) dataSLFNN = numpy.zeros((dataSCNN.shape[0], dataSCNN.shape[2])) for i in range( dataSCNN.shape[0]): numberOfToken = 0 for embedding in dataSCNN[i]: if not numpy.any(embedding): pass else: numberOfToken += 1 dataSLFNN[i] += embedding if numberOfToken > 0: dataSLFNN[i] = dataSLFNN[i] / numberOfToken # Input layers: inputLP = Input(shape=dataSLFNN.shape[1]) inputCNN = Input(shape=[dataSCNN.shape[1],dataSCNN.shape[2]]) # SLFNN component: ontoSpaceSize = labels.shape[2] denseLP = layers.Dense(units=ontoSpaceSize, use_bias=True, kernel_initializer=initializers.GlorotUniform())(inputLP) modelLP = Model(inputs=inputLP, outputs=denseLP) # Shallow-CNN component: l_subLayers = list() for i, filterSize in enumerate(l_filterSizes): convLayer = (layers.Conv1D(l_numberOfFilters[i], filterSize, strides=1, kernel_initializer=initializers.GlorotUniform()))(inputCNN) outputSize = phraseMaxSize - filterSize + 1 pool = (layers.MaxPool1D(pool_size=outputSize))(convLayer) activationLayer = (layers.LeakyReLU(alpha=0.3))(pool) l_subLayers.append(activationLayer) if len(l_filterSizes) > 1: concatenateLayer = (layers.Concatenate(axis=-1))(l_subLayers) # axis=-1 // concatenating on the last dimension else: concatenateLayer = l_subLayers[0] denseLayer = layers.Dense(ontoSpaceSize, kernel_initializer=initializers.GlorotUniform())(concatenateLayer) modelCNN = Model(inputs=inputCNN, outputs=denseLayer) convModel = Model(inputs=inputCNN, outputs=concatenateLayer) fullmodel = models.Sequential() fullmodel.add(convModel) # Combination of the two components: combinedLayer = layers.average([modelLP.output, modelCNN.output]) fullModel = Model(inputs=[inputLP, inputCNN], outputs=combinedLayer) fullModel.summary() # Compile and train: fullModel.compile(optimizer=optimizers.Nadam(), loss=losses.LogCosh(), metrics=[metrics.CosineSimilarity(), metrics.MeanSquaredError()]) fullModel.fit([dataSLFNN, dataSCNN], labels, epochs=nbEpochs, batch_size=batchSize) return fullModel, vso, l_unkownTokens ####################################################################################################### # Run class: ####################################################################################################### class Train(OptionParser): def __init__(self): OptionParser.__init__(self, usage='usage: %prog [options]') self.add_option('--word-vectors', action='store', type='string', dest='word_vectors', help='path to word vectors JSON file as produced by word2vec') self.add_option('--word-vectors-bin', action='store', type='string', dest='word_vectors_bin', help='path to word vectors binary file as produced by word2vec') self.add_option('--terms', action='store', type='string', dest='terms', help='path to terms file in JSON format (map: id -> array of tokens)') self.add_option('--attributions', action='store', type='string', dest='attributions', help='path to attributions file in JSON format (map: id -> array of concept ids)') self.add_option('--ontology', action='store', type='string', dest='ontology', help='path to ontology file in OBO format') self.add_option('--outputModel', action='store', type='string', dest='model', help='path to save the NN model directory') # Methods hyperparameters: self.add_option('--factor', action='store', type='float', dest='factors', default=0.65, help='parent concept weight factor (default=0.6).') self.add_option('--epochs', action='store', type='int', dest='epochs', default=150, help='number of epochs (default=150).') self.add_option('--batch', action='store', type='int', dest='batch', default=64, help='number of samples in batch (default=64).') self.add_option('--filtersSize', action='append', type='int', dest='filtersSize', help='list of the different size of filters (default=1)') self.add_option('--filtersNb', action='append', type='int', dest='filtersNb', help='list of the number of filters from filtersSize (default=100)') self.add_option('--phraseMaxSize', action='store', type='int', dest='phrase_max_size', default=15, help='max considered size of phrases in inputs (default=15).') self.add_option('--normalizedInputs', action='store', type='string', dest='normalizedInputs', default="True", help='unit normalize embeddings if "True" (default: True).') def run(self): options, args = self.parse_args() if len(args) > 0: raise Exception('stray arguments: ' + ' '.join(args)) if options.word_vectors is None and options.word_vectors_bin is None: raise Exception('missing either --word-vectors or --word-vectors-bin') if options.word_vectors is not None and options.word_vectors_bin is not None: raise Exception('incompatible --word-vectors or --word-vectors-bin') if options.ontology is None: raise Exception('missing --ontology') if not options.terms: raise Exception('missing --terms') if not options.attributions: raise Exception('missing --attributions') if not options.model: raise Exception('missing --outputModel') if options.filtersSize is None: options.filtersSize = [1] if options.filtersNb is None: options.filtersNb = [100] if options.filtersSize is not None and options.filtersNb is not None: if len(options.filtersSize) != len(options.filtersNb): raise Exception('ERROR: number of elements in --filtersSize different from number of elements in --filtersNb') # Selected hyperparameters (can have an important influence...): print("\nRuning C-Norm with next hyperparameters:") print("factor=", options.factors) print("epochs=", options.epochs) print("batch=", options.batch) print("filtersSize=", options.filtersSize) print("filtersNb=", options.filtersNb) print("phraseMaxSize=", options.phrase_max_size) print("normalizedInputs=", options.normalizedInputs) # Loading ontology: print("\nloading ontology:", options.ontology) ontology = loadOnto(options.ontology) # Loading word embeddings: if options.word_vectors is not None: print("loading word embeddings:", options.word_vectors) word_vectors = loadJSON(options.word_vectors) elif options.word_vectors_bin is not None: print("loading word embeddings:", options.word_vectors_bin) EmbModel = gensim.models.Word2Vec.load(options.word_vectors_bin) word_vectors = dict((k, list(numpy.float_(npf32) for npf32 in EmbModel.wv[k])) for k in EmbModel.wv.vocab.keys()) # Loading all mentions: print("Loading terms:", options.terms) dl_terms = loadJSON(options.terms) # Loading training examples: print("Loading attributions:", options.attributions) attributions = loadJSON(options.attributions) # Scaling of all embeddings: if options.normalizedInputs is not None: if options.normalizedInputs == "True": print("\nScaling: Unit normalization of input embeddings (recommended)...") word_vectors = normalizeEmbedding(word_vectors) print("Scaling done.\n") else: print("No scaling of input embeddings (not recommended, see normalizedInputs option).") # Building ontological space print("Building ontological space (with factor applied)...") vso = ontoToVec(ontology, options.factors) print("Ontological space built.\n") print("C-Norm training...") model, ontology_vector, _ = CNorm(word_vectors, dl_terms, attributions, vso, nbEpochs=options.epochs, batchSize=options.batch, l_numberOfFilters=options.filtersNb, l_filterSizes=options.filtersSize, phraseMaxSize=options.phrase_max_size) print("C-Norm training done.\n") # Saving model: if options.model is not None: print("Saving trained Tensorflow model...") d = dirname(options.model) if not exists(d) and d != '': makedirs(d) model.save(options.model) print("Model saved.") ####################################################################################################### # Test section ####################################################################################################### if __name__ == '__main__': Train().run()
{"hexsha": "804df5e345a19fbd0e940f19119eaec2491a4aeb", "size": 13136, "ext": "py", "lang": "Python", "max_stars_repo_path": "train.py", "max_stars_repo_name": "ArnaudFerre/C-Norm_PostLab", "max_stars_repo_head_hexsha": "edb9462a32b3e47b38bfd62836427d3a90f510ab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "train.py", "max_issues_repo_name": "ArnaudFerre/C-Norm_PostLab", "max_issues_repo_head_hexsha": "edb9462a32b3e47b38bfd62836427d3a90f510ab", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "train.py", "max_forks_repo_name": "ArnaudFerre/C-Norm_PostLab", "max_forks_repo_head_hexsha": "edb9462a32b3e47b38bfd62836427d3a90f510ab", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5696202532, "max_line_length": 178, "alphanum_fraction": 0.6079476248, "include": true, "reason": "import numpy", "num_tokens": 2792}
# Implementation of the Douglas-Peucker algorithm for line thinning # http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm simplify_rec <- function(points, tol = 0.01) { n <- nrow(points) if (n <= 2) return() # c(1, n)) dist <- with(points, point_line_dist(x, y, x[1], y[1], x[n], y[n])) if (max(dist, na.rm = T) > tol) { furthest <- which.max(dist) c( simplify_rec(points[1:(furthest - 1), ], tol), furthest, simplify_rec(points[(furthest + 1):n, ], tol) + furthest ) } else { c() } } # From http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html point_line_dist <- function(px, py, lx_1, ly_1, lx_2, ly_2) { abs((lx_2 - lx_1) * (ly_1 - py) - (lx_1 - px) * (ly_2 - ly_1)) / sqrt((lx_2 - lx_1) ^ 2 + (ly_2 - ly_1) ^ 2) } # Precompute all tolerances so that we can post-select quickly compute_tol <- function(points, offset = 0) { n <- nrow(points) if (n <= 2) { c() } else if (n == 3) { with(points, point_line_dist(long[2], lat[2], long[1], lat[1], long[3], lat[3])) } else { dist <- with(points, point_line_dist(long[2:(n-1)], lat[2:(n-1)], long[1], lat[1], long[n], lat[n]) ) furthest <- which.max(dist) if (length(furthest) == 0) browser() c( compute_tol(points[1:(furthest + 1), ], offset), dist[furthest], compute_tol(points[(furthest + 1):n, ], furthest + offset) ) } }
{"hexsha": "edbf20b3138c8f8fc93ddb53695948b70d8deb6c", "size": 1431, "ext": "r", "lang": "R", "max_stars_repo_path": "data/r/4d3b204f419e13c711e427f1e3aae40b_thin.r", "max_stars_repo_name": "maxim5/code-inspector", "max_stars_repo_head_hexsha": "14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-01-03T06:43:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-30T13:15:29.000Z", "max_issues_repo_path": "data/r/4d3b204f419e13c711e427f1e3aae40b_thin.r", "max_issues_repo_name": "maxim5/code-inspector", "max_issues_repo_head_hexsha": "14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/r/4d3b204f419e13c711e427f1e3aae40b_thin.r", "max_forks_repo_name": "maxim5/code-inspector", "max_forks_repo_head_hexsha": "14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-04T02:54:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-24T17:50:46.000Z", "avg_line_length": 30.4468085106, "max_line_length": 84, "alphanum_fraction": 0.5828092243, "num_tokens": 496}
SUBROUTINE ADDEND( SPDBSP, LASCEN, SAMPLE, ENDRAD, & CVECT, PERPVE, PERPVN, & ATMAX, ATNO, ATXYZ, ATVDW, CUTSIZE) IMPLICIT NONE C ******************************************************************** C * * C * This software is an unpublished work containing confidential and * C * proprietary information of Oliver Smart. Use, disclosure, * C * reproduction and transfer of this work without the express * C * written consent of Oliver Smart are prohibited. This notice * C * must be attached to all copies or extracts of the software. * C * * C * (c) 2000 Oliver Smart * C * * C ******************************************************************** C C s/r add end records to spdbsp - needed to prevent dumbbells C in graphics calcs C C Modification history: C C Date Author Modification C 01/00 O.S.S. First version C passed vbles ***************** C pdb format output file 'atoms' are sphere centres C default to none by setting FPDBSP to 'NONE' C CHARACTER*200 FPDBSP INTEGER SPDBSP C Last accepted HOLE centre - C done (s/r holcal normal supplies lowcen) DOUBLE PRECISION LASCEN(3) C a sampling distance - the distance between planes C use here for the sign - if -ve then need to work in this direction DOUBLE PRECISION SAMPLE C a vector in the direction of the channel C must be a unit vector - return unchanged DOUBLE PRECISION CVECT(3) C New option 22/11/93 - For wide channels need to C be able to specify the radius at which an end is reached C in this routine need to add a series of points that are above this radius DOUBLE PRECISION ENDRAD C unit vectors in plane normal to cvect C needed to a number of routines - originally h2dmap but now conn C and addend C these are normal - first is east direction (x on plane) C and second is north (y on plane) C return unchanged!!! DOUBLE PRECISION PERPVE(3), PERPVN(3) C maximum no. of atoms C returned unchanged INTEGER ATMAX C number of atoms read in from each file: C returned unchanged INTEGER ATNO C co-ordinates C returned unchanged DOUBLE PRECISION ATXYZ( 3, ATMAX) C vdw radius of each atom C returned unchanged DOUBLE PRECISION ATVDW(ATMAX) C cut off list control vble, -ve: no cutoff lists used in calculation C otherwise this is the additional radius above the sphere radius C to be used for cutoff list (see s/r holeen) DOUBLE PRECISION CUTSIZE C internals ******************** C sign of sample DOUBLE PRECISION SSIGN C loop counts Z north east, XYZ INTEGER ZCOUNT, NCOUNT, ECOUNT, XCOUNT C displacements Z north east DOUBLE PRECISION ZDISP, NDISP, EDISP C a new point DOUBLE PRECISION TSTXYZ(3), NEWENG C atom list no. with smallest dist-vdw radius, 2nd smallest C 07/06/94 as iat's may or may not be supplied with previously C found numbers then we can use this to speed up the procedure C Dec 97 add iat3 INTEGER IAT1, IAT2, IAT3 C 2nd/3rd smallest distance-vdw radius (of iat2/3) DOUBLE PRECISION DAT2, DAT3 C end of decs ****************** C sign of sample IF (SAMPLE.GT.0D0) THEN SSIGN = +1D0 ELSE SSIGN = -1D0 ENDIF C produce a grid of prospective points: C go along cvect DO 10 ZCOUNT = 0, 4 ZDISP = SSIGN*REAL(ZCOUNT)*(0.5*ENDRAD) DO 20 NCOUNT = -2, 2 NDISP = REAL(NCOUNT)*(0.5*ENDRAD) DO 30 ECOUNT = -2, 2 EDISP = REAL(ECOUNT)*(0.5*ENDRAD) C the test point TSTXYZ(1) = LASCEN(1) TSTXYZ(2) = LASCEN(2) TSTXYZ(3) = LASCEN(3) C displace Z TSTXYZ(1) = TSTXYZ(1) + ZDISP*CVECT(1) TSTXYZ(2) = TSTXYZ(2) + ZDISP*CVECT(2) TSTXYZ(3) = TSTXYZ(3) + ZDISP*CVECT(3) C displace N TSTXYZ(1) = TSTXYZ(1) + NDISP*PERPVN(1) TSTXYZ(2) = TSTXYZ(2) + NDISP*PERPVN(2) TSTXYZ(3) = TSTXYZ(3) + NDISP*PERPVN(3) C displace E TSTXYZ(1) = TSTXYZ(1) + EDISP*PERPVE(1) TSTXYZ(2) = TSTXYZ(2) + EDISP*PERPVE(2) TSTXYZ(3) = TSTXYZ(3) + EDISP*PERPVE(3) C test point CALL HOLEEN( TSTXYZ, NEWENG, & IAT1, IAT2, IAT3, DAT2, DAT3, & ATMAX, ATNO, ATXYZ, ATVDW, CUTSIZE) NEWENG = - NEWENG C write out only points with pore radius above endrad IF (NEWENG.GT.ENDRAD) THEN WRITE( SPDBSP, '(A,I4,4X,3F8.3,2F6.2)') & 'ATOM 1 QSS SPH S', -888, & (TSTXYZ(XCOUNT), XCOUNT= 1, 3), & NEWENG, 0.0 WRITE( SPDBSP, '(A)') 'LAST-REC-END' ENDIF 30 CONTINUE 20 CONTINUE 10 CONTINUE RETURN END
{"hexsha": "4e8d9c86cbbc3598e0ea05e9a27769b32a3bea9b", "size": 4961, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "src/addend.f", "max_stars_repo_name": "MDAnalysis/hole2", "max_stars_repo_head_hexsha": "ed28b2ac0dfc714933ddf2befe0a06ed87ede98e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-06-09T14:42:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T09:23:08.000Z", "max_issues_repo_path": "src/addend.f", "max_issues_repo_name": "osmart/hole2", "max_issues_repo_head_hexsha": "ba82cfcea8782ce59f68804ef6914582290a9b30", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-11-17T20:19:40.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-17T20:19:40.000Z", "max_forks_repo_path": "src/addend.f", "max_forks_repo_name": "MDAnalysis/hole2", "max_forks_repo_head_hexsha": "ed28b2ac0dfc714933ddf2befe0a06ed87ede98e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-06-09T14:42:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-27T03:38:01.000Z", "avg_line_length": 32.4248366013, "max_line_length": 75, "alphanum_fraction": 0.5881878653, "num_tokens": 1464}
#!python import os from os.path import join import sys import click import json import csv from tqdm import tqdm import hashlib from glob import glob import cv2 as cv import imutils import faiss import pickle import numpy as np import pandas as pd import sqlite3 import time import csv # TODO change to relative sys.path.append('/vframe/tools/') from utils import fiox from utils import imx from utils.im_mgmt import ImageManagement from config import settings as cfg # -------------------------------------------------------- # Click CLI parser # -------------------------------------------------------- @click.group() def cli(): pass # -------------------------------------------------------- # Resize video images # -------------------------------------------------------- @cli.command() @click.option('--input',required=True,type=click.File('r'), help="Path features .pkl") @click.option('--output',required=True,type=click.Path(exists=True), help="Path to output folder (.index, timing.txt)") @click.option('--type',required=True,type=click.Option( ['Flat','PCA80,Flat','IVF512,Flat','IVF512,SQ4','IVF512,SQ8','PCAR8,IMI2x10,SQ8']), help="FAISS factory type") @click.option('--store-db/--no-store-db',default=True, help='Store result in SQLITE DB') @click.option('--store-index/--no-store-index',default=True, help='Store index?') @click.option('--append/--no-append',default=True, help='Append to timing output file') def train(**kwargs): """Train FAISS options""" fp_pkl = kwargs['features'] fpp_pkl = Path(fpp_pkl) feat_net_name = fpp_pkl.parent # (vgg16, resnet-18, alexnet) #pkl_fn = './features/{}/index.pkl'.format(dataset) #index_fn = "./indexes/{}-{}.index".format(dataset, factory_type.replace(",", "_")) #db_fn = "./indexes/{}.db".format(dataset) fp_index = join(kwargs['output'],'{}.index'.format(feat_net_name)) fp_db = join(kwargs['output'],'{}.db'.format(feat_net_name)) fp_timing = join(kwargs['output'],'{}_timing.txt'.format(feat_net_name)) # load features data = pickle.loads(kwargs['input']) # insert features in DB if kwargs['store_db']: print("[+] saving database...") db = sqlite3.connect(db_fn) cursor = db.cursor() cursor.execute(''' DROP TABLE IF EXISTS frames ''') cursor.execute(''' CREATE TABLE frames(id INTEGER PRIMARY KEY, sha256 TEXT, frame TEXT) ''') db.commit() for sha256 in data['videos'].keys(): for frame in data['videos'][sha256].keys(): cursor.execute('''INSERT INTO frames(sha256, frame) VALUES(?,?)''', (sha256, frame)) db.commit() feats = np.array([ data['videos'][v][frame] for v in data['videos'].keys() for frame in data['videos'][v].keys() ]) n, d = feats.shape # process FAISS print("[+] processing {}x {}d features...".format(n, d)) index = faiss.index_factory(d, factory_type) time_start = time.time() index.train(feats) train_time = time.time() - time_start print("[+] train time: {}".format(train_time)) time_start = time.time() # for i in range(10): # feats[:, 0] += np.arange(feats) / 1000. index.add(feats) add_time = time.time() - time_start print("[+] add time: {}".format(add_time)) # print(index.is_trained) # print(index.ntotal) #if opt.store_index: if kwargs['store_index']: faiss.write_index(index, fp_index) keys = list(data['videos'].keys()) key = keys[0] frames = list(data['videos'][key].keys()) frame = frames[0] # print(key, frame) vec = data['videos'][key][frame] # print('sanity check:') time_start = time.time() D, I = index.search(np.array([vec]).astype('float32'), 15) search_end = time.time() search_time = search_end - time_start print("search time: {}".format(search_time)) fmode = 'a' if kwargs['append'] else 'w' with open("timing.txt", fmode) as fp: index_size = os.path.getsize(index_fn) print("index size: {}".format(int(index_size/(1024*1024)))) writer = csv.writer(fp) if not fmode == 'a': writer.writerow("#dataset, #index.ntotal, #d, #factory_type, #train_time, #add_time, #search_time, #index_size") writer.writerow([dataset, index.ntotal, d, factory_type, train_time, add_time, search_time, index_size]) # print("distances:") # print(D[0]) # print("indexes:") # print(I[0]) # -------------------------------------------------------- # Entrypoint # -------------------------------------------------------- if __name__ == '__main__': cli() # parser = argparse.ArgumentParser() # parser.add_argument('--dataset', required=True) # parser.add_argument('--factory_type', required=True) # parser.add_argument('--store_db', action='store_true') # parser.add_argument('--store_index', action='store_true') # opt = parser.parse_args() # dataset = opt.dataset # factory_type = opt.factory_type pkl_fn = './features/{}/index.pkl'.format(dataset) index_fn = "./indexes/{}-{}.index".format(dataset, factory_type.replace(",", "_")) db_fn = "./indexes/{}.db".format(dataset) fh = open(pkl_fn, 'rb') raw = fh.read() fh.close() data = pickle.loads(raw) if opt.store_db: print("saving database...") db = sqlite3.connect(db_fn) cursor = db.cursor() cursor.execute(''' DROP TABLE IF EXISTS frames ''') cursor.execute(''' CREATE TABLE frames(id INTEGER PRIMARY KEY, hash TEXT, frame TEXT) ''') db.commit() for hash in data['videos'].keys(): for frame in data['videos'][hash].keys(): cursor.execute('''INSERT INTO frames(hash, frame) VALUES(?,?)''', (hash, frame)) db.commit() feats = np.array([ data['videos'][v][frame] for v in data['videos'].keys() for frame in data['videos'][v].keys() ]) n, d = feats.shape print("processing {}x {}d features...".format(n, d)) index = faiss.index_factory(d, factory_type) train_start = time.time() index.train(feats) train_end = time.time() train_time = train_end - train_start print("train time: {}".format(train_time)) add_start = time.time() # for i in range(10): # feats[:, 0] += np.arange(feats) / 1000. index.add(feats) add_end = time.time() add_time = add_end - add_start print("add time: {}".format(add_time)) # print(index.is_trained) # print(index.ntotal) if opt.store_index: faiss.write_index(index, index_fn) keys = list(data['videos'].keys()) key = keys[0] frames = list(data['videos'][key].keys()) frame = frames[0] # print(key, frame) vec = data['videos'][key][frame] # print('sanity check:') search_start = time.time() D, I = index.search(np.array([vec]).astype('float32'), 15) search_end = time.time() search_time = search_end - search_start print("search time: {}".format(search_time)) with open("timing.txt", "a") as f: index_size = os.path.getsize(index_fn) print("index size: {}".format(int(index_size/(1024*1024)))) writer = csv.writer(f) writer.writerow("#dataset, #index.ntotal, #d, #factory_type, #train_time, #add_time, #search_time, #index_size") writer.writerow([dataset, index.ntotal, d, factory_type, train_time, add_time, search_time, index_size]) # print("distances:") # print(D[0]) # print("indexes:") # print(I[0])
{"hexsha": "4848c7fbf4c2a028685944d476191cc3865325ca", "size": 7146, "ext": "py", "lang": "Python", "max_stars_repo_path": "vframe/vframe/tools/faiss/train_ah.py", "max_stars_repo_name": "kant/vframe", "max_stars_repo_head_hexsha": "28e49ca62d9036a78a25b26eb0fb7e3cf8c79031", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-18T10:42:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T10:42:10.000Z", "max_issues_repo_path": "vframe/vframe/tools/faiss/train_ah.py", "max_issues_repo_name": "vframeio/_vframe_v0_archived", "max_issues_repo_head_hexsha": "28e49ca62d9036a78a25b26eb0fb7e3cf8c79031", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vframe/vframe/tools/faiss/train_ah.py", "max_forks_repo_name": "vframeio/_vframe_v0_archived", "max_forks_repo_head_hexsha": "28e49ca62d9036a78a25b26eb0fb7e3cf8c79031", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1338582677, "max_line_length": 118, "alphanum_fraction": 0.6312622446, "include": true, "reason": "import numpy", "num_tokens": 1849}
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh class dynamogp_2d_dedalus(ptype): """ """ def __init__(self, problem_params, dtype_u=mesh, dtype_f=imex_mesh): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'Rm', 'kx', 'comm', 'initial'] for key in essential_keys: if key not in problem_params: msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys())) raise ParameterError(msg) ybasis = de.Fourier('y', problem_params['nvars'][0], interval=(0, 2 * np.pi), dealias=1) zbasis = de.Fourier('z', problem_params['nvars'][1], interval=(0, 2 * np.pi), dealias=1) self.domain = de.Domain([ybasis, zbasis], grid_dtype=np.complex128, comm=problem_params['comm']) nvars = tuple(self.domain.local_grid_shape()) + (2,) # invoke super init, passing number of dofs (and more), dtype_u and dtype_f super(dynamogp_2d_dedalus, self).__init__(init=(nvars, self.domain.dist.comm, ybasis.grid_dtype), dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params) self.y = self.domain.grid(0, scales=1) self.z = self.domain.grid(1, scales=1) self.problem = de.IVP(domain=self.domain, variables=['by', 'bz']) self.problem.parameters['Rm'] = self.params.Rm self.problem.parameters['kx'] = self.params.kx self.problem.add_equation("dt(by) - (1/Rm) * ( dz(dz(by)) + dy(dy(by)) - kx ** 2 * (by) ) = 0") self.problem.add_equation("dt(bz) - (1/Rm) * ( dz(dz(bz)) + dy(dy(bz)) - kx ** 2 * (bz) ) = 0") self.solver = self.problem.build_solver(de.timesteppers.SBDF1) self.by = self.solver.state['by'] self.bz = self.solver.state['bz'] self.u = self.domain.new_field() self.v = self.domain.new_field() self.w = self.domain.new_field() self.w_y = self.domain.new_field() self.v_z = self.domain.new_field() def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ f = self.dtype_f(self.init) A = np.sqrt(3/2) C = np.sqrt(3/2) self.u['g'] = A * np.sin(self.z + np.sin(t)) + C * np.cos(self.y + np.cos(t)) self.v['g'] = A * np.cos(self.z + np.sin(t)) self.w['g'] = C * np.sin(self.y + np.cos(t)) self.w_y['g'] = self.w.differentiate(y=1)['g'] self.v_z['g'] = self.v.differentiate(z=1)['g'] self.by['g'] = u[..., 0] self.bz['g'] = u[..., 1] by_y = self.by.differentiate(y=1) by_z = self.by.differentiate(z=1) bz_y = self.bz.differentiate(y=1) bz_z = self.bz.differentiate(z=1) tmpfy = (-self.u * self.by * 1j * self.params.kx - self.v * by_y - self.w * by_z + self.bz * self.v_z).evaluate() f.expl[..., 0] = tmpfy['g'] tmpfz = (-self.u * self.bz * 1j * self.params.kx - self.v * bz_y - self.w * bz_z + self.by * self.w_y).evaluate() f.expl[..., 1] = tmpfz['g'] self.by['g'] = u[..., 0] self.bz['g'] = u[..., 1] pseudo_dt = 1E-05 self.solver.step(pseudo_dt) f.impl[..., 0] = 1.0 / pseudo_dt * (self.by['g'] - u[..., 0]) f.impl[..., 1] = 1.0 / pseudo_dt * (self.bz['g'] - u[..., 1]) return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as mesh """ self.by['g'] = rhs[..., 0] self.bz['g'] = rhs[..., 1] self.solver.step(factor) me = self.dtype_u(self.init) me[..., 0] = self.by['g'] me[..., 1] = self.bz['g'] return me def u_exact(self, t): """ Routine to compute the exact solution at time t Args: t (float): current time Returns: dtype_u: exact solution """ zvar_loc = self.z.shape[1] yvar_loc = self.y.shape[0] np.random.seed(0) me = self.dtype_u(self.init) if self.params.initial == 'random': me[..., 0] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) me[..., 1] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) elif self.params.initial == 'low-res': tmp0 = self.domain.new_field() tmp1 = self.domain.new_field() tmp0['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) tmp1['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) tmp0.set_scales(4.0 / self.params.nvars[0]) # Need to do that because otherwise Dedalus tries to be clever.. tmpx = tmp0['g'] tmp1.set_scales(4.0 / self.params.nvars[1]) # Need to do that because otherwise Dedalus tries to be clever.. tmpy = tmp1['g'] tmp0.set_scales(1) tmp1.set_scales(1) me[..., 0] = tmp0['g'] me[..., 1] = tmp1['g'] return me
{"hexsha": "099ba8af28bddede6fdfec5fee7cdaee9ca9c4bb", "size": 6224, "ext": "py", "lang": "Python", "max_stars_repo_path": "pySDC/playgrounds/deprecated/Dedalus/DynamoGP_2D_Dedalus_NEW.py", "max_stars_repo_name": "brownbaerchen/pySDC", "max_stars_repo_head_hexsha": "31293859d731646aa09cef4345669eac65501550", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2015-03-21T09:02:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T20:22:21.000Z", "max_issues_repo_path": "pySDC/playgrounds/deprecated/Dedalus/DynamoGP_2D_Dedalus_NEW.py", "max_issues_repo_name": "brownbaerchen/pySDC", "max_issues_repo_head_hexsha": "31293859d731646aa09cef4345669eac65501550", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 61, "max_issues_repo_issues_event_min_datetime": "2015-03-02T09:35:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T12:42:48.000Z", "max_forks_repo_path": "pySDC/playgrounds/deprecated/Dedalus/DynamoGP_2D_Dedalus_NEW.py", "max_forks_repo_name": "brownbaerchen/pySDC", "max_forks_repo_head_hexsha": "31293859d731646aa09cef4345669eac65501550", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:52:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T10:46:27.000Z", "avg_line_length": 34.3867403315, "max_line_length": 105, "alphanum_fraction": 0.5395244216, "include": true, "reason": "import numpy", "num_tokens": 1724}
theory nat_pow_le_factorial imports Main "$HIPSTER_HOME/IsaHipster" begin datatype Nat = Z | S "Nat" fun plus :: "Nat => Nat => Nat" where "plus (Z) y = y" | "plus (S n) y = S (plus n y)" fun mult :: "Nat => Nat => Nat" where "mult (Z) y = Z" | "mult (S n) y = plus y (mult n y)" fun pow :: "Nat => Nat => Nat" where "pow x (Z) = S Z" | "pow x (S m) = mult x (pow x m)" fun lt :: "Nat => Nat => bool" where "lt (Z) y = True" | "lt (S z) (Z) = False" | "lt (S z) (S x2) = lt z x2" fun factorial :: "Nat => Nat" where "factorial (Z) = S Z" | "factorial (S n) = mult (S n) (factorial n)" (*hipster plus mult pow lt factorial *) theorem x0 : "!! (n :: Nat) . lt (pow (S (S Z)) (S (S (S (S n))))) (factorial (S (S (S (S n)))))" by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>) end
{"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/benchmark/tip2015/nat_pow_le_factorial.thy"}
""" .. currentmodule: arim.geometry Utilities for geometric operations: translation, rotation, change of basis, etc. Points ====== A :class:`Points` object contains the Cartesian coordinates of one or more points. The points can be stored as a ndarray. However ray tracing and many parts of arim expects as input an 1d array of points. Function :func:`points_1d_wall_z` provides an easy way to create a flat line. For more complicated lines and surfaces, create the points manually. Oriented points =============== An oriented point is defined as a point and three orthonormal vectors. It is actually a full coordinate system. For probe and surfaces (front, back wall), the two first vectors must be tangential to the surface and the third vector must be normal to it. In the block in immersion model, the probe normals must be towards the examination object. The front and back walls' normals must be towards the probe. For scatterers and grid points, there is no tangent or normal vectors. Only the third vector of the basis is used. It defines the reference orientation of the scatterer. To use a rotated scatterer, one can therefore change the orientation of this third vector; however, the recommend technique is to argument ``scat_angle`` in :func:`arim.model.model_amplitudes_factory`. Basis ===== A basis (i_hat, j_hat, k_hat) is stored as a matrix:: (i1 i2 i3) basis = (j1 j2 j3) (k1 k2 k3) where (i1, i2, i3) is the coordinate of the basis vector i_hat in the global coordinate system. Remark: this storage is consistent with the :class:`Points` layout: ``basis[0, :] = (i1, i2, i3)``. A basis can be seen as three points (i_hat, j_hat, k_hat). Warning: basis in :class:`CoordinateSystem` objects are stored in a different convention: they are transposed i.e. ``basis[:, 0] = (i1, i2, i3)``. Spherical coordinate system =========================== Physics and ISO convention (r, theta, phi): - r is the radial distance, - theta is the polar angle (inclination) in the rangle in the range [0, pi], - phi is the azimuthal angle in the range [-pi, pi]. Cf. `Wikipedia article on Spherical coordinate system <https://en.wikipedia.org/wiki/Spherical_coordinate_system>`_ .. data:: GCS Global coordinate system (:class:`CoordinateSystem`). ``i = (1, 0, 0)``, ``j = (0, 1, 0)``, ``k = (0, 0, 1)``, ``O = (0, 0, 0)``. """ # Remark: declaration of constant GCS at the end of this file import math from collections import namedtuple import concurrent.futures from warnings import warn import numba import numpy as np from .helpers import Cache, NoCache, chunk_array from . import settings as s from .exceptions import ArimWarning, InvalidDimension, InvalidShape class SphericalCoordinates(namedtuple("SphericalCoordinates", "r theta phi")): """ Spherical coordinates as usually defined in physics Cf. https://en.wikipedia.org/wiki/Spherical_coordinate_system """ @property def radius(self): return self.r @property def polar(self): return self.theta @property def azimuth(self): return self.phi def aspoints(array_like): """ Returns a Point object: the input itself if it is a point, or wrap the object as a Point otherwise. Parameters ---------- array_like : Iterable or Points Returns ------- Points """ if isinstance(array_like, Points): return array_like else: return Points(array_like) class Points: r""" Set of points in a 3D space. The coordinates (x, y, z) are stored contiguously. This object can contain a grid of any dimension of points: - one point (``points.shape == ()``) - a vector of points (``points.shape == (n, )``) - a matrix of points (``points.shape == (n, m)``) - etc. The lenght of Points (``len(points)``) is the number of points in the first dimension of the grid. If there is only one point, a TypeError is raised. Unless otherwise stated, in this class ``idx`` is a multidimensional index of a point. ``len(idx)`` equals the dimension of the Points object. Points objects support indexing: ``points[idx]`` is one point (ndarray of 3 numbers). Points objects are iterable: one point at a time is returned. The points are iterated over such as the right-hand side of the multidimensional varies the quickest. For example, for a Points object of shape (2, 2, 2), the points are returned in the following order: (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1). The method ``enumerate`` returns the indices and the points in the same order. For convenience, wraps several functions of ``arim.geometry``. Parameters ---------- coords: ndarray Dimension: (\*shape, 3) name: str or None Name of the set of points. Attributes ---------- shape : tuple () if there is one point, (n, ) if vector of n points, (n, m) if matrix of points, etc. size_npoints : int Total number of points. """ __slots__ = ("coords", "name") def __init__(self, coords, name=None): coords = np.asarray(coords) if coords.shape[-1] != 3: msg = "The dimension of the coords array should be (..., 3)" msg += " where 3 stands for x, y and z." raise ValueError(msg) self.coords = coords self.name = name @classmethod def from_xyz(cls, x, y, z, name=None): assert x.ndim == y.ndim == z.ndim assert x.shape == y.shape == z.shape assert x.dtype == y.dtype == z.dtype coords = np.stack([x, y, z], axis=-1) return cls(coords, name) @property def shape(self): return self.coords.shape[:-1] @property def ndim(self): return self.coords.ndim - 1 @property def size(self): return self.coords.size // 3 @property def numpoints(self): return self.size def __str__(self): return "P:{}".format(self.name) def __repr__(self): classname = self.__class__.__qualname__ if self.name is None: return "<{}{} at {}>".format(classname, self.shape, hex(id(self))) else: return "<{}{}: {} at {}>".format( classname, self.shape, self.name, hex(id(self)) ) @property def x(self): return self.coords[..., 0] @property def y(self): return self.coords[..., 1] @property def z(self): return self.coords[..., 2] @property def dtype(self): return self.coords.dtype def closest_point(self, x, y, z): dx = self.x - x dy = self.y - y dz = self.z - z return np.argmin(dx * dx + dy * dy + dz * dz) def allclose(self, other, atol=1e-8, rtol=0.0): return are_points_close(self, other, atol=atol, rtol=rtol) def __len__(self): try: return self.shape[0] except IndexError: raise TypeError("Points is unsized") def __getitem__(self, key): """ Returns one point (array of three numbers). """ return self.coords[key] def norm2(self, out=None): """ Returns a array of shape `shape` """ return norm2(self.x, self.y, self.z, out=out) def translate(self, direction): """ Translate the points along a given direction or several directions. If one direction is given (array of shape (3, )), the same direction is applied to all points:: NewCoords[idx] = OldCoords[idx] + Direction, for all idx If as many direction as points are given, each point will be translated from the corresponding direction given:: NewCoords[idx] = OldCoords[idx] + Direction[idx], for all idx Returns a new Points object with the same shape as the current one. Parameters ---------- direction : ndarray Shape: (3, ) Returns ------- translated_points : Points """ new_coords = self.coords + direction translated_points = self.__class__(new_coords, self.name) return translated_points def rotate(self, rotation_matrix, centre=None): """Rotates the points. Returns a new Points object. Cf. :func:`rotate` """ return Points(rotate(self.coords, rotation_matrix, centre), self.name) def to_gcs(self, bases, origins): """Returns the coordinates of the points expressed in the global coordinate system. Returns a new Points object. Cf. :func:`to_gcs` """ return Points(to_gcs(self.coords, bases, origins), self.name) def from_gcs(self, bases, origins): """Returns the coordinates of the points expressed in the basis/bases given as parameter. Returns a new Points object. Cf. :func:`from_gcs` """ return Points(from_gcs(self.coords, bases, origins), self.name) def spherical_coordinates(self): """ (r, theta, phi) Quoted from [Spherical coordinate system](https://en.wikipedia.org/wiki/Spherical_coordinate_system): Spherical coordinates (r, θ, φ) as commonly used in physics: radial distance r, polar angle θ (theta), and azimuthal angle φ (phi). Returns ------- r Radial distance. theta Polar angle. phi Azimuthal angle. """ return spherical_coordinates(self.x, self.y, self.z) def __iter__(self): for idx in np.ndindex(self.shape): yield self.coords[idx] def enumerate(self): """ Yield the index and the coordinates of each point. Yields ------ idx: tuple Multidimensional index of the point (x, y, z) : ndarray of 3 numbers """ for idx in np.ndindex(self.shape): yield idx, self.coords[idx] def points_in_rectbox( self, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None ): """ Returns points in the rectangular box. See Also -------- points_in_rectbox """ return points_in_rectbox( self.x, self.y, self.z, xmin, xmax, ymin, ymax, zmin, zmax ) def to_1d_points(self): """ Returns a new 1d Points object (shape: (numpoints, )) Returns ------- Points """ return Points(self.coords.reshape((self.size, 3)), self.name) OrientedPoints = namedtuple("OrientedPoints", "points orientations") class CoordinateSystem: """ A point and a direct 3D affine basis. A more accurate word to describe this object should be "affine frame", however we keep coordinate system to be consistent with MFMC terminology (global and probe coordinate systems) and to avoid confusion with the word "frame" as a set of timetrace. Attributes ---------- origin i_hat j_hat k_hat basis_matrix : ndarray i_hat, j_hat and k_hat stored in columns ('matrice de passage' de la base locale vers GCS). TODO: different convention as stated in header of the file """ __slots__ = ["_origin", "_i_hat", "_j_hat"] def __init__(self, origin, i_hat, j_hat): # init values self._i_hat = None self._j_hat = None self._origin = None # use the setters (they check the data for us): self.origin = origin self.i_hat = i_hat self.j_hat = j_hat @property def i_hat(self): return self._i_hat @i_hat.setter def i_hat(self, i_hat): i_hat = np.asarray(i_hat) if i_hat.shape != (3,): raise ValueError if not np.isclose(norm2(*i_hat), 1.0): raise ValueError("Vector must be normalised.") self._i_hat = i_hat @property def j_hat(self): return self._j_hat @j_hat.setter def j_hat(self, j_hat): j_hat = np.asarray(j_hat) if j_hat.shape != (3,): raise ValueError if not np.isclose(norm2(*j_hat), 1.0): raise ValueError("Vector must be normalised.") self._j_hat = j_hat @property def origin(self): return self._origin @origin.setter def origin(self, origin): origin = np.asarray(origin) if origin.shape != (3,): raise ValueError self._origin = origin @property def k_hat(self): return np.cross(self.i_hat, self.j_hat) def convert_from_gcs(self, points_gcs): """ Convert from global to local coordinate system Parameters ---------- points_gcs : Points Points whose coordinates are expressed in the GCS. Returns ------- points_cs : Points Points whose coordinates are expressed in this coordinate system. See Also -------- convert_to_gcs """ points = points_gcs.translate(-self.origin) # TODO: improve convert_from_gcs return Points(points.coords @ self.basis_matrix) def convert_from_gcs_pairwise(self, points_gcs, origins): """ Returns the coordinates of the 'points_gcs' in the following CS: - (origins[0], i_hat, j_hat, k_hat) - (origins[1], i_hat, j_hat, k_hat) - ... - (origins[num2-1], i_hat, j_hat, k_hat) Coordinates are returned as three 2d ndarrays (x, y, z) such as x[i, j] is the x-coordinate of the i-th point of ``points_gcs`` in the j-th coordinate system. Parameters ---------- points_gcs : Points Points to convert (coordinates in GCS). origins : Points Origins of the coordinate systems where to express the points. Must be in the current coordinate system. Returns ------- x, y, z : ndarray 2d ndarray. Notes ----- This function is used to express a set of points relatively to a set of probe elements. """ # The rotation of the points is likely to be the longest operation. Do it only once. points_cs = self.convert_from_gcs(points_gcs) # C_ij = A_i + B_j x = points_cs.x[..., np.newaxis] - origins.x[np.newaxis, ...] y = points_cs.y[..., np.newaxis] - origins.y[np.newaxis, ...] z = points_cs.z[..., np.newaxis] - origins.z[np.newaxis, ...] return x, y, z def convert_to_gcs(self, points_cs): """ Convert coordinates in the current coordinate system in the global one. OM' = Origin + OM_x * i_hat + OM_y * j_hat + OM_z * k_hat Parameters ---------- points_cs : Points Points whose coordinates are expressed in this coordinate system. Returns ------- points_gcs : Points Points whose coordinates are expressed in the global coordinate system. See Also -------- convert_from_gcs """ points_cs = points_cs.coords # Vectorise the following operation: # OM' = Origin + OM_x * i_hat + OM_y * j_hat + OM_z * k_hat return Points((points_cs @ self.basis_matrix.T) + self.origin) def translate(self, vector): """ Translate the coordinate system. Returns a new instance. Parameters ---------- vector Returns ------- cs New coordinate system. """ old_origin = Points(self.origin) new_origin = old_origin.translate(vector)[()] return self.__class__(new_origin, self.i_hat, self.j_hat) def rotate(self, rotation_matrix, centre=None): """ Rotate the coordinate system. Returns a new instance. Parameters ---------- rotation_matrix centre Returns ------- cs New coordinate system. """ old_basis = np.stack( (self.origin, self.origin + self.i_hat, self.origin + self.j_hat), axis=0 ) new_basis = Points(old_basis).rotate(rotation_matrix, centre).coords origin = new_basis[0, :] i_hat = new_basis[1, :] - origin j_hat = new_basis[2, :] - origin return self.__class__(origin, i_hat, j_hat) def isclose(self, other, atol=1e-8, rtol=0.0): """ Compare two coordinate system. """ return ( np.allclose(self.origin, other.origin, rtol=rtol, atol=atol) and np.allclose(self.i_hat, other.i_hat, rtol=rtol, atol=atol) and np.allclose(self.j_hat, other.j_hat, rtol=rtol, atol=atol) ) @property def basis_matrix(self): # i_hat, j_hat and k_hat stored in columns return np.stack((self.i_hat, self.j_hat, self.k_hat), axis=1) def copy(self): return self.__class__(self.origin.copy(), self.i_hat.copy(), self.j_hat.copy()) class Grid(Points): """ Regularly spaced 3d grid Attributes ---------- xvect: ndarray Unique points along first axis yvect: ndarray Unique points along second axis zvect: ndarray Unique points along third axis x: ndarray First coordinate of all points. Shape: ``(numx, numy, numz)`` y: ndarray Second coordinate of all points. Shape: ``(numx, numy, numz)`` z: ndarray Third coordinate of all points. Shape: ``(numx, numy, numz)`` dx, dy, dz: float or None Exact distance between points. None if only one point along the axis numx, numy, numz, numpoints Parameters ---------- xmin : float xmax : float xmin : float ymax : float zmin : float zmax : float pixel_size: float *Approximative* distance between points to use. Either one or three floats. """ __slots__ = ("coords", "name", "xvect", "yvect", "zvect") def __init__(self, xmin, xmax, ymin, ymax, zmin, zmax, pixel_size): try: dx, dy, dz = pixel_size except TypeError: dx = pixel_size dy = pixel_size dz = pixel_size if xmin == xmax: x = np.array([xmin]) else: if xmin > xmax: warn("xmin > xmax in grid", ArimWarning) x = np.linspace( xmin, xmax, round((abs(xmax - xmin) + dx) / dx), dtype=s.FLOAT ) if ymin == ymax: y = np.array([ymin], dtype=s.FLOAT) else: if ymin > ymax: warn("ymin > ymax in grid", ArimWarning) y = np.linspace( ymin, ymax, round((abs(ymax - ymin) + dy) / dy), dtype=s.FLOAT ) if zmin == zmax: z = np.array([zmin], dtype=s.FLOAT) else: if zmin > zmax: warn("zmin > zmax in grid", ArimWarning) z = np.linspace( zmin, zmax, round((abs(zmax - zmin) + dz) / dz), dtype=s.FLOAT ) all_coords = np.stack(np.meshgrid(x, y, z, indexing="ij"), axis=-1) super().__init__(all_coords, "Grid") self.xvect = x self.yvect = y self.zvect = z @classmethod def grid_centred_at_point( cls, centre_x, centre_y, centre_z, size_x, size_y, size_z, pixel_size ): """ Create a regularly spaced 3d grid centred around a point. The centre is a point of the grid, which imposes the number of points in any non-null direction is odd. Parameters ---------- centre_x : float centre_y : float centre_z : float size_x : float size_y : float size_z : float pixel_size : float Approximate size Returns ------- Grid """ # Reminder: # L = (N-1)*D # D = L/(N-1) # N = L/D + 1 # The smallest odd integer above x is: math.ceil(x)|1 assert size_x >= 0.0 assert size_y >= 0.0 assert size_z >= 0.0 numpoints_x = math.ceil(size_x / pixel_size + 1) | 1 numpoints_y = math.ceil(size_y / pixel_size + 1) | 1 numpoints_z = math.ceil(size_z / pixel_size + 1) | 1 # The pixel size is exactly size/(numpoints-1) try: dx = size_x / (numpoints_x - 1) except ZeroDivisionError: dx = size_x try: dy = size_y / (numpoints_y - 1) except ZeroDivisionError: dy = size_y try: dz = size_z / (numpoints_z - 1) except ZeroDivisionError: dz = size_z return cls( centre_x - size_x / 2, centre_x + size_x / 2, centre_y - size_y / 2, centre_y + size_y / 2, centre_z - size_z / 2, centre_z + size_z / 2, (dx, dy, dz), ) def resample(self, new_pixel_size): """ Returns a new Grid object with a new pixel size Parameters ---------- new_pixel_size Returns ------- Grid """ return self.__class__( self.xmin, self.xmax, self.ymin, self.ymax, self.zmin, self.zmax, new_pixel_size, ) @property def xmin(self): return self.xvect[0] @property def xmax(self): return self.xvect[-1] @property def ymin(self): return self.yvect[0] @property def ymax(self): return self.yvect[-1] @property def zmin(self): return self.zvect[0] @property def zmax(self): return self.zvect[-1] @property def numx(self): return len(self.xvect) @property def numy(self): return len(self.yvect) @property def numz(self): return len(self.zvect) @property def dx(self): try: return self.xvect[1] - self.xvect[0] except IndexError: return None @property def dy(self): try: return self.yvect[1] - self.yvect[0] except IndexError: return None @property def dz(self): try: return self.zvect[1] - self.zvect[0] except IndexError: return None @property def as_points(self): """ Returns the grid points as Points object of dimension 1 (flatten the grid points). """ warn(DeprecationWarning("use method to_1d_points() instead")) return self.to_1d_points() def to_oriented_points(self): """ Returns a 1d OrientedPoints from the grid points (assume default orientation) Returns ------- OrientedPoints """ return default_oriented_points(self.to_1d_points()) def spherical_coordinates_r(x, y, z, out=None): """radial distance """ return norm2(x, y, z, out=out) def spherical_coordinates_theta(z, r, out=None): """polar angle""" return np.arccos(z / r, out=out) def spherical_coordinates_phi(x, y, out=None): """azimuthal angle""" return np.arctan2(y, x, out=out) def spherical_coordinates(x, y, z, r=None): """ Compute the spherical coordinates (r, θ, φ) of points. r is positive or null. Theta is in [0, pi]. Phi is in [-pi, pi]. Quoted from [Spherical coordinate system](https://en.wikipedia.org/wiki/Spherical_coordinate_system): Spherical coordinates (r, θ, φ) as commonly used in physics: radial distance r, polar angle θ (theta), and azimuthal angle φ (phi). Parameters ---------- x : ndarray y : ndarray z : ndarray r : ndarray or None Computed on the fly is not provided. Returns ------- r, theta, phi : SphericalCoordinates Three arrays with same shape as input. See Also -------- Points.spherical_coordinates : corresponding function with the ``Points`` interface. """ if r is None: r = spherical_coordinates_r(x, y, z) theta = spherical_coordinates_theta(z, r) phi = spherical_coordinates_phi(x, y) return SphericalCoordinates(r, theta, phi) def rotation_matrix_x(theta): s = np.sin(theta) c = np.cos(theta) return np.array(((1, 0, 0), (0, c, -s), (0, s, c)), dtype=np.float) def rotation_matrix_y(theta): s = np.sin(theta) c = np.cos(theta) return np.array(((c, 0, s), (0, 1, 0), (-s, 0, c)), dtype=np.float) def rotation_matrix_z(theta): s = np.sin(theta) c = np.cos(theta) return np.array(((c, -s, 0), (s, c, 0), (0, 0, 1)), dtype=np.float) def rotate(coords, rotation_matrix, centre=None): r""" Rotate these points given a rotation matrix and the centre. The rotation of a point OM (in column) is given by OM' such as: OM' := RotationMatrix x OM + Centre This function accepts multiple rotations: for example to have one rotation matrix per point of index ``idx``, ``rotation_matrix[idx]`` must be a 3x3 matrix. Parameters ---------- coords : ndarray Coordinates to rotate. Shape: (\*shape_points, 3) rotation_matrix Shape: (3, 3) or (\*shape_points, 3, 3). Rotation matrices to apply: either one for all points or one per point. centre : ndarray, optional Centre of the rotation. This point is invariant by rotation. Shape: Shape: (3, 3) or (\*shape_points, 3). Default: centre = (0., 0., 0.) Returns ------- rotated_points : ndarray Shape: (\*shape_points, 3 """ assert rotation_matrix.shape[-2:] == (3, 3) if centre is None: # Out[..., j] = Sum_i Rotation[...,j, i].In[...,i] rotated = np.einsum("...ji,...i->...j", rotation_matrix, coords) else: centre = np.asarray(centre) assert centre.shape[-1] == 3 rotated = ( np.einsum("...ji,...i->...j", rotation_matrix, coords - centre) + centre ) return rotated def to_gcs(coords_cs, bases, origins): r""" Convert the coordinates of points expressed in the basis/bases given as parameter to coordinates expressed in the global coordinate system. Warning: the bases must be **orthogonal**. No check is performed. Parameters ---------- coords_cs : ndarray Shape: (\*shape_points, 3) Coordinates of the points in the basis. bases : ndarray Shape: (\*shape_points, 3, 3) or (3, 3) One or several orthogonal bases. For each basis, the coordinates of the basis vectors in the global coordinate system must be given row per row: i_hat, j_hat, k_hat. origins Shape: (\*shape_points, 3) or (3, 3) Returns ------- coords_gcs : ndarray Shape: (\*shape_points, 3) """ # OM' = Origin + OM_x * i_hat + OM_y * j_hat + OM_z * k_hat return np.einsum("...ij,...i->...j", bases, coords_cs) + origins def from_gcs(points_gcs, bases, origins): r""" Convert the coordinates of points expressed in the global coordinate system to coordinates expressed in the basis/bases given as parameter. Warning: the bases must be **orthogonal**. No check is performed. Parameters ---------- coords_gcs : ndarray Shape: (\*shape_points, 3) Coordinates of the points in the GCS. bases : ndarray Shape: (\*shape_points, 3, 3) or (3, 3) One or several orthogonal bases. For each basis, the coordinates of the basis vectors in the global coordinate system must be given row per row: i_hat, j_hat, k_hat. origins Shape: (\*shape_points, 3) or (3, 3) Returns ------- coords_gcs : ndarray Shape: (\*shape_points, 3) """ return np.einsum("...ji,...i->...j", bases, points_gcs - origins) def rotation_matrix_ypr(yaw, pitch, roll): """Returns the rotation matrix (as a ndarray) from the yaw, pitch and roll in radians. This matrix corresponds to a intrinsic rotation around axes z, y, x respectively. https://en.wikipedia.org/wiki/Rotation_matrix#General_rotations """ return rotation_matrix_z(yaw) @ rotation_matrix_y(pitch) @ rotation_matrix_x(roll) def are_points_close(points1, points2, atol=1e-8, rtol=0.0): """ Return True if and only if the two sets of points have the same shape and coordinates close to the given precision. Attribute name is ignored. Parameters ---------- points1 : Points points2 : Points atol : float rtol : float Returns ------- bool """ return len(points1.shape) == len(points2.shape) and np.allclose( points1.coords, points2.coords, rtol=rtol, atol=atol ) def are_points_aligned(points, rtol=0.0, atol=1e-08): """ Are the points aligned? Returns a boolean. Compute the cross products AB ^ AC, AB ^ AD, AB ^ AE, ... Warning: the two first points must be distinct (TODO: fix this). Parameters ---------- points : Points Points rtol, atol : float Parameters for numpy.allclose. """ numpoints = len(points) # TODO: are_points_aligned -> use coordinate system? points = points.coords if numpoints <= 2: return True # We call A, B, C, ... the points. # vectors AB, AC, AD... AM = points[1:, :] - points[0, :] AB = AM[0, :] assert not np.allclose( AB, np.zeros(3) ), "this function does not work if the two first points are the same" # Cross product AC ^ AB, AD ^ AB, AE ^ AB... cross = np.cross(AM[1:, :], AB) return np.allclose(cross, np.zeros_like(cross), rtol=rtol, atol=atol) def norm2(x, y, z, out=None): """ Euclidean norm of a ndarray Parameters ---------- x : ndarray y : ndarray z : ndarray out : ndarray or None For inplace operations. Returns ------- """ if out is None: out = np.zeros_like(x) out += x * x out += y * y out += z * z return np.sqrt(out, out=out) def norm2_2d(x, y, out=None): """ Euclidean norm of a ndarray Parameters ---------- x : ndarray y : ndarray z : ndarray out : ndarray or None For inplace operations. Returns ------- """ if out is None: out = np.zeros_like(x) out += x * x out += y * y return np.sqrt(out, out=out) def direct_isometry_2d(A, B, Ap, Bp): """ Returns a direct isometry that transform A to A' and B to B'. Parameters ---------- originalA originalB transformedA transformedB Returns ------- M : ndarray P : ndarray Such as: X' = M @ X + P """ # Shorter notations: A = np.asarray(A) B = np.asarray(B) Ap = np.asarray(Ap) Bp = np.asarray(Bp) assert A.shape == (2,) assert B.shape == (2,) assert Ap.shape == (2,) assert Bp.shape == (2,) assert np.isclose(norm2_2d(*(B - A)), norm2_2d(*(Bp - Ap))) # Angle (Ox, AB) AB = B - A phi = np.arctan2(AB[1], AB[0]) # Angle (Ox, ApBp) ApBp = Bp - Ap psi = np.arctan2(ApBp[1], ApBp[0]) theta = psi - phi C = np.cos(theta) S = np.sin(theta) M = np.array([(C, -S), (S, C)]) P = Bp - M @ B return M, P def direct_isometry_3d(A, i_hat, j_hat, B, u_hat, v_hat): """ Returns the isometry that send the direct orthogonal base (A, i_hat, j_hat, i_hat^j_hat) to (B, u_hat, v_hat, u_hat^v_hat) Returns M, P such as: X' = M @ X + P Parameters ---------- A i_hat j_hat B u_hat v_hat Returns ------- M P """ A = np.asarray(A) B = np.asarray(B) u_hat = np.asarray(u_hat) v_hat = np.asarray(v_hat) i_hat = np.asarray(i_hat) j_hat = np.asarray(j_hat) assert A.shape == (3,) assert B.shape == (3,) assert u_hat.shape == (3,) assert v_hat.shape == (3,) assert i_hat.shape == (3,) assert j_hat.shape == (3,) assert np.isclose(norm2(*u_hat), 1.0) assert np.isclose(norm2(*v_hat), 1.0) assert np.isclose(norm2(*i_hat), 1.0) assert np.isclose(norm2(*j_hat), 1.0) assert np.allclose(i_hat @ j_hat, 0.0) assert np.allclose(u_hat @ v_hat, 0.0) k_hat = np.cross(i_hat, j_hat) w_hat = np.cross(u_hat, v_hat) baseDep = np.stack((i_hat, j_hat, k_hat), axis=1) baseArr = np.stack((u_hat, v_hat, w_hat), axis=1) # baseArr = M @ baseDep # <=> baseDep.T @ M.T = baseArr.T M = np.linalg.solve(baseDep.T, baseArr.T).T # assert np.allclose(M @ baseDep, baseArr) # Y = M @ (X - A) + B AB = B - A P = B - M @ A return M, P def distance_pairwise( points1, points2, out=None, dtype=None, block_size=None, numthreads=None ): """ Compute the Euclidean distances of flight between two sets of points. The time of flight between the two points ``A(x1[i], y1[i], z1[i])`` and ``B(x2[i], y2[i], z2[i])`` is: distance[i, j] := distance_pairwise(A, B) := sqrt( delta_x**2 + delta_y**2 + delta_z**2 ) The computation is parallelized with multithreading. Both sets of points are chunked. Parameters ---------- points1 : Points Coordinates of the first set of points (num1 points). points2 : Points Coordinates of the first set of points (num2 points). out : ndarray, optional Preallocated array where to write the result. Default: allocate on the fly. dtype : numpy.dtype, optional Data type for `out`, if not given. Default: infer from points1, points2. block_size : int, optional Number of points to treat in a row. Default: arim.settings.BLOCK_SIZE_EUC_DISTANCE numthreads int, optional Number of threads to start. Default: number of CPU cores plus one. Returns ------- distance : ndarray [num1 x num2] Euclidean distances between the points of the two input sets. """ # Check dimensions and shapes try: (num1,) = points1.x.shape (num2,) = points2.x.shape except ValueError: raise InvalidDimension( "The dimension of the coordinates of points must be one." ) if not (points1.x.shape == points1.y.shape == points1.z.shape): raise InvalidShape( "Must have: points1.x.shape == points1.y.shape == points1.z.shape" ) if not (points2.x.shape == points2.y.shape == points2.z.shape): raise InvalidShape( "Must have: points2.x.shape == points2.y.shape == points2.z.shape" ) if out is None: if dtype is None: # Infer dtype: dtype = np.result_type(points1.dtype, points2.dtype) distance = np.full((num1, num2), 0, dtype=dtype) else: distance = out if distance.shape != (num1, num2): raise InvalidShape("'distance'") if block_size is None: block_size = s.BLOCK_SIZE_EUC_DISTANCE if numthreads is None: numthreads = s.NUMTHREADS chunk_size = math.ceil(block_size / 6) futures = [] with concurrent.futures.ThreadPoolExecutor(max_workers=numthreads) as executor: for chunk1 in chunk_array((num1,), chunk_size): for chunk2 in chunk_array((num2,), chunk_size): chunk_tof = (chunk1[0], chunk2[0]) futures.append( executor.submit( _distance_pairwise, points1.x[chunk1], points1.y[chunk1], points1.z[chunk1], points2.x[chunk2], points2.y[chunk2], points2.z[chunk2], distance[chunk_tof], ) ) # Raise exceptions that happened, if any: for future in futures: future.result() return distance def is_orthonormal(basis): assert basis.shape == (3, 3) return basis.dtype.kind == "f" and np.allclose( # must be real basis.T, np.linalg.inv(basis) ) def is_orthonormal_direct(basis): """ Returns True if the basis is orthonormal and direct: Parameters ---------- basis Returns ------- """ return is_orthonormal(basis) and np.allclose( np.cross(basis[0, :], basis[1, :]), basis[2, :] ) @numba.jit(nopython=True, nogil=True, cache=True) def _distance_pairwise(x1, y1, z1, x2, y2, z2, distance): """ Cf. distance_pairwise. ``distance`` is the result. The array must be preallocated before. """ # For each grid point and each element: num1, num2 = distance.shape for i in range(num1): for j in range(num2): dx = x1[i] - x2[j] dy = y1[i] - y2[j] dz = z1[i] - z2[j] distance[i, j] = math.sqrt(dx * dx + dy * dy + dz * dz) return def points_in_rectbox( x, y, z, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None ): """ Returns points in the rectangular box. Some constraints can be ignored (unbounded box). Parameters ---------- x : ndarray Coordinates x of the points to filter. y : ndarray Coordinates y of the points to filter. z : ndarray Coordinates z of the points to filter. xmin : float or None xmax : float or None ymin : float or None ymax : float or None zmin : float or None zmax : float or None Returns ------- out : ndarray Array of bool whose shape is the one as x, y and z. For each entry: true if all the constraints are satisfied, false otherwise. Examples -------- >>> points_in_rectbox(x, y, z, xmin=10, ymax=20, zmin=30, zmax=39) Returns points such as ``10 <= x`` and ``y <= 20`` and ``30 <= z <= zmax``. """ if not (x.shape == y.shape == z.shape): raise ValueError("shape must be equal") out = np.ones(x.shape, dtype=bool) valid_ones = [] if xmin is not None: valid_ones.append(xmin <= x) if ymin is not None: valid_ones.append(ymin <= y) if zmin is not None: valid_ones.append(zmin <= z) if xmax is not None: valid_ones.append(x <= xmax) if ymax is not None: valid_ones.append(y <= ymax) if zmax is not None: valid_ones.append(z <= zmax) for valid in valid_ones: np.logical_and(out, valid, out=out) return out GCS = CoordinateSystem( origin=np.array((0.0, 0.0, 0.0)), i_hat=np.array((1.0, 0.0, 0.0)), j_hat=np.array((0.0, 1.0, 0.0)), ) def points_1d_wall_z(xmin, xmax, z, numpoints, y=0.0, name=None, dtype=None): """ Returns a set of regularly spaced points between (xmin, y, z) and (xmax, y, z). Orientation of the point: (0., 0., 1.) Parameters ---------- xmin : float xmax : float z : float numpoints : int y : float Default 0 name : str or None dtype : numpy.dtype Returns ------- Oriented points """ if dtype is None: dtype = s.FLOAT points = Points.from_xyz( x=np.linspace(xmin, xmax, numpoints, dtype=dtype), y=np.full((numpoints,), y, dtype=dtype), z=np.full((numpoints,), z, dtype=dtype), name=name, ) orientations = default_orientations(points) return OrientedPoints(points, orientations) def default_orientations(points): """ Returns the default orientations for unoriented points. Assign to each point the following orientation:: x = (1, 0, 0) y = (0, 1, 0) z = (0, 0, 1) Parameters ---------- points: Points Returns ------- orientations : Points """ # No need to create a full array because all values are the same: we cheat # using a broadcast array. This saves memory space and reduces access time. orientations_arr = np.broadcast_to( np.identity(3, dtype=points.dtype), (*points.shape, 3, 3) ) orientations = Points(orientations_arr) return orientations def default_oriented_points(points): """ Returns OrientedPoints from Points assuming the default orientations. Parameters ---------- points : Points Returns ------- oriented_points : OrientedPOints """ return OrientedPoints(points, default_orientations(points)) def points_from_probe(probe, name="Probe"): """ Probe object to OrientedPoints (points and orientations). Parameters ---------- probe name Returns ------- OrientedPoints """ points = probe.locations if name is not None: points.name = name orientations_arr = np.zeros((3, 3), dtype=points.dtype) orientations_arr[0] = probe.pcs.i_hat orientations_arr[1] = probe.pcs.j_hat orientations_arr[2] = probe.pcs.k_hat orientations = Points(np.broadcast_to(orientations_arr, (*points.shape, 3, 3))) return OrientedPoints(points, orientations)
{"hexsha": "f4e662c29f5a389c03705061d5ae23080eb8a010", "size": 41425, "ext": "py", "lang": "Python", "max_stars_repo_path": "arim/geometry.py", "max_stars_repo_name": "will-jj/arim", "max_stars_repo_head_hexsha": "fc15efe171a41355090123fcea10406ee75efe31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-04-05T13:43:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T21:38:19.000Z", "max_issues_repo_path": "arim/geometry.py", "max_issues_repo_name": "will-jj/arim", "max_issues_repo_head_hexsha": "fc15efe171a41355090123fcea10406ee75efe31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-09T10:38:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-17T16:23:16.000Z", "max_forks_repo_path": "arim/geometry.py", "max_forks_repo_name": "will-jj/arim", "max_forks_repo_head_hexsha": "fc15efe171a41355090123fcea10406ee75efe31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-04-04T17:02:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T15:36:03.000Z", "avg_line_length": 26.6741790084, "max_line_length": 128, "alphanum_fraction": 0.5826674713, "include": true, "reason": "import numpy,import numba", "num_tokens": 10619}
import argparse import os import torch import numpy as np import torch import random def set_deterministic(seed): # seed by default is None if seed is not None: print(f"Deterministic with seed = {seed}") random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False else: print("Non-deterministic") def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') # training specific args parser.add_argument('--dataset', type=str, default='cifar10', help='choose from random, stl10, mnist, cifar10, cifar100, imagenet') parser.add_argument('--download', action='store_true', help="if can't find dataset, download from web") parser.add_argument('--image_size', type=int, default=224) parser.add_argument('--num_workers', type=int, default=4) parser.add_argument('--data_dir', type=str, default=os.getenv('DATA')) parser.add_argument('--output_dir', type=str, default=os.getenv('OUTPUT')) parser.add_argument('--device', type=str, default='cuda' if torch.cuda.is_available() else 'cpu') parser.add_argument('--resume', type=str, default=None) parser.add_argument('--eval_from', type=str, default=None) parser.add_argument('--hide_progress', action='store_true') parser.add_argument('--use_default_hyperparameters', action='store_true') # model related params parser.add_argument('--model', type=str, default='simsiam') parser.add_argument('--backbone', type=str, default='resnet50') parser.add_argument('--num_epochs', type=int, default=100, help='This will affect learning rate decay') parser.add_argument('--stop_at_epoch', type=int, default=None) parser.add_argument('--batch_size', type=int, default=512) parser.add_argument('--proj_layers', type=int, default=None, help="number of projector layers. In cifar experiment, this is set to 2") # optimization params parser.add_argument('--optimizer', type=str, default='sgd', help='sgd, lars(from lars paper), lars_simclr(used in simclr and byol), larc(used in swav)') parser.add_argument('--warmup_epochs', type=int, default=0, help='learning rate will be linearly scaled during warm up period') parser.add_argument('--warmup_lr', type=float, default=0, help='Initial warmup learning rate') parser.add_argument('--base_lr', type=float, default=0.05) parser.add_argument('--final_lr', type=float, default=0) parser.add_argument('--momentum', type=float, default=0.9) parser.add_argument('--weight_decay', type=float, default=0.0001) parser.add_argument('--eval_after_train', type=str, default=None) parser.add_argument('--head_tail_accuracy', action='store_true', help='the acc in first epoch will indicate whether collapse or not, the last epoch shows the final accuracy') args = parser.parse_args() if args.debug: args.batch_size = 2 args.stop_at_epoch = 2 args.num_epochs = 3 # train only one epoch args.num_workers = 0 assert not None in [args.output_dir, args.data_dir] os.makedirs(args.output_dir, exist_ok=True) # assert args.stop_at_epoch <= args.num_epochs if args.stop_at_epoch is not None: if args.stop_at_epoch > args.num_epochs: raise Exception else: args.stop_at_epoch = args.num_epochs if args.use_default_hyperparameters: raise NotImplementedError return args
{"hexsha": "35ff1d403d5b16d2b9d9aa10621be2c87764b34e", "size": 3598, "ext": "py", "lang": "Python", "max_stars_repo_path": "configs/__init__.py", "max_stars_repo_name": "rjean/SimSiam", "max_stars_repo_head_hexsha": "d754dc0b5adf408c57cc23f4eb207276d559b3c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-03T02:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T02:23:35.000Z", "max_issues_repo_path": "configs/__init__.py", "max_issues_repo_name": "rjean/SimSiam", "max_issues_repo_head_hexsha": "d754dc0b5adf408c57cc23f4eb207276d559b3c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "configs/__init__.py", "max_forks_repo_name": "rjean/SimSiam", "max_forks_repo_head_hexsha": "d754dc0b5adf408c57cc23f4eb207276d559b3c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1282051282, "max_line_length": 178, "alphanum_fraction": 0.7034463591, "include": true, "reason": "import numpy", "num_tokens": 841}
(* * Unique.v * Wolf Honore * * Defines an interface for a generator of unique values. *) Require Import Le. Require Import List. Require Import Max. Module Type UNIQUE. Parameter t : Set. Parameter init : list t. Parameter new : list t -> list t * t. Parameter eq : forall (u1 u2 : t), {u1 = u2} + {u1 <> u2}. Definition is_unique (us : list t) : Prop := NoDup us. Hypothesis init_unique : is_unique init. Hypothesis new_spec : forall u us us', is_unique us -> new us = (us', u) -> In u us' /\ is_unique us'. End UNIQUE. Module NatUnique <: UNIQUE. Definition t := nat. Definition maximum (us : list t) := fold_right max 0 us. Definition init := @nil t. Definition new (us : list t) := let u := S (maximum us) in (u :: us, u). Definition eq : forall (u1 u2 : t), {u1 = u2} + {u1 <> u2}. decide equality. Defined. Definition is_unique (us : list t) : Prop := NoDup us. Lemma maximum_ge : forall u us, In u us -> u <= maximum us. Proof. induction us; intros; inversion H; subst; simpl. - destruct (max_dec u (maximum us)); rewrite e. + constructor. + rewrite <- e. apply le_max_l. - apply IHus in H0. destruct (max_dec a (maximum us)); rewrite e. + assert (maximum us <= a). { rewrite <- e. apply le_max_r. } apply le_trans with (m := maximum us); assumption. + assumption. Qed. Lemma init_unique : is_unique init. Proof. constructor. Qed. Lemma new_spec : forall u us us', is_unique us -> new us = (us', u) -> In u us' /\ is_unique us'. Proof. unfold new, is_unique; intros. inversion H0; subst. split. - simpl; left; reflexivity. - destruct us. + constructor; auto. + constructor; [| assumption]. unfold not; intros. apply maximum_ge in H1. apply le_Sn_n in H1; assumption. Qed. End NatUnique.
{"author": "whonore", "repo": "CerTiger", "sha": "b99908ce11a2e8095d7f33353cb69f8b0d6315b8", "save_path": "github-repos/coq/whonore-CerTiger", "path": "github-repos/coq/whonore-CerTiger/CerTiger-b99908ce11a2e8095d7f33353cb69f8b0d6315b8/util/Unique.v"}
#!/usr/bin/env python3 import numpy as np import cv2 import sys import rospkg from sensor_msgs.msg import Image from cv_bridge import CvBridge import rospy def lane_callback(msg): #print(msg) br = CvBridge() current_frame = br.imgmsg_to_cv2(msg) cv2.imshow("test", current_frame) def main(): print("#################### I've started and I'm running: " + sys.version) rospy.init_node('lane_identification') lane_sub = rospy.Subscriber('unity_image/normal', Image, lane_callback) rospy.spin() if __name__ == '__main__': main()
{"hexsha": "36cddcb49a5c6fda84343ff9686a3107342e6f50", "size": 565, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/binocular_p3/src/basic_python3.py", "max_stars_repo_name": "PatWatson/Queens-Autonomous-Taxi-2021-Capstone", "max_stars_repo_head_hexsha": "2706927e9c98c3ddddf7f5f03301d178a827e147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-20T01:59:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T01:59:31.000Z", "max_issues_repo_path": "src/binocular_p3/src/basic_python3.py", "max_issues_repo_name": "PatWatson/Queens-Autonomous-Taxi-2021-Capstone", "max_issues_repo_head_hexsha": "2706927e9c98c3ddddf7f5f03301d178a827e147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/binocular_p3/src/basic_python3.py", "max_forks_repo_name": "PatWatson/Queens-Autonomous-Taxi-2021-Capstone", "max_forks_repo_head_hexsha": "2706927e9c98c3ddddf7f5f03301d178a827e147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-20T01:57:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T21:24:23.000Z", "avg_line_length": 22.6, "max_line_length": 78, "alphanum_fraction": 0.6867256637, "include": true, "reason": "import numpy", "num_tokens": 142}
""" Copyright (c) 2019 Intel Corporation Licensed 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. """ import itertools import math import numpy as np from ..topology_types import YoloV1Tiny, YoloV2, YoloV2Tiny, YoloV3, YoloV3Tiny, SSD, FasterRCNN from ..adapters import Adapter from ..config import ConfigValidator, NumberField, StringField, ListField from ..postprocessor.nms import NMS from ..representation import DetectionPrediction, ContainerPrediction from ..utils import get_or_parse_value class TinyYOLOv1Adapter(Adapter): """ Class for converting output of Tiny YOLO v1 model to DetectionPrediction representation """ __provider__ = 'tiny_yolo_v1' prediction_types = (DetectionPrediction, ) topology_types = (YoloV1Tiny, ) def process(self, raw, identifiers=None, frame_meta=None): """ Args: identifiers: list of input data identifiers raw: output of model Returns: list of DetectionPrediction objects """ prediction = self._extract_predictions(raw, frame_meta)[self.output_blob] PROBABILITY_SIZE = 980 CONFIDENCE_SIZE = 98 BOXES_SIZE = 392 CELLS_X, CELLS_Y = 7, 7 CLASSES = 20 OBJECTS_PER_CELL = 2 result = [] for identifier, output in zip(identifiers, prediction): assert PROBABILITY_SIZE + CONFIDENCE_SIZE + BOXES_SIZE == output.shape[0] probability, scale, boxes = np.split(output, [PROBABILITY_SIZE, PROBABILITY_SIZE + CONFIDENCE_SIZE]) probability = np.reshape(probability, (CELLS_Y, CELLS_X, CLASSES)) scale = np.reshape(scale, (CELLS_Y, CELLS_X, OBJECTS_PER_CELL)) boxes = np.reshape(boxes, (CELLS_Y, CELLS_X, OBJECTS_PER_CELL, 4)) confidence = np.zeros((CELLS_Y, CELLS_X, OBJECTS_PER_CELL, CLASSES + 4)) for cls in range(CLASSES): confidence[:, :, 0, cls] = np.multiply(probability[:, :, cls], scale[:, :, 0]) confidence[:, :, 1, cls] = np.multiply(probability[:, :, cls], scale[:, :, 1]) labels, scores, x_mins, y_mins, x_maxs, y_maxs = [], [], [], [], [], [] for i, j, k in np.ndindex((CELLS_X, CELLS_Y, OBJECTS_PER_CELL)): box = boxes[j, i, k] box = [(box[0] + i) / float(CELLS_X), (box[1] + j) / float(CELLS_Y), box[2] ** 2, box[3] ** 2] label = np.argmax(confidence[j, i, k, :CLASSES]) score = confidence[j, i, k, label] labels.append(label) scores.append(score) x_mins.append(box[0] - box[2] / 2.0) y_mins.append(box[1] - box[3] / 2.0) x_maxs.append(box[0] + box[2] / 2.0) y_maxs.append(box[1] + box[3] / 2.0) result.append(DetectionPrediction(identifier, labels, scores, x_mins, y_mins, x_maxs, y_maxs)) return result def entry_index(w, h, n_coords, n_classes, pos, entry): row = pos // (w * h) col = pos % (w * h) return row * w * h * (n_classes + n_coords + 1) + entry * w * h + col class YoloV2Adapter(Adapter): """ Class for converting output of YOLO v2 family models to DetectionPrediction representation """ __provider__ = 'yolo_v2' prediction_types = (DetectionPrediction, ) topology_types = (YoloV2, YoloV2Tiny, ) PRECOMPUTED_ANCHORS = { 'yolo_v2': [1.3221, 1.73145, 3.19275, 4.00944, 5.05587, 8.09892, 9.47112, 4.84053, 11.2364, 10.0071], 'tiny_yolo_v2': [1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52] } @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'classes': NumberField( value_type=int, optional=True, min_value=1, default=20, description="Number of detection classes." ), 'coords': NumberField( value_type=int, optional=True, min_value=1, default=4, description="Number of bbox coordinates." ), 'num': NumberField( value_type=int, optional=True, min_value=1, default=5, description="Num parameter from DarkNet configuration file." ), 'anchors': StringField( optional=True, choices=YoloV2Adapter.PRECOMPUTED_ANCHORS, allow_own_choice=True, default='yolo_v2', description="Anchor values provided as comma-separated list or one of precomputed: " "{}".format(', '.join(YoloV2Adapter.PRECOMPUTED_ANCHORS))) }) return parameters def validate_config(self): super().validate_config(on_extra_argument=ConfigValidator.WARN_ON_EXTRA_ARGUMENT) def configure(self): self.classes = self.get_value_from_config('classes') self.coords = self.get_value_from_config('coords') self.num = self.get_value_from_config('num') self.anchors = get_or_parse_value(self.get_value_from_config('anchors'), YoloV2Adapter.PRECOMPUTED_ANCHORS) def process(self, raw, identifiers=None, frame_meta=None): """ Args: identifiers: list of input data identifiers raw: output of model Returns: list of DetectionPrediction objects """ predictions = self._extract_predictions(raw, frame_meta)[self.output_blob] cells_x, cells_y = 13, 13 result = [] for identifier, prediction in zip(identifiers, predictions): labels, scores, x_mins, y_mins, x_maxs, y_maxs = [], [], [], [], [], [] for y, x, n in np.ndindex((cells_y, cells_x, self.num)): index = n * cells_y * cells_x + y * cells_x + x box_index = entry_index(cells_x, cells_y, self.coords, self.classes, index, 0) obj_index = entry_index(cells_x, cells_y, self.coords, self.classes, index, self.coords) scale = prediction[obj_index] box = [ (x + prediction[box_index + 0 * (cells_y * cells_x)]) / cells_x, (y + prediction[box_index + 1 * (cells_y * cells_x)]) / cells_y, np.exp(prediction[box_index + 2 * (cells_y * cells_x)]) * self.anchors[2 * n + 0] / cells_x, np.exp(prediction[box_index + 3 * (cells_y * cells_x)]) * self.anchors[2 * n + 1] / cells_y ] classes_prob = np.empty(self.classes) for cls in range(self.classes): cls_index = entry_index(cells_x, cells_y, self.coords, self.classes, index, self.coords + 1 + cls) classes_prob[cls] = prediction[cls_index] classes_prob = classes_prob * scale label = np.argmax(classes_prob) labels.append(label) scores.append(classes_prob[label]) x_mins.append(box[0] - box[2] / 2.0) y_mins.append(box[1] - box[3] / 2.0) x_maxs.append(box[0] + box[2] / 2.0) y_maxs.append(box[1] + box[3] / 2.0) result.append(DetectionPrediction(identifier, labels, scores, x_mins, y_mins, x_maxs, y_maxs)) return result class YoloV3Adapter(Adapter): """ Class for converting output of YOLO v3 family models to DetectionPrediction representation """ __provider__ = 'yolo_v3' prediction_types = (DetectionPrediction, ) topology_types = (YoloV3, YoloV3Tiny, ) PRECOMPUTED_ANCHORS = { 'yolo_v3': [ 10.0, 13.0, 16.0, 30.0, 33.0, 23.0, 30.0, 61.0, 62.0, 45.0, 59.0, 119.0, 116.0, 90.0, 156.0, 198.0, 373.0, 326.0 ], 'tiny_yolo_v3': [ 10.0, 14.0, 23.0, 27.0, 37.0, 58.0, 81.0, 82.0, 135.0, 169.0, 344.0, 319.0 ] } @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'classes': NumberField( value_type=int, optional=True, min_value=1, default=80, description="Number of detection classes." ), 'coords': NumberField( value_type=int, optional=True, min_value=1, default=4, description="Number of bbox coordinates." ), 'num': NumberField( value_type=int, optional=True, min_value=1, default=3, description="Num parameter from DarkNet configuration file." ), 'anchors': StringField( optional=True, choices=YoloV3Adapter.PRECOMPUTED_ANCHORS.keys(), allow_own_choice=True, default='yolo_v3', description="Anchor values provided as comma-separated list or one of precomputed: " "{}.".format(', '.join(YoloV3Adapter.PRECOMPUTED_ANCHORS.keys()))), 'threshold': NumberField(value_type=float, optional=True, min_value=0, default=0.001, description="Minimal objectiveness score value for valid detections."), 'outputs': ListField( optional=True, default=[], description="The list of output layers names (optional)," " if specified there should be exactly 3 output layers provided." ) }) return parameters def validate_config(self): super().validate_config(on_extra_argument=ConfigValidator.WARN_ON_EXTRA_ARGUMENT) def configure(self): self.classes = self.get_value_from_config('classes') self.coords = self.get_value_from_config('coords') self.num = self.get_value_from_config('num') self.anchors = get_or_parse_value(self.get_value_from_config('anchors'), YoloV3Adapter.PRECOMPUTED_ANCHORS) self.threshold = self.get_value_from_config('threshold') self.outputs = self.get_value_from_config('outputs') def process(self, raw, identifiers=None, frame_meta=None): """ Args: identifiers: list of input data identifiers raw: output of model Returns: list of DetectionPrediction objects """ def get_anchors_offset(x): return int((self.num * 2) * (len(self.anchors) / (self.num * 2) - 1 - math.log2(x / 13))) def parse_yolo_v3_results(prediction, threshold, w, h, det): cells_x, cells_y = prediction.shape[1:] prediction = prediction.flatten() for y, x, n in np.ndindex((cells_y, cells_x, self.num)): index = n * cells_y * cells_x + y * cells_x + x anchors_offset = get_anchors_offset(cells_x) box_index = entry_index(cells_x, cells_y, self.coords, self.classes, index, 0) obj_index = entry_index(cells_x, cells_y, self.coords, self.classes, index, self.coords) scale = prediction[obj_index] if scale < threshold: continue box = [ (x + prediction[box_index + 0 * (cells_y * cells_x)]) / cells_x, (y + prediction[box_index + 1 * (cells_y * cells_x)]) / cells_y, np.exp(prediction[box_index + 2 * (cells_y * cells_x)]) * self.anchors[ anchors_offset + 2 * n + 0] / w, np.exp(prediction[box_index + 3 * (cells_y * cells_x)]) * self.anchors[ anchors_offset + 2 * n + 1] / h ] classes_prob = np.empty(self.classes) for cls in range(self.classes): cls_index = entry_index(cells_x, cells_y, self.coords, self.classes, index, self.coords + 1 + cls) classes_prob[cls] = prediction[cls_index] * scale det['labels'].append(cls) det['scores'].append(classes_prob[cls]) det['x_mins'].append(box[0] - box[2] / 2.0) det['y_mins'].append(box[1] - box[3] / 2.0) det['x_maxs'].append(box[0] + box[2] / 2.0) det['y_maxs'].append(box[1] + box[3] / 2.0) return det result = [] raw_outputs = self._extract_predictions(raw, frame_meta) if self.outputs: outputs = self.outputs else: outputs = raw_outputs.keys() batch = len(identifiers) predictions = [[] for _ in range(batch)] for blob in outputs: for b in range(batch): predictions[b].append(raw_outputs[blob][b]) for identifier, prediction, meta in zip(identifiers, predictions, frame_meta): detections = {'labels': [], 'scores': [], 'x_mins': [], 'y_mins': [], 'x_maxs': [], 'y_maxs': []} input_shape = list(meta.get('input_shape', {'data': (1, 3, 416, 416)}).values())[0] self.input_width = input_shape[3] self.input_height = input_shape[2] for p in prediction: parse_yolo_v3_results(p, self.threshold, self.input_width, self.input_height, detections) result.append(DetectionPrediction( identifier, detections['labels'], detections['scores'], detections['x_mins'], detections['y_mins'], detections['x_maxs'], detections['y_maxs'] )) return result class SSDAdapter(Adapter): """ Class for converting output of SSD model to DetectionPrediction representation """ __provider__ = 'ssd' prediction_types = (DetectionPrediction, ) topology_types = (SSD, FasterRCNN, ) def process(self, raw, identifiers=None, frame_meta=None): """ Args: identifiers: list of input data identifiers raw: output of model Returns: list of DetectionPrediction objects """ prediction_batch = self._extract_predictions(raw, frame_meta)[self.output_blob] prediction_count = prediction_batch.shape[2] if len(prediction_batch.shape) > 2 else prediction_batch.shape[0] prediction_batch = prediction_batch.reshape(prediction_count, -1) prediction_batch = self.remove_empty_detections(prediction_batch) result = [] for batch_index, identifier in enumerate(identifiers): prediction_mask = np.where(prediction_batch[:, 0] == batch_index) detections = prediction_batch[prediction_mask] detections = detections[:, 1::] result.append(DetectionPrediction(identifier, *zip(*detections))) return result @staticmethod def remove_empty_detections(prediction_blob): ind = prediction_blob[:, 0] ind_ = np.where(ind == -1)[0] m = ind_[0] if ind_.size else prediction_blob.shape[0] return prediction_blob[:m, :] class PyTorchSSDDecoder(Adapter): """ Class for converting output of PyTorch SSD models to DetectionPrediction representation """ __provider__ = 'pytorch_ssd_decoder' def validate_config(self): super().validate_config(on_extra_argument=ConfigValidator.ERROR_ON_EXTRA_ARGUMENT) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'scores_out': StringField(description="Scores output layer name."), 'boxes_out': StringField(description="Boxes output layer name."), 'confidence_threshold': NumberField(optional=True, default=0.05, description="Confidence threshold."), 'nms_threshold': NumberField(optional=True, default=0.5, description="NMS threshold."), 'keep_top_k': NumberField(optional=True, value_type=int, default=200, description="Keep top K.") }) return parameters def configure(self): self.scores_out = self.get_value_from_config('scores_out') self.boxes_out = self.get_value_from_config('boxes_out') self.confidence_threshold = self.get_value_from_config('confidence_threshold') self.nms_threshold = self.get_value_from_config('nms_threshold') self.keep_top_k = self.get_value_from_config('keep_top_k') # Set default values according to: # https://github.com/mlperf/inference/tree/master/cloud/single_stage_detector self.aspect_ratios = [[2], [2, 3], [2, 3], [2, 3], [2], [2]] self.feat_size = [[50, 50], [25, 25], [13, 13], [7, 7], [3, 3], [3, 3]] self.scales = [21, 45, 99, 153, 207, 261, 315] self.strides = [3, 3, 2, 2, 2, 2] self.scale_xy = 0.1 self.scale_wh = 0.2 @staticmethod def softmax(x, axis=0): return np.transpose(np.transpose(np.exp(x)) * np.reciprocal(np.sum(np.exp(x), axis=axis))) @staticmethod def default_boxes(fig_size, feat_size, scales, aspect_ratios): fig_size_w, fig_size_h = fig_size scales = [(int(s * fig_size_w / 300), int(s * fig_size_h / 300)) for s in scales] fkw, fkh = np.transpose(feat_size) default_boxes = [] for idx, sfeat in enumerate(feat_size): sfeat_w, sfeat_h = sfeat sk1 = scales[idx][0] / fig_size_w sk2 = scales[idx + 1][1] / fig_size_h sk3 = math.sqrt(sk1 * sk2) all_sizes = [(sk1, sk1), (sk3, sk3)] for alpha in aspect_ratios[idx]: w, h = sk1 * math.sqrt(alpha), sk1 / math.sqrt(alpha) all_sizes.append((w, h)) all_sizes.append((h, w)) for w, h in all_sizes: for i, j in itertools.product(range(sfeat_w), range(sfeat_h)): cx, cy = (j + 0.5) / fkh[idx], (i + 0.5) / fkw[idx] default_boxes.append((cx, cy, w, h)) default_boxes = np.clip(default_boxes, 0, 1) return default_boxes def process(self, raw, identifiers=None, frame_meta=None): """ Args: identifiers: list of input data identifiers raw: output of model Returns: list of DetectionPrediction objects """ raw_outputs = self._extract_predictions(raw, frame_meta) batch_scores = raw_outputs[self.scores_out] batch_boxes = raw_outputs[self.boxes_out] result = [] for identifier, scores, boxes, meta in zip(identifiers, batch_scores, batch_boxes, frame_meta): detections = {'labels': [], 'scores': [], 'x_mins': [], 'y_mins': [], 'x_maxs': [], 'y_maxs': []} image_info = meta.get("image_info")[0:2] # Default boxes dboxes = self.default_boxes(image_info, self.feat_size, self.scales, self.aspect_ratios) # Scores scores = np.transpose(scores) scores = self.softmax(scores, axis=1) # Boxes boxes = np.transpose(boxes) boxes[:, :2] = self.scale_xy * boxes[:, :2] boxes[:, 2:] = self.scale_wh * boxes[:, 2:] boxes[:, :2] = boxes[:, :2] * dboxes[:, 2:] + dboxes[:, :2] boxes[:, 2:] = np.exp(boxes[:, 2:]) * dboxes[:, 2:] for label, score in enumerate(np.transpose(scores)): # Skip background label if label == 0: continue # Filter out detections with score < confidence_threshold mask = score > self.confidence_threshold filtered_boxes, filtered_score = boxes[mask, :], score[mask] if filtered_score.size == 0: continue # Transform to format (x_min, y_min, x_max, y_max) x_mins = (filtered_boxes[:, 0] - 0.5 * filtered_boxes[:, 2]) y_mins = (filtered_boxes[:, 1] - 0.5 * filtered_boxes[:, 3]) x_maxs = (filtered_boxes[:, 0] + 0.5 * filtered_boxes[:, 2]) y_maxs = (filtered_boxes[:, 1] + 0.5 * filtered_boxes[:, 3]) # Apply NMS keep = NMS.nms(x_mins, y_mins, x_maxs, y_maxs, filtered_score, self.nms_threshold, include_boundaries=False, keep_top_k=self.keep_top_k) filtered_score = filtered_score[keep] x_mins = x_mins[keep] y_mins = y_mins[keep] x_maxs = x_maxs[keep] y_maxs = y_maxs[keep] # Keep topK # Applied just after NMS - no additional sorting is required for filtered_score array filtered_score = filtered_score[:self.keep_top_k] x_mins = x_mins[:self.keep_top_k] y_mins = y_mins[:self.keep_top_k] x_maxs = x_maxs[:self.keep_top_k] y_maxs = y_maxs[:self.keep_top_k] # Save detections labels = np.full_like(filtered_score, label) detections['labels'].extend(labels) detections['scores'].extend(filtered_score) detections['x_mins'].extend(x_mins) detections['y_mins'].extend(y_mins) detections['x_maxs'].extend(x_maxs) detections['y_maxs'].extend(y_maxs) result.append( DetectionPrediction( identifier, detections['labels'], detections['scores'], detections['x_mins'], detections['y_mins'], detections['x_maxs'], detections['y_maxs'] ) ) return result class TFObjectDetectionAPIAdapter(Adapter): """ Class for converting output of SSD model to DetectionPrediction representation """ __provider__ = 'tf_object_detection' def validate_config(self): super().validate_config(on_extra_argument=ConfigValidator.ERROR_ON_EXTRA_ARGUMENT) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'classes_out': StringField(description="Classes output layer name."), 'boxes_out': StringField(description="Boxes output layer name."), 'scores_out': StringField(description="Scores output layer name."), 'num_detections_out': StringField(description="Number of detections output layer name.") }) return parameters def configure(self): self.classe_out = self.get_value_from_config('classes_out') self.boxes_out = self.get_value_from_config('boxes_out') self.scores_out = self.get_value_from_config('scores_out') self.num_detections_out = self.get_value_from_config('num_detections_out') def process(self, raw, identifiers=None, frame_meta=None): """ Args: identifiers: list of input data identifiers raw: output of model Returns: list of DetectionPrediction objects """ prediction_batch = self._extract_predictions(raw, frame_meta) classes_batch = prediction_batch[self.classe_out] scores_batch = prediction_batch[self.scores_out] boxes_batch = prediction_batch[self.boxes_out] num_detections_batch = prediction_batch[self.num_detections_out].astype(int) result = [] for identifier, classes, scores, boxes, num_detections in zip( identifiers, classes_batch, scores_batch, boxes_batch, num_detections_batch ): valid_classes = classes[:num_detections] valid_scores = scores[:num_detections] valid_boxes = boxes[:num_detections] y_mins, x_mins, y_maxs, x_maxs = valid_boxes.T result.append(DetectionPrediction(identifier, valid_classes, valid_scores, x_mins, y_mins, x_maxs, y_maxs)) return result class FacePersonAdapter(Adapter): __provider__ = 'face_person_detection' prediction_types = (DetectionPrediction, ) @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'face_out': StringField(description="Face detection output layer name."), 'person_out': StringField(description="Person detection output layer name"), }) return parameters def validate_config(self): super().validate_config(on_extra_argument=ConfigValidator.ERROR_ON_EXTRA_ARGUMENT) def configure(self): self.face_detection_out = self.launcher_config['face_out'] self.person_detection_out = self.launcher_config['person_out'] self.face_adapter = SSDAdapter(self.launcher_config, self.label_map, self.face_detection_out) self.person_adapter = SSDAdapter(self.launcher_config, self.label_map, self.person_detection_out) def process(self, raw, identifiers=None, frame_meta=None): face_batch_result = self.face_adapter.process(raw, identifiers) person_batch_result = self.person_adapter.process(raw, identifiers) result = [ContainerPrediction({self.face_detection_out: face_result, self.person_detection_out: person_result}) for face_result, person_result in zip(face_batch_result, person_batch_result)] return result class SSDAdapterMxNet(Adapter): """ Class for converting output of MxNet SSD model to DetectionPrediction representation """ __provider__ = 'ssd_mxnet' def process(self, raw, identifiers=None, frame_meta=None): """ Args: identifiers: list of input data identifiers raw: output of model which is ndarray of shape (batch, det_count, 6), each detection is defined by 6 values: class_id, prob, x_min, y_min, x_max, y_max Returns: list of DetectionPrediction objects """ raw_outputs = self._extract_predictions(raw, frame_meta) result = [] for identifier, prediction_batch in enumerate(identifiers, raw_outputs[self.output_blob]): # Filter detections (get only detections with class_id >= 0) detections = prediction_batch[np.where(prediction_batch[:, 0] >= 0)] # Append detections to results result.append(DetectionPrediction(identifier, *zip(*detections))) return result
{"hexsha": "60d4b5d9cb66efb7bc8cff3526fa055767263c00", "size": 26829, "ext": "py", "lang": "Python", "max_stars_repo_path": "tools/accuracy_checker/accuracy_checker/adapters/detection.py", "max_stars_repo_name": "allnes/open_model_zoo", "max_stars_repo_head_hexsha": "693ba31b3b7671f5fb8ecf8f9b8d670cfec21bc3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-31T06:38:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T06:38:49.000Z", "max_issues_repo_path": "tools/accuracy_checker/accuracy_checker/adapters/detection.py", "max_issues_repo_name": "allnes/open_model_zoo", "max_issues_repo_head_hexsha": "693ba31b3b7671f5fb8ecf8f9b8d670cfec21bc3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-09-26T01:24:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T02:16:03.000Z", "max_forks_repo_path": "tools/accuracy_checker/accuracy_checker/adapters/detection.py", "max_forks_repo_name": "allnes/open_model_zoo", "max_forks_repo_head_hexsha": "693ba31b3b7671f5fb8ecf8f9b8d670cfec21bc3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-11T13:47:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T08:08:06.000Z", "avg_line_length": 41.5309597523, "max_line_length": 119, "alphanum_fraction": 0.5984196206, "include": true, "reason": "import numpy", "num_tokens": 6264}
// Copyright Gavin Band 2008 - 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef COMPONENTS_RELATEDNESS_COMPONENT_PCA_COMPUTER_HPP #define COMPONENTS_RELATEDNESS_COMPONENT_PCA_COMPUTER_HPP #include <string> #include <boost/shared_ptr.hpp> #include <boost/signals2/signal.hpp> #include <Eigen/Core> #include "genfile/SingleSNPGenotypeProbabilities.hpp" #include "genfile/CohortIndividualSource.hpp" #include "statfile/BuiltInTypeStatSource.hpp" #include "components/SampleSummaryComponent/SampleStorage.hpp" #include "appcontext/OptionProcessor.hpp" #include "appcontext/UIContext.hpp" struct PCAComputer { public: typedef std::auto_ptr< PCAComputer > UniquePtr ; typedef boost::shared_ptr< PCAComputer > SharedPtr ; typedef sample_stats::SampleStorage SampleStorage ; static void load_matrix( genfile::CohortIndividualSource const& samples, std::string const& filename, Eigen::MatrixXd* matrix, std::size_t* number_of_snps, appcontext::UIContext& ui_context ) ; static void load_long_form_matrix( genfile::CohortIndividualSource const& samples, std::string const& filename, Eigen::MatrixXd* matrix, std::size_t* number_of_snps, appcontext::UIContext& ui_context ) ; static void load_matrix_metadata( genfile::CohortIndividualSource const& samples, statfile::BuiltInTypeStatSource& source, std::size_t* number_of_samples, std::size_t* number_of_snps, appcontext::UIContext& ui_context ) ; static genfile::VariantEntry get_pca_name( std::size_t i ) ; public: virtual ~PCAComputer() throw() {} PCAComputer( appcontext::OptionProcessor const& options, genfile::CohortIndividualSource const& samples, appcontext::UIContext& ui_context ) ; void compute( Eigen::MatrixXd const& matrix, std::size_t const number_of_snps, std::string const& name ) ; void begin_processing_snps( std::size_t number_of_samples, genfile::SNPDataSource::Metadata const& ) ; void processed_snp( genfile::VariantIdentifyingData const&, genfile::VariantDataReader& ) ; void end_processing_snps() ; typedef boost::function< genfile::VariantEntry ( std::size_t ) > GetNames ; typedef boost::signals2::signal< void( std::string, std::size_t, Eigen::MatrixXd const&, GetNames, GetNames ) > UDUTSignal ; typedef UDUTSignal::slot_type UDUTCallback ; void send_UDUT_to( UDUTCallback ) ; void send_PCs_to( SampleStorage::SharedPtr ) ; void send_UDUT( std::string description, std::size_t, Eigen::MatrixXd const& UDUT, GetNames row_names, GetNames column_names ) ; void send_PCs( std::string description, Eigen::VectorXd const& eigenvalues, Eigen::MatrixXd const& PCAs, GetNames pca_row_names, GetNames pca_column_names ) ; private: appcontext::OptionProcessor const& m_options ; appcontext::UIContext& m_ui_context ; genfile::CohortIndividualSource const& m_samples ; std::string m_filename ; std::size_t m_number_of_samples ; std::size_t m_number_of_snps ; std::size_t m_number_of_snps_processed ; Eigen::MatrixXd m_kinship_matrix ; Eigen::MatrixXd m_kinship_eigendecomposition ; Eigen::VectorXd m_PC_eigenvalues ; Eigen::MatrixXd m_PC_components ; UDUTSignal m_UDUT_signal ; SampleStorage::SharedPtr m_PC_storage ; std::size_t m_number_of_PCs_to_compute ; double m_threshhold ; genfile::SingleSNPGenotypeProbabilities m_genotype_probabilities ; Eigen::VectorXd m_genotype_calls ; Eigen::VectorXd m_non_missingness ; Eigen::VectorXd m_loading_vectors ; private: void compute_PCA() ; } ; #endif
{"hexsha": "610e3270b49511fb1c1921350829cbac56e293ce", "size": 3564, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "components/RelatednessComponent/include/components/RelatednessComponent/PCAComputer.hpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "components/RelatednessComponent/include/components/RelatednessComponent/PCAComputer.hpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "components/RelatednessComponent/include/components/RelatednessComponent/PCAComputer.hpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0449438202, "max_line_length": 222, "alphanum_fraction": 0.7887205387, "num_tokens": 895}
from lltk.imports import * def newpolyfit(X,Y): newdf=pd.DataFrame({'X':X, 'Y':Y}) results = smf.ols('Y ~ X + I(X**2)', data=newdf).fit() return results.rsquared, results.f_pvalue def regressions(df,resultdf=None): word2rp={} RRs=[] Ps=[] for word in df.index: Y=list(df.loc[word]) X=list(range(len(Y))) r,p=newpolyfit(X,Y) RRs+=[r] Ps+=[p] if resultdf is None: resultdf=pd.DataFrame(index=df.index) resultdf['polyfit_r^2']=RRs resultdf['polyfit_p']=Ps return resultdf def dist(df): from scipy.spatial.distance import squareform, pdist distmatrix=pdist(df,metric='correlation') return 1-pd.DataFrame(squareform(distmatrix), columns=df.index, index=df.index) def kmeans(datadf,df_dist=None,n_kmeans=5,colname='kmeans_cluster',resultdf=None): if df_dist is None: df_dist=dist(datadf) m_dist=df_dist.values from sklearn.cluster import KMeans model_kclust = KMeans(n_clusters=n_kmeans) model_kclust.fit(m_dist) labels = model_kclust.labels_ word2label = dict(list(zip(datadf.index, labels))) if resultdf is None: resultdf=pd.DataFrame(index=datadf.index) resultdf[colname]=[word2label[word] for word in datadf.index] return resultdf def corr_with_cluster(df,colname_cluster='kmeans_cluster',resultdf=None): cluster_avg={} for clust,cluster in resultdf.groupby(by=colname_cluster): df_for_cluster = df.loc[cluster.index] cluster_avg[clust]=df_for_cluster.median(axis=0) word2clustcorr={} for word in df.index: clust=resultdf.loc[word][colname_cluster] word_avgs=list(df.loc[word]) clust_avgs=list(cluster_avg[clust]) word2clustcorr[word]=pearsonr(word_avgs,clust_avgs) if resultdf is None: resultdf=pd.DataFrame(index=df.index) resultdf['kmeans_cluster_corr_r']=[word2clustcorr[word][0] for word in df.index] resultdf['kmeans_cluster_corr_p']=[word2clustcorr[word][1] for word in df.index] return resultdf def tsne(datadf,df_dist=None,n_components=2,resultdf=None): if df_dist is None: df_dist=dist(datadf) m_dist=df_dist.values from sklearn.manifold import TSNE model = TSNE(n_components=n_components, random_state=0) fit = model.fit_transform(m_dist) from collections import defaultdict newcols=defaultdict(list) for i,word in enumerate(datadf.index): for ii,xx in enumerate(fit[i]): newcols['tsne_V'+str(ii+1)] += [xx] if resultdf is None: resultdf=pd.DataFrame(index=datadf.index) for k,v in list(newcols.items()): resultdf[k]=v return resultdf def analyze_as_dist(datadf,df_dist=None,n_kmeans=5, do_tsne=True): from .tools import now if df_dist is None: print('>> dist(datadf)',now()) df_dist=dist(datadf) print('>> kmeans(datadf)',now()) resultdf=kmeans(datadf,n_kmeans=n_kmeans) print('>> corr_with_cluster(datadf)',now()) resultdf=corr_with_cluster(datadf,resultdf=resultdf) print('>> regressions(datadf)',now()) resultdf=regressions(datadf,resultdf=resultdf) if do_tsne: print('>> tsne(datadf)',now()) resultdf=tsne(datadf,df_dist=df_dist,resultdf=resultdf) return resultdf def linreg(X, Y): from math import sqrt from numpy import nan, isnan from numpy import array, mean, std, random if len(X)<2 or len(Y)<2: return 0,0,0 """ Summary Linear regression of y = ax + b Usage real, real, real = linreg(list, list) Returns coefficients to the regression line "y=ax+b" from x[] and y[], and R^2 Value """ if len(X) != len(Y): raise ValueError#, 'unequal length' N = len(X) Sx = Sy = Sxx = Syy = Sxy = 0.0 for x, y in map(None, X, Y): Sx = Sx + x Sy = Sy + y Sxx = Sxx + x*x Syy = Syy + y*y Sxy = Sxy + x*y det = Sxx * N - Sx * Sx a, b = (Sxy * N - Sy * Sx)/det, (Sxx * Sy - Sx * Sxy)/det meanerror = residual = 0.0 for x, y in map(None, X, Y): meanerror = meanerror + (y - Sy/N)**2 residual = residual + (y - a * x - b)**2 RR = 1 - residual/meanerror if meanerror else 1 ss = residual / (N-2) if (N-2) else 0 Var_a, Var_b = ss * N / det, ss * Sxx / det #print "y=ax+b" #print "N= %d" % N #print "a= %g \\pm t_{%d;\\alpha/2} %g" % (a, N-2, sqrt(Var_a)) #print "b= %g \\pm t_{%d;\\alpha/2} %g" % (b, N-2, sqrt(Var_b)) #print "R^2= %g" % RR #print "s^2= %g" % ss return a, b, RR def reset_index(df): '''Returns DataFrame with index as columns''' index_df = df.index.to_frame(index=False) df = df.reset_index(drop=True) # In merge is important the order in which you pass the dataframes # if the index contains a Categorical. # pd.merge(df, index_df, left_index=True, right_index=True) does not work return pd.merge(index_df, df, left_index=True, right_index=True) def to_tf(dtm): dfq=dtm.select_dtypes('number') rowsums = dfq.sum(axis=1) return dfq.div(rowsums,axis=0) def to_tfidf(dtm): import numpy as np,pandas as pd dtm_tf = to_tf(dtm) # idf num_docs = len(dtm_tf) num_docs_per_word = dtm_tf[dtm_tf>0].count() idf=np.log10(num_docs / num_docs_per_word) return dtm_tf.apply(lambda x: x * idf,axis='columns') def to_mdw(dtm,groupby,agg='median'): df = dtm.groupby(groupby).agg(agg).T df=reset_index(df).rename({0:'word'},axis=1)#.set_index('word') return df.set_index('word') def to_counts(dtm,scale_by=1000000,**y): return pmap_apply_cols( rescale_col, dtm, kwargs=dict(scale_by=scale_by), **y ) def pmap_apply_cols(func, df, lim=None, **y): from yapmap import pmap cols=list(df.columns)[:lim] new_seriess = pmap( func, [df[col].values for col in cols], **y ) odf=pd.DataFrame(dict(zip(cols,new_seriess)), index=df.index) return odf def rescale_col(colvals,scale_by=1000000,as_int=True): maxval=max(colvals) minval=min(colvals) if minval>=1: return colvals if minval<0: print(f'!! Negative values in column {col}') return colvals return [ x*scale_by if not as_int else int(x*scale_by) for x in colvals ] def do_mannwhitney(obj): x,y,meta=obj from scipy.stats import mannwhitneyu,zscore try: xz=zscore(x) yz=zscore(y) mwU, pvalue = mannwhitneyu(x,y) result_dict=dict(meta.items()) result_dict['U']=mwU result_dict['pvalue']=pvalue result_dict['is_signif']=issign=pvalue<=0.05 result_dict['group1_mean']=xm=x.mean() result_dict['group2_mean']=ym=y.mean() result_dict['distinctive_of']=None if not issign else ( meta.get('group1') if xm>ym else meta.get('group2') ) return result_dict except ValueError as e: # print('!!',e,meta) return meta def to_mdw_mannwhitney(dtm,groupby,words=set(),group_names=None,progress=False,**pmap_kwargs): from yapmap import pmap_iter from scipy.stats import zscore # get words groups = dtm.groupby(groupby) if not words: for gname,gdf in groups: words = set(gdf.columns) if not words else words&set(gdf.columns) objs=[] for group1name,group1df in groups: for group2name,group2df in groups: if group1name>=group2name: continue for word in words: x=group1df[word] y=group2df[word] meta={ 'group1':group1name, 'group2':group2name, 'word':word, } objs+=[(x,y,meta)] odf = pd.DataFrame( pmap_iter( do_mannwhitney, objs, progress=progress, **pmap_kwargs ) ).sort_values('U') odf=odf.sort_values(['distinctive_of','U'],ascending=[True,False]) odf=odf.set_index(['distinctive_of','group1','group2','word']) odf['U_z']=zscore(odf['U']) return odf
{"hexsha": "9da686ffba36749208eee6345e1a9c029a79e890", "size": 7999, "ext": "py", "lang": "Python", "max_stars_repo_path": "lltk/tools/stats.py", "max_stars_repo_name": "literarylab/lltk", "max_stars_repo_head_hexsha": "0e516d7fa0978c1a3bd2cb7636f0089772e515ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-15T21:05:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T10:52:16.000Z", "max_issues_repo_path": "lltk/tools/stats.py", "max_issues_repo_name": "literarylab/lltk", "max_issues_repo_head_hexsha": "0e516d7fa0978c1a3bd2cb7636f0089772e515ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-04T17:01:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T15:14:55.000Z", "max_forks_repo_path": "lltk/tools/stats.py", "max_forks_repo_name": "literarylab/lltk", "max_forks_repo_head_hexsha": "0e516d7fa0978c1a3bd2cb7636f0089772e515ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1849056604, "max_line_length": 94, "alphanum_fraction": 0.6335791974, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 2368}
import unittest class PackagesTestCase(unittest.TestCase): def test_pygame_installation(self): try: import pygame pygame.init() pygame.display.set_mode((500, 400), 0, 32) pygame.quit() except ModuleNotFoundError: self.fail("PyGame is not installed properly!") def test_numpy_installation(self): try: import numpy as np except ModuleNotFoundError: self.fail("Numpy is not installed properly!") if __name__ == '__main__': unittest.main()
{"hexsha": "41766b2c008b581ca2b4f9c6701ceba7102bd822", "size": 569, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/environment_test.py", "max_stars_repo_name": "jfajkowski/PyCheckers", "max_stars_repo_head_hexsha": "2747ec645fe78bbaa9306987cfad0117b366dcc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/environment_test.py", "max_issues_repo_name": "jfajkowski/PyCheckers", "max_issues_repo_head_hexsha": "2747ec645fe78bbaa9306987cfad0117b366dcc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/environment_test.py", "max_forks_repo_name": "jfajkowski/PyCheckers", "max_forks_repo_head_hexsha": "2747ec645fe78bbaa9306987cfad0117b366dcc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7391304348, "max_line_length": 58, "alphanum_fraction": 0.6080843585, "include": true, "reason": "import numpy", "num_tokens": 112}
import os import timeit import numpy as np import argparse from psyneulink import * from double_dqn import DoubleDQNAgent from gym_forager.envs.forager_env import ForagerEnv parser = argparse.ArgumentParser() parser.add_argument("--seed", type=int, default=int.from_bytes(os.urandom(4), byteorder="big"), help='Random seed, seed from os.urandom if unspecified.') #args = parser.parse_args() SEED = int.from_bytes(os.urandom(4), byteorder="big") from psyneulink.core.globals.utilities import set_global_seed set_global_seed(SEED) np.random.seed(SEED+1) # ********************************************************************************************************************* # *********************************************** CONSTANTS *********************************************************** # ********************************************************************************************************************* # Runtime switches: MPI_IMPLEMENTATION = True RENDER = False PNL_COMPILE = False RUN = True SHOW_GRAPH = False MODEL_PATH = '../../../../double-dqn/models/trained_models/policy_net_trained_0.99_20190214-1651.pt' # Switch for determining actual action taken in each step OPTIMAL_ACTION = 'OPTIMAL_ACTION' AGENT_ACTION = 'AGENT_ACTION' ACTION = AGENT_ACTION # Verbosity levels for console printout ACTION_REPORTING = 2 STANDARD_REPORTING = 1 VERBOSE = 0 # ControlSignal parameters COST_RATE = -.05 # -0.05 COST_BIAS = 1 # COST_RATE = 0#-0.0015 # COST_BIAS = 0 ALLOCATION_SAMPLES = [0, 100, 200, 300, 400, 500] ALLOCATION_SAMPLES_PREY = [0, 100, 200, 300, 400, 500] # [0, 500] ALLOCATION_SAMPLES_PREDATOR = [0, 100, 200, 300, 400, 500] # [0, 500] ALLOCATION_SAMPLES_PLAYER = [0] # FEATURE_FUNCTION = Buffer(history=3) FEATURE_FUNCTION = AdaptiveIntegrator(rate=0.5) # Environment coordinates # (these should probably be replaced by reference to ForagerEnv constants) obs_len = 2 obs_coords = 2 action_len = 2 player_idx = 0 player_obs_start_idx = player_idx * obs_len player_value_idx = player_idx * obs_len + obs_coords player_coord_slice = slice(player_obs_start_idx,player_value_idx) predator_idx = 1 predator_obs_start_idx = predator_idx * obs_len predator_value_idx = predator_idx * obs_len + obs_coords predator_coord_slice = slice(predator_obs_start_idx,predator_value_idx) prey_idx = 2 prey_obs_start_idx = prey_idx * obs_len prey_value_idx = prey_idx * obs_len + obs_coords prey_coord_slice = slice(prey_obs_start_idx,prey_value_idx) player_len = prey_len = predator_len = obs_coords NUM_EPISODES = 100 # ********************************************************************************************************************** # ************************************** CREATE COMPOSITION *********************************************************** # ********************************************************************************************************************** # ************************************** DOUBLE_DQN AGENT ************************************************************** class PredatorPreySimulator: def __init__(self): self.seed = int.from_bytes(os.urandom(4), byteorder="big") from psyneulink.core.globals.utilities import set_global_seed set_global_seed(self.seed) np.random.seed(self.seed+1) # Setup a Gym Forager environment for the game self.gym_forager_env = ForagerEnv(obs_type='egocentric', incl_values=False, frameskip=2) self.gym_forager_env.seed(self.seed+2) # Setup an instance of the double DQN agent for determining optimal actions self.ddqn_agent = DoubleDQNAgent(model_load_path=MODEL_PATH, eval_mode=True, save_frames=False, render=RENDER, env=self.gym_forager_env) # Setup the PsyNeuLink composition self._setup_composition() # Helper function for getting the optimal action from the double DQN def _get_optimal_action(self, observation): # Get new state based on observation: veridical_state = self.ddqn_agent.buffer.next(np.array(observation)) optimal_action = np.array(self.ddqn_agent._io_map(self.ddqn_agent._select_action(veridical_state).item())) if VERBOSE >= ACTION_REPORTING: print(f'\n\nOPTIMAL OBSERVATION: {observation}' f'\nVERIDICAL STATE: {veridical_state.reshape(12, )}' f'\nOPTIMAL ACTION: {optimal_action}') return optimal_action def _setup_composition(self): def get_new_episode_flag(): return self.new_episode_flag # Condition for executing controller, execute on a new episode. self.new_episode_flag = True self.CONTROLLER_CONDITION = Condition(func=get_new_episode_flag) # tells schedule when to run OCM # ************************************** PROCESSING MECHANISMS ******************************************************** # Perceptual Mechanisms self.player_percept = ProcessingMechanism(size=prey_len, function=GaussianDistort(), name="PLAYER PERCEPT") self.predator_percept = ProcessingMechanism(size=predator_len, function=GaussianDistort(), name="PREDATOR PERCEPT") self.prey_percept = ProcessingMechanism(size=prey_len, function=GaussianDistort(), name="PREY PERCEPT") # Mechanism used to encode trialtype from environment self.prey_pred_trial_input_mech = ProcessingMechanism(name="PREY PREDATOR TRIAL") self.single_prey_trial_input_mech = ProcessingMechanism(name="SINGLE PREY TRIAL") self.double_prey_trial_input_mech = ProcessingMechanism(name="DOUBLE PREY TRIAL") # Mechanism used to encode a reward from environment self.reward_input_mech = ProcessingMechanism(name="REWARD INPUT") # Function used by action_mech to generate action from trained DQN def get_action(variable=[[0, 0], [0, 0], [0, 0]]): # Convert variable to observation: observation = variable.reshape(6, ) # Get new state # - first cache initial state of buffer buffer_cache = self.ddqn_agent.buffer.buffer.copy() # - then get new state based on current observation perceptual_state = self.ddqn_agent.buffer.next(observation) # - finally, restore frame buffer to initial state for use by next simulation or actual action self.ddqn_agent.buffer.buffer = buffer_cache # Get and return action action = np.array(self.ddqn_agent._io_map(self.ddqn_agent._select_action(perceptual_state).item())) if VERBOSE >= ACTION_REPORTING: print(f'\n\nACTUAL OBSERVATION: {observation}' f'\nACTUAL PERCEPTUAL STATE: {perceptual_state.reshape(12, )}' f'\nACTUAL ACTION FROM FUNCTION: {action}') return action # Action Mechanism # Use ddqn's eval function to compute action for a given observation # note: unitization is done in main loop, to allow compilation of LinearCombination function in ObjectiveMech) (TBI) self.action_mech = ProcessingMechanism(default_variable=[[0,0],[0,0],[0,0]], function=get_action, name='ACTION', output_ports='agent action') # ************************************** BASIC COMPOSITION ************************************************************* self.agent_comp = Composition(name='PREDATOR-PREY COMPOSITION') self.agent_comp.add_nodes([self.player_percept, self.predator_percept, self.prey_percept, self.prey_pred_trial_input_mech, self.single_prey_trial_input_mech, self.double_prey_trial_input_mech, self.reward_input_mech]) self.agent_comp.add_node(self.action_mech, required_roles=[NodeRole.OUTPUT]) a = MappingProjection(sender=self.player_percept, receiver=self.action_mech.input_ports[0]) b = MappingProjection(sender=self.predator_percept, receiver=self.action_mech.input_ports[1]) c = MappingProjection(sender=self.prey_percept, receiver=self.action_mech.input_ports[2]) self.agent_comp.add_projections([a,b,c]) # ************************************** CONOTROL APPARATUS *********************************************************** self.ocm = OptimizationControlMechanism(name='EVC', state_features=[self.prey_pred_trial_input_mech, self.single_prey_trial_input_mech, self.double_prey_trial_input_mech], # state_feature_functions=FEATURE_FUNCTION, agent_rep=RegressionCFA( update_weights=BayesGLM(mu_0=-0.0, sigma_0=0.0001), prediction_terms=[PV.F, PV.C, PV.COST] ), function=GridSearch(direction=MAXIMIZE, save_values=True), objective_mechanism=ObjectiveMechanism(name='OBJECTIVE MECHANISM', monitor=[self.reward_input_mech]), control_signals=[ControlSignal(projections=(VARIANCE,self.player_percept), allocation_samples=ALLOCATION_SAMPLES_PLAYER, intensity_cost_function=Exponential(rate=COST_RATE, bias=COST_BIAS)), ControlSignal(projections=(VARIANCE,self.predator_percept), allocation_samples=ALLOCATION_SAMPLES_PREDATOR, intensity_cost_function=Exponential(rate=COST_RATE, bias=COST_BIAS)), ControlSignal(projections=(VARIANCE,self.prey_percept), allocation_samples=ALLOCATION_SAMPLES_PREY, intensity_cost_function=Exponential(rate=COST_RATE, bias=COST_BIAS))]) # Add controller to Composition # agent_comp.add_node(ocm) self.agent_comp.add_controller(self.ocm) self.agent_comp.enable_controller = True self.agent_comp.controller_mode = BEFORE self.agent_comp.controller_condition=self.CONTROLLER_CONDITION # can also specify this condition on the node if the ocm is added as a node # agent_comp,scheduler_processing.add_condition((com, CONTROLLER_CONDITION)) if SHOW_GRAPH: self.agent_comp.show_graph(show_controller=True, show_cim=True) # Wrap the entire composition inside another composition so we can perform # parameter optimization. self.opt_comp = Composition(name='outer_opt_comp') self.opt_comp.add_node(self.agent_comp) def make_input_generator(self, num_episodes=100): self.outcome_log = [] self.reward_log = [] self.predator_control_log = [] self.prey_control_log = [] # The context/execution id to use for all the runs self.context = Context() # Helper function to print controller details def print_controller(): print(f'\nOCM:' f'\n\tControlSignals:' f'\n\t\tPlayer:\t\t{self.ocm.control_signals[0].parameters.value.get(self.context)}' f'\n\t\tPredator\t{self.ocm.control_signals[1].parameters.value.get(self.context)}' f'\n\t\tPrey:\t\t{self.ocm.control_signals[2].parameters.value.get(self.context)}' f'\n\n\tControlSignal Costs:' f'\n\t\tPlayer:\t\t{self.ocm.control_signals[0].parameters.cost.get(self.context)}' f'\n\t\tPredator:\t{self.ocm.control_signals[1].parameters.cost.get(self.context)}' f'\n\t\tPrey:\t\t{self.ocm.control_signals[2].parameters.cost.get(self.context)}') # The input generator function def input_generator(): if RENDER: self.ddqn_agent.env.render() # If visualization is desired else: print('\nRunning simulation... ') reward = 0 steps = 0 start_time = timeit.default_timer() for episode_i in range(num_episodes): trialType = 2 prey_pred_trialType = 0 single_prey_trialType = 0 double_prey_trialType = 0 print(f'EPISODE {episode_i}') self.ddqn_agent.env.trialType = trialType # 0 is single prey, 1 is two prey, 2 is prey & predator # Start a new episode by resetting the enviroment observation = self.ddqn_agent.env.reset() # Set the new episode flag, controller condition depends on this. self.new_episode_flag = True while True: if VERBOSE >= STANDARD_REPORTING: print(f'\nEPISODE {episode_i}, STEP: {steps} ************************************************') # Cache frame buffer trial_start_buffer = self.ddqn_agent.buffer.buffer.copy() # Get optimal action based on observation optimal_action = self._get_optimal_action(observation) # Save frame buffer after optimal action optimal_agent_frame_buffer = self.ddqn_agent.buffer.buffer # Restore initial state of frame buffer (for use by Composition) self.ddqn_agent.buffer.buffer = trial_start_buffer if VERBOSE >= ACTION_REPORTING: print(f'\nOUTER LOOP OPTIMAL ACTION:{optimal_action}') # Yield the next input the agent composition. Since this generator is # passed to the outert optimization composition, it must generate # an input dictionary keyed by the inner agent composition node. yield { self.agent_comp: { self.player_percept:[observation[player_coord_slice]], self.predator_percept:[observation[predator_coord_slice]], self.prey_percept:[observation[prey_coord_slice]], self.prey_pred_trial_input_mech:[prey_pred_trialType], self.single_prey_trial_input_mech: [single_prey_trialType], self.double_prey_trial_input_mech: [double_prey_trialType], self.reward_input_mech: [reward] } } # Get agent's action based on perceptual distortion of observation (and application of control) run_results = self.opt_comp.results[-1] agent_action = np.where(run_results[0]==0,0,run_results[0]/np.abs(run_results[0])) if VERBOSE >= ACTION_REPORTING: print(f'OUTER LOOP RUN RESULTS:{run_results}') print(f'OUTER LOOP AGENT ACTION:{agent_action}') if VERBOSE >= STANDARD_REPORTING: if self.agent_comp.controller_mode is BEFORE: print_controller() print(f'\nObservations:' f'\n\tPlayer:\n\t\tveridical: {self.player_percept.parameters.variable.get(self.context)}' f'\n\t\tperceived: {self.player_percept.parameters.value.get(self.context)}' f'\n\tPredator:\n\t\tveridical: {self.predator_percept.parameters.variable.get(self.context)}' f'\n\t\tperceived: {self.predator_percept.parameters.value.get(self.context)}' f'\n\tPrey:\n\t\tveridical: {self.prey_percept.parameters.variable.get(self.context)}' f'\n\t\tperceived: {self.prey_percept.parameters.value.get(self.context)}' f'\n\nActions:\n\tAgent: {agent_action}\n\tOptimal: {optimal_action}' f'\n\nOutcome:\n\t{self.ocm.objective_mechanism.parameters.value.get(self.context)}' ) if self.agent_comp.controller_mode is AFTER: print_controller() self.outcome_log.append(self.ocm.objective_mechanism.parameters.value.get(self.context)) # Restore frame buffer to state after optimal action taken (at beginning of trial) # This is so that agent's action's can be compared to optimal ones on a trial-by-trial basis self.ddqn_agent.buffer.buffer = optimal_agent_frame_buffer # if ACTION is OPTIMAL_ACTION: # action = optimal_action # elif ACTION is AGENT_ACTION: # action = agent_action # else: # assert False, "Must choose either OPTIMAL_ACTION or AGENT_ACTION" action = agent_action # Get observation for next iteration based on optimal action taken in this one observation, reward, done, _ = self.ddqn_agent.env.step(action) if VERBOSE >= STANDARD_REPORTING: print(f'\nAction Taken (using {ACTION}): {action}') self.new_episode_flag = False steps += 1 if done: break self.predator_control_log.append(self.ocm.control_signals[1].parameters.value.get(self.context)) self.prey_control_log.append(self.ocm.control_signals[2].parameters.value.get(self.context)) self.reward_log.append(reward) stop_time = timeit.default_timer() print(f'{steps / (stop_time - start_time):.1f} steps/second, {steps} total steps in ' f'{stop_time - start_time:.2f} seconds') outcome_mean = np.mean(np.asarray(self.outcome_log)) reward_mean = np.mean(np.asarray(self.reward_log)) print(f'\nTotal Outcome: {outcome_mean}') print(f'\nTotal Reward: {reward_mean}') print('predator control log') print(self.predator_control_log) print('prey control log') print(self.prey_control_log) predator_control_mean = np.mean(np.asarray(self.predator_control_log)) print(f'\npredator control MEAN: {predator_control_mean}') prey_control_mean = np.mean(np.asarray(self.prey_control_log)) print(f'\nprey control MEAN: {prey_control_mean}') if RENDER: self.ddqn_agent.env.render(close=True) # If visualization is desired # Return the generator instantiation function. return input_generator def run_games(self, cost_rate): # Setup data generator. input_gen = self.make_input_generator(NUM_EPISODES) self.ocm.control_signals[0].parameters.intensity_cost_function.get(self.context).parameters.rate.set(cost_rate, self.context) self.ocm.control_signals[0].parameters.intensity_cost_function.get(self.context).parameters.rate.set(cost_rate, self.context) self.ocm.control_signals[0].parameters.intensity_cost_function.get(self.context).parameters.rate.set(cost_rate, self.context) # Run num_episodes games to completion. self.opt_comp.run(inputs=input_gen, bin_execute='LLVM' if PNL_COMPILE else 'Python', context=self.context) loss = np.abs(np.mean(np.asarray(self.predator_control_log[-20:])) - 500) + np.mean(np.asarray(self.prey_control_log[-20:])) print(f"Loss = {loss}") return loss def run_games(cost_rate): return PredatorPreySimulator().run_games(cost_rate) def run_search(): from dask.distributed import Client, LocalCluster import joblib import hypertunity as ht #client = Client(scheduler_file='scheduler.json') client = Client() print(client) domain = ht.Domain({ "cost_rate": set([-.8]) }) # with joblib.parallel_backend('dask'): # with joblib.Parallel() as parallel: # print("Doing the work ... ") # results = parallel(joblib.delayed(run_games)(*domain.sample().as_namedtuple()) for s in range(1)) # # print(results) run_games(-.8) if __name__ == "__main__": run_search()
{"hexsha": "0eb89fb2ed7109fa04aeb17f2e138fc497fa7bc6", "size": 21477, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scripts/Debug/predator_prey_opt/predator_prey_dmt.py", "max_stars_repo_name": "MetaCell/PsyNeuLink", "max_stars_repo_head_hexsha": "aeddf3e8ea62504a5d928b100b59aa18e593156c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 67, "max_stars_repo_stars_event_min_datetime": "2018-01-05T22:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T11:27:31.000Z", "max_issues_repo_path": "Scripts/Debug/predator_prey_opt/predator_prey_dmt.py", "max_issues_repo_name": "MetaCell/PsyNeuLink", "max_issues_repo_head_hexsha": "aeddf3e8ea62504a5d928b100b59aa18e593156c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1064, "max_issues_repo_issues_event_min_datetime": "2017-12-01T18:58:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:22:24.000Z", "max_forks_repo_path": "Scripts/Debug/predator_prey_opt/predator_prey_dmt.py", "max_forks_repo_name": "MetaCell/PsyNeuLink", "max_forks_repo_head_hexsha": "aeddf3e8ea62504a5d928b100b59aa18e593156c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2017-12-01T20:27:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T21:49:39.000Z", "avg_line_length": 49.0342465753, "max_line_length": 167, "alphanum_fraction": 0.5721003865, "include": true, "reason": "import numpy", "num_tokens": 4178}
# -*- coding: utf-8 -*- """ Module to implement acoustic shadowing along with spherical spreading of sound Created on Mon Jun 17 16:08:50 2019 @author: tbeleyur """ import time import sys sys.path.append('..//bridson//') sys.path.append('..//') import numpy as np import pandas as pd import scipy.spatial as spatial import statsmodels.api as sm def soundprop_w_acoustic_shadowing(start_point, end_point, all_other_points, **kwargs): '''Calculate the received level of a sound emitter at the start point and reaching the end point after potentially passing through other points on the way. Each point sound passes through creates a drop in the intensity because of acoustic shadowing. Parameters ---------- start_point : 1 x 2 array like end_point : 1 x 2 array like all_other_points : Nbats-2 x 2 array like xy coordinates of all points between start and end point in a rectangular area of given width Keyword Arguments ---------------- implement_shadowing : Boolean. If True then shadowing calculations are done, else only simple spherical spreading. R : float. straight line distance between soure and receiver rectangle_width : float >0. width of the rectangle emitted_source_level : dictionary with key 'dBSPL' and 'ref_distance' , indicating source level in dB SPL re 20muPa and reference distance in metres. R : float >0. straight line distance between source and receiver. This is used in case there are no obstacles between them. acoustic_shadowing_model : statsmodel object that allows calculation of how much shadowing will be observed. min_spacing : float> 0. Returns ------- received_level : float. received level of the sound ''' if kwargs.get('implement_shadowing'): all_points_between = get_points_in_between(start_point, end_point, all_other_points, **kwargs) received_level = calc_RL(kwargs['R'],kwargs['emitted_source_level']['dBSPL'], kwargs['emitted_source_level']['ref_distance']) num_obstacles = all_points_between.shape[0] if num_obstacles >= 1: acoustic_shadowing = calculate_acoustic_shadowing(num_obstacles, **kwargs) received_level += acoustic_shadowing else: received_level = calc_RL(kwargs['R'],kwargs['emitted_source_level']['dBSPL'], kwargs['emitted_source_level']['ref_distance']) return(received_level) def get_distances_between_points(xy_between, start, end): ''' ''' all_xy = np.row_stack((start, xy_between, end)) distance_matrix = spatial.distance_matrix(all_xy, all_xy) distance_to_source = np.argsort(distance_matrix[:,0]) points_sorted = all_xy[distance_to_source,:] distances_sorted = spatial.distance_matrix(points_sorted, points_sorted) num_distances = all_xy.shape[0] - 1 point_2_point_distances = np.zeros(num_distances) for i, (point0, point1) in enumerate(zip(range(all_xy.shape[0]-1), range(1,all_xy.shape[0]))): point_2_point_distances[i] = distances_sorted[point0, point1] return(point_2_point_distances) def calculate_acoustic_shadowing(num_obstacles, **kwargs): '''Calculates received level of a call with acoustic shadowing included. The received level of the call with shadowing is calculated with an iterative application of the bistatic sonar equation. The TS used here is the bistatic target strength at emitter-receiver angular separations of 180 degrees. Parameters ---------- num_obstacles : int >1 . Number of obstacles between receiver and emitter. Keyword Arguments ----------------- acoustic_shadowing_model : statsmodel object A statistical model that allows calculation of the amount of acoustic shadowing in dB. For predictions the model accepts a pd.DataFrame which has the following columns (this might depend on the exact model loaded too!) obstacles spacing min_spacing : float>0. Separation between bats/obstacles see the_cocktail_party_nightmare Returns ------- shadowing_reduction : float. Reduction of received level due to shadowing in dB. ''' no_obstacle = pd.DataFrame(data={'obstacles':[0], 'spacing':[kwargs['min_spacing']], }) with_obstacles = pd.DataFrame(data={'obstacles':[num_obstacles], 'spacing':[kwargs['min_spacing']], }) #convert_to_categorical(no_obstacle, 'spacing') #convert_to_categorical(with_obstacles, 'spacing') level_w_obstacles = kwargs['acoustic_shadowing_model'].predict(with_obstacles) level_wo_obstacles = kwargs['acoustic_shadowing_model'].predict(no_obstacle) shadowing_reduction = float(level_w_obstacles - level_wo_obstacles) return(shadowing_reduction) def convert_to_categorical(df, column): ''' ''' df[column] = pd.Categorical(df[column]) return(df) def calc_RL(distance, SL, ref_dist, **kwargs): '''calculates received level only because of spherical spreading. Parameters ----------- distance : float>0. receiver distance from source in metres. SL : float. source level in dB SPL re 20 muPa at the reference distance. ref_dist : float >0. distance at which source level was measured in metres. Typically 1metre by convention. Keyword Arguments ----------------- atmospheric_attenuation : float <= 0. Atmospheric attenuation in dB/m. This has to be negative number. Defaults to no atmospheric attenuations (0 dB/m ) Returns ------- RL : received level in dB SPL re 20muPa. ''' RL = SL - 20*np.log10(float(distance/ref_dist)) RL += kwargs.get('atmospheric_attenuation', 0)*distance return(RL) def get_points_in_between(start_point, end_point, all_other_points, **kwargs): ''' Parameters ---------- start_point : 1x2 array like xy coordinates of starting point end_point : 1x2 array like xy coordinates of end points all_other_points : N x 2 array like xy coordinates of all other points Keyword Arguments ----------------- rectangle_width : float >0. The width of the rectangle between the start and end point. Returns ------- points_between : Mpoints_between x 2 np.array where Mpoints can be >= 0. ''' rectangle_limits, rotation_matrix = make_rectangle_between_2_points(start_point, end_point,**kwargs) points_between = get_points_in_rectangle(rectangle_limits, start_point, all_other_points, rotation_matrix) return(points_between) def get_points_in_between_thecircleversion(start_point, end_point, all_other_points,**kwargs): '''Take 2 at getting perhaps a faster version of the previous get_points_in_between function. It is fast *and* dirty ... and doesn't quite apply when many bats are packed tightly together ... as long as the 'rectangle_width' is decently large -- then it should be okay.. ''' # get line equation from A to B diff_x_y = end_point-start_point vertical, m = calculate_slope(diff_x_y) numpoints = 100 # choose a default density for now points_along_line = np.zeros((numpoints, 2)) if not vertical: points_along_line[:,0] = np.linspace(start_point[0],end_point[0], numpoints) # x coordinates c = solve_for_intercept(start_point,end_point,m) points_along_line[:,1] = m*points_along_line[:,0] + c # y coordinates else: points_along_line[:,0] = start_point[0] # x coordinates points_along_line[:,1] = np.linspace(start_point[1], end_point[1], numpoints)# y coordinates # get the distance from each of the points to all other points distance_from_line = spatial.distance_matrix(points_along_line, all_other_points) within_r_dist_from_line = distance_from_line<= kwargs['rectangle_width'] point_ids = np.argwhere(np.any(within_r_dist_from_line, axis=0)) return(all_other_points[point_ids]) def calculate_slope(deltax_deltay): ''' Parameters ---------- deltax_deltay : 1 x array-like. [X2-X2, Y2-Y1 ] Returns ------- vertical : boolean. True if the line is vertically oriented (deltaX==0) slope : float. ''' zeros_present = tuple((deltax_deltay == 0).tolist()) if sum(zeros_present)>0: return(slope_dict[zeros_present]) else: return(False, deltax_deltay[1]/float(deltax_deltay[0])) slope_dict = {(True,False) : (True, np.nan) ,# xchanges y doesnt (False, True): (False, 0.0), #y doesnt, x changes (True, True): Exception('Zero slopes for both not possible!!')} def solve_for_intercept(x1y1, x2y2,m): ''' ''' x1,y1 = x1y1 x2,y2 = x2y2 c = (y1 + y2 - m*x1 - m*x2)/2.0 return(c) def make_rectangle_between_2_points(A, B, **kwargs): '''First calculate the relative coordinates of B wref to A. Then draw a straight line between 0,0 and B_rel and 'undo' the slope. To this vertical line not apply rectangular bands on left and right. Output bottom left and top right vertices along with the rotation matrix along with the rotation matrix used to undo the slope of the 0,0-B_rel line for application to other poitns. Parameters ---------- A, B : 1x2 array like. xy coordinates of start(A) and end(B) points Keyword Arguments ----------------- rectangle_width : float>0. The width of the rectangle between A and B. Returns ------- corner_limits : tuple. Consisting of x0,x1,y0,y1 ''' # treat A as origin, calculate slope between B and A B_rel = B-A # 'un-rotate' B and thus form a vertical rectangle easily theta = np.arctan2(B_rel[1], B_rel[0]) #theta_tobe_rotated = np.remainder(theta, np.pi/2) theta_tobe_rotated = np.pi/2.0 - theta rotation_matrix = rot_mat(theta_tobe_rotated) B_rotated = np.dot(rotation_matrix, B_rel) x0, x1 = -kwargs['rectangle_width']*0.5, kwargs['rectangle_width']*0.5 y0, y1 = 0, B_rotated[1] return([x0,x1,y0,y1], rotation_matrix) def get_points_in_rectangle(corner_limits, startpt, many_points, rotn_matrix): ''' Many points are checked if they are within the rectangle defined by the bottom left point (x0,y0) and the top right corner (x1,y1). Corner limits is a tuple with four entries (x0,x1,y0,y1) x0,x1 the x coordinates defining the width of the rectangle y0,y1 the y coordinates defininf the height of the rectanlge rotn_matrix is the rotation matrix to rotate the many points into the same frame of reference as the rectangle. it is in the form of a 2 x 2 array with the form described [here](https://en.wikipedia.org/wiki/Rotation_matrix) ''' x0,x1,y0,y1 = corner_limits relative_posns = many_points - startpt rotated_pts = np.apply_along_axis(dot_product_for_rows, 1, relative_posns, rotn_matrix) within_x = np.logical_and(rotated_pts[:,0] >= np.min([x0,x1]), rotated_pts[:,0] <= np.max([x1,x0])) within_y = np.logical_and(rotated_pts[:,1] >= np.min([y0,y1]), rotated_pts[:,1] <= np.max([y0,y1])) within_pts = np.logical_and(within_x, within_y) return(many_points[within_pts]) def dot_product_for_rows(xy_row, rotation_matrix): return(np.dot(rotation_matrix, xy_row)) def dot_product_w_sum(xy_row, rotation_matrix): return(np.sum(rotation_matrix*xy_row, 1)) def rot_mat(theta): rotation_matrix = np.float32(np.row_stack(([np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]))) return(rotation_matrix) if __name__ == '__main__': # kwargs = {'rectangle_width':0.1, 'implement_shadowing':True, # 'emitted_source_level': {'dBSPL':90, 'ref_distance':1.0}} # kwargs['shadow_TS'] = [-15] # np.random.seed(82319) # #otherpts = np.random.normal(0,5,2000).reshape(-1,2) # # #otherpts = np.array(([1,0],[1,0.05])) # #print(get_points_in_between(np.array([2,0]), np.array([0,0]), otherpts, **kwargs ) ) # start = time.time() # numpoints = [5,90, 100, 1000, 2000, 4000, 8000, 10000, 100000] # for num_points in numpoints: # y_coods = np.random.choice(np.arange(0.1, 5, 0.01),num_points) # x_coods = np.tile(0.05,num_points) # # between_points = np.column_stack((x_coods, y_coods)) # q=get_points_in_between(np.array([0,0]), np.array([0,10]), between_points, # **kwargs) # print(time.time()-start) kwargs = {} kwargs['bats_xy'] = np.array(([0,0], [1,0], [2,0])) kwargs['focal_bat'] = np.array([0,0]) kwargs['R'] = 2.0 kwargs['implement_shadowing'] = False kwargs['rectangle_width'] = 0.3 kwargs['acoustic_shadowing_model'] = sm.load('../data/acoustic_shadowing_model.pkl') kwargs['min_spacing'] = 1.0 kwargs['emitted_source_level'] = {'dBSPL':90, 'ref_distance':1.0} A = soundprop_w_acoustic_shadowing( kwargs['focal_bat'], kwargs['bats_xy'][-1,:], kwargs['bats_xy'], **kwargs) print(A)
{"hexsha": "bde9076396af94c726fc4471c10686e14a136a25", "size": 15041, "ext": "py", "lang": "Python", "max_stars_repo_path": "acoustics/detailed_sound_propagation.py", "max_stars_repo_name": "thejasvibr/the_cocktail_party_nightmare", "max_stars_repo_head_hexsha": "385bd4c6d1b8bfc7079b3ba68a0fc3ce79cec3f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-15T14:08:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T09:00:25.000Z", "max_issues_repo_path": "acoustics/detailed_sound_propagation.py", "max_issues_repo_name": "thejasvibr/the_cocktail_party_nightmare", "max_issues_repo_head_hexsha": "385bd4c6d1b8bfc7079b3ba68a0fc3ce79cec3f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "acoustics/detailed_sound_propagation.py", "max_forks_repo_name": "thejasvibr/the_cocktail_party_nightmare", "max_forks_repo_head_hexsha": "385bd4c6d1b8bfc7079b3ba68a0fc3ce79cec3f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8979118329, "max_line_length": 119, "alphanum_fraction": 0.593178645, "include": true, "reason": "import numpy,import scipy,import statsmodels", "num_tokens": 3429}
c********************************************************* c c Test program for subroutine ABLE77V2 c c********************************************************* c INCLUDE 'VICMAIN_FOR' SUBROUTINE MAIN44 c INTEGER IND, ARR(50), UNIT, NUM(3) DATA NUM /39,6,22/ CHARACTER*132 MSG c CALL XVUNIT(UNIT,'INP',1,ISTAT,' ') CALL XVOPEN(UNIT,ISTAT,' ') IF(ISTAT.NE.1)THEN CALL XVMESSAGE(' CANT OPEN INPUT',' ') CALL ABEND ENDIF c CALL XVMESSAGE('*****************FORTRAN CALLABLE*********',' ') c DO I = 1, 3 WRITE (MSG,9900) NUM(I) 9900 FORMAT (' ABLE77 TEST RUN--SIZE=',I4,'.') CALL XVMESSAGE(MSG(2:28),' ') ARR(1) = NUM(I) CALL ABLE77V2(IND,UNIT,ARR) CALL PRNT(4,1,ARR(1),' label type=.') CALL PRNT(4,1,ARR(2),' FDS COUNT=.') CALL PRNT(7,1,ARR(3),' EXPOSURE=.') CALL PRNT(4,1,ARR(4),' FILTER POSITION=.') CALL PRNT(4,1,ARR(5),' SCAN RATE=.') CALL PRNT(4,1,ARR(6),' CAMERA SERIAL NUMBER=.') c IF (NUM(I).EQ.6) THEN CALL XVMESSAGE('6 VALUES RETURNED, ................',' ') GO TO 100 ENDIF CALL PRNT(4,1,ARR(7),' CAMERA =.') CALL PRNT(4,1,ARR(8),' GAIN = .') CALL PRNT(4,1,ARR(10),' EVENT YEAR =.') CALL PRNT(4,1,ARR(11),' EVENT DAY = .') CALL PRNT(4,1,ARR(12),' EVENT HOUR =.') CALL PRNT(4,1,ARR(13),' EVENT MINUTE =.') CALL PRNT(4,1,ARR(14),' EVENT SECOND =.') CALL PRNT(4,1,ARR(19),' S/C ID =.') CALL PRNT(99,10,ARR(20),'PICNO =.') c IF (NUM(I).EQ.22) THEN CALL XVMESSAGE(' 22 VALUES RETURNED, ................',' ') GO TO 100 ENDIF CALL PRNT(99,6,ARR(29),'INPUT TAPE =.') CALL PRNT(99,6,ARR(31),'OUTPUT TAPE =.') CALL PRNT(4,1,ARR(33),'INPUT FILE =.') CALL PRNT(4,1,ARR(34),'OUTPUT FILE =.') CALL PRNT(4,1,ARR(35),'ERT YEAR =.') CALL PRNT(4,1,ARR(36),'ERT DAY = .') CALL PRNT(4,1,ARR(37),'ERT HOUR =.') CALL PRNT(4,1,ARR(38),'ERT MINUTE =.') CALL PRNT(4,1,ARR(39),'ERT SECOND =.') 100 CALL PRNT(4,1,IND,'IND =.') END DO C CALL XVMESSAGE('*****************C CALLABLE***************',' ') c DO I = 1, 3 WRITE (MSG,9990) NUM(I) 9990 FORMAT (' ABLE77 TEST RUN--SIZE=',I4,'.') CALL XVMESSAGE(MSG(2:28),' ') ARR(1) = NUM(I) CALL TZABLE77V2(IND,UNIT,ARR) CALL PRNT(4,1,ARR(1),' label type=.') CALL PRNT(4,1,ARR(2),' FDS COUNT=.') CALL PRNT(7,1,ARR(3),' EXPOSURE=.') CALL PRNT(4,1,ARR(4),' FILTER POSITION=.') CALL PRNT(4,1,ARR(5),' SCAN RATE=.') CALL PRNT(4,1,ARR(6),' CAMERA SERIAL NUMBER=.') c IF (NUM(I).EQ.6) THEN CALL XVMESSAGE('6 VALUES RETURNED, ................',' ') GO TO 200 ENDIF CALL PRNT(4,1,ARR(7),' CAMERA =.') CALL PRNT(4,1,ARR(8),' GAIN = .') CALL PRNT(4,1,ARR(10),' EVENT YEAR =.') CALL PRNT(4,1,ARR(11),' EVENT DAY = .') CALL PRNT(4,1,ARR(12),' EVENT HOUR =.') CALL PRNT(4,1,ARR(13),' EVENT MINUTE =.') CALL PRNT(4,1,ARR(14),' EVENT SECOND =.') CALL PRNT(4,1,ARR(19),' S/C ID =.') CALL PRNT(99,10,ARR(20),'PICNO =.') c IF (NUM(I).EQ.22) THEN CALL XVMESSAGE(' 22 VALUES RETURNED, ................',' ') GO TO 200 ENDIF CALL PRNT(99,6,ARR(29),'INPUT TAPE =.') CALL PRNT(99,6,ARR(31),'OUTPUT TAPE =.') CALL PRNT(4,1,ARR(33),'INPUT FILE =.') CALL PRNT(4,1,ARR(34),'OUTPUT FILE =.') CALL PRNT(4,1,ARR(35),'ERT YEAR =.') CALL PRNT(4,1,ARR(36),'ERT DAY = .') CALL PRNT(4,1,ARR(37),'ERT HOUR =.') CALL PRNT(4,1,ARR(38),'ERT MINUTE =.') CALL PRNT(4,1,ARR(39),'ERT SECOND =.') 200 CALL PRNT(4,1,IND,'IND =.') END DO C RETURN END
{"hexsha": "ebc7015d3884beb580ad726ad0b93dcc035fba12", "size": 4068, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "vos/p2/sub/able77v2/test/table77v2.f", "max_stars_repo_name": "NASA-AMMOS/VICAR", "max_stars_repo_head_hexsha": "4504c1f558855d9c6eaef89f4460217aa4909f8e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2020-10-21T05:56:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:02:01.000Z", "max_issues_repo_path": "vos/p2/sub/able77v2/test/table77v2.f", "max_issues_repo_name": "NASA-AMMOS/VICAR", "max_issues_repo_head_hexsha": "4504c1f558855d9c6eaef89f4460217aa4909f8e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vos/p2/sub/able77v2/test/table77v2.f", "max_forks_repo_name": "NASA-AMMOS/VICAR", "max_forks_repo_head_hexsha": "4504c1f558855d9c6eaef89f4460217aa4909f8e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-09T01:51:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T00:23:24.000Z", "avg_line_length": 36.0, "max_line_length": 71, "alphanum_fraction": 0.4621435595, "num_tokens": 1345}
# hack until we figure out how to detect automatically if Sys.iswindows() const libniscope = "C:/Program Files/IVI Foundation/IVI/Bin/niScope_64" const libnidmm = "C:/Program Files/IVI Foundation/IVI/Bin/nidmm_64" const libnifgen = "C:/Program Files/IVI Foundation/IVI/Bin/niFgen_64" const libnihsdio = "C:/Program Files/IVI Foundation/IVI/Bin/niHSDIO_64" const libvisa = "C:/Windows/System32/visa64" elseif Sys.islinux() @error "Please add the lib paths manually and rebuild the package!" const libniscope = "" const libnidmm = "" const libnifgen = "" const libnihsdio = "" const libvisa = "" elseif Sys.isapple() @error "Please add the lib paths manually and rebuild the package!" const libniscope = "" const libnidmm = "" const libnifgen = "" const libnihsdio = "" const libvisa = "" elseif Sys.isunix() @error "Please add the lib paths manually and rebuild the package!" const libniscope = "" const libnidmm = "" const libnifgen = "" const libnihsdio = "" const libvisa = "" end
{"hexsha": "9986d2e8160a14448022667c8573731b0f086fd8", "size": 1012, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/lib_locations.jl", "max_stars_repo_name": "iuliancioarca/GenericInstruments.jl", "max_stars_repo_head_hexsha": "93d411d026b8fad36c46a8e99206b2d788176f8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-02-09T21:43:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T22:16:47.000Z", "max_issues_repo_path": "src/lib_locations.jl", "max_issues_repo_name": "iuliancioarca/GenericInstruments.jl", "max_issues_repo_head_hexsha": "93d411d026b8fad36c46a8e99206b2d788176f8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib_locations.jl", "max_forks_repo_name": "iuliancioarca/GenericInstruments.jl", "max_forks_repo_head_hexsha": "93d411d026b8fad36c46a8e99206b2d788176f8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-13T09:53:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T15:29:01.000Z", "avg_line_length": 33.7333333333, "max_line_length": 72, "alphanum_fraction": 0.7213438735, "num_tokens": 293}
#!/usr/bin/python import csv import time import json import talib import requests import numpy as np import pandas as pd from datetime import datetime, date, timedelta, timezone from backtesting import Backtest from backtesting import Strategy from backtesting.lib import crossover from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, f1_score from sklearn.metrics import confusion_matrix from sklearn.model_selection import cross_val_score, StratifiedKFold headers = {'Content-Type': 'application/json'} api_url_base = 'https://public.bitbank.cc' pair = 'btc_jpy' period = '1min' today = datetime.today() yesterday = today - timedelta(days=1) today = "{0:%Y%m%d}".format(today) yesterday = "{0:%Y%m%d}".format(yesterday) def api_ohlcv(timestamp): api_url = '{0}/{1}/candlestick/{2}/{3}'.format(api_url_base, pair, period, timestamp) response = requests.get(api_url, headers=headers) if response.status_code == 200: ohlcv = json.loads(response.content.decode('utf-8'))['data']['candlestick'][0]['ohlcv'] return ohlcv else: return None def main(): ohlcv = api_ohlcv('20190901') open, high, low, close, volume, timestamp = [],[],[],[],[],[] for i in ohlcv: open.append(int(i[0])) high.append(int(i[1])) low.append(int(i[2])) close.append(int(i[3])) volume.append(float(i[4])) time_str = str(i[5]) timestamp.append(datetime.fromtimestamp(int(time_str[:10])).strftime('%Y/%m/%d %H:%M:%M')) date_time_index = pd.to_datetime(timestamp) # convert to DateTimeIndex type df = pd.DataFrame({'open': open, 'high': high, 'low': low, 'close': close, 'volume': volume}, index=date_time_index) # df.index += pd.offsets.Hour(9) # adjustment for JST if required print(df.shape) print(df.columns) # pct_change f = lambda x: 1 if x>0.0001 else -1 if x<-0.0001 else 0 if -0.0001<=x<=0.0001 else np.nan y = df.rename(columns={'close': 'y'}).loc[:, 'y'].pct_change(1).shift(-1).fillna(0) X = df.copy() y_ = pd.DataFrame(y.map(f), columns=['y']) df_ = pd.concat([X, y_], axis=1) # check the shape print('----------------------------------------------------------------------------------------') print('X shape: (%i,%i)' % X.shape) print('y shape: (%i,%i)' % y_.shape) print('----------------------------------------------------------------------------------------') print(y_.groupby('y').size()) print('y=1 up, y=0 stay, y=-1 down') print('----------------------------------------------------------------------------------------') # feature calculation open = pd.Series(df['open']) high = pd.Series(df['high']) low = pd.Series(df['low']) close = pd.Series(df['close']) volume = pd.Series(df['volume']) # pct_change for new column X['diff'] = y # Exponential Moving Average ema = talib.EMA(close, timeperiod=3) ema = ema.fillna(ema.mean()) # Momentum momentum = talib.MOM(close, timeperiod=5) momentum = momentum.fillna(momentum.mean()) # RSI rsi = talib.RSI(close, timeperiod=14) rsi = rsi.fillna(rsi.mean()) # ADX adx = talib.ADX(high, low, close, timeperiod=14) adx = adx.fillna(adx.mean()) # ADX change adx_change = adx.pct_change(1).shift(-1) adx_change = adx_change.fillna(adx_change.mean()) # AD ad = talib.AD(high, low, close, volume) ad = ad.fillna(ad.mean()) X_ = pd.concat([X, ema, momentum, rsi, adx_change, ad], axis=1).drop(['open', 'high', 'low', 'close'], axis=1) X_.columns = ['volume','diff', 'ema', 'momentum', 'rsi', 'adx', 'ad'] X_.join(y_).head(10) X_train, X_test, y_train, y_test = train_test_split(X_, y_, test_size=0.33, random_state=42) print('X_train shape: {}'.format(X_train.shape)) print('X_test shape: {}'.format(X_test.shape)) print('y_train shape: {}'.format(y_train.shape)) print('y_test shape: {}'.format(y_test.shape)) pipe_knn = Pipeline([('scl', StandardScaler()), ('est', KNeighborsClassifier(n_neighbors=3))]) pipe_logistic = Pipeline([('scl', StandardScaler()), ('est', LogisticRegression(solver='lbfgs', multi_class='multinomial', random_state=39))]) pipe_rf = Pipeline([('scl', StandardScaler()), ('est', RandomForestClassifier(random_state=39))]) pipe_gb = Pipeline([('scl', StandardScaler()), ('est', GradientBoostingClassifier(random_state=39))]) pipe_names = ['KNN','Logistic','RandomForest','GradientBoosting'] pipe_lines = [pipe_knn, pipe_logistic, pipe_rf, pipe_gb] for (i, pipe) in enumerate(pipe_lines): pipe.fit(X_train, y_train.values.ravel()) print('%s: %.3f' % (pipe_names[i] + ' Train Accuracy', accuracy_score(y_train.values.ravel(), pipe.predict(X_train)))) print('%s: %.3f' % (pipe_names[i] + ' Test Accuracy', accuracy_score(y_test.values.ravel(), pipe.predict(X_test)))) print('%s: %.3f' % (pipe_names[i] + ' Train F1 Score', f1_score(y_train.values.ravel(), pipe.predict(X_train), average='micro'))) print('%s: %.3f' % (pipe_names[i] + ' Test F1 Score', f1_score(y_test.values.ravel(), pipe.predict(X_test), average='micro'))) for (i, pipe) in enumerate(pipe_lines): predict = pipe.predict(X_test) cm = confusion_matrix(y_test.values.ravel(), predict, labels=[-1, 0, 1]) print('{} Confusion Matrix'.format(pipe_names[i])) print(cm) cv = cross_val_score(pipe_gb, X_, y_.values.ravel(), cv=StratifiedKFold(n_splits=10, shuffle=True, random_state=39)) print('Cross Validation with StatifiedKFold mean: {}'.format(cv.mean())) if __name__ == '__main__': main()
{"hexsha": "7baec853bf26e394a40c3621490078738595c920", "size": 5972, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "yuyasugano/ml-classifier-Ta-Lib-ohlc", "max_stars_repo_head_hexsha": "02f4b24bc2b80f962dca49e6469f45ee0cb6d37d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "yuyasugano/ml-classifier-Ta-Lib-ohlc", "max_issues_repo_head_hexsha": "02f4b24bc2b80f962dca49e6469f45ee0cb6d37d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "yuyasugano/ml-classifier-Ta-Lib-ohlc", "max_forks_repo_head_hexsha": "02f4b24bc2b80f962dca49e6469f45ee0cb6d37d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0805369128, "max_line_length": 146, "alphanum_fraction": 0.6299397187, "include": true, "reason": "import numpy", "num_tokens": 1583}
import os import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from common.utils import AverageMeter, split_states, generate_eom, gen_loader from common.model import DeLaN, init_weights from common.obj import Visualizer import argparse parser = argparse.ArgumentParser() # model argument parser.add_argument('--inp_dim', type=int, default=2) parser.add_argument('--hid_dim', type=int, default=128) parser.add_argument('--num_layers', type=int, default=4) parser.add_argument('--bias', type=float, default=1e-4) # training argument parser.add_argument('-e','--epochs', type=int, default=200) parser.add_argument('--lr', type=float, default=0.005) parser.add_argument('--T', type=float, default=1.0) parser.add_argument('--dt', type=float, default=0.01) args = parser.parse_args() # read datasets datasets = 'cosine' train_states = np.load(os.path.join('data', 'train_states_{}.npy'.format(datasets))) train_torque = np.load(os.path.join('data', 'train_torque_{}.npy'.format(datasets))) test_states = np.load(os.path.join('data', 'test_states_{}.npy'.format(datasets))) test_torque = np.load(os.path.join('data', 'test_torque_{}.npy'.format(datasets))) train_loader = gen_loader(train_states, train_torque, batch_size=64, shuffle=True) test_loader = gen_loader(test_states, test_torque, batch_size=1, shuffle=False) def main(args): print('>>> Loading model...') model = DeLaN(args) model.apply(init_weights) print('>>> total params: {:.2f}M'.format(sum(p.numel() for p in model.parameters()) / 1000000.0)) criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=args.lr) scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.92) print('\n>>> start train') for epoch in range(args.epochs): train(train_loader, model, criterion, optimizer, scheduler, epoch) print('\n>>> start evaluate') evaluate(test_loader, model, criterion) def train(data_loader, model, criterion, optimizer, scheduler, epoch): running_loss = AverageMeter() # Switch to train mode torch.set_grad_enabled(True) model.train() for i, (state, target) in enumerate(data_loader): state = state.float(); target = target.float() num_states = state.shape[0] pred, M, c, g = model(state) # pred.shape: (batch_size, 2) loss = criterion(pred, target) / 1000000 optimizer.zero_grad() loss.backward() optimizer.step() running_loss.update(loss.item(), num_states) print('[{}] loss: {:.3f}, lr: {:.5f}'.format(epoch+1, running_loss.avg, scheduler.get_last_lr()[0])) scheduler.step() def evaluate(data_loader, model, criterion): running_loss = AverageMeter() # Switch to eval mode model.eval() # visualizer viz = Visualizer() for i, (state, target) in enumerate(data_loader): state = state.float(); target = target.float() # state.shape: (batch_size, 2, 3) num_states = state.shape[0] pred, M, c, g = model(state) # pred.shape: (batch_size, 2) loss = criterion(pred, target) / 1000000 running_loss.update(loss.item(), num_states) # test q, qdot, qddot = split_states(state.numpy().squeeze()) M_gt, c_gt, g_gt = generate_eom(q, qdot) M_pred = M.detach().numpy() c_pred = c.detach().numpy() g_pred = g.detach().numpy() u_pred, u_gt = pred.detach().numpy(), target.detach().numpy() viz.add_data(q, qdot, qddot, (u_pred, u_gt), (M_pred @ qddot.reshape(2,), M_gt @ qddot.reshape(2,)), (c_pred, c_gt), (g_pred, g_gt) ) print('evaluate loss: {:.3f}'.format(running_loss.avg)) viz.save_plot() if __name__ == "__main__": main(args)
{"hexsha": "f2f309ef7680b1c9f9e8474942484fa9ec27d670", "size": 3905, "ext": "py", "lang": "Python", "max_stars_repo_path": "main.py", "max_stars_repo_name": "xth430/DeepLagrangian", "max_stars_repo_head_hexsha": "acec4cc4429b6d08e9f7b8caadea9a2750837598", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.py", "max_issues_repo_name": "xth430/DeepLagrangian", "max_issues_repo_head_hexsha": "acec4cc4429b6d08e9f7b8caadea9a2750837598", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.py", "max_forks_repo_name": "xth430/DeepLagrangian", "max_forks_repo_head_hexsha": "acec4cc4429b6d08e9f7b8caadea9a2750837598", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8091603053, "max_line_length": 104, "alphanum_fraction": 0.6591549296, "include": true, "reason": "import numpy", "num_tokens": 999}
import os import sys # Add /Modules to sys path so that program has access to the files in the Modules folder sys.path.append(os.getcwd() + '/Modules') import time import mysql.connector import numpy as np import pandas as pd import json from datetime import datetime import os.path import csv from DepartureDelay import predictCompulsaryDelay from DepartureDelay import predictDepartureDelay from ArrivalDelay import predictArrivalDelay from WeatherDelay import predictWeatherDelay from WeatherDelay import findNearest # Connect to Database flightdb = mysql.connector.connect( host="localhost", user="root", passwd="", database="flights" ) # Constant MIN_PREP_TIME for setting minimum preperation time (Use same value as that used while training) MIN_PREP_TIME = 30 def getLatestInfo(tailNum): ''' Returns tuple with info about last Occurance of flight with particular tail number Parameters: tailNumber (string) Returns: tuple (Destination Airport, Scheduled Arrival Epoch, Arrival Delay) ''' dbnewcursor = flightdb.cursor() # Fetch the flight with passed Tail number present in FlightInfo having the highest Scheduled Departure Epoch (Latest) sqlst = "SELECT FlightIdentifier, SchArrEpoch, DestinationAirport, HasDeparted FROM FlightInfo WHERE SchDepEpoch = (SELECT MAX(SchDepEpoch) FROM FlightInfo WHERE TailNumber = '" + tailNum + "') AND TailNumber = '" + tailNum + "'" dbnewcursor.execute(sqlst) # Maximum one flight will be returned (We can use fetchone() but it will raise error in case length of cursor is 0) tl = dbnewcursor.fetchall() # If length of result is not 0 then flight is present in either InAir or Scheduled (whose Info is in FlightInfo) # Get Arrival Delay of this flight (Predicted) and return all values. if len(tl) != 0: fi, sae, da, hd = tl[0] if hd == 'Y': dbnewcursor.reset() sqlst = "SELECT ArrivalDelay FROM InAir WHERE FlightIdentifier = '" + fi + "'" dbnewcursor.execute(sqlst) ad = dbnewcursor.fetchone()[0] else: dbnewcursor.reset() sqlst = "SELECT ArrivalDelay FROM Scheduled WHERE FlightIdentifier = '" + fi + "'" dbnewcursor.execute(sqlst) ad = dbnewcursor.fetchone()[0] dbnewcursor.close() return (da, sae, ad) # If length of result is 0 then no flight is present in InAir or Scheduled with given tail number # Search for flight in LastLanding and return values if found sqlst = "SELECT LastLandingLocation, ArrivalDelay, ScheduledArrivalEpoch FROM LastLanding WHERE TailNumber = '" + tailNum + "'" dbnewcursor.execute(sqlst) tl = dbnewcursor.fetchall() dbnewcursor.close() if len(tl) != 0: lll, ad, sae = tl[0] return(lll, sae, ad) # If no flight with given tail number is found return ('UNKNOWN', -1, -1) # Open log.json file and read the value (integer) # log.json file contains the CE of previous exucution of cron job # LUE = Last Update Epoch with open("log.json", "r") as read_file: LUE = json.load(read_file) # ToDo: Change to system utc epoch while deployment # CE = Current Epoch # Windows Testing # CE = LUE + 5 # LinuxDeployment CE = int(int(time.time())/60) # When running for the first time with empty database # log.json --> 23667020 # CE = 23668465 # Edited will hold the tail numbers of all the flights that will be updated Edited = list() dbcursor = flightdb.cursor() # ************* SECTION TO HANDLE LANDED FLIGHTS ************* # Each row in Data_Jan/Actual_Arrival.csv contains Flight Identifier, Actual Arrival Epoch and Actual Arrival Delay # Read the CSV # Make a dataframe that contains only the flights which landed after Last Update epoch (LUE) and till Current Epoch (CE) (Including CE) actual_arrival = pd.read_csv('Data_Jan/Actual_Arrival.csv') actual_arrival = actual_arrival[(actual_arrival.ARRIVAL_EPOCH > LUE) & (actual_arrival.ARRIVAL_EPOCH <= CE)] arrival_log = [] if len(actual_arrival) != 0: flights_landed_mat = actual_arrival[['FLIGHT_IDENTIFIER', 'ARRIVAL_DELAY']].values # Will contain Flight Identifiers flights_landed = list() # Will store mapping flight Identifier -> Arrival Delay and will be while updating LastLanding flights_landed_dict = dict() for fi, ad in flights_landed_mat: flights_landed.append(fi) flights_landed_dict[fi] = int(ad) # arrival_log will store the Predicted Arrival Delays before removing the entry to store in Log dbcursor.execute("SELECT FlightIdentifier, ArrivalDelay FROM InAir WHERE FlightIdentifier IN " + str(tuple(flights_landed) + ('Junk','More_Junk'))) arrival_log = dbcursor.fetchall() # Delete entries of landed flights from InAir, WeatherInfo, PrevFlightInfo sqlst = "DELETE FROM InAir WHERE FlightIdentifier IN " + str(tuple(flights_landed) + ('Junk','More_Junk')) dbcursor.execute(sqlst) flightdb.commit() sqlst = "DELETE FROM WeatherInfo WHERE FlightIdentifier IN " + str(tuple(flights_landed) + ('Junk','More_Junk')) dbcursor.execute(sqlst) flightdb.commit() sqlst = "DELETE FROM PrevFlightInfo WHERE FlightIdentifier IN " + str(tuple(flights_landed) + ('Junk','More_Junk')) dbcursor.execute(sqlst) flightdb.commit() # Update the Destination Airport, Scheduled Arrival Epoch and Arrival Delay for landed Tail Numbers dbcursor.execute("SELECT FlightIdentifier, TailNumber, DestinationAirport, SchArrEpoch FROM FlightInfo WHERE FlightIdentifier IN " + str(tuple(flights_landed) + ('Junk','More_Junk'))) result = dbcursor.fetchall() templist = list() for fi, tn, da, sae in result: t = (tn, da, flights_landed_dict[fi], sae) templist.append(t) # Add Tail Number to Edited Edited.append(tn) sqlst = "REPLACE INTO LastLanding VALUES (%s, %s, %s, %s)" dbcursor.executemany(sqlst, templist) flightdb.commit() # Delete entries of landed flights from FlightInfo sqlst = "DELETE FROM FlightInfo WHERE FlightIdentifier IN " + str(tuple(flights_landed) + ('Junk','More_Junk')) dbcursor.execute(sqlst) flightdb.commit() # Variables from sections that will be used later too: Edited, arrival_log, actual_arrival # ************* SECTION TO HANDLE FLIGHTS THAT TOOK OFF or GOT CANCELLED ************* # Each row in Data_Jan/Actual_Departure.csv contains Flight Identifier, Actual Departure Epoch and Actual Departure Delay # Read the CSV # Make a dataframe that contains only the flights which took off after Last Update epoch (LUE) and till Current Epoch (CE) (Including CE) actual_departure = pd.read_csv('Data_Jan/Actual_Departure.csv') actual_departure = actual_departure[(actual_departure.DEPARTURE_EPOCH > LUE) & (actual_departure.DEPARTURE_EPOCH <= CE)] # Add Tail Numbers to Edited for fi in actual_departure['FLIGHT_IDENTIFIER'].values: sqlst = "SELECT TailNumber FROM FlightInfo WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) tn = dbcursor.fetchone()[0] Edited.append(tn) # Departure_log will store the Predicted Departure Delays before transfering flights from Scheduled to InAir dbcursor.execute("SELECT FlightIdentifier, DepartureDelay FROM Scheduled WHERE FlightIdentifier IN " + str(tuple(actual_departure['FLIGHT_IDENTIFIER'].values) + ('Junk','More_Junk'))) departure_log = dbcursor.fetchall() # Delete entries of flights that took off from FlightInfo sqlst = "DELETE FROM Scheduled WHERE FlightIdentifier IN " + str(tuple(actual_departure['FLIGHT_IDENTIFIER'].values) + ('Junk','More_Junk')) dbcursor.execute(sqlst) flightdb.commit() if len(actual_departure) != 0: # actual_departure.CANCELLED can be equal to: # 0 -> Not Cancelled # 1 -> Cancelled, But didn't take off only # 2 -> Diverted to unknown location and then cancelled (Basically we don't know the landing location of these flights) # departure_cancelled is a dataframe that contains flights that are cancelled # actual_departure now contains only flights that were not cancelled and landed successfully in future departure_cancelled = actual_departure[(actual_departure.CANCELLED != 0)] actual_departure = actual_departure[(actual_departure.CANCELLED == 0)] if len(actual_departure) != 0: flights_departed_mat = actual_departure[['FLIGHT_IDENTIFIER', 'DEPARTURE_EPOCH', 'DEPARTURE_DELAY']].values # For all the flights that took off predict the Arrival Delay with and INSERT the entry in InAir with each row in InAir containing: # Flight Identifier, Actual Departure Delay, Predicted Arrival Delay, Wrong(Default Zero) # 'Wrong' is used later # Also update HasDeparted in FlightInfo to 'Y' and the LastUpdateEpoch which is used to check if flight was updated in WebApp while implementing automatic refresh for fi, de, dd in flights_departed_mat: sqlst = "SELECT OriginAirport, ScheduledTime, ScheduledArrival FROM FlightInfo WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) oa, st, sa = dbcursor.fetchone() ad = predictArrivalDelay(st, sa, dd) t = (fi, int(dd), int(ad), 0) sqlst = "INSERT INTO InAir VALUES " + str(t) dbcursor.execute(sqlst) flightdb.commit() sqlst = "UPDATE FlightInfo SET HasDeparted = 'Y', LastUpdateEpoch = " + str(CE) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() # Update WeatherInfo with the closest point to actual departure epoch in weather information available cP = findNearest(oa, int(de)) if cP == None: cP = -1 else: cP = cP['valid_time_gmt'] sqlst = "UPDATE WeatherInfo SET WeatherDelay = -1, WeatherPointEpoch = " + str(int(cP)) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() if len(departure_cancelled) != 0: # For all the flights that were cancelled: # if departure_cancelled.CANCELLED == 1: # Don't do anything as the LastLanding already contains the info of last successful landing # if departure_cancelled.CANCELLED == 2: # Delete entry from Last Landing for that tail number as the information becomes invalid # Delete entries of flights that were cancelled from WeatherInfo, PrevFlightInfo, FlightInfo if len(departure_cancelled[departure_cancelled.CANCELLED == 2]) != 0: location_unknown = departure_cancelled[departure_cancelled.CANCELLED == 2]['FLIGHT_IDENTIFIER'].values dbcursor.execute("SELECT TailNumber FROM FlightInfo WHERE FlightIdentifier IN " + str(tuple(location_unknown) + ('Junk','More_Junk'))) t = dbcursor.fetchone()[0] print(t) sqlst = "DELETE FROM LastLanding WHERE TailNumber IN " + str(tuple(t) + ('Junk', 'More_Junk')) dbcursor.execute(sqlst) flightdb.commit() sqlst = "DELETE FROM WeatherInfo WHERE FlightIdentifier IN " + str(tuple(departure_cancelled['FLIGHT_IDENTIFIER'].values) + ('Junk','More_Junk')) dbcursor.execute(sqlst) flightdb.commit() sqlst = "DELETE FROM PrevFlightInfo WHERE FlightIdentifier IN " + str(tuple(departure_cancelled['FLIGHT_IDENTIFIER'].values) + ('Junk','More_Junk')) dbcursor.execute(sqlst) flightdb.commit() sqlst = "DELETE FROM FlightInfo WHERE FlightIdentifier IN " + str(tuple(departure_cancelled['FLIGHT_IDENTIFIER'].values) + ('Junk','More_Junk')) dbcursor.execute(sqlst) flightdb.commit() # Variables from sections that will be used later too: Edited, departure_log, actual_departure # ************* SECTION TO UPDATE FLIGHTS IN SCHEDULED WHERE TAIL NUMBER IS PRESENT IN Edited ************* # Check Edited for Duplicate Entries Edited = list(set(Edited)) # SELECT information required for predicting Departure Delay of flights with tail numbers as that in Edited which are present in InAir # Means that the update is required because the flight with the same tail number took off # Store result of Select query to tail_changed1 # Also remove the found tail numbers from Edited sqlst = "SELECT FlightInfo.TailNumber, FlightInfo.DestinationAirport, FlightInfo.SchArrEpoch, InAir.ArrivalDelay FROM FlightInfo INNER JOIN InAir ON FlightInfo.FlightIdentifier = InAir.FlightIdentifier WHERE FlightInfo.TailNumber IN " + str(tuple(Edited) + ('Junk', 'More_Junk')) dbcursor.execute(sqlst) tail_changed1 = dbcursor.fetchall() for t in tail_changed1: Edited.remove(t[0]) # SELECT information required for predicting Departure Delay of flights with tail numbers as that in Edited which are present in LastLanding # Means that the update is required because the flight with the same tail number Landed # Store result of Select query to tail_changed2 # Also remove the found tail numbers from Edited sqlst = "SELECT TailNumber, LastLandingLocation, ScheduledArrivalEpoch, ArrivalDelay FROM LastLanding WHERE TailNumber IN " + str(tuple(Edited) + ('Junk', 'More_Junk')) dbcursor.execute(sqlst) tail_changed2 = dbcursor.fetchall() for t in tail_changed2: Edited.remove(t[0]) # Add lists tail_changed1, tail_changed2 tail_changed = tail_changed1 + tail_changed2 # Now only remaining tail numbers in Edited are of flights which departed but were diverted and never reached the destination for tailNum in Edited: t = (tailNum, 'UNKNOWN', -1, -1) tail_changed.append(t) # Now all entries in this list tail_changed contains a tupple: # (Tail Number, Current Know Location, Previous flights Scheduled Arrival Epoch, Previous flights Scheduled Arrival Delay) # Which will be used to predict departure delay for next flight for tailNum, currLoc, prevSchArrEpoch, prevArrDelay in tail_changed: # Select all flights with tail number in Scheduled # These flights need to be updated sqlst = "SELECT FlightIdentifier, Month, DayOfWeek, Distance, OriginAirport, DestinationAirport, SchDepEpoch, SchArrEpoch, ScheduledTime, ScheduledArrival FROM FlightInfo WHERE TailNumber = '" + tailNum + "' AND HasDeparted = 'N' ORDER BY SchDepEpoch" dbcursor.execute(sqlst) flights_scheduled = dbcursor.fetchall() # Iteratively predict departure and arrival delay and store predictions for fi, m, dOW, d, oA, dA, sDE, sAE, sT, sA in flights_scheduled: # interval = Scheduled Departure Epoch of current flight - Scheduled Arrival Epoch of prev Flight # Store the prevArrDelay and interval in PrevFlightInfo to display in WebApp Later # Check if Origin Airport of current flight is same as destination of previous if currLoc == oA: interval = sDE - prevSchArrEpoch sqlst = "UPDATE PrevFlightInfo SET PrevArrivalDelay = " + str(int(prevArrDelay)) + ", PrepTime = " + str(interval) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() else: interval = MIN_PREP_TIME prevArrDelay = 0 sqlst = "UPDATE PrevFlightInfo SET PrevArrivalDelay = -999, PrepTime = -999 WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() m, dOW, sD, interval, compulsaryDelay = predictCompulsaryDelay(oA, interval, prevArrDelay, sDE) dd = int(predictDepartureDelay(m, dOW, sD, d, interval) + compulsaryDelay) wd, cP = predictWeatherDelay(oA, sDE, dd) ad = int(predictArrivalDelay(sT, sA, dd + wd)) # Update Scheduled sqlst = "UPDATE Scheduled SET DepartureDelay = " + str(int(dd + wd)) + ", ArrivalDelay = " + str(ad) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() # Update WeatherInfo with new calculated Weather Delay and Closest Point Found(To be used to display weather info in WebApp) sqlst = "UPDATE WeatherInfo SET WeatherDelay = " + str(int(wd)) + ", WeatherPointEpoch = " + str(int(cP)) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() # Update LastUpdateEpoch sqlst = "UPDATE flightinfo SET LastUpdateEpoch = " + str(CE) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() # Find out currLoc, prevSchArrEpoch, predictArrivalDelay which will be used for next flight in the chain currLoc = dA prevSchArrEpoch = sAE prevArrDelay = ad # ************* SECTION TO ADD NEW FLIGHTS TO SCHEDULED ************* # Each row in Data_Jan/Schedule.csv contains Flights information that we know beforehand # Read the CSV # Scheduled table in database contains flights scheduled for next day from LUE # Add flights of 'n' mins after that # Make a dataframe that contains only the flights which are scheduled 'n' mins between 'LUE + 1 day' and 'CE + 1 day' # n = interval of running cronjob flights_new = pd.read_csv('Data_Jan/Schedule.csv') flights_new = flights_new[(flights_new.SCH_DEP_EPOCH > LUE + 1440) & (flights_new.SCH_DEP_EPOCH <= CE + 1440)] flights_new_identifier = flights_new["FLIGHT_IDENTIFIER"].values flights_new_tail = flights_new["TAIL_NUMBER"].values LatestInfo = dict() # Get last occurance of flight with same tail number as that to be added to schedule # Dictionary mapping Tail Number -> Tuple of Latest Flights Info for tn in flights_new_tail: LatestInfo[tn] = getLatestInfo(tn) # INSERT information into FlightInfo for each flight with Last Update Epoch as Current Epoch flights_new["HAS_DEPARTED"] = "N" flights_new["LastUpdateEpoch"] = CE flights_new.SCH_DEP_EPOCH = flights_new.SCH_DEP_EPOCH.astype(int) flights_new.SCH_ARR_EPOCH = flights_new.SCH_ARR_EPOCH.astype(int) flights_new.FLIGHT_NUMBER = flights_new.FLIGHT_NUMBER.astype(str) tuples = [tuple(x) for x in flights_new.values] sqlst = "INSERT INTO FlightInfo VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" dbcursor.executemany(sqlst, tuples) flightdb.commit() # Predict Departure and Arrival Delays for flights and store in Scheduled # Also INSERT in PrevFlightInfo, WeatherInfo # This operation is similar to that done previously of predicting delays and storing for fi in flights_new_identifier: sqlst = "SELECT TailNumber FROM FlightInfo WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) tailNum = dbcursor.fetchone()[0] currLoc, prevSchArrEpoch, prevArrDelay = LatestInfo[tailNum] sqlst = "SELECT Month, DayOfWeek, Distance, OriginAirport, DestinationAirport, SchDepEpoch, SchArrEpoch, ScheduledTime, ScheduledArrival FROM FlightInfo WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) m, dOW, d, oA, dA, sDE, sAE, sT, sA = dbcursor.fetchone() if currLoc == oA: interval = sDE - prevSchArrEpoch t = (fi, int(prevArrDelay), int(interval)) sqlst = "INSERT INTO PrevFlightInfo VALUES " + str(t) dbcursor.execute(sqlst) flightdb.commit() else: interval = MIN_PREP_TIME prevArrDelay = 0 t = (fi, -999, -999) sqlst = "INSERT INTO PrevFlightInfo VALUES " + str(t) dbcursor.execute(sqlst) flightdb.commit() m, dOW, sD, interval, compulsaryDelay = predictCompulsaryDelay(oA, interval, prevArrDelay, sDE) dd = int(predictDepartureDelay(m, dOW, sD, d, interval) + compulsaryDelay) wd, cP = predictWeatherDelay(oA, sDE, dd) ad = int(predictArrivalDelay(sT, sA, dd + wd)) t = (fi, int(dd + wd), int(ad), 0) sqlst = "INSERT INTO Scheduled VALUES " + str(t) dbcursor.execute(sqlst) flightdb.commit() t = (fi, int(wd), int(cP)) sqlst = "INSERT INTO WeatherInfo VALUES " + str(t) dbcursor.execute(sqlst) flightdb.commit() # ************* SECTION FOR HANDLING WRONG DELAY PROPOGATION************* # Select all flights for which --> Scheduled Arrival Epoch + Predicted Arrival Delay > Current Epoch sqlst = "SELECT FlightInfo.FlightIdentifier, FlightInfo.HasDeparted, FlightInfo.TailNumber, FlightInfo.DestinationAirport, FlightInfo.SchArrEpoch, InAir.Wrong FROM Flightinfo INNER JOIN InAir ON Flightinfo.FlightIdentifier = InAir.FlightIdentifier WHERE FlightInfo.SchArrEpoch + InAir.ArrivalDelay <= " + str(CE) + ";" dbcursor.execute(sqlst) flights_wrong_arr_pred = dbcursor.fetchall() # Select all flights for which --> Scheduled Departure Epoch + Predicted Departure Delay > Current Epoch sqlst = "SELECT FlightInfo.FlightIdentifier, FlightInfo.HasDeparted, FlightInfo.TailNumber, FlightInfo.DestinationAirport, FlightInfo.SchArrEpoch, Scheduled.Wrong FROM Flightinfo INNER JOIN Scheduled ON Flightinfo.FlightIdentifier = Scheduled.FlightIdentifier WHERE FlightInfo.SchDepEpoch + Scheduled.DepartureDelay <= " + str(CE) + ";" dbcursor.execute(sqlst) flights_wrong_dep_pred = dbcursor.fetchall() flights_wrong_pred = flights_wrong_arr_pred + flights_wrong_dep_pred for fliId, hasDep, tailNum, currLoc, prevSchArrEpoch, wrong in flights_wrong_pred: # Check if Arrival is Predicted Wrong(hasDep == 'Y') or Departure(hasDep == 'N') if hasDep == 'Y': # Update InAir.Wrong and FlightInfo.LastUpdateEpoch if needed # Calculate prevArrDelay (i.e Predict new Arrival Delay of the flight DON'T STORE) so that it can be used for further flights correction if wrong == 0: sqlst = "UPDATE InAir SET Wrong = 1 WHERE FlightIdentifier = '" + fliId + "'" dbcursor.execute(sqlst) flightdb.commit() sqlst = "UPDATE flightinfo SET LastUpdateEpoch = " + str(CE) + " WHERE FlightIdentifier = '" + fliId + "'" dbcursor.execute(sqlst) flightdb.commit() prevArrDelay = CE - prevSchArrEpoch else: # Update InAir.Wrong and FlightInfo.LastUpdateEpoch if needed if wrong == 0: sqlst = "UPDATE Scheduled SET Wrong = 1 WHERE FlightIdentifier = '" + fliId + "'" dbcursor.execute(sqlst) flightdb.commit() sqlst = "UPDATE flightinfo SET LastUpdateEpoch = " + str(CE) + " WHERE FlightIdentifier = '" + fliId + "'" dbcursor.execute(sqlst) flightdb.commit() sqlst = "SELECT SchDepEpoch, ScheduledTime, ScheduledArrival FROM FlightInfo WHERE FlightIdentifier = '" + fliId + "'" dbcursor.execute(sqlst) schDepEp, schTime, schArr = dbcursor.fetchone() depDelay = CE - schDepEp prevArrDelay = int(predictArrivalDelay(schTime, schArr, depDelay)) # Update the Departure and Arrival Delay of next flights in the chain (Same operations as done previously) sqlst = "SELECT FlightIdentifier, Month, DayOfWeek, Distance, OriginAirport, DestinationAirport, SchDepEpoch, SchArrEpoch, ScheduledTime, ScheduledArrival FROM FlightInfo WHERE TailNumber = '" + tailNum + "' AND HasDeparted = 'N' AND SchDepEpoch > " + str(prevSchArrEpoch) + " ORDER BY SchDepEpoch" dbcursor.execute(sqlst) flights_scheduled = dbcursor.fetchall() for fi, m, dOW, d, oA, dA, sDE, sAE, sT, sA in flights_scheduled: if currLoc == oA: interval = sDE - prevSchArrEpoch sqlst = "UPDATE PrevFlightInfo SET PrevArrivalDelay = " + str(int(prevArrDelay)) + ", PrepTime = " + str(interval) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() else: interval = MIN_PREP_TIME prevArrDelay = 0 sqlst = "UPDATE PrevFlightInfo SET PrevArrivalDelay = -999, PrepTime = -999 WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() m, dOW, sD, interval, compulsaryDelay = predictCompulsaryDelay(oA, interval, prevArrDelay, sDE) dd = int(predictDepartureDelay(m, dOW, sD, d, interval) + compulsaryDelay) wd, cP = predictWeatherDelay(oA, sDE, dd) ad = int(predictArrivalDelay(sT, sA, dd + wd)) sqlst = "UPDATE Scheduled SET DepartureDelay = " + str(int(dd + wd)) + ", ArrivalDelay = " + str(ad) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() sqlst = "UPDATE WeatherInfo SET WeatherDelay = " + str(int(wd)) + ", WeatherPointEpoch = " + str(int(cP)) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() sqlst = "UPDATE flightinfo SET LastUpdateEpoch = " + str(CE) + " WHERE FlightIdentifier = '" + fi + "'" dbcursor.execute(sqlst) flightdb.commit() currLoc = dA prevSchArrEpoch = sAE prevArrDelay = ad # All operations were succussful # Now update the log.json file with current epoch with open("log.json", "w") as write_file: json.dump(CE, write_file) dbcursor.close() flightdb.close() # Write Log according to date fileDeparturePath = "Logs/Departure/" + datetime.utcnow().strftime("%d_%m_%Y") + ".csv" fileArrivalPath = "Logs/Arrival/" + datetime.utcnow().strftime("%d_%m_%Y") + ".csv" with open (fileDeparturePath, 'a', newline='') as log: csv_out=csv.writer(log) if os.stat(fileDeparturePath).st_size == 0: csv_out.writerow(['FlightIdentifier','Predicted', 'Actual']) for fI, pDD in departure_log: if actual_departure[actual_departure.FLIGHT_IDENTIFIER == fI].shape[0] != 0: aDD = actual_departure[actual_departure.FLIGHT_IDENTIFIER == fI]['DEPARTURE_DELAY'].iloc[0] tempTup = (fI, pDD, int(aDD)) csv_out.writerow(tempTup) with open (fileArrivalPath, 'a', newline='') as log: csv_out=csv.writer(log) if os.stat(fileArrivalPath).st_size == 0: csv_out.writerow(['FlightIdentifier','Predicted', 'Actual']) for fI, pAD in arrival_log: aAD = actual_arrival[actual_arrival.FLIGHT_IDENTIFIER == fI]['ARRIVAL_DELAY'].iloc[0] tempTup = (fI, pAD, int(aAD)) csv_out.writerow(tempTup) #ToDo: Implement flock while deploying on Linux
{"hexsha": "ba06601ca826bba0b50ebaed269dab8f7fc16406", "size": 24799, "ext": "py", "lang": "Python", "max_stars_repo_path": "CronJob/cron_job.py", "max_stars_repo_name": "md3997/FYP", "max_stars_repo_head_hexsha": "428a54714255dcd4cfd222cd4e3f8b28285c8b6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CronJob/cron_job.py", "max_issues_repo_name": "md3997/FYP", "max_issues_repo_head_hexsha": "428a54714255dcd4cfd222cd4e3f8b28285c8b6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CronJob/cron_job.py", "max_forks_repo_name": "md3997/FYP", "max_forks_repo_head_hexsha": "428a54714255dcd4cfd222cd4e3f8b28285c8b6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6784, "max_line_length": 336, "alphanum_fraction": 0.7349489899, "include": true, "reason": "import numpy", "num_tokens": 6636}
module TestCount using Test using LazyGroupBy @testset begin @test count.(_ -> true, grouped(isodd, [0, 7, 3, 1, 5, 9, 4, 3, 0, 5])) == Dict(false => 3, true => 7) @test count.(grouped(identity, [true, false, true, true, true])) == Dict(false => 0, true => 4) @test_throws( Exception, count.(_ -> 0.5, grouped(isodd, [0, 7, 3, 1, 5, 9, 4, 3, 0, 5])), ) end end # module
{"hexsha": "88db30ff12ddae142829ec1edc3d96183f606512", "size": 426, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/test_count.jl", "max_stars_repo_name": "JuliaFolds/LazyGroupBy.jl", "max_stars_repo_head_hexsha": "293c338d6a1efc4d17453bf85eb3addf7fa90194", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-06-29T04:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T01:40:27.000Z", "max_issues_repo_path": "test/test_count.jl", "max_issues_repo_name": "JuliaFolds/LazyGroupBy.jl", "max_issues_repo_head_hexsha": "293c338d6a1efc4d17453bf85eb3addf7fa90194", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2020-06-28T22:40:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T09:01:14.000Z", "max_forks_repo_path": "test/test_count.jl", "max_forks_repo_name": "JuliaFolds/LazyGroupBy.jl", "max_forks_repo_head_hexsha": "293c338d6a1efc4d17453bf85eb3addf7fa90194", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-25T13:26:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T13:26:45.000Z", "avg_line_length": 23.6666666667, "max_line_length": 78, "alphanum_fraction": 0.5281690141, "num_tokens": 167}
[GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') ⊢ HasFDerivWithinAt f f' (closure s) x [PROOFSTEP] classical -- one can assume without loss of generality that `x` belongs to the closure of `s`, as the -- statement is empty otherwise by_cases hx : x ∉ closure s · rw [← closure_closure] at hx ; exact hasFDerivWithinAt_of_not_mem_closure hx push_neg at hx rw [HasFDerivWithinAt, HasFDerivAtFilter, Asymptotics.isLittleO_iff] /- One needs to show that `‖f y - f x - f' (y - x)‖ ≤ ε ‖y - x‖` for `y` close to `x` in `closure s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is arbitrarily close to `f'` by assumption. The mean value inequality completes the proof. -/ intro ε ε_pos obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε := by simpa [dist_zero_right] using tendsto_nhdsWithin_nhds.1 h ε ε_pos set B := ball x δ suffices : ∀ y ∈ B ∩ closure s, ‖f y - f x - (f' y - f' x)‖ ≤ ε * ‖y - x‖ exact mem_nhdsWithin_iff.2 ⟨δ, δ_pos, fun y hy => by simpa using this y hy⟩ suffices ∀ p : E × E, p ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) → ‖f p.2 - f p.1 - (f' p.2 - f' p.1)‖ ≤ ε * ‖p.2 - p.1‖ by rw [closure_prod_eq] at this intro y y_in apply this ⟨x, y⟩ have : B ∩ closure s ⊆ closure (B ∩ s) := isOpen_ball.inter_closure exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ have key : ∀ p : E × E, p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.2 - f p.1 - (f' p.2 - f' p.1)‖ ≤ ε * ‖p.2 - p.1‖ := by rintro ⟨u, v⟩ ⟨u_in, v_in⟩ have conv : Convex ℝ (B ∩ s) := (convex_ball _ _).inter s_conv have diff : DifferentiableOn ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _) have bound : ∀ z ∈ B ∩ s, ‖fderivWithin ℝ f (B ∩ s) z - f'‖ ≤ ε := by intro z z_in have h := hδ z have : fderivWithin ℝ f (B ∩ s) z = fderiv ℝ f z := by have op : IsOpen (B ∩ s) := isOpen_ball.inter s_open rw [DifferentiableAt.fderivWithin _ (op.uniqueDiffOn z z_in)] exact (diff z z_in).differentiableAt (IsOpen.mem_nhds op z_in) rw [← this] at h exact (le_of_lt (h z_in.2 z_in.1)) simpa using conv.norm_image_sub_le_of_norm_fderivWithin_le' diff bound u_in v_in rintro ⟨u, v⟩ uv_in refine' ContinuousWithinAt.closure_le uv_in _ _ key have f_cont' : ∀ y ∈ closure s, ContinuousWithinAt (f - ⇑f') s y := by intro y y_in exact Tendsto.sub (f_cont y y_in) f'.cont.continuousWithinAt all_goals -- common start for both continuity proofs have : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s := by mono <;> exact inter_subset_right _ _ obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s := by simpa [closure_prod_eq] using closure_mono this uv_in apply ContinuousWithinAt.mono _ this simp only [ContinuousWithinAt] rw [nhdsWithin_prod_eq] · have : ∀ u v, f v - f u - (f' v - f' u) = f v - f' v - (f u - f' u) := by intros; abel simp only [this] exact Tendsto.comp continuous_norm.continuousAt ((Tendsto.comp (f_cont' v v_in) tendsto_snd).sub <| Tendsto.comp (f_cont' u u_in) tendsto_fst) · apply tendsto_nhdsWithin_of_tendsto_nhds rw [nhds_prod_eq] exact tendsto_const_nhds.mul (Tendsto.comp continuous_norm.continuousAt <| tendsto_snd.sub tendsto_fst) [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') ⊢ HasFDerivWithinAt f f' (closure s) x [PROOFSTEP] by_cases hx : x ∉ closure s [GOAL] case pos E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : ¬x ∈ closure s ⊢ HasFDerivWithinAt f f' (closure s) x [PROOFSTEP] rw [← closure_closure] at hx [GOAL] case pos E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : ¬x ∈ closure (closure s) ⊢ HasFDerivWithinAt f f' (closure s) x [PROOFSTEP] exact hasFDerivWithinAt_of_not_mem_closure hx [GOAL] case neg E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : ¬¬x ∈ closure s ⊢ HasFDerivWithinAt f f' (closure s) x [PROOFSTEP] push_neg at hx [GOAL] case neg E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ⊢ HasFDerivWithinAt f f' (closure s) x [PROOFSTEP] rw [HasFDerivWithinAt, HasFDerivAtFilter, Asymptotics.isLittleO_iff] /- One needs to show that `‖f y - f x - f' (y - x)‖ ≤ ε ‖y - x‖` for `y` close to `x` in `closure s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is arbitrarily close to `f'` by assumption. The mean value inequality completes the proof. -/ [GOAL] case neg E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ⊢ ∀ ⦃c : ℝ⦄, 0 < c → ∀ᶠ (x_1 : E) in 𝓝[closure s] x, ‖f x_1 - f x - ↑f' (x_1 - x)‖ ≤ c * ‖x_1 - x‖ [PROOFSTEP] intro ε ε_pos [GOAL] case neg E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε ⊢ ∀ᶠ (x_1 : E) in 𝓝[closure s] x, ‖f x_1 - f x - ↑f' (x_1 - x)‖ ≤ ε * ‖x_1 - x‖ [PROOFSTEP] obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε := by simpa [dist_zero_right] using tendsto_nhdsWithin_nhds.1 h ε ε_pos [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε ⊢ ∃ δ, δ > 0 ∧ ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε [PROOFSTEP] simpa [dist_zero_right] using tendsto_nhdsWithin_nhds.1 h ε ε_pos [GOAL] case neg.intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε ⊢ ∀ᶠ (x_1 : E) in 𝓝[closure s] x, ‖f x_1 - f x - ↑f' (x_1 - x)‖ ≤ ε * ‖x_1 - x‖ [PROOFSTEP] set B := ball x δ [GOAL] case neg.intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ ⊢ ∀ᶠ (x_1 : E) in 𝓝[closure s] x, ‖f x_1 - f x - ↑f' (x_1 - x)‖ ≤ ε * ‖x_1 - x‖ [PROOFSTEP] suffices : ∀ y ∈ B ∩ closure s, ‖f y - f x - (f' y - f' x)‖ ≤ ε * ‖y - x‖ [GOAL] case neg.intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ this : ∀ (y : E), y ∈ B ∩ closure s → ‖f y - f x - (↑f' y - ↑f' x)‖ ≤ ε * ‖y - x‖ ⊢ ∀ᶠ (x_1 : E) in 𝓝[closure s] x, ‖f x_1 - f x - ↑f' (x_1 - x)‖ ≤ ε * ‖x_1 - x‖ case this E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ ⊢ ∀ (y : E), y ∈ B ∩ closure s → ‖f y - f x - (↑f' y - ↑f' x)‖ ≤ ε * ‖y - x‖ [PROOFSTEP] exact mem_nhdsWithin_iff.2 ⟨δ, δ_pos, fun y hy => by simpa using this y hy⟩ [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ this : ∀ (y : E), y ∈ B ∩ closure s → ‖f y - f x - (↑f' y - ↑f' x)‖ ≤ ε * ‖y - x‖ y : E hy : y ∈ ball x δ ∩ closure s ⊢ y ∈ {x_1 | (fun x_2 => ‖f x_2 - f x - ↑f' (x_2 - x)‖ ≤ ε * ‖x_2 - x‖) x_1} [PROOFSTEP] simpa using this y hy [GOAL] case this E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ ⊢ ∀ (y : E), y ∈ B ∩ closure s → ‖f y - f x - (↑f' y - ↑f' x)‖ ≤ ε * ‖y - x‖ [PROOFSTEP] suffices ∀ p : E × E, p ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) → ‖f p.2 - f p.1 - (f' p.2 - f' p.1)‖ ≤ ε * ‖p.2 - p.1‖ by rw [closure_prod_eq] at this intro y y_in apply this ⟨x, y⟩ have : B ∩ closure s ⊆ closure (B ∩ s) := isOpen_ball.inter_closure exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ this : ∀ (p : E × E), p ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ ⊢ ∀ (y : E), y ∈ B ∩ closure s → ‖f y - f x - (↑f' y - ↑f' x)‖ ≤ ε * ‖y - x‖ [PROOFSTEP] rw [closure_prod_eq] at this [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ this : ∀ (p : E × E), p ∈ closure (B ∩ s) ×ˢ closure (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ ⊢ ∀ (y : E), y ∈ B ∩ closure s → ‖f y - f x - (↑f' y - ↑f' x)‖ ≤ ε * ‖y - x‖ [PROOFSTEP] intro y y_in [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ this : ∀ (p : E × E), p ∈ closure (B ∩ s) ×ˢ closure (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ y : E y_in : y ∈ B ∩ closure s ⊢ ‖f y - f x - (↑f' y - ↑f' x)‖ ≤ ε * ‖y - x‖ [PROOFSTEP] apply this ⟨x, y⟩ [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ this : ∀ (p : E × E), p ∈ closure (B ∩ s) ×ˢ closure (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ y : E y_in : y ∈ B ∩ closure s ⊢ (x, y) ∈ closure (B ∩ s) ×ˢ closure (B ∩ s) [PROOFSTEP] have : B ∩ closure s ⊆ closure (B ∩ s) := isOpen_ball.inter_closure [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ this✝ : ∀ (p : E × E), p ∈ closure (B ∩ s) ×ˢ closure (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ y : E y_in : y ∈ B ∩ closure s this : B ∩ closure s ⊆ closure (B ∩ s) ⊢ (x, y) ∈ closure (B ∩ s) ×ˢ closure (B ∩ s) [PROOFSTEP] exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ [GOAL] case this E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ ⊢ ∀ (p : E × E), p ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ [PROOFSTEP] have key : ∀ p : E × E, p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.2 - f p.1 - (f' p.2 - f' p.1)‖ ≤ ε * ‖p.2 - p.1‖ := by rintro ⟨u, v⟩ ⟨u_in, v_in⟩ have conv : Convex ℝ (B ∩ s) := (convex_ball _ _).inter s_conv have diff : DifferentiableOn ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _) have bound : ∀ z ∈ B ∩ s, ‖fderivWithin ℝ f (B ∩ s) z - f'‖ ≤ ε := by intro z z_in have h := hδ z have : fderivWithin ℝ f (B ∩ s) z = fderiv ℝ f z := by have op : IsOpen (B ∩ s) := isOpen_ball.inter s_open rw [DifferentiableAt.fderivWithin _ (op.uniqueDiffOn z z_in)] exact (diff z z_in).differentiableAt (IsOpen.mem_nhds op z_in) rw [← this] at h exact (le_of_lt (h z_in.2 z_in.1)) simpa using conv.norm_image_sub_le_of_norm_fderivWithin_le' diff bound u_in v_in [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ ⊢ ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ [PROOFSTEP] rintro ⟨u, v⟩ ⟨u_in, v_in⟩ [GOAL] case mk.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s ⊢ ‖f (u, v).snd - f (u, v).fst - (↑f' (u, v).snd - ↑f' (u, v).fst)‖ ≤ ε * ‖(u, v).snd - (u, v).fst‖ [PROOFSTEP] have conv : Convex ℝ (B ∩ s) := (convex_ball _ _).inter s_conv [GOAL] case mk.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) ⊢ ‖f (u, v).snd - f (u, v).fst - (↑f' (u, v).snd - ↑f' (u, v).fst)‖ ≤ ε * ‖(u, v).snd - (u, v).fst‖ [PROOFSTEP] have diff : DifferentiableOn ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _) [GOAL] case mk.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) ⊢ ‖f (u, v).snd - f (u, v).fst - (↑f' (u, v).snd - ↑f' (u, v).fst)‖ ≤ ε * ‖(u, v).snd - (u, v).fst‖ [PROOFSTEP] have bound : ∀ z ∈ B ∩ s, ‖fderivWithin ℝ f (B ∩ s) z - f'‖ ≤ ε := by intro z z_in have h := hδ z have : fderivWithin ℝ f (B ∩ s) z = fderiv ℝ f z := by have op : IsOpen (B ∩ s) := isOpen_ball.inter s_open rw [DifferentiableAt.fderivWithin _ (op.uniqueDiffOn z z_in)] exact (diff z z_in).differentiableAt (IsOpen.mem_nhds op z_in) rw [← this] at h exact (le_of_lt (h z_in.2 z_in.1)) [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) ⊢ ∀ (z : E), z ∈ B ∩ s → ‖fderivWithin ℝ f (B ∩ s) z - f'‖ ≤ ε [PROOFSTEP] intro z z_in [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) z : E z_in : z ∈ B ∩ s ⊢ ‖fderivWithin ℝ f (B ∩ s) z - f'‖ ≤ ε [PROOFSTEP] have h := hδ z [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h✝ : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) z : E z_in : z ∈ B ∩ s h : z ∈ s → dist z x < δ → ‖fderiv ℝ f z - f'‖ < ε ⊢ ‖fderivWithin ℝ f (B ∩ s) z - f'‖ ≤ ε [PROOFSTEP] have : fderivWithin ℝ f (B ∩ s) z = fderiv ℝ f z := by have op : IsOpen (B ∩ s) := isOpen_ball.inter s_open rw [DifferentiableAt.fderivWithin _ (op.uniqueDiffOn z z_in)] exact (diff z z_in).differentiableAt (IsOpen.mem_nhds op z_in) [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h✝ : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) z : E z_in : z ∈ B ∩ s h : z ∈ s → dist z x < δ → ‖fderiv ℝ f z - f'‖ < ε ⊢ fderivWithin ℝ f (B ∩ s) z = fderiv ℝ f z [PROOFSTEP] have op : IsOpen (B ∩ s) := isOpen_ball.inter s_open [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h✝ : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) z : E z_in : z ∈ B ∩ s h : z ∈ s → dist z x < δ → ‖fderiv ℝ f z - f'‖ < ε op : IsOpen (B ∩ s) ⊢ fderivWithin ℝ f (B ∩ s) z = fderiv ℝ f z [PROOFSTEP] rw [DifferentiableAt.fderivWithin _ (op.uniqueDiffOn z z_in)] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h✝ : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) z : E z_in : z ∈ B ∩ s h : z ∈ s → dist z x < δ → ‖fderiv ℝ f z - f'‖ < ε op : IsOpen (B ∩ s) ⊢ DifferentiableAt ℝ f z [PROOFSTEP] exact (diff z z_in).differentiableAt (IsOpen.mem_nhds op z_in) [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h✝ : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) z : E z_in : z ∈ B ∩ s h : z ∈ s → dist z x < δ → ‖fderiv ℝ f z - f'‖ < ε this : fderivWithin ℝ f (B ∩ s) z = fderiv ℝ f z ⊢ ‖fderivWithin ℝ f (B ∩ s) z - f'‖ ≤ ε [PROOFSTEP] rw [← this] at h [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h✝ : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) z : E z_in : z ∈ B ∩ s h : z ∈ s → dist z x < δ → ‖fderivWithin ℝ f (B ∩ s) z - f'‖ < ε this : fderivWithin ℝ f (B ∩ s) z = fderiv ℝ f z ⊢ ‖fderivWithin ℝ f (B ∩ s) z - f'‖ ≤ ε [PROOFSTEP] exact (le_of_lt (h z_in.2 z_in.1)) [GOAL] case mk.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ u v : E u_in : (u, v).fst ∈ B ∩ s v_in : (u, v).snd ∈ B ∩ s conv : Convex ℝ (B ∩ s) diff : DifferentiableOn ℝ f (B ∩ s) bound : ∀ (z : E), z ∈ B ∩ s → ‖fderivWithin ℝ f (B ∩ s) z - f'‖ ≤ ε ⊢ ‖f (u, v).snd - f (u, v).fst - (↑f' (u, v).snd - ↑f' (u, v).fst)‖ ≤ ε * ‖(u, v).snd - (u, v).fst‖ [PROOFSTEP] simpa using conv.norm_image_sub_le_of_norm_fderivWithin_le' diff bound u_in v_in [GOAL] case this E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ ⊢ ∀ (p : E × E), p ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ [PROOFSTEP] rintro ⟨u, v⟩ uv_in [GOAL] case this.mk E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) ⊢ ‖f (u, v).snd - f (u, v).fst - (↑f' (u, v).snd - ↑f' (u, v).fst)‖ ≤ ε * ‖(u, v).snd - (u, v).fst‖ [PROOFSTEP] refine' ContinuousWithinAt.closure_le uv_in _ _ key [GOAL] case this.mk.refine'_1 E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) ⊢ ContinuousWithinAt (fun y => ‖f y.snd - f y.fst - (↑f' y.snd - ↑f' y.fst)‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) case this.mk.refine'_2 E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) ⊢ ContinuousWithinAt (fun y => ε * ‖y.snd - y.fst‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) [PROOFSTEP] have f_cont' : ∀ y ∈ closure s, ContinuousWithinAt (f - ⇑f') s y := by intro y y_in exact Tendsto.sub (f_cont y y_in) f'.cont.continuousWithinAt [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) ⊢ ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y [PROOFSTEP] intro y y_in [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) y : E y_in : y ∈ closure s ⊢ ContinuousWithinAt (f - ↑f') s y [PROOFSTEP] exact Tendsto.sub (f_cont y y_in) f'.cont.continuousWithinAt [GOAL] case this.mk.refine'_1 E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y ⊢ ContinuousWithinAt (fun y => ‖f y.snd - f y.fst - (↑f' y.snd - ↑f' y.fst)‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) case this.mk.refine'_2 E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) ⊢ ContinuousWithinAt (fun y => ε * ‖y.snd - y.fst‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) [PROOFSTEP] all_goals -- common start for both continuity proofs have : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s := by mono <;> exact inter_subset_right _ _ obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s := by simpa [closure_prod_eq] using closure_mono this uv_in apply ContinuousWithinAt.mono _ this simp only [ContinuousWithinAt] [GOAL] case this.mk.refine'_1 E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y ⊢ ContinuousWithinAt (fun y => ‖f y.snd - f y.fst - (↑f' y.snd - ↑f' y.fst)‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) [PROOFSTEP] have : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s := by mono <;> exact inter_subset_right _ _ [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y ⊢ (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s [PROOFSTEP] mono [GOAL] case hs E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y ⊢ B ∩ s ⊆ s [PROOFSTEP] exact inter_subset_right _ _ [GOAL] case ht E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y ⊢ B ∩ s ⊆ s [PROOFSTEP] exact inter_subset_right _ _ [GOAL] case this.mk.refine'_1 E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s ⊢ ContinuousWithinAt (fun y => ‖f y.snd - f y.fst - (↑f' y.snd - ↑f' y.fst)‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) [PROOFSTEP] obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s := by simpa [closure_prod_eq] using closure_mono this uv_in [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s ⊢ u ∈ closure s ∧ v ∈ closure s [PROOFSTEP] simpa [closure_prod_eq] using closure_mono this uv_in [GOAL] case this.mk.refine'_1.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ ContinuousWithinAt (fun y => ‖f y.snd - f y.fst - (↑f' y.snd - ↑f' y.fst)‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) [PROOFSTEP] apply ContinuousWithinAt.mono _ this [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ ContinuousWithinAt (fun y => ‖f y.snd - f y.fst - (↑f' y.snd - ↑f' y.fst)‖) (s ×ˢ s) (u, v) [PROOFSTEP] simp only [ContinuousWithinAt] [GOAL] case this.mk.refine'_2 E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) ⊢ ContinuousWithinAt (fun y => ε * ‖y.snd - y.fst‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) [PROOFSTEP] have : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s := by mono <;> exact inter_subset_right _ _ [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) ⊢ (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s [PROOFSTEP] mono [GOAL] case hs E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) ⊢ B ∩ s ⊆ s [PROOFSTEP] exact inter_subset_right _ _ [GOAL] case ht E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) ⊢ B ∩ s ⊆ s [PROOFSTEP] exact inter_subset_right _ _ [GOAL] case this.mk.refine'_2 E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s ⊢ ContinuousWithinAt (fun y => ε * ‖y.snd - y.fst‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) [PROOFSTEP] obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s := by simpa [closure_prod_eq] using closure_mono this uv_in [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s ⊢ u ∈ closure s ∧ v ∈ closure s [PROOFSTEP] simpa [closure_prod_eq] using closure_mono this uv_in [GOAL] case this.mk.refine'_2.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ ContinuousWithinAt (fun y => ε * ‖y.snd - y.fst‖) ((B ∩ s) ×ˢ (B ∩ s)) (u, v) [PROOFSTEP] apply ContinuousWithinAt.mono _ this [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ ContinuousWithinAt (fun y => ε * ‖y.snd - y.fst‖) (s ×ˢ s) (u, v) [PROOFSTEP] simp only [ContinuousWithinAt] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ Tendsto (fun y => ‖f y.snd - f y.fst - (↑f' y.snd - ↑f' y.fst)‖) (𝓝[s ×ˢ s] (u, v)) (𝓝 ‖f v - f u - (↑f' v - ↑f' u)‖) E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ Tendsto (fun y => ε * ‖y.snd - y.fst‖) (𝓝[s ×ˢ s] (u, v)) (𝓝 (ε * ‖v - u‖)) [PROOFSTEP] rw [nhdsWithin_prod_eq] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ Tendsto (fun y => ‖f y.snd - f y.fst - (↑f' y.snd - ↑f' y.fst)‖) (𝓝[s] u ×ˢ 𝓝[s] v) (𝓝 ‖f v - f u - (↑f' v - ↑f' u)‖) [PROOFSTEP] have : ∀ u v, f v - f u - (f' v - f' u) = f v - f' v - (f u - f' u) := by intros; abel [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ ∀ (u v : E), f v - f u - (↑f' v - ↑f' u) = f v - ↑f' v - (f u - ↑f' u) [PROOFSTEP] intros [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s u✝ v✝ : E ⊢ f v✝ - f u✝ - (↑f' v✝ - ↑f' u✝) = f v✝ - ↑f' v✝ - (f u✝ - ↑f' u✝) [PROOFSTEP] abel [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s u✝ v✝ : E ⊢ f v✝ - f u✝ - (↑f' v✝ - ↑f' u✝) = f v✝ - ↑f' v✝ - (f u✝ - ↑f' u✝) [PROOFSTEP] abel [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this✝ : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s this : ∀ (u v : E), f v - f u - (↑f' v - ↑f' u) = f v - ↑f' v - (f u - ↑f' u) ⊢ Tendsto (fun y => ‖f y.snd - f y.fst - (↑f' y.snd - ↑f' y.fst)‖) (𝓝[s] u ×ˢ 𝓝[s] v) (𝓝 ‖f v - f u - (↑f' v - ↑f' u)‖) [PROOFSTEP] simp only [this] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) f_cont' : ∀ (y : E), y ∈ closure s → ContinuousWithinAt (f - ↑f') s y this✝ : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s this : ∀ (u v : E), f v - f u - (↑f' v - ↑f' u) = f v - ↑f' v - (f u - ↑f' u) ⊢ Tendsto (fun y => ‖f y.snd - ↑f' y.snd - (f y.fst - ↑f' y.fst)‖) (𝓝[s] u ×ˢ 𝓝[s] v) (𝓝 ‖f v - ↑f' v - (f u - ↑f' u)‖) [PROOFSTEP] exact Tendsto.comp continuous_norm.continuousAt ((Tendsto.comp (f_cont' v v_in) tendsto_snd).sub <| Tendsto.comp (f_cont' u u_in) tendsto_fst) [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ Tendsto (fun y => ε * ‖y.snd - y.fst‖) (𝓝[s ×ˢ s] (u, v)) (𝓝 (ε * ‖v - u‖)) [PROOFSTEP] apply tendsto_nhdsWithin_of_tendsto_nhds [GOAL] case h E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ Tendsto (fun y => ε * ‖y.snd - y.fst‖) (𝓝 (u, v)) (𝓝 (ε * ‖v - u‖)) [PROOFSTEP] rw [nhds_prod_eq] [GOAL] case h E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f : E → F s : Set E x : E f' : E →L[ℝ] F f_diff : DifferentiableOn ℝ f s s_conv : Convex ℝ s s_open : IsOpen s f_cont : ∀ (y : E), y ∈ closure s → ContinuousWithinAt f s y h : Tendsto (fun y => fderiv ℝ f y) (𝓝[s] x) (𝓝 f') hx : x ∈ closure s ε : ℝ ε_pos : 0 < ε δ : ℝ δ_pos : δ > 0 hδ : ∀ (y : E), y ∈ s → dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε B : Set E := ball x δ key : ∀ (p : E × E), p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.snd - f p.fst - (↑f' p.snd - ↑f' p.fst)‖ ≤ ε * ‖p.snd - p.fst‖ u v : E uv_in : (u, v) ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) this : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s u_in : u ∈ closure s v_in : v ∈ closure s ⊢ Tendsto (fun y => ε * ‖y.snd - y.fst‖) (𝓝 u ×ˢ 𝓝 v) (𝓝 (ε * ‖v - u‖)) [PROOFSTEP] exact tendsto_const_nhds.mul (Tendsto.comp continuous_norm.continuousAt <| tendsto_snd.sub tendsto_fst) [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] obtain ⟨b, ab : a < b, sab : Ioc a b ⊆ s⟩ := mem_nhdsWithin_Ioi_iff_exists_Ioc_subset.1 hs [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] let t := Ioo a b [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] have ts : t ⊆ s := Subset.trans Ioo_subset_Ioc_self sab [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] have t_diff : DifferentiableOn ℝ f t := f_diff.mono ts [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] have t_conv : Convex ℝ t := convex_Ioo a b [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] have t_open : IsOpen t := isOpen_Ioo [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] have t_closure : closure t = Icc a b := closure_Ioo ab.ne [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] have t_cont : ∀ y ∈ closure t, ContinuousWithinAt f t y := by rw [t_closure] intro y hy by_cases h : y = a · rw [h]; exact f_lim.mono ts · have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (Ne.symm h), hy.2⟩ exact (f_diff.continuousOn y this).mono ts [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b ⊢ ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y [PROOFSTEP] rw [t_closure] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b ⊢ ∀ (y : ℝ), y ∈ Icc a b → ContinuousWithinAt f t y [PROOFSTEP] intro y hy [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b y : ℝ hy : y ∈ Icc a b ⊢ ContinuousWithinAt f t y [PROOFSTEP] by_cases h : y = a [GOAL] case pos E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b y : ℝ hy : y ∈ Icc a b h : y = a ⊢ ContinuousWithinAt f t y [PROOFSTEP] rw [h] [GOAL] case pos E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b y : ℝ hy : y ∈ Icc a b h : y = a ⊢ ContinuousWithinAt f t a [PROOFSTEP] exact f_lim.mono ts [GOAL] case neg E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b y : ℝ hy : y ∈ Icc a b h : ¬y = a ⊢ ContinuousWithinAt f t y [PROOFSTEP] have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (Ne.symm h), hy.2⟩ [GOAL] case neg E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b y : ℝ hy : y ∈ Icc a b h : ¬y = a this : y ∈ s ⊢ ContinuousWithinAt f t y [PROOFSTEP] exact (f_diff.continuousOn y this).mono ts [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] have t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) := by simp only [deriv_fderiv.symm] exact Tendsto.comp (isBoundedBilinearMap_smulRight : IsBoundedBilinearMap ℝ _).continuous_right.continuousAt (tendsto_nhdsWithin_mono_left Ioo_subset_Ioi_self f_lim') -- now we can apply `has_fderiv_at_boundary_of_differentiable` [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y ⊢ Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) [PROOFSTEP] simp only [deriv_fderiv.symm] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y ⊢ Tendsto (fun x => smulRight 1 (deriv f x)) (𝓝[Ioo a b] a) (𝓝 (smulRight 1 e)) [PROOFSTEP] exact Tendsto.comp (isBoundedBilinearMap_smulRight : IsBoundedBilinearMap ℝ _).continuous_right.continuousAt (tendsto_nhdsWithin_mono_left Ioo_subset_Ioi_self f_lim') -- now we can apply `has_fderiv_at_boundary_of_differentiable` [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] have : HasDerivWithinAt f e (Icc a b) a := by rw [hasDerivWithinAt_iff_hasFDerivWithinAt, ← t_closure] exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) ⊢ HasDerivWithinAt f e (Icc a b) a [PROOFSTEP] rw [hasDerivWithinAt_iff_hasFDerivWithinAt, ← t_closure] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) ⊢ HasFDerivWithinAt f (smulRight 1 e) (closure t) a [PROOFSTEP] exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Ioi a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Ioi a] a) (𝓝 e) b : ℝ ab : a < b sab : Ioc a b ⊆ s t : Set ℝ := Ioo a b ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc a b t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) this : HasDerivWithinAt f e (Icc a b) a ⊢ HasDerivWithinAt f e (Ici a) a [PROOFSTEP] exact this.nhdsWithin (Icc_mem_nhdsWithin_Ici <| left_mem_Ico.2 ab) [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] obtain ⟨b, ba, sab⟩ : ∃ b ∈ Iio a, Ico b a ⊆ s := mem_nhdsWithin_Iio_iff_exists_Ico_subset.1 hs [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] let t := Ioo b a [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] have ts : t ⊆ s := Subset.trans Ioo_subset_Ico_self sab [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] have t_diff : DifferentiableOn ℝ f t := f_diff.mono ts [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] have t_conv : Convex ℝ t := convex_Ioo b a [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] have t_open : IsOpen t := isOpen_Ioo [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] have t_closure : closure t = Icc b a := closure_Ioo (ne_of_lt ba) [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] have t_cont : ∀ y ∈ closure t, ContinuousWithinAt f t y := by rw [t_closure] intro y hy by_cases h : y = a · rw [h]; exact f_lim.mono ts · have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩ exact (f_diff.continuousOn y this).mono ts [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a ⊢ ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y [PROOFSTEP] rw [t_closure] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a ⊢ ∀ (y : ℝ), y ∈ Icc b a → ContinuousWithinAt f t y [PROOFSTEP] intro y hy [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a y : ℝ hy : y ∈ Icc b a ⊢ ContinuousWithinAt f t y [PROOFSTEP] by_cases h : y = a [GOAL] case pos E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a y : ℝ hy : y ∈ Icc b a h : y = a ⊢ ContinuousWithinAt f t y [PROOFSTEP] rw [h] [GOAL] case pos E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a y : ℝ hy : y ∈ Icc b a h : y = a ⊢ ContinuousWithinAt f t a [PROOFSTEP] exact f_lim.mono ts [GOAL] case neg E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a y : ℝ hy : y ∈ Icc b a h : ¬y = a ⊢ ContinuousWithinAt f t y [PROOFSTEP] have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩ [GOAL] case neg E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a y : ℝ hy : y ∈ Icc b a h : ¬y = a this : y ∈ s ⊢ ContinuousWithinAt f t y [PROOFSTEP] exact (f_diff.continuousOn y this).mono ts [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] have t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) := by simp only [deriv_fderiv.symm] exact Tendsto.comp (isBoundedBilinearMap_smulRight : IsBoundedBilinearMap ℝ _).continuous_right.continuousAt (tendsto_nhdsWithin_mono_left Ioo_subset_Iio_self f_lim') -- now we can apply `has_fderiv_at_boundary_of_differentiable` [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y ⊢ Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) [PROOFSTEP] simp only [deriv_fderiv.symm] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y ⊢ Tendsto (fun x => smulRight 1 (deriv f x)) (𝓝[Ioo b a] a) (𝓝 (smulRight 1 e)) [PROOFSTEP] exact Tendsto.comp (isBoundedBilinearMap_smulRight : IsBoundedBilinearMap ℝ _).continuous_right.continuousAt (tendsto_nhdsWithin_mono_left Ioo_subset_Iio_self f_lim') -- now we can apply `has_fderiv_at_boundary_of_differentiable` [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] have : HasDerivWithinAt f e (Icc b a) a := by rw [hasDerivWithinAt_iff_hasFDerivWithinAt, ← t_closure] exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) ⊢ HasDerivWithinAt f e (Icc b a) a [PROOFSTEP] rw [hasDerivWithinAt_iff_hasFDerivWithinAt, ← t_closure] [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) ⊢ HasFDerivWithinAt f (smulRight 1 e) (closure t) a [PROOFSTEP] exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' [GOAL] case intro.intro E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F s : Set ℝ e : E a : ℝ f : ℝ → E f_diff : DifferentiableOn ℝ f s f_lim : ContinuousWithinAt f s a hs : s ∈ 𝓝[Iio a] a f_lim' : Tendsto (fun x => deriv f x) (𝓝[Iio a] a) (𝓝 e) b : ℝ ba : b ∈ Iio a sab : Ico b a ⊆ s t : Set ℝ := Ioo b a ts : t ⊆ s t_diff : DifferentiableOn ℝ f t t_conv : Convex ℝ t t_open : IsOpen t t_closure : closure t = Icc b a t_cont : ∀ (y : ℝ), y ∈ closure t → ContinuousWithinAt f t y t_diff' : Tendsto (fun x => fderiv ℝ f x) (𝓝[t] a) (𝓝 (smulRight 1 e)) this : HasDerivWithinAt f e (Icc b a) a ⊢ HasDerivWithinAt f e (Iic a) a [PROOFSTEP] exact this.nhdsWithin (Icc_mem_nhdsWithin_Iic <| right_mem_Ioc.2 ba) [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x ⊢ HasDerivAt f (g x) x [PROOFSTEP] have A : HasDerivWithinAt f (g x) (Ici x) x := by have diff : DifferentiableOn ℝ f (Ioi x) := fun y hy => (f_diff y (ne_of_gt hy)).differentiableAt.differentiableWithinAt apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff hf.continuousWithinAt self_mem_nhdsWithin have : Tendsto g (𝓝[>] x) (𝓝 (g x)) := tendsto_inf_left hg apply this.congr' _ apply mem_of_superset self_mem_nhdsWithin fun y hy => _ intros y hy exact (f_diff y (ne_of_gt hy)).deriv.symm [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x ⊢ HasDerivWithinAt f (g x) (Ici x) x [PROOFSTEP] have diff : DifferentiableOn ℝ f (Ioi x) := fun y hy => (f_diff y (ne_of_gt hy)).differentiableAt.differentiableWithinAt [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x diff : DifferentiableOn ℝ f (Ioi x) ⊢ HasDerivWithinAt f (g x) (Ici x) x [PROOFSTEP] apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff hf.continuousWithinAt self_mem_nhdsWithin [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x diff : DifferentiableOn ℝ f (Ioi x) ⊢ Tendsto (fun x => deriv f x) (𝓝[Ioi x] x) (𝓝 (g x)) [PROOFSTEP] have : Tendsto g (𝓝[>] x) (𝓝 (g x)) := tendsto_inf_left hg [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x diff : DifferentiableOn ℝ f (Ioi x) this : Tendsto g (𝓝[Ioi x] x) (𝓝 (g x)) ⊢ Tendsto (fun x => deriv f x) (𝓝[Ioi x] x) (𝓝 (g x)) [PROOFSTEP] apply this.congr' _ [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x diff : DifferentiableOn ℝ f (Ioi x) this : Tendsto g (𝓝[Ioi x] x) (𝓝 (g x)) ⊢ g =ᶠ[𝓝[Ioi x] x] fun x => deriv f x [PROOFSTEP] apply mem_of_superset self_mem_nhdsWithin fun y hy => _ [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x diff : DifferentiableOn ℝ f (Ioi x) this : Tendsto g (𝓝[Ioi x] x) (𝓝 (g x)) ⊢ ∀ (y : ℝ), y ∈ Ioi x → y ∈ {x | (fun x => g x = (fun x => deriv f x) x) x} [PROOFSTEP] intros y hy [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x diff : DifferentiableOn ℝ f (Ioi x) this : Tendsto g (𝓝[Ioi x] x) (𝓝 (g x)) y : ℝ hy : y ∈ Ioi x ⊢ y ∈ {x | (fun x => g x = (fun x => deriv f x) x) x} [PROOFSTEP] exact (f_diff y (ne_of_gt hy)).deriv.symm [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x A : HasDerivWithinAt f (g x) (Ici x) x ⊢ HasDerivAt f (g x) x [PROOFSTEP] have B : HasDerivWithinAt f (g x) (Iic x) x := by have diff : DifferentiableOn ℝ f (Iio x) := fun y hy => (f_diff y (ne_of_lt hy)).differentiableAt.differentiableWithinAt apply has_deriv_at_interval_right_endpoint_of_tendsto_deriv diff hf.continuousWithinAt self_mem_nhdsWithin have : Tendsto g (𝓝[<] x) (𝓝 (g x)) := tendsto_inf_left hg apply this.congr' _ apply mem_of_superset self_mem_nhdsWithin fun y hy => _ intros y hy exact (f_diff y (ne_of_lt hy)).deriv.symm [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x A : HasDerivWithinAt f (g x) (Ici x) x ⊢ HasDerivWithinAt f (g x) (Iic x) x [PROOFSTEP] have diff : DifferentiableOn ℝ f (Iio x) := fun y hy => (f_diff y (ne_of_lt hy)).differentiableAt.differentiableWithinAt [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x A : HasDerivWithinAt f (g x) (Ici x) x diff : DifferentiableOn ℝ f (Iio x) ⊢ HasDerivWithinAt f (g x) (Iic x) x [PROOFSTEP] apply has_deriv_at_interval_right_endpoint_of_tendsto_deriv diff hf.continuousWithinAt self_mem_nhdsWithin [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x A : HasDerivWithinAt f (g x) (Ici x) x diff : DifferentiableOn ℝ f (Iio x) ⊢ Tendsto (fun x => deriv f x) (𝓝[Iio x] x) (𝓝 (g x)) [PROOFSTEP] have : Tendsto g (𝓝[<] x) (𝓝 (g x)) := tendsto_inf_left hg [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x A : HasDerivWithinAt f (g x) (Ici x) x diff : DifferentiableOn ℝ f (Iio x) this : Tendsto g (𝓝[Iio x] x) (𝓝 (g x)) ⊢ Tendsto (fun x => deriv f x) (𝓝[Iio x] x) (𝓝 (g x)) [PROOFSTEP] apply this.congr' _ [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x A : HasDerivWithinAt f (g x) (Ici x) x diff : DifferentiableOn ℝ f (Iio x) this : Tendsto g (𝓝[Iio x] x) (𝓝 (g x)) ⊢ g =ᶠ[𝓝[Iio x] x] fun x => deriv f x [PROOFSTEP] apply mem_of_superset self_mem_nhdsWithin fun y hy => _ [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x A : HasDerivWithinAt f (g x) (Ici x) x diff : DifferentiableOn ℝ f (Iio x) this : Tendsto g (𝓝[Iio x] x) (𝓝 (g x)) ⊢ ∀ (y : ℝ), y ∈ Iio x → y ∈ {x | (fun x => g x = (fun x => deriv f x) x) x} [PROOFSTEP] intros y hy [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x A : HasDerivWithinAt f (g x) (Ici x) x diff : DifferentiableOn ℝ f (Iio x) this : Tendsto g (𝓝[Iio x] x) (𝓝 (g x)) y : ℝ hy : y ∈ Iio x ⊢ y ∈ {x | (fun x => g x = (fun x => deriv f x) x) x} [PROOFSTEP] exact (f_diff y (ne_of_lt hy)).deriv.symm [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x A : HasDerivWithinAt f (g x) (Ici x) x B : HasDerivWithinAt f (g x) (Iic x) x ⊢ HasDerivAt f (g x) x [PROOFSTEP] simpa using B.union A [GOAL] E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x y : ℝ ⊢ HasDerivAt f (g y) y [PROOFSTEP] rcases eq_or_ne y x with (rfl | hne) [GOAL] case inl E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E y : ℝ f_diff : ∀ (y_1 : ℝ), y_1 ≠ y → HasDerivAt f (g y_1) y_1 hf : ContinuousAt f y hg : ContinuousAt g y ⊢ HasDerivAt f (g y) y [PROOFSTEP] exact hasDerivAt_of_hasDerivAt_of_ne f_diff hf hg [GOAL] case inr E : Type u_1 inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E F : Type u_2 inst✝¹ : NormedAddCommGroup F inst✝ : NormedSpace ℝ F f g : ℝ → E x : ℝ f_diff : ∀ (y : ℝ), y ≠ x → HasDerivAt f (g y) y hf : ContinuousAt f x hg : ContinuousAt g x y : ℝ hne : y ≠ x ⊢ HasDerivAt f (g y) y [PROOFSTEP] exact f_diff y hne
{"mathlib_filename": "Mathlib.Analysis.Calculus.FDeriv.Extend", "llama_tokens": 51779}
#!/usr/bin/env python # -*- coding: utf-8 -*- # this file is from https://github.com/ucbdrive/dla/blob/master/dla.py. import math from os.path import join import numpy as np import torch from torch import nn import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import fvcore.nn.weight_init as weight_init from detectron2.modeling.backbone import FPN from detectron2.layers import ShapeSpec, ModulatedDeformConv, Conv2d from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers.batch_norm import get_norm from detectron2.modeling.backbone import Backbone WEB_ROOT = 'http://dl.yf.io/dla/models' def get_model_url(data, name, hash): return join( 'http://dl.yf.io/dla/models', data, '{}-{}.pth'.format(name, hash)) def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation) self.bn1 = get_norm(cfg.MODEL.DLA.NORM, planes) self.relu = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=dilation, bias=False, dilation=dilation) self.bn2 = get_norm(cfg.MODEL.DLA.NORM, planes) self.stride = stride def forward(self, x, residual=None): if residual is None: residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out += residual out = self.relu(out) return out class Bottleneck(nn.Module): expansion = 2 def __init__(self, cfg, inplanes, planes, stride=1, dilation=1): super(Bottleneck, self).__init__() expansion = Bottleneck.expansion bottle_planes = planes // expansion self.conv1 = nn.Conv2d(inplanes, bottle_planes, kernel_size=1, bias=False) self.bn1 = get_norm(cfg.MODEL.DLA.NORM, bottle_planes) self.conv2 = nn.Conv2d(bottle_planes, bottle_planes, kernel_size=3, stride=stride, padding=dilation, bias=False, dilation=dilation) self.bn2 = get_norm(cfg.MODEL.DLA.NORM, bottle_planes) self.conv3 = nn.Conv2d(bottle_planes, planes, kernel_size=1, bias=False) self.bn3 = get_norm(cfg.MODEL.DLA.NORM, planes) self.relu = nn.ReLU(inplace=True) self.stride = stride def forward(self, x, residual=None): if residual is None: residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) out += residual out = self.relu(out) return out class Root(nn.Module): def __init__(self, cfg, in_channels, out_channels, kernel_size, residual): super(Root, self).__init__() self.conv = nn.Conv2d( in_channels, out_channels, kernel_size, stride=1, bias=False, padding=(kernel_size - 1) // 2) self.bn = get_norm(cfg.MODEL.DLA.NORM, out_channels) self.relu = nn.ReLU(inplace=True) self.residual = residual def forward(self, *x): children = x x = self.conv(torch.cat(x, 1)) x = self.bn(x) if self.residual: x += children[0] x = self.relu(x) return x class Tree(nn.Module): def __init__(self, cfg, levels, block, in_channels, out_channels, stride=1, level_root=False, root_dim=0, root_kernel_size=1, dilation=1, root_residual=False): super(Tree, self).__init__() if root_dim == 0: root_dim = 2 * out_channels if level_root: root_dim += in_channels if levels == 1: self.tree1 = block(cfg, in_channels, out_channels, stride, dilation=dilation) self.tree2 = block(cfg, out_channels, out_channels, 1, dilation=dilation) else: self.tree1 = Tree(cfg, levels - 1, block, in_channels, out_channels, stride, root_dim=0, root_kernel_size=root_kernel_size, dilation=dilation, root_residual=root_residual) self.tree2 = Tree(cfg, levels - 1, block, out_channels, out_channels, root_dim=root_dim + out_channels, root_kernel_size=root_kernel_size, dilation=dilation, root_residual=root_residual) if levels == 1: self.root = Root(cfg, root_dim, out_channels, root_kernel_size, root_residual) self.level_root = level_root self.root_dim = root_dim self.downsample = None self.project = None self.levels = levels if stride > 1: self.downsample = nn.MaxPool2d(stride, stride=stride) if in_channels != out_channels: self.project = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, bias=False), get_norm(cfg.MODEL.DLA.NORM, out_channels) ) def forward(self, x, residual=None, children=None): if self.training and residual is not None: x = x + residual.sum() * 0.0 children = [] if children is None else children bottom = self.downsample(x) if self.downsample else x residual = self.project(bottom) if self.project else bottom if self.level_root: children.append(bottom) x1 = self.tree1(x, residual) if self.levels == 1: x2 = self.tree2(x1) x = self.root(x2, x1, *children) else: children.append(x1) x = self.tree2(x1, children=children) return x class DLA(Backbone): def __init__(self, cfg, levels, channels, block=BasicBlock, residual_root=False): super(DLA, self).__init__() self.cfg = cfg self.channels = channels self._out_features = ["dla{}".format(i) for i in range(6)] self._out_feature_channels = {k: channels[i] for i, k in enumerate(self._out_features)} self._out_feature_strides = {k: 2 ** i for i, k in enumerate(self._out_features)} self.base_layer = nn.Sequential( nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False), get_norm(cfg.MODEL.DLA.NORM, channels[0]), nn.ReLU(inplace=True)) self.level0 = self._make_conv_level( channels[0], channels[0], levels[0]) self.level1 = self._make_conv_level( channels[0], channels[1], levels[1], stride=2) self.level2 = Tree(cfg, levels[2], block, channels[1], channels[2], 2, level_root=False, root_residual=residual_root) self.level3 = Tree(cfg, levels[3], block, channels[2], channels[3], 2, level_root=True, root_residual=residual_root) self.level4 = Tree(cfg, levels[4], block, channels[3], channels[4], 2, level_root=True, root_residual=residual_root) self.level5 = Tree(cfg, levels[5], block, channels[4], channels[5], 2, level_root=True, root_residual=residual_root) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) self.load_pretrained_model( data='imagenet', name='dla34', hash='ba72cf86') def load_pretrained_model(self, data, name, hash): model_url = get_model_url(data, name, hash) model_weights = model_zoo.load_url(model_url) del model_weights['fc.weight'] del model_weights['fc.bias'] print('Loading pretrained DLA!') self.load_state_dict(model_weights, strict=True) def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1): modules = [] for i in range(convs): modules.extend([ nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride if i == 0 else 1, padding=dilation, bias=False, dilation=dilation), get_norm(self.cfg.MODEL.DLA.NORM, planes), nn.ReLU(inplace=True)]) inplanes = planes return nn.Sequential(*modules) def forward(self, x): y = {} x = self.base_layer(x) for i in range(6): name = 'level{}'.format(i) x = getattr(self, name)(x) y['dla{}'.format(i)] = x return y def fill_up_weights(up): w = up.weight.data f = math.ceil(w.size(2) / 2) c = (2 * f - 1 - f % 2) / (2. * f) for i in range(w.size(2)): for j in range(w.size(3)): w[0, 0, i, j] = \ (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c)) for c in range(1, w.size(0)): w[c, 0, :, :] = w[0, 0, :, :] class Conv(nn.Module): def __init__(self, chi, cho, norm): super(Conv, self).__init__() self.conv = nn.Sequential( nn.Conv2d(chi, cho, kernel_size=1, stride=1, bias=False), get_norm(norm, cho), nn.ReLU(inplace=True)) def forward(self, x): return self.conv(x) class DeformConv(nn.Module): def __init__(self, chi, cho, norm): super(DeformConv, self).__init__() self.actf = nn.Sequential( get_norm(norm, cho), nn.ReLU(inplace=True) ) self.offset = Conv2d( chi, 27, kernel_size=3, stride=1, padding=1, dilation=1) self.conv = ModulatedDeformConv( chi, cho, kernel_size=3, stride=1, padding=1, dilation=1, deformable_groups=1) nn.init.constant_(self.offset.weight, 0) nn.init.constant_(self.offset.bias, 0) def forward(self, x): offset_mask = self.offset(x) offset_x, offset_y, mask = torch.chunk(offset_mask, 3, dim=1) offset = torch.cat((offset_x, offset_y), dim=1) mask = mask.sigmoid() x = self.conv(x, offset, mask) x = self.actf(x) return x class IDAUp(nn.Module): def __init__(self, o, channels, up_f, norm='FrozenBN', node_type=Conv): super(IDAUp, self).__init__() for i in range(1, len(channels)): c = channels[i] f = int(up_f[i]) proj = node_type(c, o, norm) node = node_type(o, o, norm) up = nn.ConvTranspose2d(o, o, f * 2, stride=f, padding=f // 2, output_padding=0, groups=o, bias=False) fill_up_weights(up) setattr(self, 'proj_' + str(i), proj) setattr(self, 'up_' + str(i), up) setattr(self, 'node_' + str(i), node) def forward(self, layers, startp, endp): for i in range(startp + 1, endp): upsample = getattr(self, 'up_' + str(i - startp)) project = getattr(self, 'proj_' + str(i - startp)) layers[i] = upsample(project(layers[i])) node = getattr(self, 'node_' + str(i - startp)) layers[i] = node(layers[i] + layers[i - 1]) DLAUP_NODE_MAP = { 'conv': Conv, 'dcn': DeformConv, } class DLAUP(Backbone): def __init__(self, bottom_up, in_features, norm, dlaup_node='conv'): super(DLAUP, self).__init__() assert isinstance(bottom_up, Backbone) self.bottom_up = bottom_up input_shapes = bottom_up.output_shape() in_strides = [input_shapes[f].stride for f in in_features] in_channels = [input_shapes[f].channels for f in in_features] in_levels = [int(math.log2(input_shapes[f].stride)) for f in in_features] self.in_features = in_features out_features = ['dlaup{}'.format(l) for l in in_levels] self._out_features = out_features self._out_feature_channels = { 'dlaup{}'.format(l): in_channels[i] for i, l in enumerate(in_levels)} self._out_feature_strides = { 'dlaup{}'.format(l): 2 ** l for l in in_levels} print('self._out_features', self._out_features) print('self._out_feature_channels', self._out_feature_channels) print('self._out_feature_strides', self._out_feature_strides) self._size_divisibility = 32 node_type = DLAUP_NODE_MAP[dlaup_node] self.startp = int(math.log2(in_strides[0])) self.channels = in_channels channels = list(in_channels) scales = np.array([2 ** i for i in range(len(out_features))], dtype=int) for i in range(len(channels) - 1): j = -i - 2 setattr(self, 'ida_{}'.format(i), IDAUp(channels[j], in_channels[j:], scales[j:] // scales[j], norm=norm, node_type=node_type)) scales[j + 1:] = scales[j] in_channels[j + 1:] = [channels[j] for _ in channels[j + 1:]] @property def size_divisibility(self): return self._size_divisibility def forward(self, x): bottom_up_features = self.bottom_up(x) layers = [bottom_up_features[f] for f in self.in_features] out = [layers[-1]] # start with 32 for i in range(len(layers) - 1): ida = getattr(self, 'ida_{}'.format(i)) ida(layers, len(layers) - i - 2, len(layers)) out.insert(0, layers[-1]) ret = {} for k, v in zip(self._out_features, out): ret[k] = v # import pdb; pdb.set_trace() return ret def dla34(cfg, pretrained=None): # DLA-34 model = DLA(cfg, [1, 1, 1, 2, 2, 1], [16, 32, 64, 128, 256, 512], block=BasicBlock) return model class LastLevelP6P7(nn.Module): """ This module is used in RetinaNet to generate extra layers, P6 and P7 from C5 feature. """ def __init__(self, in_channels, out_channels): super().__init__() self.num_levels = 2 self.in_feature = "dla5" self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, 1) for module in [self.p6, self.p7]: weight_init.c2_xavier_fill(module) def forward(self, c5): p6 = self.p6(c5) p7 = self.p7(F.relu(p6)) return [p6, p7] @BACKBONE_REGISTRY.register() def build_dla_fpn3_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ depth_to_creator = {"dla34": dla34} bottom_up = depth_to_creator['dla{}'.format(cfg.MODEL.DLA.NUM_LAYERS)](cfg) in_features = cfg.MODEL.FPN.IN_FEATURES out_channels = cfg.MODEL.FPN.OUT_CHANNELS backbone = FPN( bottom_up=bottom_up, in_features=in_features, out_channels=out_channels, norm=cfg.MODEL.FPN.NORM, top_block=None, fuse_type=cfg.MODEL.FPN.FUSE_TYPE, ) return backbone @BACKBONE_REGISTRY.register() def build_dla_fpn5_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ depth_to_creator = {"dla34": dla34} bottom_up = depth_to_creator['dla{}'.format(cfg.MODEL.DLA.NUM_LAYERS)](cfg) in_features = cfg.MODEL.FPN.IN_FEATURES out_channels = cfg.MODEL.FPN.OUT_CHANNELS in_channels_top = bottom_up.output_shape()['dla5'].channels backbone = FPN( bottom_up=bottom_up, in_features=in_features, out_channels=out_channels, norm=cfg.MODEL.FPN.NORM, top_block=LastLevelP6P7(in_channels_top, out_channels), fuse_type=cfg.MODEL.FPN.FUSE_TYPE, ) return backbone @BACKBONE_REGISTRY.register() def build_dlaup_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ depth_to_creator = {"dla34": dla34} bottom_up = depth_to_creator['dla{}'.format(cfg.MODEL.DLA.NUM_LAYERS)](cfg) backbone = DLAUP( bottom_up=bottom_up, in_features=cfg.MODEL.DLA.DLAUP_IN_FEATURES, norm=cfg.MODEL.DLA.NORM, dlaup_node=cfg.MODEL.DLA.DLAUP_NODE, ) return backbone
{"hexsha": "2a33c66bf3d5b97bf882eaf0b80de012151a62b4", "size": 17423, "ext": "py", "lang": "Python", "max_stars_repo_path": "projects/CenterNet2/centernet/modeling/backbone/dlafpn.py", "max_stars_repo_name": "collector-m/CenterNet2", "max_stars_repo_head_hexsha": "68c0a468254b013e1d08309cd7a506756120ca62", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1050, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:06:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:12:10.000Z", "max_issues_repo_path": "projects/CenterNet2/centernet/modeling/backbone/dlafpn.py", "max_issues_repo_name": "collector-m/CenterNet2", "max_issues_repo_head_hexsha": "68c0a468254b013e1d08309cd7a506756120ca62", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 74, "max_issues_repo_issues_event_min_datetime": "2021-03-16T02:37:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T15:52:15.000Z", "max_forks_repo_path": "projects/CenterNet2/centernet/modeling/backbone/dlafpn.py", "max_forks_repo_name": "collector-m/CenterNet2", "max_forks_repo_head_hexsha": "68c0a468254b013e1d08309cd7a506756120ca62", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 168, "max_forks_repo_forks_event_min_datetime": "2021-03-15T02:26:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T09:03:52.000Z", "avg_line_length": 35.2692307692, "max_line_length": 95, "alphanum_fraction": 0.5784308098, "include": true, "reason": "import numpy", "num_tokens": 4357}
import argparse import numpy as np import torch from torch import nn from torch.autograd import Function # https://zhuanlan.zhihu.com/p/359524837 class AddModelFunction(Function): @staticmethod def forward(ctx, a, b, n): c = torch.empty(n).to(device="cuda:0") if args.compiler == 'jit': cuda_module.torch_launch_add2(c, a, b, n) elif args.compiler == 'setup': add2.torch_launch_add2(c, a, b, n) elif args.compiler == 'cmake': torch.ops.add2.torch_launch_add2(c, a, b, n) else: raise Exception("Type of cuda compiler must be one of jit/setup/cmake.") return c @staticmethod def backward(ctx, grad_output): return (grad_output, grad_output, None) class AddModel(nn.Module): def __init__(self, n): super(AddModel, self).__init__() self.n = n self.a = nn.Parameter(torch.Tensor(self.n)) self.b = nn.Parameter(torch.Tensor(self.n)) self.a.data.normal_(mean=0.0, std=1.0) self.b.data.normal_(mean=0.0, std=1.0) def forward(self): a2 = torch.square(self.a) b2 = torch.square(self.b) c = AddModelFunction.apply(a2, b2, self.n) return c if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--compiler', type=str, choices=['jit', 'setup', 'cmake'], default='jit') args = parser.parse_args() if args.compiler == 'jit': from torch.utils.cpp_extension import load cuda_module = load(name="add2", extra_include_paths=["include"], sources=["pytorch/add2_ops.cpp", "kernel/add2_kernel.cu"], verbose=True) elif args.compiler == 'setup': import add2 elif args.compiler == 'cmake': torch.ops.load_library("build/libadd2.so") else: raise Exception("Type of cuda compiler must be one of jit/setup/cmake.") n = 1024 print("Initializing model...") model = AddModel(n) model.to(device="cuda:0") print("Initializing optimizer...") opt = torch.optim.SGD(model.parameters(), lr=0.01) print("Begin training...") for epoch in range(500): opt.zero_grad() output = model() loss = output.sum() loss.backward() opt.step() if epoch % 25 == 0: print("epoch {:>3d}: loss = {:>8.3f}".format(epoch, loss))
{"hexsha": "e25ba968602b69de0dd0db4c2b6660b1c9086220", "size": 2459, "ext": "py", "lang": "Python", "max_stars_repo_path": "pytorch/train.py", "max_stars_repo_name": "yuanzhedong/NN-CUDA-Example", "max_stars_repo_head_hexsha": "15f37a07591d29459abc290173e95aa9918615be", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pytorch/train.py", "max_issues_repo_name": "yuanzhedong/NN-CUDA-Example", "max_issues_repo_head_hexsha": "15f37a07591d29459abc290173e95aa9918615be", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pytorch/train.py", "max_forks_repo_name": "yuanzhedong/NN-CUDA-Example", "max_forks_repo_head_hexsha": "15f37a07591d29459abc290173e95aa9918615be", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1265822785, "max_line_length": 97, "alphanum_fraction": 0.5892639284, "include": true, "reason": "import numpy", "num_tokens": 606}
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~## ## ## ## This file forms part of the Badlands surface processes modelling application. ## ## ## ## For full license and copyright information, please refer to the LICENSE.md file ## ## located at the project root, or contact the authors. ## ## ## ##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~## """ This module defines pelagic evolution in **badlands** simulation based on forcing parameter: **depth**. """ import os import numpy import pandas from scipy.ndimage.filters import gaussian_filter from scipy import interpolate from scipy.spatial import cKDTree class pelagicGrowth: """ This class defines external pelagic growth parameters. Args: input: class containing XML input file parameters. """ def __init__(self, input=None): self.growth = input.pelGrowth self.depthfile = input.pelDepth self.depthval = None self.depthfct = None self.depthFunc = None self.depthgrowth = None if self.depthfile != None: self._build_depth_function() return def _build_depth_function(self): """ Using Pandas library to read the depth control file and define depth interpolation function based on Scipy 1D linear function. """ # Read depth control file depthdata = pandas.read_csv(self.depthfile, sep=r'\s+', engine='c', header=None, na_filter=False, dtype=numpy.float, low_memory=False) self.depthval = numpy.zeros(len(depthdata.values[:,0])+2) self.depthfct = numpy.zeros(len(self.depthval)) self.depthval[1:-1] = depthdata.values[:,0] self.depthfct[1:-1] = depthdata.values[:,1] self.depthval[0] = -1.0e7 self.depthfct[0] = self.depthfct[1] self.depthval[-1] = 1.e7 self.depthfct[-1] = self.depthfct[-2] self.depthFunc = interpolate.interp1d(self.depthval, self.depthfct, kind='linear') return def _getDepthFct(self, depthfield): """ Computes for a given depth field the pelagic growth function. Parameters ---------- depthfield : numpy array containing depth. """ if self.depthfile == None: self.depthgrowth = numpy.zeros(len(depthfield)) else: self.depthgrowth = self.depthFunc(-depthfield) return def computePelagic(self, depthfield, dt): """ Computes pelagic growth. Args: depthfield : numpy array containing depth. dt: pelagic growth time step in years. Returns: - growth - numpy array containing the growth (in metres) of pelagic. """ # Get each controlling function values self._getDepthFct(depthfield) # Average growth function limitation growth = self.growth*self.depthgrowth*dt growth[growth<0.] = 0. return growth
{"hexsha": "16ebd6945c0d1a323ed381040dffe53e61f28f9a", "size": 3373, "ext": "py", "lang": "Python", "max_stars_repo_path": "badlands/badlands/forcing/pelagicGrowth.py", "max_stars_repo_name": "intelligentEarth/surrogateBayeslands", "max_stars_repo_head_hexsha": "24462cafed05ac0c377865d8fe039cafa0aa59d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:54:01.000Z", "max_issues_repo_path": "badlands/badlands/forcing/pelagicGrowth.py", "max_issues_repo_name": "intelligentEarth/surrogateBayeslands", "max_issues_repo_head_hexsha": "24462cafed05ac0c377865d8fe039cafa0aa59d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "badlands/badlands/forcing/pelagicGrowth.py", "max_forks_repo_name": "intelligentEarth/surrogateBayeslands", "max_forks_repo_head_hexsha": "24462cafed05ac0c377865d8fe039cafa0aa59d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1238095238, "max_line_length": 103, "alphanum_fraction": 0.5336495701, "include": true, "reason": "import numpy,from scipy", "num_tokens": 826}
[STATEMENT] lemma bc_mt_corresp_IAdd: " bc_mt_corresp [IAdd] (replST 2 (PrimT Integer)) (PrimT Integer # PrimT Integer # ST, LT) cG rT mxr (Suc 0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. bc_mt_corresp [IAdd] (replST 2 (PrimT Integer)) (PrimT Integer # PrimT Integer # ST, LT) cG rT mxr (Suc 0) [PROOF STEP] apply (simp add: bc_mt_corresp_def replST_def wt_instr_altern_def eff_def norm_eff_def) [PROOF STATE] proof (prove) goal (1 subgoal): 1. check_type cG (Suc (Suc (length ST))) mxr (OK (Some (PrimT Integer # PrimT Integer # ST, LT))) \<longrightarrow> check_type cG (max_ssize [Some (PrimT Integer # PrimT Integer # ST, LT), Some (PrimT Integer # ST, LT)]) mxr (OK (Some (PrimT Integer # PrimT Integer # ST, LT))) \<and> check_type cG (max_ssize [Some (PrimT Integer # PrimT Integer # ST, LT), Some (PrimT Integer # ST, LT)]) mxr (OK (Some (PrimT Integer # ST, LT))) [PROOF STEP] apply (simp add: max_ssize_def max_of_list_def ssize_sto_def) [PROOF STATE] proof (prove) goal (1 subgoal): 1. check_type cG (Suc (Suc (length ST))) mxr (OK (Some (PrimT Integer # PrimT Integer # ST, LT))) \<longrightarrow> check_type cG (Suc (Suc (length ST))) mxr (OK (Some (PrimT Integer # ST, LT))) [PROOF STEP] apply (simp add: check_type_simps max.absorb1) [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>n. PrimT Integer # PrimT Integer # ST \<in> list n (types cG) \<and> n \<le> Suc (Suc (length ST))) \<and> LT \<in> list mxr (err (types cG)) \<longrightarrow> (\<exists>n. PrimT Integer # ST \<in> list n (types cG) \<and> n \<le> Suc (Suc (length ST))) [PROOF STEP] apply clarify [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n n' n'a. \<lbrakk>LT \<in> list mxr (err (types cG)); ST \<in> list n'a (types cG); n'a \<le> length ST; is_type cG (PrimT Integer); is_type cG (PrimT Integer)\<rbrakk> \<Longrightarrow> \<exists>n. PrimT Integer # ST \<in> list n (types cG) \<and> n \<le> Suc (Suc (length ST)) [PROOF STEP] apply (rule_tac x="Suc (length ST)" in exI) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>n n' n'a. \<lbrakk>LT \<in> list mxr (err (types cG)); ST \<in> list n'a (types cG); n'a \<le> length ST; is_type cG (PrimT Integer); is_type cG (PrimT Integer)\<rbrakk> \<Longrightarrow> PrimT Integer # ST \<in> list (Suc (length ST)) (types cG) \<and> Suc (length ST) \<le> Suc (Suc (length ST)) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
{"llama_tokens": 1014, "file": null, "length": 7}
#include "c8-sq-lite/SelectResult.hpp" #include <boost/format.hpp> #include <gmock/gmock.h> #include <stdexcept> namespace C8::SqLite { using namespace testing; class SelectResultTestSuite : public Test { public: void SetUp() override { sut.addColumn("id", 0); sut.addColumn("name", 1); sut.addColumn("value", 2); } SelectResult sut; }; MATCHER_P4( CheckRow, index, id, name, value, boost::str(boost::format("expected { %1%, %2%, %3% }") % id % name % value)) { return arg.at(index, "id") == id && arg.at(index, "name") == name && arg.at(index, "value") == value; } TEST_F(SelectResultTestSuite, testEmptyResult) { ASSERT_TRUE(sut.empty()); ASSERT_THAT(sut, SizeIs(0u)); } TEST_F(SelectResultTestSuite, testFewElements) { sut.push_back({"1", "ted", "dal"}); sut.push_back({"2", "kyra", "shadow"}); sut.push_back({"3", "izzie", "lone"}); ASSERT_FALSE(sut.empty()); ASSERT_THAT(sut, SizeIs(3u)); ASSERT_THAT(sut, CheckRow(0u, "1", "ted", "dal")); ASSERT_THAT(sut, CheckRow(1u, "2", "kyra", "shadow")); ASSERT_THAT(sut, CheckRow(2u, "3", "izzie", "lone")); ASSERT_THROW(sut.at(0, "non-existing"), std::out_of_range); size_t id, value, name; std::tie(id, value, name) = sut.mapColumns("id", "value", "name"); ASSERT_THAT(id, Eq(0)); ASSERT_THAT(value, Eq(2)); ASSERT_THAT(name, Eq(1)); ASSERT_THAT(sut.rows[0][value], Eq("dal")); ASSERT_THAT(sut.rows[1][name], Eq("kyra")); } } // namespace C8::SqLite
{"hexsha": "5dbd9f19ffb46e082f92586c7647de9f81c4189a", "size": 1539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/c8-sq-lite/SelectResultTestSuite.cpp", "max_stars_repo_name": "chaos0x8/cpp-c8", "max_stars_repo_head_hexsha": "f64004e59339a5e3e066128aa75e6a090449b644", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/c8-sq-lite/SelectResultTestSuite.cpp", "max_issues_repo_name": "chaos0x8/cpp-c8", "max_issues_repo_head_hexsha": "f64004e59339a5e3e066128aa75e6a090449b644", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/c8-sq-lite/SelectResultTestSuite.cpp", "max_forks_repo_name": "chaos0x8/cpp-c8", "max_forks_repo_head_hexsha": "f64004e59339a5e3e066128aa75e6a090449b644", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5, "max_line_length": 116, "alphanum_fraction": 0.6114359974, "num_tokens": 472}
#! /usr/bin/env python3 ########################################################### # The example shows how to get mapping data # # The peak ratio at 1315 cm^-1 and 1380 cm^-1 are plotted # # Details see Small 14, 1804006 (2018). # ########################################################### import numpy as np from renishawWiRE import WDFReader from _path import curdir, imgdir try: import matplotlib.pyplot as plt plot = True except ImportError: plot = False def peak_in_range(spectra, wn, range, method="max", **params): """Find the max intensity of peak within range method can be max, min, or mean """ cond = np.where((wn >= range[0]) & (wn <= range[1]))[0] spectra_cut = spectra[:, :, cond] return getattr(np, method)(spectra_cut, axis=2, **params) def main(): filename = curdir / "spectra_files" / "mapping.wdf" reader = WDFReader(filename) assert reader.measurement_type == 3 wn = reader.xdata spectra = reader.spectra print(wn.shape, spectra.shape) x = reader.xpos y = reader.ypos w, h = reader.map_shape print("The size of mapping is {0:d} * {1:d}". format(w, h)) # w and h are the measure in xy coordinates # Level the spectra spectra = spectra - np.min(spectra, axis=2, keepdims=True) peaks_a = peak_in_range(spectra, wn, [1295, 1340]) peaks_b = peak_in_range(spectra, wn, [1350, 1400]) ratio = peaks_a / peaks_b ratio_fl = ratio.flatten() if plot is True: plt.figure(figsize=(10, 5)) # Left plot histogram of Peak A/B ratio plt.subplot(121) plt.hist(ratio_fl, bins=50, range=(0.1, 2)) plt.xlabel("Ratio peak A / peak B") plt.ylabel("Counts") # Right plot histogram of Peak A/B mapping plt.subplot(122) plt.imshow(ratio, interpolation="bicubic", extent=[0, x.max() - x.min(), y.max() - y.min(), 0], vmin=0.5, vmax=1.5) plt.xlabel("Mapping x [μm]") plt.ylabel("Mapping y [μm]") cb = plt.colorbar() cb.ax.set_title("Ratio") plt.tight_layout() plt.show(block=False) plt.pause(3) plt.savefig(imgdir / "mapping.png", dpi=100) plt.close() else: pass return if __name__ == "__main__": main()
{"hexsha": "8a70aebddaee853d32090cf748aea94d45f0b9c8", "size": 2391, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/ex5_mapping.py", "max_stars_repo_name": "lovaulonze/py-wdf-reader", "max_stars_repo_head_hexsha": "f9632eaf35fe51634bdce71dc0a6937e1454707f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-08-24T04:47:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-08T10:47:32.000Z", "max_issues_repo_path": "examples/ex5_mapping.py", "max_issues_repo_name": "lovaulonze/py-wdf-reader", "max_issues_repo_head_hexsha": "f9632eaf35fe51634bdce71dc0a6937e1454707f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-10-02T08:17:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-06T15:32:30.000Z", "max_forks_repo_path": "examples/ex5_mapping.py", "max_forks_repo_name": "lovaulonze/py-wdf-reader", "max_forks_repo_head_hexsha": "f9632eaf35fe51634bdce71dc0a6937e1454707f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-10-09T11:51:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-11T09:23:44.000Z", "avg_line_length": 29.8875, "max_line_length": 62, "alphanum_fraction": 0.5554161439, "include": true, "reason": "import numpy", "num_tokens": 630}
import sys import numpy as np import pandas as pd import requests from epw import epw from datetime import datetime import calendar def download_epw(lat, lon, year, location, attributes, interval, utc, your_name, api_key, reason_for_use, your_affiliation, your_email, mailing_list, leap_year): currentYear = datetime.now().year if int(year) == currentYear: raise Exception("NREL does not provide data for the current year " + str( year) + ". It is also unlikely that there is data availability for " + str(int(year) - 1) + ".") # Declare url string url = 'https://developer.nrel.gov/api/solar/nsrdb_psm3_download.csv?wkt=POINT({lon}%20{lat})&names={year}&leap_day={leap}&interval={interval}&utc={utc}&full_name={name}&email={email}&affiliation={affiliation}&mailing_list={mailing_list}&reason={reason}&api_key={api}&attributes={attr}'.format( year=year, lat=lat, lon=lon, leap=leap_year, interval=interval, utc=utc, name=your_name, email=your_email, mailing_list=mailing_list, affiliation=your_affiliation, reason=reason_for_use, api=api_key, attr=attributes) r = None all_data = None try: r = requests.get(url, timeout=20) r.raise_for_status() # Return just the first 2 lines to get metadata: all_data = pd.read_csv(url) if all_data is None: raise("Could not retrieve any data") except requests.exceptions.HTTPError as errh: print("Http Error:", errh) [print(err) for err in r.json()['errors']] sys.exit("There is an issue with the input url") except requests.exceptions.ConnectionError as errc: print("Error Connecting:", errc) except requests.exceptions.Timeout as errt: print("Timeout Error:", errt) except requests.exceptions.RequestException as err: print("OOps: Something Else", err) hours_per_year = 8760 if calendar.isleap(int(year)) and bool(leap_year) is True and all_data.shape[0] == 8784+2: hours_per_year = 8784 datetimes = pd.date_range('01/01/' + str(year), periods=hours_per_year, freq='H') # Take first row for metadata metadata = all_data.iloc[0, :] # Return all but first 2 lines of csv to get data: df = all_data.iloc[2:, :] df.columns = all_data.iloc[1] # Set the time index in the pandas dataframe: df = df.set_index(datetimes) # See metadata for specified properties, e.g., timezone and elevation timezone = elevation = location_id = "Could not be retrieved from NREL" if metadata is not None: timezone, elevation, location_id = metadata['Local Time Zone'], metadata['Elevation'], metadata['Location ID'] out = epw() out.headers = { 'LOCATION': [location, 'STATE', 'COUNTRY', 'NREL PSM3 SOURCE', 'XXX', lat, lon, timezone, elevation], 'DESIGN CONDITIONS': ['1', 'This is ficticious header data to make the EPW readable', '', 'Heating', '1', '3.8', '4.9', '-3.7', '2.8', '10.7', '-1.2', '3.4', '11.2', '12.9', '12.1', '11.6', '12.2', '2.2', '150', 'Cooling', '8', '8.5', '28.3', '17.2', '25.7', '16.7', '23.6', '16.2', '18.6', '25.7', '17.8', '23.9', '17', '22.4', '5.9', '310', '16.1', '11.5', '19.9', '15.3', '10.9', '19.2', '14.7', '10.4', '18.7', '52.4', '25.8', '49.8', '23.8', '47.6', '22.4', '2038', 'Extremes', '12.8', '11.5', '10.6', '22.3', '1.8', '34.6', '1.5', '2.3', '0.8', '36.2', '-0.1', '37.5', '-0.9', '38.8', '-1.9', '40.5'], 'TYPICAL/EXTREME PERIODS': ['6', 'Summer - Week Nearest Max Temperature For Period', 'Extreme', '8/ 1', '8/ 7', 'Summer - Week Nearest Average Temperature For Period', 'Typical', '9/ 5', '9/11', 'Winter - Week Nearest Min Temperature For Period', 'Extreme', '2/ 1', '2/ 7', 'Winter - Week Nearest Average Temperature For Period', 'Typical', '2/15', '2/21', 'Autumn - Week Nearest Average Temperature For Period', 'Typical', '12/ 6', '12/12', 'Spring - Week Nearest Average Temperature For Period', 'Typical', '5/29', '6/ 4'], 'GROUND TEMPERATURES': ['3', '.5', '', '', '', '10.86', '10.57', '11.08', '11.88', '13.97', '15.58', '16.67', '17.00', '16.44', '15.19', '13.51', '11.96', '2', '', '', '', '11.92', '11.41', '11.51', '11.93', '13.33', '14.60', '15.61', '16.15', '16.03', '15.32', '14.17', '12.95', '4', '', '', '', '12.79', '12.27', '12.15', '12.31', '13.10', '13.96', '14.74', '15.28', '15.41', '15.10', '14.42', '13.60'], 'HOLIDAYS/DAYLIGHT SAVINGS': ['No', '0', '0', '0'], 'COMMENTS 1': ['NREL PSM3 DATA'], 'COMMENTS 2': ['https://bit.ly/NREL--PSM3-2-EPW'], 'DATA PERIODS': ['1', '1', 'Data', 'Sunday', ' 1/ 1', '12/31'] } # Actual file starts here missing_values = np.array(np.ones(hours_per_year) * 999999).astype(int) # st.write(df.index) epw_df = pd.DataFrame() epw_df['Year'] = datetimes.year.astype(int) epw_df['Month'] = datetimes.month.astype(int) epw_df['Day'] = datetimes.day.astype(int) epw_df['Hour'] = datetimes.hour.astype(int) + 1 epw_df['Minute'] = datetimes.minute.astype(int) epw_df['Data Source and Uncertainty Flags'] = missing_values epw_df['Dry Bulb Temperature'] = df['Temperature'].values.flatten() epw_df['Dew Point Temperature'] = df['Dew Point'].values.flatten() epw_df['Relative Humidity'] = df['Relative Humidity'].values.flatten() epw_df['Atmospheric Station Pressure'] = df['Pressure'].values.flatten() epw_df['Extraterrestrial Horizontal Radiation'] = missing_values # epw_df['Extraterrestrial Direct Normal Radiation'] = missing_values # epw_df['Horizontal Infrared Radiation Intensity'] = missing_values # epw_df['Global Horizontal Radiation'] = df['GHI'].values.flatten() epw_df['Direct Normal Radiation'] = df['DNI'].values.flatten() epw_df['Diffuse Horizontal Radiation'] = df['DHI'].values.flatten() epw_df['Global Horizontal Illuminance'] = missing_values epw_df['Direct Normal Illuminance'] = missing_values epw_df['Diffuse Horizontal Illuminance'] = missing_values epw_df['Zenith Luminance'] = missing_values epw_df['Wind Direction'] = df['Wind Direction'].values.flatten() epw_df['Wind Speed'] = df['Wind Speed'].values.flatten() epw_df['Total Sky Cover'] = df['Cloud Type'].values.flatten() # used if Horizontal IR Intensity missing epw_df['Opaque Sky Cover'] = df['Cloud Type'].values.flatten() # epw_df['Visibility'] = missing_values epw_df['Ceiling Height'] = missing_values epw_df['Present Weather Observation'] = missing_values # epw_df['Present Weather Codes'] = missing_values epw_df['Precipitable Water'] = df['Precipitable Water'].values.flatten() epw_df['Aerosol Optical Depth'] = missing_values # epw_df['Snow Depth'] = missing_values epw_df['Days Since Last Snowfall'] = missing_values epw_df['Albedo'] = df['Surface Albedo'].values.flatten() # epw_df['Liquid Precipitation Depth'] = missing_values epw_df['Liquid Precipitation Quantity'] = missing_values out.dataframe = epw_df d = "_" file_name = str(location) + d + str(lat) + d + str(lon) + d + str(year) + '.epw' out.write(file_name) print("Success: File", file_name, "written") return file_name
{"hexsha": "0ec8999d3574ec862b49c1d6739f4af7dea1db4f", "size": 11887, "ext": "py", "lang": "Python", "max_stars_repo_path": "assets.py", "max_stars_repo_name": "kastnerp/NREL-PSB3-2-EPW", "max_stars_repo_head_hexsha": "94a4407073f09e2718a9efe8ed24c9a78e1990f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets.py", "max_issues_repo_name": "kastnerp/NREL-PSB3-2-EPW", "max_issues_repo_head_hexsha": "94a4407073f09e2718a9efe8ed24c9a78e1990f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets.py", "max_forks_repo_name": "kastnerp/NREL-PSB3-2-EPW", "max_forks_repo_head_hexsha": "94a4407073f09e2718a9efe8ed24c9a78e1990f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7558528428, "max_line_length": 297, "alphanum_fraction": 0.3873979978, "include": true, "reason": "import numpy", "num_tokens": 2387}
// // Copyright (c) 2008, 2009 Boris Schaeling <[email protected]> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #define BOOST_AUTO_TEST_MAIN #include <boost/test/auto_unit_test.hpp> #include <boost/filesystem.hpp> #include "dir_monitor/dir_monitor.hpp" #include "check_paths.hpp" #include "directory.hpp" boost::asio::io_service io_service; BOOST_AUTO_TEST_CASE(create_file) { directory dir(TEST_DIR1); boost::asio::dir_monitor dm(io_service); dm.add_directory(TEST_DIR1); auto test_file1 = dir.create_file(TEST_FILE1); boost::asio::dir_monitor_event ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file1); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::added); } BOOST_AUTO_TEST_CASE(rename_file) { directory dir(TEST_DIR1); auto test_file1 = dir.create_file(TEST_FILE1); boost::asio::dir_monitor dm(io_service); dm.add_directory(TEST_DIR1); auto test_file2 = dir.rename_file(TEST_FILE1, TEST_FILE2); boost::asio::dir_monitor_event ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file1); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::renamed_old_name); ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file2); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::renamed_new_name); } BOOST_AUTO_TEST_CASE(remove_file) { directory dir(TEST_DIR1); auto test_file1 = dir.create_file(TEST_FILE1); boost::asio::dir_monitor dm(io_service); dm.add_directory(TEST_DIR1); dir.remove_file(TEST_FILE1); boost::asio::dir_monitor_event ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file1); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::removed); } BOOST_AUTO_TEST_CASE(modify_file) { directory dir(TEST_DIR1); auto test_file1 = dir.create_file(TEST_FILE1); boost::asio::dir_monitor dm(io_service); dm.add_directory(TEST_DIR1); dir.write_file(TEST_FILE1, TEST_FILE2); boost::asio::dir_monitor_event ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file1); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::modified); } BOOST_AUTO_TEST_CASE(multiple_events) { directory dir(TEST_DIR1); boost::asio::dir_monitor dm(io_service); dm.add_directory(TEST_DIR1); auto test_file1 = dir.create_file(TEST_FILE1); auto test_file2 = dir.rename_file(TEST_FILE1, TEST_FILE2); dir.remove_file(TEST_FILE2); boost::asio::dir_monitor_event ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file1); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::added); ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file1); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::renamed_old_name); ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file2); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::renamed_new_name); ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file2); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::removed); } BOOST_AUTO_TEST_CASE(dir_monitor_destruction) { directory dir(TEST_DIR1); boost::asio::dir_monitor dm(io_service); dm.add_directory(TEST_DIR1); dir.create_file(TEST_FILE1); } BOOST_AUTO_TEST_CASE(non_ascii_paths) { char utf8DirName[] = "\xe6\x97\xa5\xe6\x9c\xac\xe5\x9b\xbd"; // 日本国 char utf8FileName[] = "\xd8\xa7\xd9\x84\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9"".txt"; // العربية.txt directory dir(utf8DirName); boost::asio::dir_monitor dm(io_service); dm.add_directory(utf8DirName); auto test_file = dir.create_file(utf8FileName); boost::asio::dir_monitor_event ev = dm.monitor(); BOOST_CHECK_THE_SAME_PATHS_RELATIVE(ev.path, test_file); BOOST_CHECK_EQUAL(ev.type, boost::asio::dir_monitor_event::added); }
{"hexsha": "445ff1ebf9eb6f1a200d3e7e266455357e9b2fa4", "size": 4092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_sync.cpp", "max_stars_repo_name": "Librevault/dir_monitor", "max_stars_repo_head_hexsha": "1b7220520ac3a6a543d4c63f0a5ff4a9ff113835", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_sync.cpp", "max_issues_repo_name": "Librevault/dir_monitor", "max_issues_repo_head_hexsha": "1b7220520ac3a6a543d4c63f0a5ff4a9ff113835", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_sync.cpp", "max_forks_repo_name": "Librevault/dir_monitor", "max_forks_repo_head_hexsha": "1b7220520ac3a6a543d4c63f0a5ff4a9ff113835", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-18T13:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:25:26.000Z", "avg_line_length": 29.652173913, "max_line_length": 106, "alphanum_fraction": 0.7436461388, "num_tokens": 1054}
# Licensed 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. from numpy import array from nisqai.encode._plus_minus_encoding import PlusMinusEncoding from nisqai.data._cdata import CData def test_basic(): """Tests that a PlusMinusEncoding can be instantiated.""" data = array([[1, 0, 0, 1], [0, 1, 1, 0]], dtype=int) cdata = CData(data) encoder = PlusMinusEncoding(cdata) assert encoder.data == cdata assert len(encoder.circuits) == 2 assert len(encoder) == 2 def test_correct(): """Tests for correctness in the circuit of a PlusMinusEncoding, general case.""" data = array([[1, 0, 0, 1]], dtype=int) cdata = CData(data) encoder = PlusMinusEncoding(cdata) correct = "H 0\n" + \ "H 1\n" + \ "H 2\n" + \ "H 3\n" + \ "Z 0\n" + \ "Z 3\n" assert encoder[0].__str__() == correct def test_correct_edge(): """Tests for correctness in the circuit of a PlusMinusEncoding, edge case.""" data = array([[0, 0, 0, 0]], dtype=int) cdata = CData(data) encoder = PlusMinusEncoding(cdata) correct = "H 0\n" + \ "H 1\n" + \ "H 2\n" + \ "H 3\n" assert encoder[0].__str__() == correct def test_correct_edge2(): """Tests for correctness in the circuit of a PlusMinusEncoding, edge case.""" data = array([[1, 1, 1, 1]], dtype=int) cdata = CData(data) encoder = PlusMinusEncoding(cdata) correct = "H 0\n" + \ "H 1\n" + \ "H 2\n" + \ "H 3\n" + \ "Z 0\n" + \ "Z 1\n" + \ "Z 2\n" + \ "Z 3\n" assert encoder[0].__str__() == correct if __name__ == "__main__": test_basic() test_correct() test_correct_edge() test_correct_edge2()
{"hexsha": "fc423231af76b78ce392a12bcc2b8068369293a8", "size": 2364, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/nisqai/encode/_plus_minus_encoding_test.py", "max_stars_repo_name": "obliviateandsurrender/nisqai-dev", "max_stars_repo_head_hexsha": "cf6c38d34acb8fe776913c69212845c547cb47a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-05-21T01:23:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T15:57:13.000Z", "max_issues_repo_path": "src/nisqai/encode/_plus_minus_encoding_test.py", "max_issues_repo_name": "obliviateandsurrender/nisqai-dev", "max_issues_repo_head_hexsha": "cf6c38d34acb8fe776913c69212845c547cb47a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-02-08T00:16:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-09T13:32:11.000Z", "max_forks_repo_path": "src/nisqai/encode/_plus_minus_encoding_test.py", "max_forks_repo_name": "obliviateandsurrender/nisqai-dev", "max_forks_repo_head_hexsha": "cf6c38d34acb8fe776913c69212845c547cb47a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-02-11T07:29:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-19T17:45:17.000Z", "avg_line_length": 28.1428571429, "max_line_length": 84, "alphanum_fraction": 0.5824873096, "include": true, "reason": "from numpy", "num_tokens": 653}
import streamlit as st import numpy as np import pandas as pd from PIL import Image import cv2 #inittalise haarcascade CascadeClassifier and read in model xml file for face detction face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml') #takes in image from streamlit fileuploader as PIL image and outputs image with bounding boxes of detected faces def detect_faces(image): #convert PIL image from rgb to cv2 BGR image img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) #convert cv2 BGR image into grayscale for haarcascade CascadeClassifier gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.1, 4) print(len(faces)) #draw bounding boxes on original image using coordianates provided from prediction for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) # Display image in rgb formatn and show number of detected faces st.image(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) st.markdown("Number of faces detected **{}**".format(len(faces))) st.header('Basic Face Detection Using Haarcascade') st.subheader("A simple face detection demo using haarcascade classifier from open cv") st.caption("instructions to use: upload a png ,jpg or jpeg file and it will automatically detect faces") uploaded_file = st.file_uploader('File uploader',type=["jpg","png","jpeg"]) if uploaded_file is not None: print(type(uploaded_file)) image = Image.open(uploaded_file) detect_faces(image) st.caption("Built by NYP AI team")
{"hexsha": "eb24a971bb41122073eb8536313f22aaa44457f6", "size": 1611, "ext": "py", "lang": "Python", "max_stars_repo_path": "harcasscade_stremlit_demo.py", "max_stars_repo_name": "poipiii/stream-lit-demo", "max_stars_repo_head_hexsha": "a8624ebf1c8e4d84911f569e8692d9d11f35cac1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "harcasscade_stremlit_demo.py", "max_issues_repo_name": "poipiii/stream-lit-demo", "max_issues_repo_head_hexsha": "a8624ebf1c8e4d84911f569e8692d9d11f35cac1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "harcasscade_stremlit_demo.py", "max_forks_repo_name": "poipiii/stream-lit-demo", "max_forks_repo_head_hexsha": "a8624ebf1c8e4d84911f569e8692d9d11f35cac1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3947368421, "max_line_length": 114, "alphanum_fraction": 0.7250155183, "include": true, "reason": "import numpy", "num_tokens": 397}
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 14 15:08:56 2019 @author: riselAir """ #unit testing for peakdetect_RI.py import unittest import math import numpy as np from scipy.stats import norm from peakfunctions import second_largest, fit_gaussian_to_shifted_data, xvalues_for_continuous_curve class TestSecondLargest(unittest.TestCase): def test_identifying_second_highest_number(self): self.assertEqual(second_largest(numbers = [1,1,1,3,5,3,3,6,3,3,2]), 5) def test_function_should_identify_if_none(self): abort_result_one = second_largest(numbers = [1]) abort_result_empty = second_largest(numbers = []) self.assertEqual(abort_result_one, abort_result_empty, None) class TestFunctionBolstering(unittest.TestCase): def test_stretching_x_values(self): x=np.array([1.,2.]) known_range = np.array(range(1*1000,2*1000,1))/1000 calculated_range = xvalues_for_continuous_curve(x) comparison = (calculated_range == known_range) self.assertEqual(sum(comparison), 1000) class TestGaussFit(unittest.TestCase): """ This test takes two peaks, correctly cuts off at the lower one, and calculates the area of the remaining curve. It does NOT calculate the area of the FWHM. It tests my gaussfit. Also, check cdf loc scale for scipy. Can also do fits. Hmm""" def test_passes_if_all_values_larger_than_minor_mean(self): major_mean = 7. minor_mean = 3. major_sd = 0.5 minor_sd = 0.1 scale_factor = .03 def intensity(x): return norm.pdf(x, major_mean, major_sd) + scale_factor * norm.pdf(x, minor_mean, minor_sd) offset = intensity(minor_mean) def test_fwhm_fixpoints(self): pass def test_gaussfit_for_analytic_reference_of_area_caclulation(self): major_mean = 7. minor_mean = 3. major_sd = 0.5 minor_sd = 0.1 scale_factor = .03 def intensity(x): return norm.pdf(x, major_mean, major_sd) + scale_factor * norm.pdf(x, minor_mean, minor_sd) offset = intensity(minor_mean) def inverse_pdf_sqrt(y, sigma): return math.sqrt(-2 * sigma ** 2 * math.log(y * sigma * math.sqrt(2 * math.pi))) #tau+/- = mu +/- sqrt(-2sigma**2 * log(y*sigma*sqrt(2*pi))) reference_area = norm.cdf(inverse_pdf_sqrt(offset, major_sd)/major_sd) - norm.cdf(-inverse_pdf_sqrt(offset, major_sd)/major_sd) self.assertEqual(reference_area, 0.94857078334750633) if __name__ == '__main__': unittest.main() #refactor my gaussfit as function!
{"hexsha": "9e8ccc3cf7eb2d01c6b58f43a35a09ff8824853b", "size": 2704, "ext": "py", "lang": "Python", "max_stars_repo_path": "peakdetect_testing.py", "max_stars_repo_name": "riselin/Intensity_measurement", "max_stars_repo_head_hexsha": "7edb458fe49ae3bcf30b4d025b8fb2131b99ab65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "peakdetect_testing.py", "max_issues_repo_name": "riselin/Intensity_measurement", "max_issues_repo_head_hexsha": "7edb458fe49ae3bcf30b4d025b8fb2131b99ab65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "peakdetect_testing.py", "max_forks_repo_name": "riselin/Intensity_measurement", "max_forks_repo_head_hexsha": "7edb458fe49ae3bcf30b4d025b8fb2131b99ab65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0533333333, "max_line_length": 152, "alphanum_fraction": 0.6660502959, "include": true, "reason": "import numpy,from scipy", "num_tokens": 691}
import random import unittest import numpy as np from skratch.datasets import load_boston from skratch.datasets import load_diabetes from skratch.bonsai import DecisionBonsaiRegressor def r2_score(y_true, y_pred): """ Very similar to the Sklearn implementation but without weights and single output. """ numerator = ((y_true-y_pred)**2).sum(axis=0,dtype=np.float64) denominator = ((y_true - np.average(y_true, axis=0) )** 2).sum(axis=0,dtype=np.float64) score = 1 - (numerator/ denominator) return score class ParameterssTest(unittest.TestCase): def test_max_depth(self): """ Test that the model fits and predicts with different parameter values for max_depth=1,2,3,5,10,20. """ for i in [1,2,3,5,10,20]: X = load_boston().data y = load_boston().target DecisionBonsaiRegressor(max_depth=i).fit(X, y) def test_min_samples(self): """ Test that the model fits and predicts with different parameter values for min_samples_leaf=1,2,3,5,10. """ for i in [1,2,3,5,10]: X = load_boston().data y = load_boston().target DecisionBonsaiRegressor(min_samples_leaf=i).fit(X, y) class TransformationTest(unittest.TestCase): def test_random(self): """ Test that the model does not learn when the target are randomized. """ random.seed(28) np.random.seed(28) X = np.random.rand(500,5) y = np.random.rand(500) X_train, X_test = X[0:400,:], X[400:,:] y_train, y_test = y[0:400], y[400:] clf = DecisionBonsaiRegressor().fit(X_train, y_train) y_pred = clf.predict(X_test) assert r2_score(y_test,y_pred)<0.3 def test_permutation(self): """ Test that de model does not change under feature permutation. """ X = load_boston().data y = load_boston().target clf1 = DecisionBonsaiRegressor().fit(X, y) y_pred1 = clf1.predict(X) X = X.T np.random.shuffle(X) X = X.T clf2 = DecisionBonsaiRegressor().fit(X, y) y_pred2 = clf2.predict(X) assert (y_pred1==y_pred2).all() def test_inversion(self): """ Test that the model does not change the sign of the features is inverted. """ X = load_boston().data y = load_boston().target clf1 = DecisionBonsaiRegressor().fit(X, y) y_pred1 = clf1.predict(X) y = -y clf2 = DecisionBonsaiRegressor().fit(X, y) y_pred2 = clf2.predict(X) assert (y_pred1==-y_pred2).all() def test_dilatation(self): """ Test that the model does not change under feature dilatation. """ X = load_boston().data y = load_boston().target clf1 = DecisionBonsaiRegressor().fit(X, y) y_pred1 = clf1.predict(X) X = X * np.random.randint(1,10,size=X.shape[1]) clf2 = DecisionBonsaiRegressor().fit(X, y) y_pred2 = clf2.predict(X) assert (y_pred1==y_pred2).all() class ScoreTest(unittest.TestCase): def test_boston_fitting(self): """ Test if the model is tested with the training data, the adjustment is perfect. """ X = load_boston().data y = load_boston().target clf = DecisionBonsaiRegressor().fit(X, y) y_pred = clf.predict(X) assert r2_score(y, y_pred)>0.8 def test_diabetes_fitting(self): """ Test if the model is tested with the training data, the adjustment is perfect. """ X = load_diabetes().data y = load_diabetes().target clf = DecisionBonsaiRegressor(max_depth=10).fit(X, y) y_pred = clf.predict(X) assert r2_score(y, y_pred)>0.8
{"hexsha": "e686594078f249954c62c5fb1807177019439de4", "size": 3942, "ext": "py", "lang": "Python", "max_stars_repo_path": "skratch/test/test_bonsai_regressor.py", "max_stars_repo_name": "DelgadoPanadero/Scratch-Python-Forest", "max_stars_repo_head_hexsha": "1dbeeab8a0cc5c9078dbe700ccee42c8afdcc597", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "skratch/test/test_bonsai_regressor.py", "max_issues_repo_name": "DelgadoPanadero/Scratch-Python-Forest", "max_issues_repo_head_hexsha": "1dbeeab8a0cc5c9078dbe700ccee42c8afdcc597", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2020-03-15T12:12:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-06T18:01:09.000Z", "max_forks_repo_path": "skratch/test/test_bonsai_regressor.py", "max_forks_repo_name": "DelgadoPanadero/Scratch-Python-Forest", "max_forks_repo_head_hexsha": "1dbeeab8a0cc5c9078dbe700ccee42c8afdcc597", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9186046512, "max_line_length": 77, "alphanum_fraction": 0.5872653475, "include": true, "reason": "import numpy", "num_tokens": 1018}
#!/usr/bin/env python # Copyright (c) 2011-2019, wradlib developers. # Distributed under the MIT License. See LICENSE.txt for more info. """ Xarray powered Data I/O ^^^^^^^^^^^^^^^^^^^^^^^ Reads data from netcdf-based CfRadial1, CfRadial2 and hdf5-based ODIM_H5 and other hdf5-flavours (GAMIC). Writes data to CfRadial2 and ODIM_H5 files. This reader implementation uses * `netcdf4 <http://unidata.github.io/netcdf4-python/>`_, * `h5py <https://www.h5py.org/>`_ and * `xarray <xarray.pydata.org/>`_. The data is claimed using netcdf4-Dataset in a diskless non-persistent mode:: ncf = nc.Dataset(filename, diskless=True, persist=False) Further the different netcdf/hdf groups are accessed via xarray open_dataset and the NetCDF4DataStore:: xr.open_dataset(xr.backends.NetCDF4DataStore(ncf), mask_and_scale=True) For hdf5 data scaling/masking properties will be added to the datasets before decoding. For GAMIC data compound data will be read via h5py. The data structure holds one ['root'] xarray dataset which corresponds to the CfRadial2 root-group and one or many ['sweep_X'] xarray datasets, holding the sweep data. Since for data handling xarray is utilized all xarray features can be exploited, like lazy-loading, pandas-like indexing on N-dimensional data and vectorized mathematical operations across multiple dimensions. The writer implementation uses xarray for CfRadial2 output and relies on h5py for the ODIM_H5 output. Warning ------- This implementation is considered experimental. Changes in the API should be expected. .. autosummary:: :nosignatures: :toctree: generated/ XRadVol CfRadial OdimH5 open_dataset to_cfradial2 to_odim write_odim write_odim_dataspace get_sweep_group_name get_variables_moments get_group_moments get_groups get_moment_names """ import warnings import collections import numpy as np import datetime as dt import netCDF4 as nc import h5py import xarray as xr from osgeo import osr from ..georef import spherical_to_xyz, spherical_to_proj # CfRadial 2.0 - ODIM_H5 mapping moments_mapping = { 'DBZH': {'standard_name': 'radar_equivalent_reflectivity_factor_h', 'long_name': 'Equivalent reflectivity factor H', 'short_name': 'DBZH', 'units': 'dBZ', 'gamic': 'zh'}, 'DBZV': {'standard_name': 'radar_equivalent_reflectivity_factor_v', 'long_name': 'Equivalent reflectivity factor V', 'short_name': 'DBZV', 'units': 'dBZ', 'gamic': 'zv'}, 'ZH': {'standard_name': 'radar_linear_equivalent_reflectivity_factor_h', 'long_name': 'Linear equivalent reflectivity factor H', 'short_name': 'ZH', 'units': 'unitless', 'gamic': None}, 'ZV': {'standard_name': 'radar_equivalent_reflectivity_factor_v', 'long_name': 'Linear equivalent reflectivity factor V', 'short_name': 'ZV', 'units': 'unitless', 'gamic': None}, 'DBZ': {'standard_name': 'radar_equivalent_reflectivity_factor', 'long_name': 'Equivalent reflectivity factor', 'short_name': 'DBZ', 'units': 'dBZ', 'gamic': None}, 'DBTH': {'standard_name': 'radar_equivalent_reflectivity_factor_h', 'long_name': 'Total power H (uncorrected reflectivity)', 'short_name': 'DBTH', 'units': 'dBZ', 'gamic': 'uzh'}, 'DBTV': {'standard_name': 'radar_equivalent_reflectivity_factor_v', 'long_name': 'Total power V (uncorrected reflectivity)', 'short_name': 'DBTV', 'units': 'dBZ', 'gamic': 'uzv', }, 'TH': {'standard_name': 'radar_linear_equivalent_reflectivity_factor_h', 'long_name': 'Linear total power H (uncorrected reflectivity)', 'short_name': 'TH', 'units': 'unitless', 'gamic': None}, 'TV': {'standard_name': 'radar_linear_equivalent_reflectivity_factor_v', 'long_name': 'Linear total power V (uncorrected reflectivity)', 'short_name': 'TV', 'units': 'unitless', 'gamic': None}, 'VRADH': { 'standard_name': 'radial_velocity_of_scatterers_away_' 'from_instrument_h', 'long_name': 'Radial velocity of scatterers away from instrument H', 'short_name': 'VRADH', 'units': 'meters per seconds', 'gamic': 'vh'}, 'VRADV': { 'standard_name': 'radial_velocity_of_scatterers_' 'away_from_instrument_v', 'long_name': 'Radial velocity of scatterers away from instrument V', 'short_name': 'VRADV', 'units': 'meters per second', 'gamic': 'vv', }, 'VR': { 'standard_name': 'radial_velocity_of_scatterers_away_' 'from_instrument', 'long_name': 'Radial velocity of scatterers away from instrument', 'short_name': 'VR', 'units': 'meters per seconds', 'gamic': None}, 'WRADH': {'standard_name': 'radar_doppler_spectrum_width_h', 'long_name': 'Doppler spectrum width H', 'short_name': 'WRADH', 'units': 'meters per seconds', 'gamic': 'wh'}, 'UWRADH': {'standard_name': 'radar_doppler_spectrum_width_h', 'long_name': 'Doppler spectrum width H', 'short_name': 'UWRADH', 'units': 'meters per seconds', 'gamic': 'uwh'}, 'WRADV': {'standard_name': 'radar_doppler_spectrum_width_v', 'long_name': 'Doppler spectrum width V', 'short_name': 'WRADV', 'units': 'meters per second', 'gamic': 'wv'}, 'ZDR': {'standard_name': 'radar_differential_reflectivity_hv', 'long_name': 'Log differential reflectivity H/V', 'short_name': 'ZDR', 'units': 'dB', 'gamic': 'zdr'}, 'UZDR': {'standard_name': 'radar_differential_reflectivity_hv', 'long_name': 'Log differential reflectivity H/V', 'short_name': 'UZDR', 'units': 'dB', 'gamic': 'uzdr'}, 'LDR': {'standard_name': 'radar_linear_depolarization_ratio', 'long_name': 'Log-linear depolarization ratio HV', 'short_name': 'LDR', 'units': 'dB', 'gamic': 'ldr'}, 'PHIDP': {'standard_name': 'radar_differential_phase_hv', 'long_name': 'Differential phase HV', 'short_name': 'PHIDP', 'units': 'degrees', 'gamic': 'phidp'}, 'UPHIDP': {'standard_name': 'radar_differential_phase_hv', 'long_name': 'Differential phase HV', 'short_name': 'UPHIDP', 'units': 'degrees', 'gamic': 'uphidp'}, 'KDP': {'standard_name': 'radar_specific_differential_phase_hv', 'long_name': 'Specific differential phase HV', 'short_name': 'KDP', 'units': 'degrees per kilometer', 'gamic': 'kdp'}, 'RHOHV': {'standard_name': 'radar_correlation_coefficient_hv', 'long_name': 'Correlation coefficient HV', 'short_name': 'RHOHV', 'units': 'unitless', 'gamic': 'rhohv'}, 'URHOHV': {'standard_name': 'radar_correlation_coefficient_hv', 'long_name': 'Correlation coefficient HV', 'short_name': 'URHOHV', 'units': 'unitless', 'gamic': 'urhohv'}, 'SNRH': {'standard_name': 'signal_noise_ratio_h', 'long_name': 'Signal Noise Ratio H', 'short_name': 'SNRH', 'units': 'unitless', 'gamic': None}, 'SNRV': {'standard_name': 'signal_noise_ratio_v', 'long_name': 'Signal Noise Ratio V', 'short_name': 'SNRV', 'units': 'unitless', 'gamic': None}, 'SQIH': {'standard_name': 'signal_quality_index_h', 'long_name': 'Signal Quality H', 'short_name': 'SQIH', 'units': 'unitless', 'gamic': None}, 'SQIV': {'standard_name': 'signal_quality_index_v', 'long_name': 'Signal Quality V', 'short_name': 'SQIV', 'units': 'unitless', 'gamic': None}, 'CCORH': {'standard_name': 'clutter_correction_h', 'long_name': 'Clutter Correction H', 'short_name': 'CCORH', 'units': 'unitless', 'gamic': None}, 'CCORV': {'standard_name': 'clutter_correction_v', 'long_name': 'Clutter Correction V', 'short_name': 'CCORV', 'units': 'unitless', 'gamic': None}, } ODIM_NAMES = {value['short_name']: key for (key, value) in moments_mapping.items()} GAMIC_NAMES = {value['gamic']: key for (key, value) in moments_mapping.items()} range_attrs = {'units': 'meters', 'standard_name': 'projection_range_coordinate', 'long_name': 'range_to_measurement_volume', 'spacing_is_constant': 'true', 'axis': 'radial_range_coordinate', 'meters_to_center_of_first_gate': None, } az_attrs = {'standard_name': 'ray_azimuth_angle', 'long_name': 'azimuth_angle_from_true_north', 'units': 'degrees', 'axis': 'radial_azimuth_coordinate'} el_attrs = {'standard_name': 'ray_elevation_angle', 'long_name': 'elevation_angle_from_horizontal_plane', 'units': 'degrees', 'axis': 'radial_elevation_coordinate'} time_attrs = {'standard_name': 'time', 'units': 'seconds since 1970-01-01T00:00:00Z', } root_vars = {'volume_number', 'platform_type', 'instrument_type', 'primary_axis', 'time_coverage_start', 'time_coverage_end', 'latitude', 'longitude', 'altitude', 'fixed_angle', 'status_xml'} sweep_vars1 = {'sweep_number', 'sweep_mode', 'polarization_mode', 'prt_mode', 'follow_mode', 'fixed_angle', 'target_scan_rate', 'sweep_start_ray_index', 'sweep_end_ray_index'} sweep_vars2 = {'azimuth', 'elevation', 'pulse_width', 'prt', 'nyquist_velocity', 'unambiguous_range', 'antenna_transition', 'n_samples', 'r_calib_index', 'scan_rate'} sweep_vars3 = {'DBZ', 'VR', 'time', 'range', 'reflectivity_horizontal'} global_attrs = [('Conventions', 'Cf/Radial'), ('version', 'Cf/Radial version number'), ('title', 'short description of file contents'), ('institution', 'where the original data were produced'), ('references', ('references that describe the data or the methods used ' 'to produce it')), ('source', 'method of production of the original data'), ('history', 'list of modifications to the original data'), ('comment', 'miscellaneous information'), ('instrument_name', 'name of radar or lidar'), ('site_name', 'name of site where data were gathered'), ('scan_name', 'name of scan strategy used, if applicable'), ('scan_id', 'scan strategy id, if applicable. assumed 0 if missing'), ('platform_is_mobile', '"true" or "false", assumed "false" if missing'), ('ray_times_increase', ('"true" or "false", assumed "true" if missing. ' 'This is set to true if ray times increase monotonically ' 'thoughout all of the sweeps in the volume')), ('field_names', 'array of strings of field names present in this file.'), ('time_coverage_start', 'copy of time_coverage_start global variable'), ('time_coverage_end', 'copy of time_coverage_end global variable'), ('simulated data', ('"true" or "false", assumed "false" if missing. ' 'data in this file are simulated'))] global_variables = dict([('volume_number', ''), ('platform_type', ''), ('instrument_type', ''), ('primary_axis', ''), ('time_coverage_start', ''), ('time_coverage_end', ''), ('latitude', ''), ('longitude', ''), ('altitude', ''), ('altitude_agl', ''), ('sweep_group_name', (['sweep'], [''])), ('sweep_fixed_angle', (['sweep'], [''])), ('frequency', ''), ('status_xml', '')]) def as_xarray_dataarray(data, dims, coords): """Create Xarray DataArray from NumPy Array .. versionadded:: 1.3 Parameters ---------- data : :class:`numpy:numpy.ndarray` data array dims : dictionary dictionary describing xarray dimensions coords : dictionary dictionary describing xarray coordinates Returns ------- dataset : xr.DataArray DataArray """ da = xr.DataArray(data, coords=dims.values(), dims=dims.keys()) da = da.assign_coords(**coords) return da def create_xarray_dataarray(data, r=None, phi=None, theta=None, proj=None, site=None, sweep_mode='PPI', rf=1.0, **kwargs): """Create Xarray DataArray from Polar Radar Data .. versionadded:: 1.3 Parameters ---------- data : :class:`numpy:numpy.ndarray` The data array. It is assumed that the first dimension is over the azimuth angles, while the second dimension is over the range bins r : :class:`numpy:numpy.ndarray` The ranges. Units may be chosen arbitrarily, m preferred. phi : :class:`numpy:numpy.ndarray` The azimuth angles in degrees. theta : :class:`numpy:numpy.ndarray` The elevation angles in degrees. proj : osr object Destination Spatial Reference System (Projection). site : tuple Tuple of coordinates of the radar site. sweep_mode : str Defaults to 'PPI'. rf : float factor to scale range, defaults to 1. (no scale) Keyword Arguments ----------------- re : float effective earth radius ke : float adjustment factor to account for the refractivity gradient that affects radar beam propagation. Defaults to 4/3. dim0 : str Name of the first dimension. Defaults to 'azimuth'. dim1 : str Name of the second dimension. Defaults to 'range'. Returns ------- dataset : xr.DataArray DataArray """ if (r is None) or (phi is None) or (theta is None): raise TypeError("wradlib: function `create_xarray_dataarray` requires " "r, phi and theta keyword-arguments.") r = r.copy() phi = phi.copy() theta = theta.copy() # create bins, rays 2D arrays for curvelinear coordinates if sweep_mode == 'PPI': bins, rays = np.meshgrid(r, phi, indexing='xy') else: bins, rays = np.meshgrid(r, theta, indexing='xy') # setup for spherical earth calculations re = kwargs.pop('re', None) ke = kwargs.pop('ke', 4. / 3.) if site is None: site = (0., 0., 0.) re = 6378137. # GDAL OSR, convert to this proj if isinstance(proj, osr.SpatialReference): xyz = spherical_to_proj(r, phi, theta, site, proj=proj, re=re, ke=ke) x = xyz[..., 0] y = xyz[..., 1] z = xyz[..., 2] # other proj, convert to aeqd elif proj: xyz, proj = spherical_to_xyz(r, phi, theta, site, re=re, ke=ke, squeeze=True) x = xyz[..., 0] y = xyz[..., 1] z = xyz[..., 2] # proj, convert to aeqd and add offset else: xyz, proj = spherical_to_xyz(r, phi, theta, site, re=re, ke=ke, squeeze=True) x = xyz[..., 0] + site[0] y = xyz[..., 1] + site[1] z = xyz[..., 2] + site[2] # calculate center point center = np.mean(xyz[:, 0, :], axis=0) # calculate ground range gr = np.sqrt((xyz[..., 0] - center[0]) ** 2 + (xyz[..., 1] - center[1]) ** 2) # retrieve projection information cs = [] if proj.IsProjected(): cs.append(proj.GetAttrValue('projcs')) cs.append(proj.GetAttrValue('geogcs')) projstr = ' - '.join(cs) dims = collections.OrderedDict() dim0 = kwargs.pop('dim0', 'azimuth') dim1 = kwargs.pop('dim1', 'range') dims[dim0] = np.arange(phi.shape[0]) dims[dim1] = r / rf coords = {'azimuth': ([dim0], phi), 'elevation': ([dim0], theta), 'bins': ([dim0, dim1], bins / rf), 'rays': ([dim0, dim1], rays), 'x': ([dim0, dim1], x / rf), 'y': ([dim0, dim1], y / rf), 'z': ([dim0, dim1], z / rf), 'gr': ([dim0, dim1], gr / rf), 'longitude': (site[0]), 'latitude': (site[1]), 'altitude': (site[2]), 'sweep_mode': sweep_mode, 'projection': projstr, } # create xarray dataarray da = as_xarray_dataarray(data, dims=dims, coords=coords) return da @xr.register_dataset_accessor('gamic') class GamicAccessor(object): """Dataset Accessor for handling GAMIC HDF5 data files """ def __init__(self, xarray_obj): self._obj = xarray_obj self._radial_range = None self._azimuth_range = None self._elevation_range = None self._time_range = None self._sitecoords = None self._polcoords = None self._projection = None self._time = None @property def radial_range(self): """Return the radial range of this dataset.""" if self._radial_range is None: ngates = self._obj.attrs['bin_count'] # range_start = self._obj.attrs['range_start'] range_samples = self._obj.attrs['range_samples'] range_step = self._obj.attrs['range_step'] bin_range = range_step * range_samples range_data = np.arange(bin_range / 2., bin_range * ngates, bin_range, dtype='float32') range_attrs['meters_to_center_of_first_gate'] = bin_range / 2. da = xr.DataArray(range_data, dims=['range'], attrs=range_attrs) self._radial_range = da return self._radial_range @property def azimuth_range(self): """Return the azimuth range of this dataset.""" if self._azimuth_range is None: azstart = self._obj['azimuth_start'] azstop = self._obj['azimuth_stop'] zero_index = np.where(azstop < azstart) azstop[zero_index[0]] += 360 azimuth = (azstart + azstop) / 2. azimuth = azimuth.assign_attrs(az_attrs) self._azimuth_range = azimuth return self._azimuth_range @property def elevation_range(self): """Return the elevation range of this dataset.""" if self._elevation_range is None: elstart = self._obj['elevation_start'] elstop = self._obj['elevation_stop'] elevation = (elstart + elstop) / 2. elevation = elevation.assign_attrs(el_attrs) self._elevation_range = elevation return self._elevation_range @property def time_range(self): """Return the time range of this dataset.""" if self._time_range is None: times = self._obj['timestamp'] / 1e6 attrs = {'units': 'seconds since 1970-01-01T00:00:00Z', 'standard_name': 'time'} da = xr.DataArray(times, attrs=attrs) self._time_range = da return self._time_range @xr.register_dataset_accessor('odim') class OdimAccessor(object): """Dataset Accessor for handling ODIM_H5 data files """ def __init__(self, xarray_obj): self._obj = xarray_obj self._radial_range = None self._azimuth_range = None self._elevation_range = None self._time_range = None self._time_range2 = None @property def radial_range(self): """Return the radial range of this dataset.""" if self._radial_range is None: ngates = self._obj.attrs['nbins'] range_start = self._obj.attrs['rstart'] * 1000. bin_range = self._obj.attrs['rscale'] cent_first = range_start + bin_range / 2. range_data = np.arange(cent_first, range_start + bin_range * ngates, bin_range, dtype='float32') range_attrs[ 'meters_to_center_of_first_gate'] = cent_first range_attrs[ 'meters_between_gates'] = bin_range da = xr.DataArray(range_data, dims=['range'], attrs=range_attrs) self._radial_range = da return self._radial_range @property def azimuth_range(self): """Return the azimuth range of this dataset.""" if self._azimuth_range is None: nrays = self._obj.attrs['nrays'] res = 360. / nrays azimuth_data = np.arange(res / 2., 360., res, dtype='float32') da = xr.DataArray(azimuth_data, attrs=az_attrs) self._azimuth_range = da return self._azimuth_range @property def elevation_range(self): """Return the elevation range of this dataset.""" if self._elevation_range is None: nrays = self._obj.attrs['nrays'] elangle = self._obj.attrs['elangle'] elevation_data = np.ones(nrays, dtype='float32') * elangle da = xr.DataArray(elevation_data, attrs=el_attrs) self._elevation_range = da return self._elevation_range @property def time_range(self): """Return the time range of this dataset.""" if self._time_range is None: self._time_range = self._obj.attrs['startazT'] return self._time_range @property def time_range2(self): """Return the time range of this dataset.""" if self._time_range2 is None: startdate = self._obj.attrs['startdate'] starttime = self._obj.attrs['starttime'] enddate = self._obj.attrs['enddate'] endtime = self._obj.attrs['endtime'] start = dt.datetime.strptime(startdate + starttime, '%Y%m%d%H%M%S') end = dt.datetime.strptime(enddate + endtime, '%Y%m%d%H%M%S') start = start.replace(tzinfo=dt.timezone.utc) end = end.replace(tzinfo=dt.timezone.utc) self._time_range2 = (start.timestamp(), end.timestamp()) return self._time_range2 def write_odim(src, dest): """ Writes Odim Attributes. Parameters ---------- src : dict Attributes to write dest : handle h5py-group handle """ for key, value in src.items(): if key in dest.attrs: continue if isinstance(value, str): tid = h5py.h5t.C_S1.copy() tid.set_size(len(value) + 1) H5T_C_S1_NEW = h5py.Datatype(tid) dest.attrs.create(key, value, dtype=H5T_C_S1_NEW) else: dest.attrs[key] = value def write_odim_dataspace(src, dest): """ Writes Odim Dataspaces Parameters ---------- src : dict Moments to write dest : handle h5py-group handle """ keys = [key for key in src if key in ODIM_NAMES] data_list = ['data{}'.format(i + 1) for i in range(len(keys))] data_idx = np.argsort(data_list) for idx in data_idx: value = src[keys[idx]] h5_data = dest.create_group(data_list[idx]) enc = value.encoding # p. 21 ff h5_what = h5_data.create_group('what') try: undetect = float(value._Undetect) except AttributeError: undetect = np.finfo(np.float).max what = {'quantity': value.name, 'gain': float(enc['scale_factor']), 'offset': float(enc['add_offset']), 'nodata': float(enc['_FillValue']), 'undetect': undetect, } write_odim(what, h5_what) # moments val = value.values fillval = enc['_FillValue'] * enc['scale_factor'] fillval += enc['add_offset'] val[np.isnan(val)] = fillval val = (val - enc['add_offset']) / enc['scale_factor'] val = np.rint(val).astype(enc['dtype']) ds = h5_data.create_dataset('data', data=val, compression='gzip', compression_opts=6, fillvalue=enc['_FillValue']) if enc['dtype'] == 'uint8': image = 'IMAGE' version = '1.2' tid1 = h5py.h5t.C_S1.copy() tid1.set_size(len(image) + 1) H5T_C_S1_IMG = h5py.Datatype(tid1) tid2 = h5py.h5t.C_S1.copy() tid2.set_size(len(version) + 1) H5T_C_S1_VER = h5py.Datatype(tid2) ds.attrs.create('CLASS', image, dtype=H5T_C_S1_IMG) ds.attrs.create('IMAGE_VERSION', version, dtype=H5T_C_S1_VER) def open_dataset(nch, grp=None): """ Open netcdf/hdf5 group as xarray dataset. Parameters ---------- nch : handle netcdf4-file handle grp : str group to access Returns ------- nch : handle netcdf4 group handle """ if grp is not None: nch = nch.groups.get(grp, False) if nch: nch = xr.open_dataset(xr.backends.NetCDF4DataStore(nch), mask_and_scale=True) return nch def to_cfradial2(volume, filename): """ Save XRadVol to CfRadial2.0 compliant file. Parameters ---------- volume : XRadVol object filename : str output filename """ root = volume.root.copy(deep=True) root.attrs['Conventions'] = 'Cf/Radial' root.attrs['version'] = '2.0' root.to_netcdf(filename, mode='w', group='/') for key in root.sweep_group_name.values: volume[key].to_netcdf(filename, mode='a', group=key) def to_odim(volume, filename): """ Save XRadVol to ODIM_H5/V2_2 compliant file. Parameters ---------- volume : XRadVol object filename : str output filename """ root = volume.root h5 = h5py.File(filename, 'w') # root group, only Conventions for ODIM_H5 write_odim({'Conventions': 'ODIM_H5/V2_2'}, h5) # how group # first try to use original data try: how = volume['odim']['how'].attrs except KeyError: how = {} else: how.update({'_modification_program': 'wradlib'}) h5_how = h5.create_group('how') write_odim(how, h5_how) sweepnames = root.sweep_group_name.values # what group, object, version, date, time, source, mandatory # p. 10 f try: what = volume['odim']['what'].attrs except KeyError: what = {} if len(sweepnames) > 1: what['object'] = 'PVOL' else: what['object'] = 'SCAN' what['version'] = 'H5rad 2.2' what['date'] = str(root.time_coverage_start.values)[:10].replace( '-', '') what['time'] = str(root.time_coverage_end.values)[11:19].replace( ':', '') what['source'] = root.attrs['instrument_name'] h5_what = h5.create_group('what') write_odim(what, h5_what) # where group, lon, lat, height, mandatory where = {'lon': root.longitude.values, 'lat': root.latitude.values, 'height': root.altitude.values} h5_where = h5.create_group('where') write_odim(where, h5_where) # datasets ds_list = ['dataset{}'.format(i + 1) for i in range(len(sweepnames))] ds_idx = np.argsort(ds_list) for idx in ds_idx: ds = volume['sweep_{}'.format(idx + 1)] h5_dataset = h5.create_group(ds_list[idx]) # what group p. 21 ff. h5_ds_what = h5_dataset.create_group('what') ds_what = {} t = sorted(ds.time.values) start = dt.datetime.utcfromtimestamp(t[0].astype('O') / 1e9) end = dt.datetime.utcfromtimestamp( np.rint(t[-1].astype('O') / 1e9)) ds_what['product'] = 'SCAN' ds_what['startdate'] = start.strftime('%Y%m%d') ds_what['starttime'] = start.strftime('%H%M%S') ds_what['enddate'] = end.strftime('%Y%m%d') ds_what['endtime'] = end.strftime('%H%M%S') write_odim(ds_what, h5_ds_what) # where group, p. 11 ff. mandatory h5_ds_where = h5_dataset.create_group('where') rscale = ds.range.values[1] / 1. - ds.range.values[0] rstart = (ds.range.values[0] - rscale / 2.) / 1000. ds_where = {'elangle': ds.fixed_angle, 'nbins': ds.range.shape[0], 'rstart': rstart, 'rscale': rscale, 'nrays': ds.azimuth.shape[0], 'a1gate': np.nonzero(np.argsort(ds.time.values) == 0)[0][0] } write_odim(ds_where, h5_ds_where) # how group, p. 14 ff. h5_ds_how = h5_dataset.create_group('how') try: ds_how = volume['odim']['dsets'][ds_list[idx]]['how'].attrs except KeyError: ds_how = {'scan_index': ds.sweep_number + 1, 'scan_count': len(sweepnames), } write_odim(ds_how, h5_ds_how) # write moments write_odim_dataspace(ds, h5_dataset) h5.close() def extract_gamic_ray_header(filename, scan): """Returns GAMIC ray header dictionary. Parameters ---------- filename : str filename of GAMIC file scan : int Number of scan in file Returns ------- vars : dict OrderedDict of ray header items """ # ToDo: move rayheader into own dataset h5 = h5py.File(filename) ray_header = h5['scan{}/ray_header'.format(scan)][:] h5.close() vars = collections.OrderedDict() for name in ray_header.dtype.names: rh = ray_header[name] attrs = None vars.update({name: (['dim_0'], rh, attrs)}) return vars def get_sweep_group_name(ncf, name): """ Return sweep names. Returns source names and cfradial names. Parameters ---------- ncf : handle netCDF4 Dataset handle name : str Common part of source dataset names. Returns ------- src : list list of source dataset names swg_grp_name : list list of corresponding cfradial sweep_group_name """ src = [key for key in ncf.groups.keys() if name in key] src.sort(key=lambda x: int(x[len(name):])) swp_grp_name = ['sweep_{}'.format(i) for i in range(1, len(src) + 1)] return src, swp_grp_name def get_variables_moments(ds, moments=None, **kwargs): """ Retrieve radar moments from dataset variables. Parameters ---------- ds : xarray dataset source dataset moments : list list of moment strings Returns ------- ds : xarray dataset altered dataset """ standard = kwargs.get('standard', 'cf-mandatory') mask_and_scale = kwargs.get('mask_and_scale', True) decode_coords = kwargs.get('decode_coords', True) dim0 = kwargs.get('dim0', 'time') # fix dimensions dims = list(ds.dims.keys()) ds = ds.rename({dims[0]: dim0, dims[1]: 'range', }) for mom in moments: # open dataX dataset dmom = ds[mom] name = dmom.moment.lower() if 'cf' in standard and name not in GAMIC_NAMES.keys(): ds = ds.drop(mom) continue # extract attributes dmax = np.iinfo(dmom.dtype).max dmin = np.iinfo(dmom.dtype).min minval = dmom.dyn_range_min maxval = dmom.dyn_range_max gain = (maxval - minval) / dmax offset = minval fillval = float(dmax) undetect = float(dmin) # create attribute dict attrs = collections.OrderedDict() # clean moment attributes if standard != 'none': dmom.attrs = collections.OrderedDict() if standard in ['odim']: attrs['gain'] = gain attrs['offset'] = offset attrs['nodata'] = fillval attrs['undetect'] = undetect # add cfradial moment attributes if 'cf' in standard or mask_and_scale: attrs['scale_factor'] = gain attrs['add_offset'] = minval attrs['_FillValue'] = float(dmax) if 'cf' in standard or decode_coords: attrs['coordinates'] = 'elevation azimuth range' if 'full' in standard: attrs['_Undetect'] = undetect if 'cf' in standard: cfname = GAMIC_NAMES[name] for k, v in moments_mapping[cfname].items(): attrs[k] = v name = attrs.pop('short_name') attrs.pop('gamic') # assign attributes to moment dmom.attrs.update(attrs) # keep original dataset name if standard != 'none': ds = ds.rename({mom: name.upper()}) return ds def get_group_moments(ncf, sweep, moments=None, **kwargs): """ Retrieve radar moments from hdf groups. Parameters ---------- ncf : netCDF Dataset handle sweep : str sweep key moments : list list of moment strings Returns ------- ds : dictionary moment datasets """ standard = kwargs.get('standard', 'cf-mandatory') mask_and_scale = kwargs.get('mask_and_scale', True) decode_coords = kwargs.get('decode_coords', True) dim0 = kwargs.get('dim0', 'time') datas = {} for mom in moments: dmom_what = open_dataset(ncf[sweep][mom], 'what') name = dmom_what.attrs.pop('quantity') if 'cf' in standard and name not in moments_mapping.keys(): continue dsmom = open_dataset(ncf[sweep], mom) # create attribute dict attrs = collections.OrderedDict() if standard in ['odim']: attrs.update(dmom_what.attrs) # add cfradial moment attributes if 'cf' in standard or mask_and_scale: attrs['scale_factor'] = dmom_what.attrs.get('gain') attrs['add_offset'] = dmom_what.attrs.get('offset') attrs['_FillValue'] = dmom_what.attrs.get('nodata') if 'cf' in standard or decode_coords: attrs['coordinates'] = 'elevation azimuth range' if 'cf' in standard: for k, v in moments_mapping[name].items(): attrs[k] = v # drop short_name attrs.pop('short_name') attrs.pop('gamic') if 'full' in standard: attrs['_Undetect'] = dmom_what.attrs.get('undetect') # assign attributes dmom = dsmom.data.assign_attrs(attrs) # fix dimensions dims = dmom.dims # keep original dataset name if standard == 'none': name = mom datas.update({name: dmom.rename({dims[0]: dim0, dims[1]: 'range' })}) return datas def get_groups(ncf, groups): """ Get hdf groups. Parameters ---------- ncf : netCDf4 Dataset handle groups : list list of groups-keys Returns ------- out : tuple tuple of xarray datasets """ return tuple(map(lambda x: open_dataset(ncf, x), groups)) def get_moment_names(sweep, fmt=None, src=None): """Get moment names. Parameters ---------- sweep : netCDf4 Group handle fmt : str dataset descriptor format src : str dataset location Returns ------- out : :class:`numpy:numpy.ndarray` array of moment names """ moments = [mom for mom in getattr(sweep, src).keys() if fmt in mom] moments_idx = np.argsort([int(s[len(fmt):]) for s in moments]) return np.array(moments)[moments_idx] def georeference_dataset(coords, vars, is_ppi): """Georeference Dataset. This function adds georeference data to `coords` and `vars`. Parameters ---------- coords : dict Dictionary of coordinates vars : dict Dictionary of variables is_ppi : bool PPI/RHI flag """ # adding xyz aeqd-coordinates site = (coords['longitude'], coords['latitude'], coords['altitude']) dim0 = vars['azimuth'].dims[0] xyz, aeqd = spherical_to_xyz(vars['range'], vars['azimuth'], vars['elevation'], site, squeeze=True) gr = np.sqrt(xyz[..., 0] ** 2 + xyz[..., 1] ** 2) coords['x'] = ([dim0, 'range'], xyz[..., 0]) coords['y'] = ([dim0, 'range'], xyz[..., 1]) coords['z'] = ([dim0, 'range'], xyz[..., 2]) coords['gr'] = ([dim0, 'range'], gr) # adding rays, bins coordinates if is_ppi: bins, rays = np.meshgrid(vars['range'], vars['azimuth'], indexing='xy') else: bins, rays = np.meshgrid(vars['range'], vars['elevation'], indexing='xy') coords['rays'] = ([dim0, 'range'], rays) coords['bins'] = ([dim0, 'range'], bins) class XRadVol(collections.abc.MutableMapping): """ BaseClass for xarray based RadarVolumes Implements `collections.MutableMapping` dictionary. """ def __init__(self, init_root=False): self._source = dict() self._filename = None self._ncf = None self._disk_format = None self._file_format = None self._data_model = None if init_root: self._init_root() def __getitem__(self, key): return self._source[key] def __setitem__(self, key, value): self._source[key] = value def __delitem__(self, key): del self._source[key] def __iter__(self): return iter(self._source) def __len__(self): return len(self._source) def __repr__(self): return self._source.__repr__() def __del__(self): for k in list(self._source): del self._source[k] self._ncf.close() def _init_root(self): self['root'] = xr.Dataset(data_vars=global_variables, attrs=global_attrs) @property def root(self): """ Return `root` dataset. """ return self['root'] @property def sweep(self): """ Return sweep dimension count. """ return self.root.dims['sweep'] @property def sweeps(self): """ Return zip sweep names, sweep_angles """ names = list(self.root.sweep_group_name.values) angles = list(self.root.sweep_fixed_angle.values) return zip(names, angles) @property def location(self): """ Return location of data source. """ return (self.root.longitude.values.item(), self.root.latitude.values.item(), self.root.altitude.values.item()) @property def Conventions(self): """ Return CF/ODIM `Conventions`. """ return self.root.Conventions @property def version(self): """ Return CF/ODIM version """ return self.root.version def to_cfradial2(self, filename): """ Save volume to CfRadial2.0 compliant file. """ if self.root: to_cfradial2(self, filename) else: warnings.warn(UserWarning, "No CfRadial2-compliant data structure " "available. Not saving.") def to_odim(self, filename): """ Save volume to ODIM_H5/V2_2 compliant file. """ if self.root: to_odim(self, filename) else: warnings.warn(UserWarning, "No OdimH5-compliant data structure " "available. Not saving.") class CfRadial(XRadVol): """ Class for xarray based retrieval of CfRadial data files """ def __init__(self, filename=None, flavour=None, **kwargs): super(CfRadial, self).__init__() self._filename = filename self._ncf = nc.Dataset(filename, diskless=True, persist=False) self._disk_format = self._ncf.disk_format self._file_format = self._ncf.file_format self._data_model = self._ncf.data_model if flavour is None: try: self._Conventions = self._ncf.Conventions self._version = self._ncf.version except AttributeError as e: raise AttributeError( 'wradlib: Missing "Conventions" attribute in {} ./n' 'Use the "flavour" kwarg to specify yoget_groupsur source' 'data.'.format(filename)) from e if "cf/radial" in self._Conventions.lower(): if self._version == '2.0': flavour = 'Cf/Radial2' else: flavour = 'Cf/Radial' if flavour == "Cf/Radial2": self.assign_data_radial2(**kwargs) elif flavour == "Cf/Radial": self.assign_data_radial(**kwargs) else: raise AttributeError( 'wradlib: Unknown "flavour" kwarg attribute: {} .' ''.format(flavour)) def assign_data_radial2(self, **kwargs): """ Assign from CfRadial2 data structure. """ self['root'] = open_dataset(self._ncf, **kwargs) sweepnames = self['root'].sweep_group_name.values for sw in sweepnames: self[sw] = open_dataset(self._ncf, sw) self[sw] = self[sw].assign_coords(longitude=self['root'].longitude) self[sw] = self[sw].assign_coords(latitude=self['root'].latitude) self[sw] = self[sw].assign_coords(altitude=self['root'].altitude) self[sw] = self[sw].assign_coords(azimuth=self[sw].azimuth) self[sw] = self[sw].assign_coords(elevation=self[sw].elevation) self[sw] = self[sw].assign_coords(sweep_mode=self[sw].sweep_mode) # adding xyz aeqd-coordinates ds = self[sw] site = (ds.longitude.values, ds.latitude.values, ds.altitude.values) xyz, aeqd = spherical_to_xyz(ds.range, ds.azimuth, ds.elevation, site, squeeze=True) gr = np.sqrt(xyz[..., 0] ** 2 + xyz[..., 1] ** 2) ds = ds.assign_coords(x=(['time', 'range'], xyz[..., 0])) ds = ds.assign_coords(y=(['time', 'range'], xyz[..., 1])) ds = ds.assign_coords(z=(['time', 'range'], xyz[..., 2])) ds = ds.assign_coords(gr=(['time', 'range'], gr)) # what products? is_ppi = True if self[sw].sweep_mode != 'azimuth_surveillance': is_ppi = False # adding rays, bins coordinates if is_ppi: bins, rays = np.meshgrid(ds.range, ds.azimuth, indexing='xy') else: bins, rays = np.meshgrid(ds.range, ds.elevation, indexing='xy') ds = ds.assign_coords(rays=(['time', 'range'], rays)) ds = ds.assign_coords(bins=(['time', 'range'], bins)) self[sw] = ds def assign_data_radial(self, **kwargs): """ Assign from CfRadial1 data structure. """ root = open_dataset(self._ncf, **kwargs) var = root.variables.keys() remove_root = var ^ root_vars remove_root &= var root1 = root.drop(remove_root).rename( {'fixed_angle': 'sweep_fixed_angle'}) sweep_group_name = [] for i in range(root1.dims['sweep']): sweep_group_name.append('sweep_{}'.format(i + 1)) self['root'] = root1.assign( {'sweep_group_name': (['sweep'], sweep_group_name)}) keep_vars = sweep_vars1 | sweep_vars2 | sweep_vars3 remove_vars = var ^ keep_vars remove_vars &= var data = root.drop(remove_vars) data.attrs = {} start_idx = data.sweep_start_ray_index.values end_idx = data.sweep_end_ray_index.values data = data.drop({'sweep_start_ray_index', 'sweep_end_ray_index'}) for i, sw in enumerate(sweep_group_name): tslice = slice(start_idx[i], end_idx[i]) self[sw] = data.isel(time=tslice, sweep=slice(i, i + 1)).squeeze('sweep') self[sw] = self[sw].assign_coords(longitude=self['root'].longitude) self[sw] = self[sw].assign_coords(latitude=self['root'].latitude) self[sw] = self[sw].assign_coords(altitude=self['root'].altitude) self[sw] = self[sw].assign_coords(azimuth=self[sw].azimuth) self[sw] = self[sw].assign_coords(elevation=self[sw].elevation) sweep_mode = self[sw].sweep_mode.values.item().decode() self[sw] = self[sw].assign_coords(sweep_mode=sweep_mode) # adding xyz aeqd-coordinates ds = self[sw] site = (ds.longitude.values, ds.latitude.values, ds.altitude.values) xyz, aeqd = spherical_to_xyz(ds.range, ds.azimuth, ds.elevation, site, squeeze=True) gr = np.sqrt(xyz[..., 0] ** 2 + xyz[..., 1] ** 2) ds = ds.assign_coords(x=(['time', 'range'], xyz[..., 0])) ds = ds.assign_coords(y=(['time', 'range'], xyz[..., 1])) ds = ds.assign_coords(z=(['time', 'range'], xyz[..., 2])) ds = ds.assign_coords(gr=(['time', 'range'], gr)) # what products? is_ppi = True if sweep_mode != 'azimuth_surveillance': is_ppi = False # adding rays, bins coordinates if is_ppi: bins, rays = np.meshgrid(ds.range, ds.azimuth, indexing='xy') else: bins, rays = np.meshgrid(ds.range, ds.elevation, indexing='xy') ds = ds.assign_coords(rays=(['time', 'range'], rays)) ds = ds.assign_coords(bins=(['time', 'range'], bins)) self[sw] = ds class OdimH5(XRadVol): """ Class for xarray based retrieval of ODIM_H5 data files """ def __init__(self, filename=None, flavour=None, strict=True, **kwargs): """Initialize xarray structure from hdf5 data structure. Parameters ---------- filename : str Source data file name. flavour : str Name of hdf5 flavour ('ODIM' or 'GAMIC'). Defaults to 'ODIM'. strict : bool If False, exports all groups verbatim into dedicated 'odim'-group. Keyword Arguments ----------------- decode_times : bool If True, decode cf times to np.datetime64. Defaults to True. decode_coords : bool If True, use the ‘coordinates’ attribute on variable to assign coordinates. Defaults to True. mask_and_scale : bool If True, lazily scale (using scale_factor and add_offset) and mask (using _FillValue). Defaults to True. georef : bool If True, adds 2D AEQD x,y,z-coordinates, ground_range (gr) and 2D (rays,bins)-coordinates for easy georeferencing (eg. cartopy) standard : str * `none` - data is read as verbatim as possible, no metadata * `odim` - data is read, odim metadata added to datasets * `cf-mandatory` - data is read according to cfradial2 standard importing mandatory metadata * `cf-full` - data is read according to cfradial2 standard importing all available cfradial2 metadata (not fully implemented) dim0 : str name of the ray-dimension of DataArrays and Dataset: * `time` - cfradial2 standard * `azimuth` - better for working with xarray """ super(OdimH5, self).__init__() self._filename = filename self._ncf = nc.Dataset(filename, diskless=True, persist=False) self._disk_format = self._ncf.disk_format self._file_format = self._ncf.file_format self._data_model = self._ncf.data_model if self._disk_format != 'HDF5': raise TypeError( 'wradlib: File {} is neither "NETCDF4" (using HDF5 groups) ' 'nor plain "HDF5".'.format(filename)) if flavour is None: try: self._Conventions = self._ncf.Conventions except AttributeError as e: raise AttributeError( 'wradlib: Missing "Conventions" attribute in {} ./n' 'Use the "flavour" kwarg to specify your source ' 'data.'.format(filename)) from e if "ODIM_H5" in self._Conventions: flavour = 'ODIM' else: raise AttributeError( 'wradlib: "Conventions" attribute "{}" in {} is unknown./n' 'Use the "flavour" kwarg to specify your source ' 'data.'.format(self._Conventions, filename)) self._flavour = flavour if flavour == "ODIM": self._dsdesc = 'dataset' self._swmode = 'product' self._mfmt = 'data' self._msrc = 'groups' elif flavour == "GAMIC": self._dsdesc = 'scan' self._swmode = 'scan_type' self._mfmt = 'moment_' self._msrc = 'variables' self._flavour = flavour else: raise AttributeError( 'wradlib: Unknown "flavour" kwarg attribute: {} .' ''.format(flavour)) self.assign_data(strict=strict, **kwargs) def assign_moments(self, ds, sweep, **kwargs): """Assign radar moments to dataset. Parameters ---------- ds : xarray dataset destination dataset sweep : str netcdf group name Keyword Arguments ----------------- decode_times : bool If True, decode cf times to np.datetime64. Defaults to True. decode_coords : bool If True, use the ‘coordinates’ attribute on variable to assign coordinates. Defaults to True. mask_and_scale : bool If True, lazily scale (using scale_factor and add_offset) and mask (using _FillValue). Defaults to True. georef : bool If True, adds 2D AEQD x,y,z-coordinates, ground_range (gr) and 2D (rays,bins)-coordinates for easy georeferencing (eg. cartopy) standard : str * `none` - data is read as verbatim as possible, no metadata * `odim` - data is read, odim metadata added to datasets * `cf-mandatory` - data is read according to cfradial2 standard importing mandatory metadata * `cf-full` - data is read according to cfradial2 standard importing all available cfradial2 metadata (not fully implemented) dim0 : str name of the ray-dimension of DataArrays and Dataset: * `time` - cfradial2 standard * `azimuth` - better for working with xarray Returns ------- ds : xarray dataset Dataset with assigned radar moments """ moments = get_moment_names(self._ncf[sweep], fmt=self._mfmt, src=self._msrc) if self._flavour == 'ODIM': for name, dmom in get_group_moments(self._ncf, sweep, moments=moments, **kwargs).items(): ds[name] = dmom if self._flavour == 'GAMIC': ds = get_variables_moments(ds, moments=moments, **kwargs) return ds def get_timevals(self, grps): """Retrieve TimeArray from source data. Parameters ---------- grps : dict Dictionary of dataset hdf5 groups ('how', 'what', 'where') Returns ------- timevals : :class:`numpy:numpy.ndarray` array of time values """ if self._flavour == 'ODIM': try: timevals = grps['how'].odim.time_range except (KeyError, AttributeError): # timehandling if only start and end time is given start, end = grps['what'].odim.time_range2 delta = (end - start) / grps['where'].nrays timevals = np.arange(start + delta / 2., end, delta) timevals = np.roll(timevals, shift=-grps['where'].a1gate) if self._flavour == 'GAMIC': timevals = grps['what'].gamic.time_range.values return timevals def get_coords(self, grps): """Retrieve Coordinates according OdimH5 standard. Parameters ---------- grps : dict Dictionary of dataset hdf5 groups ('how', 'what', 'where') Returns ------- coords : dict Dictionary of coordinate arrays """ flavour = self._flavour.lower() coords = collections.OrderedDict() if flavour == 'odim': az = el = rng = grps['where'] if flavour == 'gamic': az = el = grps['what'] rng = grps['how'] coords['azimuth'] = getattr(az, flavour).azimuth_range coords['elevation'] = getattr(el, flavour).elevation_range coords['range'] = getattr(rng, flavour).radial_range return coords def get_fixed_angle(self, grps, is_ppi): """Retrieve fixed angle from source data. Parameters ---------- grps : dict Dictionary of dataset hdf5 groups ('how', 'what', 'where') is_ppi : bool PPI/RHI flag Returns ------- fixed-angle : float fixed angle of specific scan """ idx = int(is_ppi) if self._flavour == 'ODIM': ang = ('azangle', 'elangle') fixed_angle = getattr(grps['where'], ang[idx]) if self._flavour == 'GAMIC': ang = ('azimuth', 'elevation') fixed_angle = grps['how'].attrs[ang[idx]] return fixed_angle def get_root_attributes(self, grps): """Retrieve root attributes according CfRadial2 standard. Parameters ---------- grps : dict Dictionary of root hdf5 groups ('how', 'what', 'where') Returns ------- attrs : dict Dictionary of root attributes """ attrs = collections.OrderedDict() attrs.update({'version': 'None', 'title': 'None', 'institution': 'None', 'references': 'None', 'source': 'None', 'history': 'None', 'comment': 'im/exported using wradlib', 'instrument_name': 'None', }) attrs['version'] = grps['what'].attrs['version'] if self._flavour == 'ODIM': attrs['institution'] = grps['what'].attrs['source'] attrs['instrument'] = grps['what'].attrs['source'] if self._flavour == 'GAMIC': attrs['title'] = grps['how'].attrs['template_name'] attrs['instrument'] = grps['how'].attrs['host_name'] return attrs def assign_data(self, strict=True, **kwargs): """Assign from hdf5 data structure. Parameters ---------- strict : bool If False, exports all groups verbatim into dedicated 'odim'-group. Keyword Arguments ----------------- decode_times : bool If True, decode cf times to np.datetime64. Defaults to True. decode_coords : bool If True, use the ‘coordinates’ attribute on variable to assign coordinates. Defaults to True. mask_and_scale : bool If True, lazily scale (using scale_factor and add_offset) and mask (using _FillValue). Defaults to True. georef : bool If True, adds 2D AEQD x,y,z-coordinates, ground_range (gr) and 2D (rays,bins)-coordinates for easy georeferencing (eg. cartopy). Defaults to True. standard : str * `none` - data is read as verbatim as possible, no metadata * `odim` - data is read, odim metadata added to datasets * `cf-mandatory` - data is read according to cfradial2 standard importing mandatory metadata, default value * `cf-full` - data is read according to cfradial2 standard importing all available cfradial2 metadata (not fully implemented) dim0 : str name of the ray-dimension of DataArrays and Dataset: * `time` - cfradial2 standard, default value * `azimuth` - better for working with xarray """ # keyword argument handling decode_times = kwargs.get('decode_times', True) decode_coords = kwargs.get('decode_coords', True) mask_and_scale = kwargs.get('mask_and_scale', True) georef = kwargs.get('georef', True) standard = kwargs.get('standard', 'cf-mandatory') dim0 = kwargs.get('dim0', 'time') # retrieve and assign global groups root and /how, /what, /where groups = [None, 'how', 'what', 'where'] root, how, what, where = get_groups(self._ncf, groups) rt_grps = {'how': how, 'what': what, 'where': where} # sweep group handling src_swp_grp_name, swp_grp_name = get_sweep_group_name(self._ncf, self._dsdesc) if 'cf' in standard: sweep_fixed_angle = [] time_coverage_start = np.datetime64('2037-01-01') time_coverage_end = np.datetime64('1970-01-01') if not decode_times: epoch = np.datetime64('1970-01-01T00:00:00Z') time_coverage_start = ((time_coverage_start - epoch) / np.timedelta64(1, 's')) time_coverage_end = ((time_coverage_end - epoch) / np.timedelta64(1, 's')) # iterate sweeps sweeps = {} for i, sweep in enumerate(src_swp_grp_name): swp = {} # retrieve ds and assign datasetX how/what/where group attributes groups = [None, 'how', 'what', 'where'] ds, ds_how, ds_what, ds_where = get_groups(self._ncf[sweep], groups) ds_grps = {'how': ds_how, 'what': ds_what, 'where': ds_where} # what products? if 'cf' in standard or georef: is_ppi = True sweep_mode = 'azimuth_surveillance' if ds_grps['what'].attrs[self._swmode] == 'RHI': sweep_mode = 'rhi' is_ppi = False # moments ds = self.assign_moments(ds, sweep, **kwargs) # retrieve and assign gamic ray_header if self._flavour == 'GAMIC': rh = extract_gamic_ray_header(self._filename, i) ds_grps['what'] = ds_grps['what'].assign(rh) # coordinates wrap-up coords = collections.OrderedDict() vars = collections.OrderedDict() if 'cf' in standard or georef: coords['longitude'] = rt_grps['where'].attrs['lon'] coords['latitude'] = rt_grps['where'].attrs['lat'] coords['altitude'] = rt_grps['where'].attrs['height'] if 'cf' in standard: coords['sweep_mode'] = sweep_mode if 'cf' in standard or decode_coords or georef: vars.update(self.get_coords(ds_grps)) vars['azimuth'] = vars['azimuth'].rename({'dim_0': dim0}) vars['elevation'] = vars['elevation'].rename({'dim_0': dim0}) # georeference needs coordinate variables if georef: georeference_dataset(coords, vars, is_ppi) # time coordinate if 'cf' in standard or decode_times: timevals = self.get_timevals(ds_grps) if decode_times: coords['time'] = ([dim0], timevals, time_attrs) else: coords['time'] = ([dim0], timevals) # assign global sweep attributes if 'cf' in standard: fixed_angle = self.get_fixed_angle(ds_grps, is_ppi) vars.update({'sweep_number': i, 'sweep_mode': sweep_mode, 'follow_mode': 'none', 'prt_mode': 'fixed', 'fixed_angle': fixed_angle}) sweep_fixed_angle.append(fixed_angle) # assign variables and coordinates ds = ds.assign(vars) ds = ds.assign_coords(**coords) # decode dataset if requested if decode_times or decode_coords or mask_and_scale: ds = xr.decode_cf(ds, decode_times=decode_times, decode_coords=decode_coords, mask_and_scale=mask_and_scale) # extract time coverage if 'cf' in standard: time_coverage_start = min(time_coverage_start, ds.time.values.min()) time_coverage_end = max(time_coverage_end, ds.time.values.max()) # assign to sweep dict if not strict: swp.update(ds_grps) sweeps[sweep] = swp # dataset only self[swp_grp_name[i]] = ds # assign root variables if 'cf' in standard: time_coverage_start = str(time_coverage_start)[:19] + 'Z' time_coverage_end = str(time_coverage_end)[:19] + 'Z' # assign root variables root = root.assign({'volume_number': 0, 'platform_type': str('fixed'), 'instrument_type': 'radar', 'primary_axis': 'axis_z', 'time_coverage_start': time_coverage_start, 'time_coverage_end': time_coverage_end, 'latitude': rt_grps['where'].attrs['lat'], 'longitude': rt_grps['where'].attrs['lon'], 'altitude': rt_grps['where'].attrs['height'], 'sweep_group_name': (['sweep'], swp_grp_name), 'sweep_fixed_angle': ( ['sweep'], sweep_fixed_angle), }) # assign root attributes attrs = self.get_root_attributes(rt_grps) root = root.assign_attrs(attrs) # assign to source dict self['root'] = root if not strict: self['odim'] = {'dsets': sweeps} self['odim'].update(rt_grps)
{"hexsha": "fb8bdc8406fb18a18c38eb11660da1c5404d6808", "size": 65078, "ext": "py", "lang": "Python", "max_stars_repo_path": "wradlib/io/xarray.py", "max_stars_repo_name": "nschaffner/wradlib", "max_stars_repo_head_hexsha": "eaa74701464e4ca2e01c96be7d47667983b6cfd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wradlib/io/xarray.py", "max_issues_repo_name": "nschaffner/wradlib", "max_issues_repo_head_hexsha": "eaa74701464e4ca2e01c96be7d47667983b6cfd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wradlib/io/xarray.py", "max_forks_repo_name": "nschaffner/wradlib", "max_forks_repo_head_hexsha": "eaa74701464e4ca2e01c96be7d47667983b6cfd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7178924259, "max_line_length": 79, "alphanum_fraction": 0.5436245736, "include": true, "reason": "import numpy", "num_tokens": 15358}
#!/usr/bin/env python import numpy as np import sys def avg_data(d_f): data = np.loadtxt(d_f) vs = [] print len(data) for i in range(len(data)): vs.append(data[i][1]) avg = np.average(vs) return avg avg = avg_data(sys.argv[1]) print avg
{"hexsha": "3fdc6986d0b17c9c10f68b3115761e69a49b5362", "size": 249, "ext": "py", "lang": "Python", "max_stars_repo_path": "projects/lipid/misc/get_avgv.py", "max_stars_repo_name": "kmckiern/scripts", "max_stars_repo_head_hexsha": "acc8326ca653d804ee06752af9e7f5b011fc6e0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-04-27T01:57:43.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-01T18:18:56.000Z", "max_issues_repo_path": "projects/lipid/misc/get_avgv.py", "max_issues_repo_name": "kmckiern/scripts", "max_issues_repo_head_hexsha": "acc8326ca653d804ee06752af9e7f5b011fc6e0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/lipid/misc/get_avgv.py", "max_forks_repo_name": "kmckiern/scripts", "max_forks_repo_head_hexsha": "acc8326ca653d804ee06752af9e7f5b011fc6e0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6470588235, "max_line_length": 27, "alphanum_fraction": 0.6626506024, "include": true, "reason": "import numpy", "num_tokens": 73}
# -*- coding: utf-8 -*- """ Created on Mon Dec 11 20:02:37 2017 @author: Anastasios Tzavellas """ import numpy as np import matplotlib.pyplot as plt import interpolation def f(x): return np.exp(-x) def df(x): return -np.exp(-x) def d2f(x): return f(x) def err2(x): return np.exp(-x) * (x-0.25) *(x-0.5) *(x-0.75) /6 def err1(x): return np.exp(-x) * (0.5-0.25) *(0.5-0.75) /6 xValues = np.array([0.25, 0.5, 0.75]) fValues = f(xValues) dValues = interpolation.differenceTable(fValues) print('Actual df(0.5)=', df(0.5)) print('Numeric df(0.5)', interpolation.df(0.5, xValues, dValues)) print('Actual d2f(0.5)=', d2f(0.5)) print('Numeric d2f(0.5)', interpolation.d2f(0.5, xValues, dValues)) error = f(xValues[0]) / 6 * \ np.abs((xValues[1]-xValues[0]) * (xValues[1] - xValues[2])) print('Max error is', error) x = np.arange(0.25, 0.76, 0.01)
{"hexsha": "727fd25f1c910c848caeff6621dcd4cb4b24d2b3", "size": 883, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment3/ex5.py", "max_stars_repo_name": "tzavellas/ComputationalPhysics", "max_stars_repo_head_hexsha": "7dd95d1a55faa4d467b9a96c7ee1933e88652370", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment3/ex5.py", "max_issues_repo_name": "tzavellas/ComputationalPhysics", "max_issues_repo_head_hexsha": "7dd95d1a55faa4d467b9a96c7ee1933e88652370", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment3/ex5.py", "max_forks_repo_name": "tzavellas/ComputationalPhysics", "max_forks_repo_head_hexsha": "7dd95d1a55faa4d467b9a96c7ee1933e88652370", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7872340426, "max_line_length": 67, "alphanum_fraction": 0.6126840317, "include": true, "reason": "import numpy", "num_tokens": 343}
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, Dataset, TensorDataset from sklearn.model_selection import train_test_split import numpy as np import logging from pdb import set_trace as st import os.path as osp import os import copy import wandb from fedml_api.data_preprocessing.utils import DatasetSplit from privacy_fedml.my_model_trainer_classification import MyModelTrainer as MyModelTrainerCLS from .MI_attack_model_trainer import MIAttackModelTrainer class NNAttackModel(nn.Module): def __init__(self, input_dim, n_classes): super().__init__() self.fc1 = nn.Linear(input_dim, 512) self.fc2 = nn.Linear(512, 256) self.fc3 = nn.Linear(256, 128) self.fc4 = nn.Linear(128, n_classes) self.dropout = nn.Dropout(p=0.5) def forward(self, x): x = F.relu(self.fc1(x)) x = self.dropout(x) x = F.relu(self.fc2(x)) x = self.dropout(x) x = F.relu(self.fc3(x)) # x = self.dropout(x) x = self.fc4(x) # return F.log_softmax(x, dim=1) return x # class NNAttackModel(nn.Module): # def __init__(self, input_dim, n_classes): # super().__init__() # self.fc1 = nn.Linear(input_dim, 64) # self.fc2 = nn.Linear(64, n_classes) # self.dropout = nn.Dropout(p=0.2) # def forward(self, x): # x = F.relu(self.fc1(x)) # x = self.dropout(x) # x = F.relu(self.fc2(x)) # return x class NNAttack(): def __init__(self, server, device, args, adv_client_idx=0, adv_branch_idx=0): self.server = server server.set_client_dataset() self.device = device self.args = args self.adv_client_idx = adv_client_idx self.adv_branch_idx = adv_branch_idx self.save_dir = osp.join(self.args.save_dir, f"{type(self).__name__}") if not os.path.exists(self.save_dir): os.makedirs(self.save_dir, exist_ok=True) self.attack_model = NNAttackModel(server.output_dim, 2) logging.info(f"################ {type(self).__name__} build attack model") logging.info(self.attack_model) self.attack_trainer = MIAttackModelTrainer(self.attack_model) attack_model_args = copy.deepcopy(args) attack_model_args.lr = 1e-1 attack_model_args.batch_size = 64 # attack_model_args.epochs = 40 attack_model_args.epochs = 40 attack_model_args.optimizer = 'sgd' self.attack_model_args = attack_model_args def eval_attack(self): self.train_attack_model() self.eval_on_other_client() def generate_attack_dataset( self, ): """ Generate attack data from the client training and testing data """ path = osp.join(self.save_dir, "mi_train_data.pt") if True: # if not os.path.exists(path): # Set client weight adv_client = self.server.client_list[self.adv_client_idx] branch_w = self.server.branches[self.adv_branch_idx] adv_client.model_trainer.set_model_params(branch_w) test_local_metrics = adv_client.local_test(True) acc = test_local_metrics['test_correct'] / test_local_metrics['test_total'] logging.info(f"################ {type(self).__name__} init adv client performance {acc:.2f}") train_dataset, test_dataset = self.convert_dataset( adv_client.model_trainer.model, adv_client, self.adv_client_idx, ) torch.save((train_dataset, test_dataset), path) else: train_dataset, test_dataset = torch.load(path) logging.info(f"################ {len(train_dataset)} training data, {len(test_dataset)} test data") return train_dataset, test_dataset def generate_eval_dataset(self): """Generate eval dataset on other clients """ path = osp.join(self.save_dir, "mi_other_client_test_data.pt") # if not os.path.exists(path): if True: adv_client = self.server.client_list[self.adv_client_idx] branch_w = self.server.branches[self.adv_branch_idx] adv_client.model_trainer.set_model_params(branch_w) test_local_metrics = adv_client.local_test(True) acc = test_local_metrics['test_correct'] / test_local_metrics['test_total'] logging.info(f"################ {type(self).__name__} init adv client (client {self.adv_client_idx} on branch {self.adv_branch_idx}) performance {acc:.2f}") client_eval_datasets = {} for client_idx in range(len(self.server.client_list)): if client_idx == self.adv_client_idx: continue client = self.server.client_list[client_idx] train_dataset, test_dataset = self.convert_dataset( adv_client.model_trainer.model, client, client_idx, ) client_eval_datasets[client_idx] = test_dataset torch.save(client_eval_datasets, path) else: client_eval_datasets = torch.load(path) return client_eval_datasets # use other client model # def generate_eval_dataset(self): # """Generate eval dataset on other clients # """ # path = osp.join(self.save_dir, "mi_other_client_test_data.pt") # # if not os.path.exists(path): # if True: # client_eval_datasets = {} # for client_idx in range(len(self.server.client_list)): # if client_idx == self.adv_client_idx: # continue # branch_idx = self.server.client_to_branch[client_idx] # client = self.server.client_list[client_idx] # branch_w = self.server.branches[branch_idx] # client.model_trainer.set_model_params(branch_w) # test_local_metrics = client.local_test(True) # acc = test_local_metrics['test_correct'] / test_local_metrics['test_total'] # logging.info(f"################ {type(self).__name__} generate MI eval dataset on client {client_idx} & branch {branch_idx}, performance {acc:.2f}") # train_dataset, test_dataset = self.convert_dataset( # client.model_trainer.model, client, client_idx, # ) # client_eval_datasets[client_idx] = test_dataset # torch.save(client_eval_datasets, path) # else: # client_eval_datasets = torch.load(path) # return client_eval_datasets def eval_on_other_client(self, ): """Eval the trained attack model on other client Args: model ([type]): [description] """ client_eval_datasets = self.generate_eval_dataset() all_metrics = { "acc": [], "precision": [], "recall": [], "f1": [], } for client_idx, test_dataset in client_eval_datasets.items(): test_dataloader = DataLoader( test_dataset, batch_size = self.attack_model_args.batch_size, shuffle=False, ) metrics = self.attack_trainer.test( test_dataloader, self.device, self.args ) logging.info(f"################ {type(self).__name__} test on other client {client_idx}: {metrics}") all_metrics["acc"].append(metrics["acc"]) all_metrics["precision"].append(metrics["precision"]) all_metrics["recall"].append(metrics["recall"]) all_metrics["f1"].append(metrics["f1"]) all_metrics["acc"] = np.mean(all_metrics["acc"]) all_metrics["precision"] = np.mean(all_metrics["precision"]) all_metrics["recall"] = np.mean(all_metrics["recall"]) all_metrics["f1"] = np.mean(all_metrics["f1"]) logging.info(f"################ {type(self).__name__} test on other client average: {all_metrics}") prefix = f"{type(self).__name__}/OtherClientTest" wandb.log({f"{prefix}/TestAcc": all_metrics['acc'], "round": 0}) wandb.log({f"{prefix}/TestPrec": all_metrics['precision'], "round": 0}) wandb.log({f"{prefix}/TestRecall": all_metrics['recall'], "round": 0}) wandb.log({f"{prefix}/TestF1": all_metrics['f1'], "round": 0}) def convert_dataset(self, model, client, client_idx): """Convert client training/test dataset to MI dataset Args: model ([type]): [description] client ([type]): [description] """ client_train = client.local_training_data client_test = client.local_test_data mem_outputs = self.test_shadow_output(model, client_train) nonmem_outputs = self.test_shadow_output(model, client_test) # Mem and nonmem balance to avoid trivial result num_select = min(len(mem_outputs), len(nonmem_outputs)) mem_idxs = np.random.choice(len(mem_outputs), num_select) mem_outputs = mem_outputs[mem_idxs] nonmem_idxs = np.random.choice(len(nonmem_outputs), num_select) nonmem_outputs = nonmem_outputs[nonmem_idxs] mem_labels = np.ones(len(mem_outputs)) nonmem_labels = np.zeros(len(nonmem_outputs)) mem_train_data, mem_test_data, mem_train_label, mem_test_label, = train_test_split( mem_outputs, mem_labels, train_size=0.8, random_state=1, ) nonmem_train_data, nonmem_test_data, nonmem_train_label, nonmem_test_label, = train_test_split( nonmem_outputs, nonmem_labels, train_size=0.8, random_state=1, ) logging.info(f"Client {client_idx} generate attack dataset mem_train: {len(mem_train_data)}, nonmem_train: {len(nonmem_train_data)}, mem_test: {len(mem_test_data)}, nonmen_test: {len(nonmem_test_data)}") train_data = np.concatenate([mem_train_data, nonmem_train_data]) train_label = np.concatenate([mem_train_label, nonmem_train_label]) test_data = np.concatenate([mem_test_data, nonmem_test_data]) test_label = np.concatenate([mem_test_label, nonmem_test_label]) train_data = torch.Tensor(train_data) train_label = torch.Tensor(train_label).long() test_data = torch.Tensor(test_data) test_label = torch.Tensor(test_label).long() train_dataset = TensorDataset(train_data, train_label) test_dataset = TensorDataset(test_data, test_label) return train_dataset, test_dataset def train_attack_model(self): train_dataset, test_dataset = self.generate_attack_dataset() train_dataloader = DataLoader( train_dataset, batch_size = self.attack_model_args.batch_size, shuffle=True, ) test_dataloader = DataLoader( test_dataset, batch_size = self.attack_model_args.batch_size, shuffle=False, ) logging.info(f"################ {type(self).__name__} train attack model") self.attack_trainer.train( train_dataloader, self.device, self.attack_model_args ) logging.info(f"################ {type(self).__name__} finish train") metrics = self.attack_trainer.test( test_dataloader, self.device, self.args ) logging.info(f"################ {type(self).__name__} adversary train on client {self.adv_client_idx} test result: {metrics}") prefix = f"{type(self).__name__}/OneClientTrain" wandb.log({f"{prefix}/TestAcc": metrics['acc'], "round": 0}) wandb.log({f"{prefix}/TestPrec": metrics['precision'], "round": 0}) wandb.log({f"{prefix}/TestRecall": metrics['recall'], "round": 0}) wandb.log({f"{prefix}/TestF1": metrics['f1'], "round": 0}) weight_path = osp.join(self.save_dir, "attack_model.pth") state_dict = self.attack_trainer.get_model_params() torch.save(state_dict, weight_path) def process_output(self, pred, target, criterion): pred = nn.Softmax(dim=1)(pred) pred = pred.cpu().numpy() pred = -np.sort(-pred) return pred def test_shadow_output(self, model, test_data): device = self.device model.to(device) model.eval() outputs = [] criterion = nn.CrossEntropyLoss().to(device) with torch.no_grad(): for batch_idx, (x, target) in enumerate(test_data): x = x.to(device) target = target.to(device) pred = model(x) assert len(pred.shape) > 1 processed_output = self.process_output( pred, target, criterion ) outputs.append(processed_output) outputs = np.concatenate(outputs) return outputs
{"hexsha": "b500a9913816ffd3452097de4d0061d7dfa91b40", "size": 13275, "ext": "py", "lang": "Python", "max_stars_repo_path": "privacy_fedml/MI_attack/NN_attack.py", "max_stars_repo_name": "ziqi-zhang/FedML", "max_stars_repo_head_hexsha": "83cfc1245609c50f21d13be5f180f67576c57735", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "privacy_fedml/MI_attack/NN_attack.py", "max_issues_repo_name": "ziqi-zhang/FedML", "max_issues_repo_head_hexsha": "83cfc1245609c50f21d13be5f180f67576c57735", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "privacy_fedml/MI_attack/NN_attack.py", "max_forks_repo_name": "ziqi-zhang/FedML", "max_forks_repo_head_hexsha": "83cfc1245609c50f21d13be5f180f67576c57735", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2267080745, "max_line_length": 211, "alphanum_fraction": 0.6033898305, "include": true, "reason": "import numpy", "num_tokens": 2858}
#!/usr/bin/env python """Tests for `datawrangler` package (decorate module).""" import os import datawrangler as dw import pandas as pd import numpy as np # noinspection PyTypeChecker def test_list_generalizer(): @dw.decorate.list_generalizer def f(x): return x ** 2 assert f(3) == 9 assert f([2, 3, 4]) == [4, 9, 16] # noinspection PyTypeChecker def test_funnel(data_file, data, img_file, text_file): @dw.decorate.list_generalizer @dw.decorate.funnel def g(x): return x.pow(2) assert int(g(3).values) == 9 assert list([int(i.values) for i in g([3, 4, 5])]) == [9, 16, 25] assert g(np.array([1, 2, 3])).values.tolist() == [[1, 4, 9]] # noinspection PyShadowingNames @dw.decorate.funnel def f(x): assert dw.zoo.is_dataframe(x[0][0]) assert dw.zoo.is_text(x[1][0]) return x dataframe_kwargs = {'load_kwargs': {'index_col': 0}} text_kwargs = {'model': 'StackedEmbeddings'} wrangle_kwargs = {'return_dtype': True} wrangled, inferred_dtypes = f([data_file, data, data.values, img_file, text_file], dataframe_kwargs=dataframe_kwargs, text_kwargs=text_kwargs, wrangle_kwargs=wrangle_kwargs) correct_dtypes = ['dataframe', 'dataframe', 'array', 'array', 'text'] assert all([i == c for i, c in zip(inferred_dtypes, correct_dtypes)]) assert np.allclose(wrangled[0].values, wrangled[1].values) assert np.allclose(wrangled[0].values, wrangled[2].values) assert wrangled[3].shape == (1400, 5760) assert np.isclose(wrangled[3].values.mean(), 152.193) assert dw.util.btwn(wrangled[3], 12, 248) assert wrangled[4].shape == (1, 4196) assert dw.util.btwn(wrangled[4], -1, 1) assert np.isclose(wrangled[4].values.mean(), 0.00449942) def test_interpolate(data): # test imputing impute_test = data.copy() impute_test.loc[4, 'SecondDim'] = np.nan impute_test.loc[8, 'FourthDim'] = np.nan @dw.decorate.interpolate def f(x): return x # noinspection PyCallingNonCallable recovered_data1 = f(impute_test, interp_kwargs={'impute_kwargs': {'model': 'IterativeImputer'}}) assert np.allclose(data, recovered_data1) assert dw.zoo.is_dataframe(data) assert dw.zoo.is_dataframe(recovered_data1) # test interpolation interp_test = data.copy() interp_test.loc[5] = np.nan # noinspection PyCallingNonCallable recovered_data2 = f(interp_test, interp_kwargs={'method': 'linear'}) assert np.allclose(data, recovered_data2) assert dw.zoo.is_dataframe(data) assert dw.zoo.is_dataframe(recovered_data2) # impute + interpolate impute_interp_test = data.copy() impute_interp_test.loc[2, 'ThirdDim'] = np.nan impute_interp_test.loc[0, 'FourthDim'] = np.nan impute_interp_test.loc[8, 'FifthDim'] = np.nan impute_interp_test.loc[4] = np.nan # noinspection PyCallingNonCallable recovered_data3 = f(impute_interp_test, interp_kwargs={'impute_kwargs': {'model': 'IterativeImputer'}, 'method': 'pchip'}) assert np.allclose(recovered_data3.values[~np.isnan(impute_interp_test)], data.values[~np.isnan(impute_interp_test)]) assert dw.zoo.is_dataframe(data) assert dw.zoo.is_dataframe(recovered_data3) def test_apply_unstacked(data): i = 3 data1 = data.iloc[:i] data2 = data.iloc[i:] stacked_data = dw.stack([data1, data2]) assert np.allclose(stacked_data, data) @dw.decorate.apply_unstacked def f(x): return pd.DataFrame(x.mean(axis=0)).T means = f(stacked_data) assert dw.zoo.is_multiindex_dataframe(means) assert np.allclose(means.iloc[0], data1.mean(axis=0)) assert np.allclose(means.iloc[1], data2.mean(axis=0)) xs = [np.cumsum(np.random.randn(100, 5), axis=0) for _ in range(10)] @dw.decorate.apply_unstacked def g(x): return x assert all(np.allclose(x, y) for x, y in zip(xs, g(xs))) assert all(np.allclose(x, y) for x, y in zip(xs, dw.unstack(g(dw.stack(xs))))) def test_unstack(data): xs = dw.wrangle([np.cumsum(np.random.randn(100, 5), axis=0) for _ in range(10)]) ys = dw.wrangle([np.cumsum(np.random.randn(100, 5), axis=0) for _ in range(10)]) stacked_xs = dw.stack(xs) stacked_ys = dw.stack(ys) stacked_xy = dw.stack([stacked_xs, stacked_ys]) assert np.allclose(dw.unstack(stacked_xs)[0], xs[0]) assert np.allclose(dw.unstack(stacked_xs)[0].index.values, xs[0].index.values) assert np.allclose(dw.unstack(stacked_xy)[0], stacked_xs) assert dw.zoo.is_multiindex_dataframe(dw.unstack(stacked_xy)[0]) assert np.allclose(dw.unstack(stacked_xy)[0].index.to_frame(), stacked_xs.index.to_frame()) def test_apply_stacked(data): i = 4 data1 = data.iloc[:i] data2 = data.iloc[i:] @dw.decorate.apply_stacked def f(x): return x.mean(axis=0) # noinspection PyTypeChecker means = f([data1, data2]) assert np.allclose(means, data.mean(axis=0))
{"hexsha": "b9f934a8376d0258765f1733a983cf48c3d49593", "size": 5147, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/wrangler/test_decorate.py", "max_stars_repo_name": "ContextLab/data-wrangler", "max_stars_repo_head_hexsha": "80cebdb1acaf0c1a2af34f56161e80d81e962ab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-07-04T14:39:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:28:03.000Z", "max_issues_repo_path": "test_decorate.py", "max_issues_repo_name": "jyotidabass/text_wrangler", "max_issues_repo_head_hexsha": "e76117d0698f2dfd9bebeebcf53d11d49650cadc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2021-07-04T14:40:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-05T15:13:37.000Z", "max_forks_repo_path": "test_decorate.py", "max_forks_repo_name": "jyotidabass/text_wrangler", "max_forks_repo_head_hexsha": "e76117d0698f2dfd9bebeebcf53d11d49650cadc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-14T18:09:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T18:09:38.000Z", "avg_line_length": 32.3710691824, "max_line_length": 106, "alphanum_fraction": 0.651641733, "include": true, "reason": "import numpy", "num_tokens": 1463}
import importlib import logging import os import pkg_resources import sys import time import numpy as np import pandas as pd import tables import yaml def setup_logging(config, log_dir, debug, log_to_file): # Log configuration to a text file in the log dir time_str = time.strftime('%Y%m%d_%H%M%S') config_filename = os.path.join(log_dir, time_str + '_config.yml') with open(config_filename, 'w') as outfile: ctlearn_version = pkg_resources.get_distribution("ctlearn").version tensorflow_version = pkg_resources.get_distribution("tensorflow").version outfile.write('# Training performed with ' 'CTLearn version {} and TensorFlow version {}.\n'.format(ctlearn_version, tensorflow_version)) yaml.dump(config, outfile, default_flow_style=False) # Set up logger logger = logging.getLogger() if debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) logger.handlers = [] # remove existing handlers from any previous runs if not log_to_file: handler = logging.StreamHandler() else: logging_filename = os.path.join(log_dir, time_str + '_logfile.log') handler = logging.FileHandler(logging_filename) handler.setFormatter(logging.Formatter("%(levelname)s:%(message)s")) logger.addHandler(handler) return logger def setup_DL1DataReader(config, mode): # Parse file list or prediction file list if mode in ['train', 'load_only']: if isinstance(config['Data']['file_list'], str): data_files = [] with open(config['Data']['file_list']) as f: for line in f: line = line.strip() if line and line[0] != "#": data_files.append(line) config['Data']['file_list'] = data_files if not isinstance(config['Data']['file_list'], list): raise ValueError("Invalid file list '{}'. " "Must be list or path to file".format(config['Data']['file_list'])) else: file_list = config['Prediction']['prediction_file_lists'][config['Prediction']['prediction_label']] if file_list.endswith(".txt"): data_files = [] with open(file_list) as f: for line in f: line = line.strip() if line and line[0] != "#": data_files.append(line) config['Data']['file_list'] = data_files elif file_list.endswith(".h5"): config['Data']['file_list'] = [file_list] if not isinstance(config['Data']['file_list'], list): raise ValueError("Invalid prediction file list '{}'. " "Must be list or path to file".format(file_list)) with tables.open_file(config['Data']['file_list'][0], mode="r") as f: if 'CTA PRODUCT DATA MODEL NAME' in f.root._v_attrs: data_format = 'stage1' elif 'dl1_data_handler_version' in f.root._v_attrs: data_format = 'dl1dh' else: raise ValueError("Data format is not implemented in the DL1DH reader. Available data formats are 'stage1' and 'dl1dh'.") allow_overwrite = config['Data'].get('allow_overwrite', True) if 'allow_overwrite' in config['Data']: del config['Data']['allow_overwrite'] selected_telescope_types = config['Data']['selected_telescope_types'] camera_types = [tel_type.split("_")[-1] for tel_type in selected_telescope_types] tasks = config['Reco'] transformations = [] event_info = [] if data_format == 'dl1dh': # Parse list of event selection filters event_selection = {} for s in config['Data'].get('event_selection', {}): s = {'module': 'dl1_data_handler.filters', **s} filter_fn, filter_params = load_from_module(**s) event_selection[filter_fn] = filter_params config['Data']['event_selection'] = event_selection # Parse list of image selection filters image_selection = {} for s in config['Data'].get('image_selection', {}): s = {'module': 'dl1_data_handler.filters', **s} filter_fn, filter_params = load_from_module(**s) image_selection[filter_fn] = filter_params config['Data']['image_selection'] = image_selection if 'direction' in tasks: event_info.append('src_pos_cam_x') event_info.append('src_pos_cam_y') transformations.append({'name': 'AltAz', 'args': {'alt_col_name': 'src_pos_cam_x', 'az_col_name': 'src_pos_cam_y', 'deg2rad': False}}) else: if 'direction' in tasks: event_info.append('true_alt') event_info.append('true_az') transformations.append({'name': 'DeltaAltAz_fix_subarray'}) if 'particletype' in tasks: event_info.append('true_shower_primary_id') transformations.append({'name': 'ShowerPrimaryID'}) if 'energy' in tasks: event_info.append('true_energy') transformations.append({'name': 'MCEnergy'}) concat_telescopes = config['Input'].get('concat_telescopes', False) if config['Data']['mode'] == 'stereo' and not concat_telescopes: for tel_desc in selected_telescope_types: transformations.append({'name': 'SortTelescopes', 'args': {'sorting': 'size', 'tel_desc': f'{tel_desc}'}}) # Convert interpolation image shapes from lists to tuples, if present if 'interpolation_image_shape' in config['Data'].get('mapping_settings',{}): config['Data']['mapping_settings']['interpolation_image_shape'] = {k: tuple(l) for k, l in config['Data']['mapping_settings']['interpolation_image_shape'].items()} if allow_overwrite: config['Data']['event_info'] = event_info config['Data']['mapping_settings']['camera_types'] = camera_types else: transformations = config['Data'].get('transforms', {}) transforms = [] # Parse list of Transforms for t in transformations: t = {'module': 'dl1_data_handler.transforms', **t} transform, args = load_from_module(**t) transforms.append(transform(**args)) config['Data']['transforms'] = transforms # Possibly add additional info to load if predicting to write later if mode == 'predict': if 'Prediction' not in config: config['Prediction'] = {} if config['Prediction'].get('save_identifiers', False): if 'event_info' not in config['Data']: config['Data']['event_info'] = [] config['Data']['event_info'].extend(['event_id', 'obs_id']) if config['Data']['mode'] == 'mono': if 'array_info' not in config['Data']: config['Data']['array_info'] = [] config['Data']['array_info'].append('id') return config['Data'], data_format def load_from_module(name, module, path=None, args=None): if path is not None and path not in sys.path: sys.path.append(path) mod = importlib.import_module(module) fn = getattr(mod, name) params = args if args is not None else {} return fn, params
{"hexsha": "999881516f5de581f406dd1f5006208493a9f300", "size": 7236, "ext": "py", "lang": "Python", "max_stars_repo_path": "ctlearn/utils.py", "max_stars_repo_name": "bryankim96/deep-learning-gamma", "max_stars_repo_head_hexsha": "cac4f2d90b6536eedf95c3a07ea73d4c7a69c5b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-03-06T01:44:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-22T12:47:03.000Z", "max_issues_repo_path": "ctlearn/utils.py", "max_issues_repo_name": "bryankim96/deep-learning-gamma", "max_issues_repo_head_hexsha": "cac4f2d90b6536eedf95c3a07ea73d4c7a69c5b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2018-02-08T22:05:38.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-13T11:44:51.000Z", "max_forks_repo_path": "ctlearn/utils.py", "max_forks_repo_name": "bryankim96/deep-learning-gamma", "max_forks_repo_head_hexsha": "cac4f2d90b6536eedf95c3a07ea73d4c7a69c5b7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-13T15:38:46.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-12T01:31:42.000Z", "avg_line_length": 41.3485714286, "max_line_length": 171, "alphanum_fraction": 0.6194029851, "include": true, "reason": "import numpy", "num_tokens": 1595}
export BackwardPlanner, BackwardGreedyPlanner, BackwardAStarPlanner "Heuristic-guided best-first backward search." @kwdef mutable struct BackwardPlanner <: Planner heuristic::Heuristic = GoalCountHeuristic(:backward) g_mult::Float64 = 1.0 # Path cost multiplier h_mult::Float64 = 1.0 # Heuristic multiplier max_nodes::Int = typemax(Int) save_search::Bool = false # Flag to save search info end "Backward greedy search, with cycle checking." BackwardGreedyPlanner(heuristic::Heuristic; kwargs...) = BackwardPlanner(;heuristic=heuristic, g_mult=0, kwargs...) "Backward A* search." BackwardAStarPlanner(heuristic::Heuristic; kwargs...) = BackwardPlanner(;heuristic=heuristic, kwargs...) function solve(planner::BackwardPlanner, domain::Domain, state::State, spec::Specification) @unpack h_mult, heuristic, save_search = planner # Precompute heuristic information precompute!(heuristic, domain, state, spec) # Convert to backward search goal specification spec = BackwardSearchGoal(spec, state) state = State(get_goal_terms(spec), PDDL.get_types(state)) # Initialize search tree and priority queue node_id = hash(state) search_tree = Dict{UInt,PathNode}(node_id => PathNode(node_id, state, 0)) est_cost = h_mult * heuristic(domain, state, spec) queue = PriorityQueue{UInt,Float64}(node_id => est_cost) # Run the search status, node_id = search!(planner, domain, spec, search_tree, queue) # Reconstruct plan and return solution if status != :failure plan, traj = reconstruct(node_id, search_tree) reverse!(plan); reverse!(traj) if save_search return PathSearchSolution(status, plan, traj, search_tree, queue) else return PathSearchSolution(status, plan, traj) end elseif save_search return PathSearchSolution(status, [], [], search_tree, queue) else return NullSolution() end end function search!(planner::BackwardPlanner, domain::Domain, spec::BackwardSearchGoal, search_tree::Dict{UInt,PathNode}, queue::PriorityQueue) count = 1 while length(queue) > 0 # Get state with lowest estimated cost to start state node_id = dequeue!(queue) node = search_tree[node_id] # Return status and current state if search terminates if is_goal(spec, domain, node.state) return :success, node_id # Start state reached elseif count >= planner.max_nodes return :max_nodes, node_id # Node budget reached end count += 1 # Expand current node expand!(planner, node, search_tree, queue, domain, spec) end return :failure, nothing end function expand!(planner::BackwardPlanner, node::PathNode, search_tree::Dict{UInt,PathNode}, queue::PriorityQueue, domain::Domain, spec::BackwardSearchGoal) @unpack g_mult, h_mult, heuristic = planner state = node.state # Iterate over relevant actions actions = relevant(state, domain) for act in actions # Regress (reverse-execute) the action next_state = regress(act, state, domain; check=false) # Add constraints to regression state add_constraints!(spec, state) next_id = hash(next_state) # Compute path cost act_cost = get_cost(spec, domain, state, act, next_state) path_cost = node.path_cost + act_cost # Update path costs if new path is shorter next_node = get!(search_tree, next_id, PathNode(next_id, next_state, Inf)) cost_diff = next_node.path_cost - path_cost if cost_diff > 0 next_node.parent_id = node.id next_node.parent_action = act next_node.path_cost = path_cost # Update estimated cost from next state to start if !(next_id in keys(queue)) g_val = g_mult * path_cost h_val = h_mult * heuristic(domain, next_state, spec) enqueue!(queue, next_id, g_val + h_val) else queue[next_id] -= cost_diff end end end end
{"hexsha": "e969f7f2b0e55789190b680dba96a75ffd5bb98b", "size": 4224, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/planners/backward.jl", "max_stars_repo_name": "owenps/SymbolicPlanners.jl", "max_stars_repo_head_hexsha": "824dedf9a73b9ee4f4881af0c16fe8963f033e4f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/planners/backward.jl", "max_issues_repo_name": "owenps/SymbolicPlanners.jl", "max_issues_repo_head_hexsha": "824dedf9a73b9ee4f4881af0c16fe8963f033e4f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/planners/backward.jl", "max_forks_repo_name": "owenps/SymbolicPlanners.jl", "max_forks_repo_head_hexsha": "824dedf9a73b9ee4f4881af0c16fe8963f033e4f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.476635514, "max_line_length": 77, "alphanum_fraction": 0.6555397727, "num_tokens": 1000}
# (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import numpy as np import matplotlib.pyplot as plt import matplotlib data_depth = [1,3,4,5,6,7,8,9,10,15,20,30,40] data_Uerr = [0.628245746335422,0.22290757952981,0.149242822500311,0.08143287647172,0.029886812723847,6.45E-05,2.46E-05,3.78E-05,4.34E-05,2.70E-05,1.21E-05,1.73E-05,1.22E-05] data_dn = [1.9230726255549,0.862176266043871,0.557000208494517,0.491780449406918,0.385602812975596,0.427080269538043,0.461409922345587,0.522259333008194,0.538863530077179,0.769370902842745,0.972278468049599,1.24556563035902,1.41580566008791] data_ref = 1.777408917389572 plt.rc('font', family='serif', serif='Palatino', size=9) plt.rc('text', usetex=True) plt.rc('xtick', labelsize=9) plt.rc('ytick', labelsize=9) plt.rc('axes', labelsize=9) COLORS = [ '#02A5CF', '#DE2019', '#FFBF00', '#29BF12', '#574AE2' ] fig, ax = plt.subplots() fig.subplots_adjust(left=.21, bottom=.16, right=.97, top=.9) ax.plot(data_depth, data_dn, color=COLORS[4]) ax.plot([0., 100.], [data_ref, data_ref], color=COLORS[1], ls='--') ax.set_title("(a)") ax.set_xlim([0, np.max(data_depth)]) ax.set_ylim([0, 2.]) ax.set_xlabel('Number of layers') ax.set_ylabel('Error (diamond norm)') #ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(xax_tick)) #ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(yax_tick)) #ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) ax.text(15., 1.8, "Reference", color=COLORS[1]) fig.set_size_inches(2.5, 2.5) plt.savefig('plots/vua_dn.pdf') fig, ax = plt.subplots() fig.subplots_adjust(left=.21, bottom=.16, right=.97, top=.9) ax.plot(data_depth, data_Uerr, color=COLORS[0]) ax.set_title("(b)") ax.set_xlim([0, 15.]) ax.set_xlabel('Number of layers') ax.set_ylabel('L2 Unitary Approximation Error') #ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(xax_tick)) #ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(yax_tick)) #ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) fig.set_size_inches(2.5, 2.5) plt.savefig('plots/vua_Uerr.pdf')
{"hexsha": "7481637669d33bf88f72b953f4d3040cc8e71d33", "size": 2490, "ext": "py", "lang": "Python", "max_stars_repo_path": "figure4/plot.py", "max_stars_repo_name": "ChriPiv/stinespring-algo-paper", "max_stars_repo_head_hexsha": "d61cf46c302c511286280e5de2b22d01284a4379", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "figure4/plot.py", "max_issues_repo_name": "ChriPiv/stinespring-algo-paper", "max_issues_repo_head_hexsha": "d61cf46c302c511286280e5de2b22d01284a4379", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure4/plot.py", "max_forks_repo_name": "ChriPiv/stinespring-algo-paper", "max_forks_repo_head_hexsha": "d61cf46c302c511286280e5de2b22d01284a4379", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-29T10:02:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T10:02:13.000Z", "avg_line_length": 39.5238095238, "max_line_length": 241, "alphanum_fraction": 0.7361445783, "include": true, "reason": "import numpy", "num_tokens": 837}
import os import numpy as np import pandas as pd import time import ray import tensorflow.keras as keras from cerebro.backend.ray.backend import RayBackend from cerebro.storage import LocalStore from cerebro.keras import RayEstimator from cerebro.tune import RandomSearch, GridSearch, hp_choice import random random.seed(2021) # Change the model/loss/optimizer definitions in this function. def estimator_gen_fn(params): # params used: lr, lambda_value (for regularization) lr = params["lr"] lambda_regularizer = params["lambda_value"] INPUT_SHAPE = (784, ) NUM_CLASSES = 10 SEED = 2021 model = keras.models.Sequential() model.add(keras.layers.Dense(1000, activation='relu', input_shape=INPUT_SHAPE)) model.add(keras.layers.Dense(500, activation='relu')) model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax')) regularizer = keras.regularizers.l2(lambda_regularizer) for layer in model.layers: for attr in ['kernel_regularizer', 'bias_regularizer']: if hasattr(layer, attr): setattr(layer, attr, regularizer) for attr in ['kernel_initializer', 'bias_initializer']: if hasattr(layer, attr): layer_initializer = getattr(layer, attr) if hasattr(layer_initializer, 'seed'): setattr(layer_initializer, 'seed', SEED) optimizer = keras.optimizers.Adam(lr=lr) loss = keras.losses.CategoricalCrossentropy() keras_estimator = RayEstimator( model=model, optimizer=optimizer, loss=loss, metrics=['acc'], batch_size=128, transformation_fn=None) return keras_estimator def main(): # Replace this root folder with the folder where you place your data OUTPUT_PATH = "/proj/orion-PG0/rayMnistDataset/" NUM_PARTITIONS = 4 print("STARTING BACKEND NOW") backend = RayBackend(num_workers=NUM_PARTITIONS) # You can change train_data.parquet and val_data.parquet with your data files, but make sure they are parquet files. store = LocalStore(OUTPUT_PATH, train_path=os.path.join(OUTPUT_PATH, 'train_data.parquet'), \ val_path=os.path.join(OUTPUT_PATH, 'val_data.parquet')) # You can change the hyperparameter search space over here. param_grid_criteo = { "lr": hp_choice([1e-3, 1e-4]), "lambda_value": hp_choice([1e-4, 1e-5]), } model_selection = GridSearch(backend, store, estimator_gen_fn, param_grid_criteo, 5, evaluation_metric='acc', feature_columns=['features'], label_columns=['label'], verbose=0) begin_time = time.time() model = model_selection.fit_on_prepared_data() time_taken = time.time() - begin_time print(model.get_best_model_history()) return time_taken if __name__ == "__main__": time_taken = main() print("Time for Cerebro Ray:") print(time_taken)
{"hexsha": "8e4b9f0832584870319dd94e7291d6e64132b1b3", "size": 3060, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/mnist/model_selection.py", "max_stars_repo_name": "Abhishek2304/Cerebro-System-Ray", "max_stars_repo_head_hexsha": "1e2f2ae291cd449573f87bb83fb2bda12e606b3a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/mnist/model_selection.py", "max_issues_repo_name": "Abhishek2304/Cerebro-System-Ray", "max_issues_repo_head_hexsha": "1e2f2ae291cd449573f87bb83fb2bda12e606b3a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/mnist/model_selection.py", "max_forks_repo_name": "Abhishek2304/Cerebro-System-Ray", "max_forks_repo_head_hexsha": "1e2f2ae291cd449573f87bb83fb2bda12e606b3a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9032258065, "max_line_length": 121, "alphanum_fraction": 0.6578431373, "include": true, "reason": "import numpy", "num_tokens": 687}
# help manual of "Data input" functions ?read.table ?read.csv # read csv to frame my_data <- read.csv('evals.csv') # open data table in window View(mydata) # structure of frame str(mydata) # return vector of value's names names(mydata) # create new var in frame mydata$nvar <- 0 # amount of rows in frame nrow(mydata) # return amount of vars(cols) in frame ncol(mydata) # identity rows in frame by num mydata$id <- 1:nrow(mydata) # summaty data of all vars in frame summary(mydata) # use one of them var in frame mydata$score *2 # create logical vector mydata$gender == 'female' # select ops by logical vector mydata[mydata$gender == 'female',1] # create set about query subset(mydata, gender == 'female') subset(mydata, score > 3.5) # separate frame to set mydata2 <- subset(mydata, gender == 'female') mydata3 <- subset(mydata, gender == 'male') # joins sets to frame mydata4 <- rbind(mydata2, mydata3) # separete frame by cols mydata5 <- mydata[,1:10] mydata6 <- mydata[,11:23] # join frame by cols mydata7 <- cbind(mydata5, mydata6) # show avaible system datasets library(help="datasets") df <- mtcars df$even_gear <- 1- df$gear %% 2 print(df$even_gear) print(df[df$cyl == 4,1]) df[c(3,7,10,12,nrow(df)),1:ncol(df)]
{"hexsha": "4b4810f169088ee0881b6eeff57c8dfa36e5f5bd", "size": 1243, "ext": "r", "lang": "R", "max_stars_repo_path": "dataframes.r", "max_stars_repo_name": "Sokel/R-shchu", "max_stars_repo_head_hexsha": "0b5b48b018bf85caca89fefb1896468f6039568c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dataframes.r", "max_issues_repo_name": "Sokel/R-shchu", "max_issues_repo_head_hexsha": "0b5b48b018bf85caca89fefb1896468f6039568c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dataframes.r", "max_forks_repo_name": "Sokel/R-shchu", "max_forks_repo_head_hexsha": "0b5b48b018bf85caca89fefb1896468f6039568c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5070422535, "max_line_length": 45, "alphanum_fraction": 0.7023330652, "num_tokens": 392}
from os import listdir from os.path import isfile, join,isdir import sys from pathlib import Path import numpy as np from PIL import Image import cv2 import os class DataPrepare(): def __init__(self): self.basedir=r'./DeepLabv3FineTuning/ADEChallengeData2016/' self.basedir_annt=r'..\freespacetrainingdataset\ADEChallengeData2016\annotations\training' self.basedir_imgt=r'..\freespacetrainingdataset/ADEChallengeData2016/images/training' #'C:\Users\caofamily\temp\freespacetrainingdataset\ADEChallengeData2016 self.target_imgdir=r'.\FloorDataLs\Images' self.target_segdir=r'.\FloorDataLs\Masks' self.names=[] for i in range(1, 20000, 1): # Just to generate bigger numbers self.names.append([f"{i:05d}.png",f"{i:05d}.jpg"]) def get_img_seg_files(self): segfiles = list(Path(self.basedir_annt).rglob("*.png")) imgfiles=list(Path(self.basedir_imgt).rglob("*.jpg")) return imgfiles,segfiles def process(self,segno=4,size=(160,120)): imgfs,segfs=self.get_img_seg_files() n_files = len(segfs) processed=0 satisfied=0 for segf in segfs: try: processed+=1 seg=np.array(Image.open(segf)) if segno in np.unique(seg): satisfied+=1 seg[seg!=segno]=0 seg[seg==segno]=255 imgr,segr=self.process_img_seg(segf,seg,size) self.write_to_target(imgr,segr) sys.stdout.write('\r>> Converting image %d/%d satisfied %d' % (processed, n_files, satisfied)) sys.stdout.flush() except Exception as e: print(segf,e) #if satisfied>150: #break def process_img_seg(self,segf,seg,size): head,tail=os.path.split(segf) imgf=tail.replace('.png','.jpg') imgf=os.path.join(self.basedir_imgt,imgf) img=np.array(Image.open(imgf)) seg=cv2.resize(seg,size,interpolation=cv2.INTER_NEAREST) img=cv2.resize(img,size,interpolation=cv2.INTER_NEAREST) return img,seg def write_to_target(self,img,seg): segf,imgf=self.names.pop(0) imgf=os.path.join(self.target_imgdir,imgf) segf=os.path.join(self.target_segdir,segf) cv2.imwrite(segf,seg) cv2.imwrite(imgf,img) if __name__ == '__main__': dp=DataPrepare() dp.process(segno=4,size=(160,120))
{"hexsha": "0040dbad23a817ac42fffbcd07ba2d8239533a59", "size": 2558, "ext": "py", "lang": "Python", "max_stars_repo_path": "dataprepare.py", "max_stars_repo_name": "angrysword/DeepLabv3FineTuning", "max_stars_repo_head_hexsha": "d97dd31620c0e65dd7cf4fd24581ded5af17465c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dataprepare.py", "max_issues_repo_name": "angrysword/DeepLabv3FineTuning", "max_issues_repo_head_hexsha": "d97dd31620c0e65dd7cf4fd24581ded5af17465c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dataprepare.py", "max_forks_repo_name": "angrysword/DeepLabv3FineTuning", "max_forks_repo_head_hexsha": "d97dd31620c0e65dd7cf4fd24581ded5af17465c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1951219512, "max_line_length": 110, "alphanum_fraction": 0.6082877248, "include": true, "reason": "import numpy", "num_tokens": 661}
import argparse import os import pickle import torch import numpy as np import matplotlib.pyplot as plt from util.bioinformatics_algorithms.edit_distance import cross_distance_matrix_threads from util.data_handling.string_generator import string_to_list class ClosestStringGenomicDatasetGenerator: def __init__(self, strings_reference, strings_query, n_queries, plot=False): # compute maximum length and transform sequences into list of integers length = max(len(s) for s in strings_reference + strings_query) sequences_references = [string_to_list(s, length=length) for s in strings_reference] sequences_queries = [string_to_list(s, length=length) for s in strings_query] # compute distances and find reference with minimum distance distances = cross_distance_matrix_threads(strings_reference, strings_query, 5) minimum = np.min(distances, axis=0, keepdims=True) # queries are only valid if there is a unique answer (no exaequo) counts = np.sum((minimum+0.5 > distances).astype(float), axis=0) valid = counts == 1 labels = np.argmin(distances, axis=0)[valid][:n_queries] # print an histogram of the minimum distances if plot: plt.hist(x=np.min(distances, axis=0)[valid], bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85) plt.show() # convert to torch self.sequences_references = torch.from_numpy(np.asarray(sequences_references)).long() self.sequences_queries = torch.from_numpy(np.asarray(sequences_queries)[valid][:n_queries]).long() self.labels = torch.from_numpy(labels).float() print("Shapes:", "References", self.sequences_references.shape, " Queries", self.sequences_queries.shape, " Labels", self.labels.shape) def save_as_pickle(self, filename): directory = os.path.dirname(filename) if directory != '' and not os.path.exists(directory): os.makedirs(directory) with open(filename, 'wb') as f: pickle.dump((self.sequences_references, self.sequences_queries, self.labels), f) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--out', type=str, default="./data/closest_qiita_large.pkl", help='Output data path') parser.add_argument('--N_reference', type=int, default=1000, help='Number of reference sequences') parser.add_argument('--test_query', type=int, default=2000, help='Query sequences tested (some may be discarded)') parser.add_argument('--N_queries', type=int, default=2000, help='Number of queries') parser.add_argument('--source_sequences', type=str, default='./data/qiita.txt', help='Sequences data path') args = parser.parse_args() # load sequences with open(args.source_sequences, 'rb') as f: L = f.readlines() L = [l[:-1].decode('UTF-8') for l in L] # L = L[7700:] add for extrapolation from edit distance training strings_reference = L[:args.N_reference] strings_queries = L[args.N_reference: (len(L) if args.test_query < 0 else args.N_reference + args.test_query)] data = ClosestStringGenomicDatasetGenerator(strings_reference, strings_queries, args.N_queries) data.save_as_pickle(args.out)
{"hexsha": "758d1773af9eeecf6f1f8a511c0ea0d4d9dce95f", "size": 3276, "ext": "py", "lang": "Python", "max_stars_repo_path": "closest_string/task/dataset_generator_genomic.py", "max_stars_repo_name": "pchlenski/NeuroSEED", "max_stars_repo_head_hexsha": "6318431dcce22df70948251b103374f4a6e96fff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2021-07-07T08:09:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T19:48:48.000Z", "max_issues_repo_path": "closest_string/task/dataset_generator_genomic.py", "max_issues_repo_name": "pchlenski/NeuroSEED", "max_issues_repo_head_hexsha": "6318431dcce22df70948251b103374f4a6e96fff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-11T01:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T01:33:43.000Z", "max_forks_repo_path": "closest_string/task/dataset_generator_genomic.py", "max_forks_repo_name": "pchlenski/NeuroSEED", "max_forks_repo_head_hexsha": "6318431dcce22df70948251b103374f4a6e96fff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-11-01T06:05:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T13:06:10.000Z", "avg_line_length": 45.5, "max_line_length": 118, "alphanum_fraction": 0.7057387057, "include": true, "reason": "import numpy", "num_tokens": 732}
# B.C. Goodwin # Oscillatory behavior in enzymatic control processes # https://doi.org/10.1016/0065-2571(65)90067-1 using Logging using StructuralIdentifiability logger = Logging.SimpleLogger(stdout, Logging.Info) global_logger(logger) ode = @ODEmodel( x1'(t) = -b * x1(t) + 1 / (c + x4(t)), x2'(t) = alpha * x1(t) - beta * x2(t), x3'(t) = gama * x2(t) - delta * x3(t), x4'(t) = sigma * x4(t) * (gama * x2(t) - delta * x3(t)) / x3(t), y(t) = x1(t) ) @time println(assess_identifiability(ode))
{"hexsha": "a6716bc0d752d99f492bd01c3ffb68581a3c5177", "size": 518, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "examples/Goodwin.jl", "max_stars_repo_name": "iliailmer/StructuralIdentifiability.jl", "max_stars_repo_head_hexsha": "29f1104e357f2f2942ff5477871856d80518a6ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2021-07-14T14:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T16:49:40.000Z", "max_issues_repo_path": "examples/Goodwin.jl", "max_issues_repo_name": "iliailmer/StructuralIdentifiability.jl", "max_issues_repo_head_hexsha": "29f1104e357f2f2942ff5477871856d80518a6ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2021-07-15T21:15:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:50:55.000Z", "max_forks_repo_path": "examples/Goodwin.jl", "max_forks_repo_name": "iliailmer/StructuralIdentifiability.jl", "max_forks_repo_head_hexsha": "29f1104e357f2f2942ff5477871856d80518a6ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-08-28T14:40:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:21:47.000Z", "avg_line_length": 24.6666666667, "max_line_length": 68, "alphanum_fraction": 0.6177606178, "num_tokens": 193}
# standard library import sys import re from typing import Any, Dict, List, Literal, Tuple, Union import os import json import subprocess import time # third-party libraries import numpy as np import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects # local from validate_utils import write_report_to_dir # # # # # # # # # # # # # # # # # # # # # # # # # # # # # INPUT # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if len(sys.argv) < 3: print("ERROR: you should specify args:") print(" #1 GWAS summary statistics file in tsv format") print(" #2 path to json config file specifying which columns are which, or string \"standard\"") print(" #3 (optional) output: dir name to save textual and graphical report") exit(1) # GWAS_FILE has to be in a tabular tab-sep format with a header on the first line GWAS_FILE = sys.argv[1] JSON_CONFIG = sys.argv[2] REPORT_DIR = None REPORT_ABS_DIR = None if len(sys.argv) > 3 and sys.argv[3]: REPORT_DIR = sys.argv[3] REPORT_ABS_DIR = os.path.abspath(REPORT_DIR) def file_exists(path: str): return os.path.isfile(path) def dir_exists(path: str): return os.path.isdir(path) if not file_exists(GWAS_FILE): print(f"ERROR: provided gwas file doesn't exist: {GWAS_FILE}") exit(1) GWAS_FILE_o = open(GWAS_FILE, 'r') if JSON_CONFIG == "standard": cols_i: Dict[str, int] = { "Chr": 0, "BP": 1, "rsID": 2, "OA": 3, "EA": 4, "EAF": 5, "beta": 6, "SE": 7, "pval": 8, "N": 9, "INFO": 10, } else: if not file_exists(GWAS_FILE): print(f"ERROR: provided gwas file doesn't exist: {JSON_CONFIG}") exit(1) cols_i: Dict[str, int] = json.load(open(JSON_CONFIG,)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # USER SETTINGS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # tick labels. Numerical value will be inferred from this string. x = ["0", "1e-8", "1e-5", "1e-3", ".03", ".3", "1"] separator = '\t' ticks_width_rule_setting: Literal['even', 'log10'] = 'log10' ##### Validation of user settings ##### # p-value interval points: ticks = [float(x_label) for x_label in x] ticks_width_rule: Literal['even', 'log10'] = ticks_width_rule_setting assert ticks == sorted(ticks) and len(ticks) == len(set(ticks)), "Ticks have to be in strictly ascending order" assert ticks[0] >= 0 and ticks[-1] <= 1, "Ticks have to be in range from 0 to 1" # # # # # # # # # # # # # # # # # # # # # # # # # # # # # CONSTANTS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # GOOD_ENTRY = 0 MISSING_P_VALUE = 1 INVALID_ENTRY = 2 # indices for boolean values in a list of issues for each SNP INVALID_ROW = 0 INVALID_RSID = 1 INVALID_CHR = 2 INVALID_BP = 3 INVALID_EA = 4 INVALID_OA = 5 INVALID_EAF = 6 INVALID_SE = 7 INVALID_ES = 8 ISSUES=[ INVALID_ROW, INVALID_RSID, INVALID_CHR, INVALID_BP, INVALID_EA, INVALID_OA, INVALID_EAF, INVALID_SE, INVALID_ES, ] ISSUES_LABELS = [ "format", "rsID", "Chr", "BP", "EA", "OA", "EAF", "SE", "beta", ] ISSUES_COLORS=[ "#ff0000", # format "#777ae5", # rsID "#cf44a1", # Chr "#ff4481", # BP "#ffa121", # EA "#ff9191", # OA "#fdbc64", # EAF "#563E3E", # std. err. "#175a63", # beta ] NUCLEOTIDES = ['a', 't', 'c', 'g'] NO_NUCLEOTIDE = '.' ALLOW_MULTI_NUCLEOTIDE_POLYMORPHISMS = True CATEGORY_CHR = [ '1', '01', '2', '02', '3', '03', '4', '04', '5', '05', '6', '06', '7', '07', '8', '08', '9', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', 'X', 'x', 'Y', 'y', 'M', 'm'] # CATEGORY_CHR = [ # '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', # '21', '22', '23', 'X', 'x', 'Y', 'y', 'M', 'm'] # # # # # # # # # # # # # # # # # # # # # # # # # # # # # FUNCTIONS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # https://stackoverflow.com/a/850962/6041933 # a comment to the answer # https://gist.github.com/zed/0ac760859e614cd03652 def wccount(filename: str): """counts the number of lines in the file""" out = subprocess.Popen(['wc', '-l', filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT ).communicate()[0] return int(out.partition(b' ')[0]) def is_null(val: str) -> bool: return val.lower() in ["", " ", ".", "-", "na", "nan"] # # # # # # # # # # # # # # # # # # # # # # # # # # # # # FUNCTION THAT CHECKS EACH SNP ENTRY # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def check_row(line_cols: List[str]) -> Union[ # "good" entry Tuple[float, Literal[0], List[bool]], # "missing p-value" entry Tuple[None, Literal[1], List[bool]], # "invalid" entry, having some issues (listed in the list) Tuple[float, Literal[2], List[bool]], ]: """ This function runs for EVERY LINE of the input file, which may be MILLIONS OF TIMES per script execution Returns: - a p-value of a SNP, - a report of whether a SNP entry is valid, - and a list of issues with it """ issues = [False] * len(ISSUES) ### First check if p-value itself is present ### try: pval = line_cols[cols_i["pval"]] if is_null(pval) or not (0 <= float(pval) <= 1): return None, MISSING_P_VALUE, issues pval = float(pval) except: return None, MISSING_P_VALUE, issues ### Try getting all columns. If some not present, will throw ### try: rsid = line_cols[cols_i["rsID"]] chrom = line_cols[cols_i["Chr"]] bp = line_cols[cols_i["BP"]] ea = line_cols[cols_i["EA"]] oa = line_cols[cols_i["OA"]] af = line_cols[cols_i["EAF"]] se = line_cols[cols_i["SE"]] es = line_cols[cols_i["beta"]] # n = line_cols[cols_i["N"]] except: issues[INVALID_ROW] = True return pval, INVALID_ENTRY, issues ### Check any reasons this SNP will be discarded later ### # 1. rsID try: if not re.match("^rs\d+$", rsid): issues[INVALID_RSID] = True except: issues[INVALID_RSID] = True # 2. chromosome try: if chrom not in CATEGORY_CHR and chrom[3:] not in CATEGORY_CHR: issues[INVALID_CHR] = True except: issues[INVALID_CHR] = True # 3. base pair position try: bp = int(float(bp)) # using float allows sci notation string if bp < 0: issues[INVALID_BP] = True except: issues[INVALID_BP] = True # 4. effect allele try: if ea == '': issues[INVALID_EA] = True elif ea == NO_NUCLEOTIDE: issues[INVALID_EA] = False elif ALLOW_MULTI_NUCLEOTIDE_POLYMORPHISMS: for char in ea.lower(): if char not in NUCLEOTIDES: issues[INVALID_EA] = True else: if ea.lower() not in NUCLEOTIDES: issues[INVALID_EA] = True except: issues[INVALID_EA] = True # 5. other allele try: if oa == '': issues[INVALID_OA] = True elif oa == NO_NUCLEOTIDE: issues[INVALID_OA] = False elif ALLOW_MULTI_NUCLEOTIDE_POLYMORPHISMS: for char in oa.lower(): if char not in NUCLEOTIDES: issues[INVALID_OA] = True else: if oa.lower() not in NUCLEOTIDES: issues[INVALID_OA] = True except: issues[INVALID_OA] = True # 6. effect allele frequency or minor allele frequency try: if not (0 <= float(af) <= 1): issues[INVALID_EAF] = True except: issues[INVALID_EAF] = True # 7. standard error try: float(se) # will throw if not float if is_null(se): issues[INVALID_SE] = True except: issues[INVALID_SE] = True # 8. effect size (odds ratio or beta-value) try: float(es) # will throw if not float if is_null(es): issues[INVALID_ES] = True except: issues[INVALID_ES] = True # # 9. n - sample size # #sometimes sample size is fractional # if null_entry(n) or not (0 < float(n)): # return INVALID_ENTRY, pval if any(issues): return pval, INVALID_ENTRY, issues else: # all good? return pval, GOOD_ENTRY, issues # # # # # # # # # # # # # # # # # # # # # # # # # # # # # MAIN # # # # # # # # # # # # # # # # # # # # # # # # # # # # # MAIN_start_time = STEP1_start_time = time.time() # # STEP #1 # read the file line by line and check the validity of each SNP entry, # and save the report and the p-value if present # num_of_lines = wccount(GWAS_FILE) num_of_snps = num_of_lines - 1 print(f"number of lines in the file: {num_of_lines}") line_i=0 # skip the first line that is the header GWAS_FILE_o.readline() line_i+=1 SNPs_pval = np.empty(num_of_snps, dtype=float) SNPs_report = np.empty(num_of_snps, dtype=int) SNPs_issues = np.empty((num_of_snps, len(ISSUES)), dtype=bool) ### populate the allocated array with report for each SNP as well as its p-value ### try: snp_i = 0 while True: SNPs_pval[snp_i], SNPs_report[snp_i], SNPs_issues[snp_i] = check_row(GWAS_FILE_o.readline().replace('\n','').split(separator)) snp_i += 1 except Exception as e: if isinstance(e, IndexError) or isinstance(e, EOFError): # it reached the end of the file pass else: print(f'An error occured on line {line_i} of the GWAS SS file (see below)') raise e ### ### GWAS_FILE_o.close() print("--- STEP1: %s seconds ---" % (time.time() - STEP1_start_time)) # result: SNPs_report, SNPs_pval # # STEP #2 # sum up the reports and calculate the parameters before plotting # STEP2_start_time = time.time() # 2.1 """ Bar widths start from the right, i.e. the last bar refers to the range between the last two ticks. The very first bar is "no p-value" bar, it has unit width and goes to the left of the first tick. If the very first tick is zero, then the bin size from zero to the next tick is 2 units. User may have choosen the rule of ticks width to either 'even' or 'log10': • With 'even', all bars will have unit width, regardless of the numerical difference between ticks • With 'log10', all bars will have widths adjusted in accord to log10 scale, with a constant unit_width defined here """ bars_widths = [1.] if ticks_width_rule == 'even': for i in range(1, len(ticks)): bars_widths.append(1.) elif ticks_width_rule == 'log10': unit_width = np.log10(1) - np.log10(1e-2) for i in range(1, len(ticks)): if ticks[i-1] == 0: bars_widths.append(2.) else: bars_widths.append( (np.log10(ticks[i]) - np.log10(ticks[i-1])) / unit_width ) else: raise ValueError(f'unknown ticks_width_rule: {ticks_width_rule}') negative_bars_widths = list(-np.array(bars_widths)) # 2.2 """ Ticks location (ticks_loc) equals to cumulative of bars_widths, shifted by the very first bar width to the left, so the tick #1 equals 0 """ ticks_loc: List[float] = [] cumulative = -bars_widths[0] # starting such that the first loc is 0 for width in bars_widths: cumulative += width ticks_loc.append(cumulative) del cumulative assert len(ticks) == len(bars_widths) == len(ticks_loc), "lists: `ticks`, `ticks_loc`, and `bars_widths` should have the same lengths" # 2.3 ### Counting how many entries are valid, don't have p-value, or invalid for other reasons ### missing_pval_bins = [0]*len(ticks) good_entry_bins = [0]*len(ticks) invalid_entry_bins = [0]*len(ticks) # besides total, for each of the bin we'll store the number of invalid entries for each type invalid_entry_bins_reason_bins = np.zeros((len(ticks), max(ISSUES)+1)).astype(int) for line_i in range(len(SNPs_report)): if SNPs_report[line_i] == MISSING_P_VALUE: missing_pval_bins[0] += 1 elif SNPs_report[line_i] == GOOD_ENTRY: for j in range(1,len(ticks)): if SNPs_pval[line_i] <= ticks[j]: good_entry_bins[j] += 1 break elif SNPs_report[line_i] == INVALID_ENTRY: for j in range(1, len(ticks)): if SNPs_pval[line_i] <= ticks[j]: invalid_entry_bins[j] += 1 invalid_entry_bins_reason_bins[j] += SNPs_issues[line_i] break ### ### print("--- STEP2: %s seconds ---" % (time.time() - STEP2_start_time)) print("=== MAIN: %s seconds ===" % (time.time() - MAIN_start_time)) # plotting doesn't count # # STEP #3 # save csv file with report for each issue # if REPORT_ABS_DIR: if not dir_exists(REPORT_ABS_DIR): os.makedirs(REPORT_ABS_DIR) issues_count: Dict[str, int] = {} for issue_i in range(0, len(ISSUES)): issues_count[ISSUES_LABELS[issue_i]] = sum([invalid_entry_bins_reason_bins[i][issue_i] for i in range(len(invalid_entry_bins))]) issues_count["pval"] = sum(missing_pval_bins) issues_count["total_entries"] = num_of_snps print(f"issues_count = {issues_count}") if REPORT_ABS_DIR: write_report_to_dir(issues_count, REPORT_ABS_DIR) # # STEP #4 # plot # ### CALC: proportion of invalid entries in total ### invalid_entries_totally = sum(invalid_entry_bins) + sum(missing_pval_bins) proportion_of_invalid_entries_totally = invalid_entries_totally / num_of_snps percentage_of_invalid_entries_totally = proportion_of_invalid_entries_totally * 100 percentage_of_invalid_entries_totally_str = str(np.round(percentage_of_invalid_entries_totally, 1)) + "%" ### PLOT: the figure, labels, ticks, bars ### fig, ax = plt.subplots(num="valid/invalid SNPs") image_name = GWAS_FILE.split('/')[-1] fig.canvas.set_window_title(image_name) # sets the window title to the filename ax.set_title( f"invalid SNPs: {invalid_entries_totally}/{num_of_snps} ({percentage_of_invalid_entries_totally_str})") # # Hide the right and top spines # ax.spines['right'].set_visible(False) # ax.spines['top'].set_visible(False) ax.tick_params(axis='x', labelsize=9) ax.set_xticks(ticks_loc) ax.set_xticklabels(x) ax.bar(ticks_loc, missing_pval_bins, negative_bars_widths, color='#7f7f7f', align='edge') ax.bar(ticks_loc, good_entry_bins, negative_bars_widths, color='#0000ff', align='edge', label="valid SNPs") ax.bar(ticks_loc, invalid_entry_bins, negative_bars_widths, color='#ff0000', align='edge', bottom=good_entry_bins, label="invalid SNPs") ax.set_xlabel("p-value", fontweight="heavy", fontsize=14) ax.set_ylabel("N of SNPs", fontweight="heavy", fontsize=14) ax.set_xlim([ticks_loc[0]+negative_bars_widths[0], ticks_loc[-1]]) max_bar_height = max( np.array(missing_pval_bins) + np.array(good_entry_bins) + np.array(invalid_entry_bins) # np arrays add element-wise ) plt_bottom, plt_top = ax.set_ylim(0, max_bar_height*1.15 if max_bar_height else 1) plt_height = plt_top - plt_bottom ### CALC: points right at the middle of each bin ### bins_mid_points = list(np.array(ticks_loc) - np.array(bars_widths)/2) ### PLOT: caption for "no p-value" bin ### ax.text(x=bins_mid_points[0], y=plt_top*-0.08, s="no\np-value", horizontalalignment='center', ) ### CALC: total entries, proportion and percentage of invalid entries ### total_p_value_entries_bins = [good_entry_bins[i]+invalid_entry_bins[i] for i in range(len(good_entry_bins))] proportion_of_invalid_entries_bins = [0.] + [ invalid_entry_bins[i]/total_p_value_entries_bins[i] if total_p_value_entries_bins[i] else 0. for i in range(1, len(good_entry_bins))] percentage_of_invalid_entries_bins = np.round(np.array(proportion_of_invalid_entries_bins)*100).astype(int) percentage_of_invalid_entries_bins_str = np.char.array(percentage_of_invalid_entries_bins) + "%" # type: ignore # pylance mistakenly doesn't recognize np.char ### PLOT: representation of the percentage of invalid entries for each bin ### # the bottom and the top spines of the plot represent 0% and 100% # skipping the first, "no p-value" bin ax.plot( # X: points right at the mid of bins (except the no p-value bin) bins_mid_points[1:], # Y: how much proportion -> that much height within the plot np.array(proportion_of_invalid_entries_bins[1:]) * plt_height + plt_bottom, linestyle='-', color="red", alpha=0.5, linewidth=2, ) ### PLOT: Captions above the points of the plot ### # shows percentage of invalid entries for each bin in text # skipping the first, "no p-value" bin # points right at the mid of bins X = bins_mid_points # how much proportion -> that much height within the plot, also lifted 5% Y = (np.array(proportion_of_invalid_entries_bins) * plt_height) + plt_height*0.05 + plt_bottom for i in range(1, len(percentage_of_invalid_entries_bins_str)): if proportion_of_invalid_entries_bins[i] > 0.15: text = ax.text(X[i], Y[i], s=percentage_of_invalid_entries_bins_str[i], horizontalalignment='center', color="#bf3f3f", # caption may overlap with the red stuff from stacked bar fontsize=10, fontweight="demibold", ) else: text = ax.text(X[i], Y[i], s=percentage_of_invalid_entries_bins_str[i], horizontalalignment='center', color="#ff0000", fontsize=10, ) # text.set_path_effects([path_effects.Stroke(linewidth=1, foreground='#000000'), # path_effects.Normal()]) if REPORT_ABS_DIR: fig.savefig(os.path.join(REPORT_ABS_DIR, image_name+'.png')) ### PLOT: bar chart for issues in each of the p-value bins ### for i in range(1, len(invalid_entry_bins)): image_name = f'bin_{i}__{x[i-1]}—{x[i]}' plot_i, ax = plt.subplots(num=image_name) issues_proportions = [0] * len(ISSUES) total_invalids = invalid_entry_bins[i] total_snps = invalid_entry_bins[i] + good_entry_bins[i] proportion_of_invalids = total_invalids / total_snps if total_snps else 0 percentage_of_invalids = proportion_of_invalids * 100 percentage_of_invalids_str = str(np.round(percentage_of_invalids, 1)) + "%" ax.set_title(f'issues in p-value: {x[i-1]} — {x[i]}\ninvalid SNPs: {total_invalids}/{total_snps} ({percentage_of_invalids_str})') ax.set_ylim(0, total_invalids if total_invalids > 0 else 1) ax.set_ylabel("N of invalid SNPs", fontweight="demibold", fontsize=14) if total_invalids == 0: ax.bar(ISSUES_LABELS, height=issues_proportions, width=1, color=ISSUES_COLORS) else: for issue in range(len(ISSUES)): # for each ISSUE issues_proportions[issue] = invalid_entry_bins_reason_bins[i][issue] / total_invalids ax.bar(ISSUES_LABELS, height=invalid_entry_bins_reason_bins[i], width=1, color=ISSUES_COLORS) if REPORT_ABS_DIR: plot_i.savefig(os.path.join(REPORT_ABS_DIR, image_name+'.png')) ### FINALLY: display results and the figure (if report directory was not set) ### # print(f'missing_pval_bins = {missing_pval_bins}') # print(f'good_entry_bins = {good_entry_bins}') # print(f'invalid_entry_bins = {invalid_entry_bins}') # print(f'proportion_of_invalid_entries_bins = {proportion_of_invalid_entries_bins}') # for i in range(1, len(invalid_entry_bins)): # print(f"{x[i-1]} — {x[i]}: {[invalid_entry_bins_reason_bins[i][issue] for issue in ISSUES]}") if not REPORT_DIR: plt.show() input("") input("")
{"hexsha": "91447de326a6694923d1d117820be2b0251adee7", "size": 20509, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/validate_GWASSS_entries.py", "max_stars_repo_name": "Titorat/SSrehab", "max_stars_repo_head_hexsha": "6691ee1ed442073bfa00a51f0d9ab74b9252d302", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/validate_GWASSS_entries.py", "max_issues_repo_name": "Titorat/SSrehab", "max_issues_repo_head_hexsha": "6691ee1ed442073bfa00a51f0d9ab74b9252d302", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/validate_GWASSS_entries.py", "max_forks_repo_name": "Titorat/SSrehab", "max_forks_repo_head_hexsha": "6691ee1ed442073bfa00a51f0d9ab74b9252d302", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9401459854, "max_line_length": 158, "alphanum_fraction": 0.5996879419, "include": true, "reason": "import numpy", "num_tokens": 5673}
@testset "678.valid-parenthesis-string.jl" begin @test check_valid_string("(())((())()()(*)(*()(())())())()()((()())((()))(*") == false @test check_valid_string(")(") == false @test check_valid_string("(*))") == true @test check_valid_string("(*)") == true @test check_valid_string("()") == true end
{"hexsha": "c70c5c4347c7c1ab92203ea069f822acca167b91", "size": 319, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/problems/678.valid-parenthesis-string.jl", "max_stars_repo_name": "jmmshn/LeetCode.jl", "max_stars_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2020-10-27T18:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:27:49.000Z", "max_issues_repo_path": "test/problems/678.valid-parenthesis-string.jl", "max_issues_repo_name": "jmmshn/LeetCode.jl", "max_issues_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57, "max_issues_repo_issues_event_min_datetime": "2020-11-01T07:26:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T11:57:53.000Z", "max_forks_repo_path": "test/problems/678.valid-parenthesis-string.jl", "max_forks_repo_name": "jmmshn/LeetCode.jl", "max_forks_repo_head_hexsha": "dd2f34af8d253b071e8a36823d390e52ad07ab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2020-10-30T11:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T10:35:11.000Z", "avg_line_length": 45.5714285714, "max_line_length": 90, "alphanum_fraction": 0.5454545455, "num_tokens": 94}
import torch import torch.nn as nn import torch.nn.functional as func from torch.autograd import Variable from torchvision.utils import save_image import os import numpy as np class Discriminator(nn.Module): def __init__(self, config): super(Discriminator, self).__init__() self.label_embedding = nn.Embedding(config.n_classes, config.n_classes) self.config = config self.model = nn.Sequential( nn.Linear(config.n_classes + int(np.prod(config.img_shape)), 512), nn.LeakyReLU(0.2, inplace=True), nn.Linear(512, 512), nn.Dropout(0.4), nn.LeakyReLU(0.2, inplace=True), nn.Linear(512, 512), nn.Dropout(0.4), nn.LeakyReLU(0.2, inplace=True), nn.Linear(512, 1), ) def forward(self, img, labels): # Concatenate label embedding and image to produce input d_in = torch.cat((img.view(img.size(0), -1), self.label_embedding(labels)), -1) validity = self.model(d_in) return validity class Generator(nn.Module): def __init__(self, config): super(Generator, self).__init__() self.label_emb = nn.Embedding(config.n_classes, config.n_classes) self.config = config def block(in_feat, out_feat, normalize=True): layers = [nn.Linear(in_feat, out_feat)] if normalize: layers.append(nn.BatchNorm1d(out_feat, 0.8)) layers.append(nn.LeakyReLU(0.2, inplace=True)) return layers self.model = nn.Sequential( *block(config.latent_dim + config.n_classes, 128, normalize=False), *block(128, 256), *block(256, 512), *block(512, 1024), nn.Linear(1024, int(np.prod(config.img_shape))), nn.Tanh() ) def forward(self, noise, labels): # Concatenate label embedding and image to produce input gen_input = torch.cat((self.label_emb(labels), noise), -1) img = self.model(gen_input) img = img.view(img.size(0), *self.config.img_shape) return img
{"hexsha": "1344a8dc65b804a057029c39b4542cad017b2104", "size": 2206, "ext": "py", "lang": "Python", "max_stars_repo_path": "models/cGan.py", "max_stars_repo_name": "Ls-Dai/Pytorch_FL_GAN", "max_stars_repo_head_hexsha": "63b38600751c6245e07b022f64e63d783e531b5e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-05T09:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T01:55:28.000Z", "max_issues_repo_path": "models/cGan.py", "max_issues_repo_name": "Ls-Dai/Pytorch_FL_GAN", "max_issues_repo_head_hexsha": "63b38600751c6245e07b022f64e63d783e531b5e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-28T03:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-28T06:04:49.000Z", "max_forks_repo_path": "models/cGan.py", "max_forks_repo_name": "Ls-Dai/Pytorch_FL_GAN", "max_forks_repo_head_hexsha": "63b38600751c6245e07b022f64e63d783e531b5e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9253731343, "max_line_length": 88, "alphanum_fraction": 0.5861287398, "include": true, "reason": "import numpy", "num_tokens": 501}
function Y = cosh(X) % Symbolic hyperbolic cosine. % Convert inputs to SymExpression % X = SymExpression(X); % construct the operation string sstr = ['Cosh[' X.s ']']; % create a new object with the evaluated string Y = SymExpression(sstr); end
{"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/matlab/symbolic/@SymExpression/cosh.m"}
import requests import re import time import datetime import numpy as np """ Prerequisite: Create access tokens You need private access token to have full access to Github search API. Generate your access token in [here](https://github.com/settings/tokens) you don't need to tick on any access permission because you are not modifying your private repositories. """ # input your token here token = "e6a9b0b2c3598c64aa84add48e13ab94c43c978c" def extract_repo(result): return (itm["url"] for itm in result.json()["items"]) def query_backoff(*args, **argv): max_tries = 5 wait = 120 for _ in range(max_tries): r = requests.get(*args, **argv) if r.status_code == 200: return r print("Query failed. Wait %d secs and try again: %s" % (wait, r.content)) time.sleep(wait) wait *= 2 def retrieve_matched_repo(query, num, from_year, to_year=None, n_per_query=5): headers = {'Authorization': 'token %s' % token} base_url = 'https://api.github.com/' from_date = datetime.date(from_year, 1, 1) if to_year is None: to_date = datetime.date.today() else: to_date = datetime.date(to_year, 1, 1) date_diff = (to_date - from_date).days date_list = [from_date + datetime.timedelta(days=d) for d in np.random.choice(date_diff, size=(num // n_per_query, ))] repos = [] for date in date_list: yestarday = date - datetime.timedelta(days=7) payload = { 'q': query + " sort:updated" + " created:%d-%02d-%02d..%d-%02d-%02d" % (yestarday.year, yestarday.month, yestarday.day, date.year, date.month, date.day)} # github block similar queries, so take extra intervals time.sleep(20) r = requests.get(base_url + 'search/repositories', params=payload, headers=headers) repos.extend(list(extract_repo(r))[:n_per_query]) return repos result = retrieve_matched_repo('tensorflow language:python', 200, 2015) with open("found_all_tensorflow.txt", 'w') as fout: for r in result: fout.write(r + '\n') result = retrieve_matched_repo('pytorch language:python', 200, 2017) with open("found_all_pytorch.txt", 'w') as fout: for r in result: fout.write(r + '\n')
{"hexsha": "076ff7f288ae3e101b0b411debeee5fea728fdf5", "size": 2265, "ext": "py", "lang": "Python", "max_stars_repo_path": "find_other_frameworks_usage.py", "max_stars_repo_name": "koreyou/chainer-usage-analysis", "max_stars_repo_head_hexsha": "f394b7e38f0608110a4e70e04c0fc91449a4351b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "find_other_frameworks_usage.py", "max_issues_repo_name": "koreyou/chainer-usage-analysis", "max_issues_repo_head_hexsha": "f394b7e38f0608110a4e70e04c0fc91449a4351b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "find_other_frameworks_usage.py", "max_forks_repo_name": "koreyou/chainer-usage-analysis", "max_forks_repo_head_hexsha": "f394b7e38f0608110a4e70e04c0fc91449a4351b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0273972603, "max_line_length": 134, "alphanum_fraction": 0.6582781457, "include": true, "reason": "import numpy", "num_tokens": 609}
import dask.array as da import numpy as np import abmvisum.engines.choice_engine as choice_engine import abmvisum.tools.utilities as utilities daskfactory = choice_engine.DaskFactory(10000) def calc_dest_zone_utility_matrix(origin_zones, betas, utility_matrices, target_zones_for_rubberbanding, logging): assert (target_zones_for_rubberbanding is None) or len(target_zones_for_rubberbanding) == len(origin_zones) betas_adapted = np.array(betas)[:, np.newaxis, np.newaxis] # if all subjects' attrExprs are 1, utility depends only on origin and dest zone # so memory can be saved by only calculating a matrix of dimension (#zones x #zones) instead of (#subjects x #zones) in this case # could be further optimized: first calculate all terms with AttrExpr == 1 based on zones and then only calculate # the remaining terms with AttrExpr != 1 based on subjects calculate_zone_based = (target_zones_for_rubberbanding is None) if calculate_zone_based: utility_matrix = daskfactory.fromarray((utility_matrices * betas_adapted).sum(axis=0)) else: # we need to use dask here to reduce memory usage # as we are dealing with matrices of size (num_subjects x num_zones x num_terms) utility_matrices = da.from_array(utility_matrices, chunks=(-1, 10000, -1)) origin_zones = daskfactory.fromarray(origin_zones) if target_zones_for_rubberbanding is None: utility_per_destZone = utility_matrices[:, origin_zones] else: target_zones_for_rubberbanding = daskfactory.fromarray(target_zones_for_rubberbanding) utility_per_destZone = utility_matrices[:, origin_zones] + \ utility_matrices.transpose((0, 2, 1))[:, target_zones_for_rubberbanding] # assert utility_per_destZone.shape[0] == obj_values.shape[0] # number of subjects # assert utility_per_destZone.shape[1] == utility_matrices.shape[0] == utility_matrices.shape[1] # number of zones # assert utility_per_destZone.shape[2] == len(betas) # number of terms # obj_values = da.from_array(obj_values.T[:, :, np.newaxis], chunks=(-1, 10000, -1)) utility_matrix = (utility_per_destZone * betas_adapted).sum(axis=0) # logging.info(utility_matrix.shape) return utility_matrix, calculate_zone_based def calc_dest_zone_probs_from_utility_matrix(utility_matrix, attraction_per_dest_zone, logging): # build probability matrix for the members of the segment exp_util = da.multiply(da.exp(utility_matrix), attraction_per_dest_zone) exp_util_sum = exp_util.sum(1) exp_util_sum_T = da.asarray(exp_util_sum[:, np.newaxis]) exp_util_sum_T = da.where(exp_util_sum_T <= 0, 1.0, exp_util_sum_T) probs = exp_util / exp_util_sum_T probs = da.maximum(probs, 0) # logging.info(probs.shape) # assert np.allclose(np.sum(probs, axis=1), 1.0) return probs # uses rubberbanding if target_zones_for_rubberbanding are provided def calc_dest_zone_probs_simple(segment, skims, act_id, Visum, logging): matrix_expr = segment['MatrixExpr'] attr_expr = segment['AttrExpr'] od_kalif_expr = segment['ODKaliFExpr'] impedance_params = segment['ImpedanceParams'] if impedance_params: nZones = Visum.Net.Zones.Count utility_matrices = np.empty((1, nZones, nZones), dtype=np.float) # logging.info('loading logsum matrix from impedance params') # for imp_expr in impedance_params: # utility_matrices[0, :, :] += np.exp(utilities.eval_matexprs(Visum, [imp_expr])[0, :, :]) utility_matrices[0, :, :] = utilities.eval_matexprs_cached_skims(Visum, impedance_params[act_id], skims) utility_matrices[0, :, :] = np.where(np.isneginf(np.log(utility_matrices[0, :, :])), -9999, np.log(utility_matrices[0, :, :])) else: logging.info("taking matrix expression") utility_matrices = utilities.eval_matexprs(Visum, matrix_expr) od_kalif_expr_act_id = [0] for i, attr in enumerate(attr_expr): if float(attr) == float(act_id): od_kalif_expr_act_id = [od_kalif_expr[i]] od_asc_matrices = utilities.eval_matexprs(Visum, od_kalif_expr_act_id) utility_matrices[0, :, :] += od_asc_matrices[0, :, :] utility_matrix = utility_matrices[0, :, :] return utility_matrix # uses rubberbanding if target_zones_for_rubberbanding are provided def calc_dest_zone_probs(filtered_subjects, skims, origin_zones, segment, attraction_per_dest_zone, Visum, logging, target_zones_for_rubberbanding=None): matrix_expr = segment['MatrixExpr'] attr_expr = segment['AttrExpr'] betas = segment['Beta'] od_kalif_expr = segment['ODKaliFExpr'] impedance_params = segment['ImpedanceParams'] if impedance_params is not None: nZones = Visum.Net.Zones.Count utility_matrices = np.empty((1, nZones, nZones), dtype=np.float) # logging.info('loading logsum matrix from impedance params') # for imp_expr in impedance_params: # utility_matrices[0, :, :] += np.exp(utilities.eval_matexprs(Visum, [imp_expr])[0, :, :]) utility_matrices[0, :, :] = utilities.eval_matexprs_cached_skims(Visum, impedance_params, skims) utility_matrices[0, :, :] = np.where(np.isneginf(np.log(utility_matrices[0, :, :])), -9999, np.log(utility_matrices[0, :, :])) else: utility_matrices = utilities.eval_matexprs(Visum, matrix_expr) # VPH.SetMatrixRaw(Visum, 99999, utility_matrices[0, :, :]) # obj_values = utilities.eval_attrexpr(filtered_subjects, attr_expr) od_asc_matrices = utilities.eval_matexprs(Visum, od_kalif_expr) utility_matrices[0, :, :] += od_asc_matrices[0, :, :] attraction_per_dest_zone = daskfactory.fromarray(attraction_per_dest_zone) utility_matrix, is_utility_matrix_still_zone_based = calc_dest_zone_utility_matrix(origin_zones, betas, utility_matrices, target_zones_for_rubberbanding, logging) probs = calc_dest_zone_probs_from_utility_matrix(utility_matrix, attraction_per_dest_zone, logging) return probs, utility_matrix, is_utility_matrix_still_zone_based def choose_and_set_minor_destinations(matrix_cache, skims, act_id, Visum, segment, attraction_per_zone, origin_zones, logging, target_zones_for_rubberbanding=None): matrix_key = (act_id, segment['Specification']) if matrix_cache.has_matrix(matrix_key): utils = matrix_cache.get_matrix(matrix_key) else: utils = calc_dest_zone_probs_simple(segment, skims, act_id, Visum, logging) matrix_cache.add_matrix_to_cache(matrix_key, utils) origin_zones = daskfactory.fromarray(origin_zones) if (target_zones_for_rubberbanding is None) or (float(act_id) == 1.0) or (float(act_id) == 7.0): exp_utils = np.exp(utils) exp_utils_attr = np.multiply(exp_utils, attraction_per_zone) util_exp_attr_matrix = daskfactory.fromarray(exp_utils_attr) utility_tot = util_exp_attr_matrix[origin_zones] else: # utils at origin origin_weight = 0.5 # todo (PM) own assumption: verify exp_utils_attr = np.multiply(np.exp(origin_weight * utils), attraction_per_zone) util_exp_attr_matrix = daskfactory.fromarray(exp_utils_attr) util_mat_ik = util_exp_attr_matrix[origin_zones] # utils at target target_weight = 0.5 # todo (PM) own assumption: verify utils_T = np.transpose(np.exp(target_weight * utils)) utility_matrix_T = daskfactory.fromarray(utils_T) target_zones_for_rubberbanding = daskfactory.fromarray(target_zones_for_rubberbanding) util_mat_kj = utility_matrix_T[target_zones_for_rubberbanding] utility_tot = da.multiply(util_mat_ik, util_mat_kj) exp_util_sum = da.asarray(utility_tot.sum(1)[:, np.newaxis]) exp_util_sum = da.where(exp_util_sum <= 0, 1.0, exp_util_sum) probs = utility_tot / exp_util_sum probs = da.maximum(probs, 0) return choose_dest_zones(probs) def choose_dest_zones(probs, originZonePerObj=None): if originZonePerObj is None: adapted_probs = probs else: originZonePerObj = da.from_array(originZonePerObj, chunks=10000) adapted_probs = probs[originZonePerObj] num_choices = adapted_probs.shape[0] choice2d = choice_engine.Choice2DParallel(num_choices, 10000) choice2d.add_prob(adapted_probs) chosen_zone_indices = choice2d.choose() return chosen_zone_indices
{"hexsha": "6c2621be24393402b9549cb29d26760b67bf5e8b", "size": 9099, "ext": "py", "lang": "Python", "max_stars_repo_path": "abmvisum/engines/location_choice_engine.py", "max_stars_repo_name": "SchweizerischeBundesbahnen/abm-in-visum", "max_stars_repo_head_hexsha": "b67451c331482a70fab20c7340d27e78b9e50461", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-07T20:44:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:26:55.000Z", "max_issues_repo_path": "abmvisum/engines/location_choice_engine.py", "max_issues_repo_name": "SchweizerischeBundesbahnen/abm-in-visum", "max_issues_repo_head_hexsha": "b67451c331482a70fab20c7340d27e78b9e50461", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-04-14T09:54:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T13:00:45.000Z", "max_forks_repo_path": "abmvisum/engines/location_choice_engine.py", "max_forks_repo_name": "SchweizerischeBundesbahnen/abm-in-visum", "max_forks_repo_head_hexsha": "b67451c331482a70fab20c7340d27e78b9e50461", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-09T11:29:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T12:31:45.000Z", "avg_line_length": 48.3989361702, "max_line_length": 133, "alphanum_fraction": 0.6755687438, "include": true, "reason": "import numpy", "num_tokens": 2133}
function load_xyz_data(file_path :: String; atom_names = nothing, radii = [3.5], weights = [1.0], masses = [1.0], boundary_type = ["p", "p", "p"], units = "lj") # frames = read_frames(file_path) # n = length(frames) # r = Vector{Configuration}(undef, n) # if atom_names == nothing # atom_names = unique(frames[1]["arrays"]["species"]) # end # num_atom_types = length(atom_names) # if length(radii) != num_atom_types # radii = radii[1] .* ones(num_atom_types) # end # if length(weights) != num_atom_types # weights = weights .* ones(num_atom_types) # end # if length(masses) != num_atom_types # masses = masses .* ones(num_atom_types) # end # for i = 1:n # frame = frames[i] # num_atoms = frame["N_atoms"] # Atoms = Vector{Atom}(undef, num_atoms) # for j = 1:num_atoms # arrays = frame["arrays"] # name = arrays["species"][j] # id = findall(name .== atom_names)[1] # pos = arrays["pos"][:, j] # if "vel" in keys(arrays) # vel = arrays[vel][:, j] # else # vel = zeros(3) # end # a = Atom(masses[id], pos, vel, name) # Atoms[j] = a # c = Configuration(Atoms, num_atom_types, # Angles, num_angle_types, # Bonds, num_bond_types, # Impropers, num_improper_types, # Dihedrals, num_dihedral_types, # atom_names, masses, radii, weights, # domain, units) # r[i] = c # end # end println("This is not yet implemented") end function save_xyz_data(c::Configuration, file_path::String) println("This is not yet implemented") end
{"hexsha": "2ca3dc241b0445739ed72fb0a69b0ec4017a3fc5", "size": 1873, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/IO/io_xyz.jl", "max_stars_repo_name": "stefanbringuier/InteratomicPotentials.jl", "max_stars_repo_head_hexsha": "96d6808d4ccd974817d0220b72b29ed4dd173e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-24T07:30:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T03:23:02.000Z", "max_issues_repo_path": "src/IO/io_xyz.jl", "max_issues_repo_name": "cesmix-mit/Potentials.jl", "max_issues_repo_head_hexsha": "b94a6746161371b426baea293b8feaae2259b6f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IO/io_xyz.jl", "max_forks_repo_name": "cesmix-mit/Potentials.jl", "max_forks_repo_head_hexsha": "b94a6746161371b426baea293b8feaae2259b6f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0545454545, "max_line_length": 160, "alphanum_fraction": 0.5114789108, "num_tokens": 515}
import numpy as np from core import GraphicalObject, DrawContext import typing as tp class Point(GraphicalObject): def __init__(self, name: str, x: float, y: float, z: float = ...): if z is ...: self.is_3d = False super().__init__(name, np.array([[x, y, 1.]])) else: self.is_3d = True super().__init__(name, np.array([[x, y, z]])) def draw_verbose(self, ctx: DrawContext) -> None: self.draw(ctx) cairo_ctx = ctx.ctx x, y = ctx.viewport_transform(self._ppc[0])[:-1] cairo_ctx.move_to(x + 5, y + 5) src = cairo_ctx.get_source() cairo_ctx.set_source_rgb(0., 1., 0.) cairo_ctx.show_text(self.name) cairo_ctx.set_source(src) def draw(self, ctx: DrawContext) -> None: cairo_ctx = ctx.ctx x, y = ctx.viewport_transform(self._ppc[0])[:-1] cairo_ctx.arc(x, y, 5, 0, 2 * np.pi) cairo_ctx.fill() PointLike = tp.Union[Point, np.ndarray, tp.Tuple[float, float], tp.Tuple[float, float, float]] def as_ndarray(point: PointLike) -> np.ndarray: if isinstance(point, np.ndarray): return point elif isinstance(point, tuple): return np.array([*point, 1.]) elif isinstance(point, Point): return point.points[0] else: raise TypeError("Invalid point.")
{"hexsha": "1159ab058cfe5d1d1d64dded00d9d60d2528e160", "size": 1361, "ext": "py", "lang": "Python", "max_stars_repo_path": "shapes/point.py", "max_stars_repo_name": "HENRDS/INE5408", "max_stars_repo_head_hexsha": "3216fe813200eff6480bd8db3d63299fb5255cda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-17T19:43:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-17T19:43:04.000Z", "max_issues_repo_path": "shapes/point.py", "max_issues_repo_name": "HENRDS/INE5408", "max_issues_repo_head_hexsha": "3216fe813200eff6480bd8db3d63299fb5255cda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shapes/point.py", "max_forks_repo_name": "HENRDS/INE5408", "max_forks_repo_head_hexsha": "3216fe813200eff6480bd8db3d63299fb5255cda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9574468085, "max_line_length": 94, "alphanum_fraction": 0.5922116091, "include": true, "reason": "import numpy", "num_tokens": 372}
! ================================================================================================================================= ! MODULE : hydrolc ! ! CONTACT : orchidee-help _at_ listes.ipsl.fr ! ! LICENCE : IPSL (2006) ! This software is governed by the CeCILL licence see ORCHIDEE/ORCHIDEE_CeCILL.LIC ! !>\BRIEF This module computes the water budget of !! land surfaces. It distinguishes three main reservoirs with separate water budgets : !! the canopy interception reservoir, the snow pack, and the soil, described here using two !! soil layers, following the so-called Choisnel scheme. The module contains the !! following subroutines: hydrolc_main, hydrolc_init, hydrolc_clear, hydrolc_var_init, !! hydrolc_snow, hydrolc_vegupd, hydrolc_canop, hydrolc_soil, hydrolc_waterbal, hydrolc_alma, !! hydrolc_hdiff. !! !! \n DESCRIPTION : The aim of this module is to update the different water prognostic variables !! (within canopy, snow and soil) and to compute the related liquid water fluxes (e.g. !! throughfall, runoff, snow melt) and diagnostic variables used in other modules (e.g. !! humrel and rsol to compute latent heat fluxes ; shumdiag for soil thermodynamics; snow mass !! and snow age for snow albedo). !! !! The main input variables are precipitation (liquid and solid) and the different terms of !! evapotranspiration (transpiration, bare soil evaporation, interception loss, sublimation). !! The module organizes the required initialisation of water prognostic variables, their !! integration at each timestep given the above forcings, and the required output (writing !! of restart file, updated prognostic variables, diagnostic variables). !! !! The specificity of hydrolc in ORCHIDEE is to describe the soil using two soil layers, !! following the so-called Choisnel scheme. The upper layer has a variable depth !! and can disappear after dry spells (Ducoudré et al., 1993). Soil moisture stress on !! transpiration and bare soil evaporation acts via the height of dry soil at the top of soil. !! !! Runoff is produced when the entire soil column is saturated, as in the bucket scheme !! of Manabe (1969). Drainage and surface runoff are only diagnosed, mostly for use in !! the routing module, using a constant 95% - 5% redistribution (Ngo-Duc et al., 2005). !! Irrigation can interact with the soil columns (de Rosnay et al., 2003), as well as !! river discharge in floodplains (Ngo-Duc et al., 2005). !! !! The dynamic of the one-layer snow pack results from accumulation, sublimation and !! snowmelt. Snow ageing is accounted for but it does not influence snow density. !! !! The subgrid variability of soil follows the one of vegetation, by introducing as many !! soil columns as PFTs (de Rosnay & Polcher, 1998). The water budget is performed !! independently in each PFT/soil column, but water can be exchanged laterally. !! The soil moisture of the bottom layer is homogenized between the soil columns at !! each timestep, and a diffusion between the top soil layers can be allowed if the !! flag ok_hdiff is true (the default value is false). !! !! RECENT CHANGE(S) : None !! !! REFERENCE(S) : !! - Ducoudré, N, Laval, K & Perrier, A, 1993. SECHIBA, a new set of parameterisations !! of the hydrologic exchanges at the land-atmosphere interface within the LMD Atmospheric General !! Circulation Model. Journal of Climate, 6, pp. 248-273. !! - Ducharne, A. Laval, K. and Polcher, J. (1998) Sensitivity of the hydrological cycle to the !! parameterization of soil hydrology in a GCM. Climate Dynamics, 14:307-327. !! - de Rosnay, P. and Polcher J. (1998) Modeling root water uptake in a complex land surface scheme !! coupled to a GCM. Hydrology and Earth System Sciences, 2(2-3):239-256. !! - de Rosnay, P., Polcher, J., Laval, K. et Sabre, M. (2003). Integrated parameterization of !! irrigation in the land surface model ORCHIDEE. Validation over Indian Peninsula. Geophys. Res. !! Lett, 30(19):HLS2-1 - !! HLS2-4. !! - Krinner, G., Viovy, N., de Noblet-Ducoudré, N., Ogee, J., Polcher, J., Friedlingstein, P., !! Ciais, P., Sitch, S. et Prentice, I. (2005). A dynamic global vegetation model for studies of the !! coupled atmosphere-biosphere system. Global Biogeochem. Cycles, 19(1). !! - Ngo-Duc, T., Laval, K., Ramillien, G., Polcher, J. et Cazenave, A. (2007). Validation of the land !! water storage simulated by Organising Carbon and Hydrology in Dynamic Ecosystems (ORCHIDEE) with !! Gravity Recovery and Climate Experiment (GRACE) data. Water Resour. Res, 43:W04427. !! - ALMA : http://www.lmd.jussieu.fr/~polcher/ALMA/ !! - Ducoudré, N. (1990). Sensibilite du climat simule a la parametrisation des echanges de vapeur !! d'eau entre la biosphere et l'atmosphere. These de Doctorat, Université Paris 6. !! - Ducharne A (1997). Le cycle de l'eau : modelisation de l'hydrologie continentale, etude de ses !! interactions avec le climat, These de Doctorat, Université Paris 6. !! - de Rosnay, P. (1999). Representation des interactions sol-plante-atmosphere dans le modele de !! circulation generale du LMD. These de doctorat, Université Paris 6. !! - Guimberteau, M. (2010). Modelisation de l'hydrologie continentale et influences de l'irrigation !! sur le cycle de l'eau, these de doctorat, Université Paris 6. !! !! SVN : !! $HeadURL: svn://forge.ipsl.jussieu.fr/orchidee/branches/ORCHIDEE-MICT/ORCHIDEE/src_sechiba/hydrolc.f90 $ !! $Date: 2017-07-17 12:59:54 +0200 (lun. 17 juil. 2017) $ !! $Revision: 4507 $ !! \n !_ ================================================================================================================================ MODULE hydrolc ! modules used USE ioipsl USE xios_orchidee USE ioipsl_para USE constantes ! contains technical constants USE constantes_soil ! soil properties and geometry (underground) USE pft_parameters ! surface and vegetation properties USE sechiba_io_p ! for inpout/output USE grid ! for grid, masks and calendar USE mod_orchidee_para ! for variable and subroutines realted to the parallelism of orchidee USE explicitsnow IMPLICIT NONE PRIVATE PUBLIC :: hydrolc_main, hydrolc_initialize, hydrolc_finalize, hydrolc_clear LOGICAL, SAVE :: ok_hdiff !! To do horizontal diffusion between soil columns !$OMP THREADPRIVATE(ok_hdiff) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: bqsb !! Water content in the bottom layer !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(bqsb) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: gqsb !! Water content in the top layer @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(gqsb) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: dsg !! Depth of the top layer (m) !$OMP THREADPRIVATE(dsg) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: dsp !! Depth of dry soil in the bottom layer plus depth of top !! layer (m) !$OMP THREADPRIVATE(dsp) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: irrig_fin !! final application of irrigation water for each pft !$OMP THREADPRIVATE(irrig_fin) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: mean_bqsb !! Mean water content in the bottom layer, averaged over the !! soil columns @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(mean_bqsb) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: mean_gqsb !! Mean water content in the top layer, averaged over the !! soil columns @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(mean_gqsb) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: tot_flux !! Total water flux !$OMP THREADPRIVATE(tot_flux) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: tot_water_beg !! Total amount of water at start of time step !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(tot_water_beg) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: tot_water_end !! Total amount of water at end of time step !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(tot_water_end) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: tot_watveg_beg !! Total amount of intercepted water on vegetation at start of !! time step @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(tot_watveg_beg) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: tot_watveg_end !! Total amount of intercepted water on vegetation at end of !! time step @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(tot_watveg_end) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: tot_watsoil_beg !! Total amount of water in the soil at start of time step !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(tot_watsoil_beg) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: tot_watsoil_end !! Total amount of water in the soil at end of time step !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(tot_watsoil_end) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: snow_beg !! Total snow water equivalent at start of time step !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(snow_beg) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: snow_end !! Total snow water equivalent at end of time step !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(snow_end) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: delsoilmoist !! Change in soil moisture during time step !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(delsoilmoist) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: delintercept !! Change in interception storage during time step !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(delintercept) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: delswe !! Change in snow water equivalent during time step !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(delswe) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: dss !! Depth of dry soil at the top, whether in the top or bottom !! layer (m) !$OMP THREADPRIVATE(dss) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: hdry !! Mean top dry soil height (m) version beton !$OMP THREADPRIVATE(hdry) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: precisol !! Throughfall @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(precisol) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: subsnowveg !! Sublimation of snow on vegetation !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(subsnowveg) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: subsnownobio !! Sublimation of snow on other surface types (ice, lakes,...) !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(subsnownobio) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: snowmelt !! Snow melt @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(snowmelt) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: icemelt !! Ice melt @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(icemelt) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: gdrainage !! Drainage between the two soil layers !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(gdrainage) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: vegtot !! Total fraction of grid-cell covered by PFTs (bare soil + !! vegetation) (0-1, unitless) !$OMP THREADPRIVATE(vegtot) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: resdist !! Previous values of "veget" (0-1, unitless) ! Last map of !! PFT fractions used to define the soil columns !$OMP THREADPRIVATE(resdist) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: mx_eau_var !! Maximum water content of the soil !! @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(mx_eau_var) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: ruu_ch !! Volumetric soil water capacity @tex ($kg m^{-3}$) @endtex !$OMP THREADPRIVATE(ruu_ch) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:,:) :: runoff !! Total runoff @tex ($kg m^{-2}$) @endtex !$OMP THREADPRIVATE(runoff) REAL(r_std), PARAMETER :: dsg_min = 0.001 !! Reference depth to define subgrid variability of saturated !! top soil layer (m) REAL(r_std), ALLOCATABLE, SAVE, DIMENSION (:) :: subsinksoil !! Excess of sublimation as a sink for the soil !$OMP THREADPRIVATE(subsinksoil) !_ ================================================================================================================================ CONTAINS !! ================================================================================================================================ !! SUBROUTINE : hydrolc_initialize !! !>\BRIEF Allocate module variables, read from restart file or initialize with default values !! !! DESCRIPTION : !! !! MAIN OUTPUT VARIABLE(S) : !! !! REFERENCE(S) : !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_initialize( kjit, kjpindex, index, rest_id, & veget, veget_max, tot_bare_soil, & rsol, drysoil_frac, snow, & snow_age, snow_nobio, snow_nobio_age, humrel, & vegstress, qsintveg, shumdiag, snowrho, & snowtemp, snowgrain, snowdz, snowheat ) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT(in) :: kjit !! Current time step number (unitless) INTEGER(i_std), INTENT(in) :: kjpindex !! Domain size (number of grid cells) (unitless) INTEGER(i_std),DIMENSION (kjpindex), INTENT (in) :: index !! Indices of the land grid points on the map INTEGER(i_std),INTENT (in) :: rest_id !! Restart file identifier REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: veget !! Grid-cell fraction effectively covered by !! vegetation for each PFT, except for soil !! (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: veget_max !! PFT fractions within grid-cells: max value of !! veget for vegetation PFTs and min value for !! bare soil (0-1, unitless) REAL(r_std),DIMENSION (kjpindex), INTENT(in) :: tot_bare_soil !! Total evaporating bare soil fraction !! 0.2 Output variables REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: rsol !! Resistance to bare soil evaporation !! @tex ($s m^{-1}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: drysoil_frac !! Fraction of visibly dry soil, for bare soil !! albedo calculation in condveg.f90 !! (0-1, unitless) REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: snow !! Snow water equivalent @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: snow_age !! Snow age (days) REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (out) :: snow_nobio !! Snow water equivalent on nobio areas !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (out) :: snow_nobio_age !! Snow age on ice, lakes, ... (days) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (out) :: humrel !! Soil moisture stress factor on transpiration and REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (out) :: vegstress !! Vegetation moisture stress (only for vegetation !! growth) (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (out) :: qsintveg !! Amount of water in the canopy interception !! reservoir @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nbdl), INTENT (out) :: shumdiag !! Mean relative soil moisture in the different !! levels used by thermosoil.f90 (0-1, unitless) REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(out) :: snowrho !! Snow density REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(out) :: snowtemp !! Snow temperature REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(out) :: snowgrain !! Snow grainsize REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(out) :: snowdz !! Snow layer thickness REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(out) :: snowheat !! Snow heat content !! 0.4 Local variables !_ ================================================================================================================================ !! 1. Initialisation CALL hydrolc_init (kjit, kjpindex, index, rest_id, & veget, tot_bare_soil, & humrel, vegstress, shumdiag, & snow, snow_age, snow_nobio, snow_nobio_age, qsintveg, & snowdz,snowgrain,snowrho,snowtemp,snowheat, & drysoil_frac, rsol) CALL hydrolc_var_init (kjpindex, veget, veget_max, tot_bare_soil, & rsol, drysoil_frac, mx_eau_var, ruu_ch, shumdiag) ! If we check the water balance, we first save the total amount of water IF (check_waterbal) CALL hydrolc_waterbal_init (kjpindex, qsintveg, snow, snow_nobio) IF (almaoutput) THEN CALL hydrolc_alma_init(kjpindex, index, qsintveg, snow, snow_nobio) ENDIF END SUBROUTINE hydrolc_initialize !! ================================================================================================================================ !! SUBROUTINE : hydrolc_main !! !>\BRIEF Main routine for water budget calculation on land surfaces. !! !! DESCRIPTION : This routine drives all the calls pertaining !! to the land-surface water budget. It is called once during the initialisation of !! ORCHIDEE, and then once for each time step, to drive the water budget calculations, !! and the link to history files processing (histwrite). It is called one more time !! at the last time step, for the writing of the restart file. !! !! The initialisation step calls hydrolc_init and hydrolc_var_init, plus hydrolc_waterbal !! if we choose to check the water balance. Writing is performed to the restart file, !! before the water budget calculations, at a timestep that is controlled by the flag !! "ldrestart_write". !! !! The water budget calculations are separated into four subroutines related to the !! main three water reservoirs over land grid-cells, and called at each time step : \n !! - hydrolc_snow for snow process (including age of snow) !! - hydrolc_vegupd to manage the required redistribution of water between reservoirs !! when the vegetation fraction of PFTs has changed !! - hydrolc_canop for canopy process (interception) !! - hydrolc_soil for soil hydrological process (soil moisture and runoff), followed by !! hydrolc_hdiff if we choose to account for horizontal diffusion between the soil columns. !! If we choose to check the water balance, this is done over each timestep dt_sechiba, !! by hydrolc_waterbal. !! !! The link to "hist" files processing has two kinds of controls: !! - the standard output ncdf file corresponds to hist_id ; if hist2_id positive, a second !! ncdf file is output, with a different frequency !! - almaoutput defines the nature/name of the written variables, whether following the !! ALMA norm or not !! Note that histwrite does different actions depending on the current time step : !! writing on "hist" files at a selected frequency ; summing of the output variables !! in between in view of averaging. !! The subroutine also handles some "CMIP5" output (mrro, mrros and prveg). !! !! We consider that any water on ice (nobio) is snow and we only peform a water balance to have consistency. !! The water balance is limited to + or - \f$10^6\f$ so that accumulation is not endless !! !! IMPORTANT NOTE : The water fluxes are used in their integrated form, over the time step !! dt_sechiba, with a unit of \f$kg.m^{-2}\f$. !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLE(S) : snow, snow_age, snow_nobio, snow_nobio_age, tot_melt, !! returnflow, irrigation, humrel, vegstress, rsol, drysoil_frac, shumdiag, litterhumdiag !! + variables declared in the module !! + variables sent for ouput by histwrite !! !! REFERENCE(S) : Same as for module hydrolc !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_main (kjit, kjpindex, index, indexveg, & & temp_sol_new, floodout, run_off_tot, drainage, frac_nobio, totfrac_nobio, vevapwet, veget, veget_max,& & qsintmax, qsintveg, vevapnu, vevapsno, vevapflo, snow, snow_age, snow_nobio, snow_nobio_age, tot_melt, transpir, & & precip_rain, precip_snow, returnflow, reinfiltration, irrigation, vegstress_old, transpot, humrel, vegstress, rsol, drysoil_frac, &!added vegestress_old & transpot for crop irrigation, xuhui & evapot, evapot_corr, flood_frac, flood_res, shumdiag, litterhumdiag, soilcap, rest_id, hist_id, hist2_id, soil_deficit, & !add soil_deficit for crop irrigation, xuhui & temp_air, pb, u, v, pgflux, & & snowrho,snowtemp, snowgrain,snowdz,snowheat,snowliq,& & grndflux,gtemp, tot_bare_soil, & & soilflxresid, & & lambda_snow,cgrnd_snow,dgrnd_snow,temp_sol_add) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT(in) :: kjit !! Current time step number (unitless) INTEGER(i_std), INTENT(in) :: kjpindex !! Domain size (number of grid cells) (unitless) INTEGER(i_std),INTENT (in) :: rest_id,hist_id !! _Restart_ file and _history_ file identifier !! (unitless) INTEGER(i_std),INTENT (in) :: hist2_id !! Second _history_ file identifier (unitless) INTEGER(i_std),DIMENSION (kjpindex), INTENT (in) :: index !! Indices of the land grid points on the map !! (unitless) INTEGER(i_std),DIMENSION (kjpindex*nvm), INTENT (in) :: indexveg !! Indices of the PFT tiles / soil columns on !! the 3D map (unitless) REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: precip_rain !! Rainfall @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: precip_snow !! Snowfall @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: returnflow !! Routed water which comes back into the soil !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: reinfiltration !! Routed water which comes back into the soil REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: irrigation !! Irrigation water applied to soils !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: vegstress_old !! vegstress of previous step REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: transpot !! potential transpiration REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: temp_sol_new !! New soil temperature (K) REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (in) :: frac_nobio !! Fraction of terrestrial ice, lakes, ... !! (0-1, unitless) REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: totfrac_nobio !! Total fraction of terrestrial ice+lakes+... !! (0-1, unitless) REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: soilcap !! Soil heat capacity @tex ($J K^{-1}$) @endtex REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: vevapwet !! Interception loss over each PFT !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: veget !! Grid-cell fraction effectively covered by !! vegetation for each PFT, except for soil !! (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: veget_max !! PFT fractions within grid-cells: max value of !! veget for vegetation PFTs and min value for bare soil (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: qsintmax !! Maximum amount of water in the canopy !! interception reservoir !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: transpir !! Transpiration over each PFT !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: evapot !! [DISPENSABLE] Soil Potential Evaporation !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: evapot_corr !! [DISPENSABLE] Soil Potential Evaporation !! Correction REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: flood_frac !! Flooded fraction REAL(r_std),DIMENSION (kjpindex), INTENT(in) :: temp_air !! Air temperature REAL(r_std),DIMENSION (kjpindex), INTENT(in) :: u,v !! Horizontal wind speed REAL(r_std),DIMENSION (kjpindex), INTENT(in) :: pb !! Surface pressure REAL(r_std),DIMENSION (kjpindex), INTENT(in) :: pgflux !! Net energy into snowpack REAL(r_std), DIMENSION (kjpindex),INTENT(inout) :: soilflxresid !! Energy flux to the snowpack REAL(r_std),DIMENSION (kjpindex),INTENT(in) :: gtemp !! First soil layer temperature REAL(r_std),DIMENSION (kjpindex), INTENT(in) :: tot_bare_soil !! Total evaporating bare soil fraction REAL(r_std),DIMENSION (kjpindex), INTENT(in) :: lambda_snow !! Coefficient of the linear extrapolation of surface temperature REAL(r_std),DIMENSION (kjpindex,nsnow), INTENT (in) :: cgrnd_snow !! Integration coefficient for snow numerical scheme REAL(r_std),DIMENSION (kjpindex,nsnow), INTENT (in) :: dgrnd_snow !! Integration coefficient for snow numerical scheme !! 0.2 Output variables REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: run_off_tot !! Diagnosed surface runoff !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: flood_res !! Flood reservoir estimate REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: drainage !! Diagnosed rainage at the bottom of soil !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: rsol !! Resistance to bare soil evaporation !! @tex ($s m^{-1}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: drysoil_frac !! Fraction of visibly dry soil, for bare soil !! albedo calculation in condveg.f90 !! (0-1, unitless) REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: litterhumdiag !! Litter humidity factor (0-1, unitless), used !! in stomate REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: tot_melt !! Total melt @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (inout) :: soil_deficit !! soil defict for flood irrigation !! 0.3 Modified variables REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: vevapnu !! Bare soil evaporation @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: vevapsno !! Snow evaporation @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: vevapflo !! Floodplains evaporation REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: snow !! Snow water equivalent @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: snow_age !! Snow age (days) REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (inout) :: snow_nobio !! Snow water equivalent on nobio areas !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (inout) :: snow_nobio_age !! Snow age on ice, lakes, ... (days) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (inout) :: humrel !! Soil moisture stress factor on transpiration and !! bare soil evaporation (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (inout) :: vegstress !! Vegetation moisture stress (only for vegetation !! growth) (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (inout) :: qsintveg !! Amount of water in the canopy interception !! reservoir @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: floodout !! flux out of floodplains REAL(r_std),DIMENSION (kjpindex,nbdl), INTENT (inout) :: shumdiag !! Mean relative soil moisture in the different !! levels used by thermosoil.f90 (0-1, unitless) REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(inout) :: snowrho !! Snow density REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(inout) :: snowtemp !! Snow temperature REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(inout) :: snowgrain !! Snow grainsize REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(inout) :: snowdz !! Snow layer thickness REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(inout) :: snowheat !! Snow heat content REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(inout) :: snowliq !! Liquid water content (m) REAL(r_std), DIMENSION (kjpindex), INTENT(inout) :: grndflux !! Net flux into soil W/m2 REAL(r_std), DIMENSION (kjpindex), INTENT (inout) :: temp_sol_add !! additional surface temperature due to the melt of first layer !! at the present time-step @tex ($K$) @endtex !! 0.4 Local variables REAL(r_std),DIMENSION (kjpindex) :: soilwet !! Temporary diagnostic of relative humidity of !! total soil (0-1, unitless) REAL(r_std) :: tempfrac REAL(r_std),DIMENSION (kjpindex) :: snowdepth !! Snow Depth (m) INTEGER(i_std) :: ji,jv !! Grid-cell and PFT indices (unitless) REAL(r_std), DIMENSION(kjpindex) :: histvar !! Ancillary variable when computations are needed !! before writing to history files CHARACTER(LEN=80) :: var_name !! To store variables names for I/O REAL(r_std), DIMENSION(kjpindex,nvm) ::irrig_demand_ratio !! pft request ratio for irrigation water !_ ================================================================================================================================ !! 1.a snow processes IF (ok_explicitsnow) THEN IF (printlev>=3) WRITE (numout,*) ' ok_explicitsnow : use three-snow layer ' CALL explicitsnow_main(kjpindex, precip_rain, precip_snow, temp_air, & pb, u, v, temp_sol_new, soilcap, & pgflux, frac_nobio, totfrac_nobio, & gtemp, & lambda_snow, cgrnd_snow, dgrnd_snow, & vevapsno, snow_age, snow_nobio_age, snow_nobio, snowrho, & snowgrain, snowdz, snowtemp, snowheat, snow, & temp_sol_add, & snowliq, subsnownobio, grndflux, snowmelt, tot_melt, & soilflxresid, subsinksoil ) ELSE CALL hydrolc_snow(kjpindex, precip_rain, precip_snow, temp_sol_new, soilcap, & frac_nobio, totfrac_nobio, vevapnu, vevapsno, snow, snow_age, snow_nobio, snow_nobio_age, & tot_melt, snowdepth) END IF !! 1.b canopy processes CALL hydrolc_vegupd(kjpindex, veget, tot_bare_soil, ruu_ch, qsintveg, gqsb, bqsb, dsg, dss,dsp, resdist) CALL hydrolc_canop(kjpindex, precip_rain, vevapwet, veget, qsintmax, tot_bare_soil, qsintveg, precisol) ! ! computes surface reservoir ! CALL hydrolc_flood(kjpindex, vevapnu, vevapflo, flood_frac, flood_res, floodout) !! 1.c soil hydrology processes !!! calculating ratio of irrigation for each pft at each point irrig_demand_ratio(:,:) = zero irrig_fin(:,:) = zero ! irrig_totfrac(:) = zero DO ji = 1,kjpindex DO jv = 2,nvm IF (veget_max(ji,jv) .GT. zero) THEN IF (irrig_drip) THEN tempfrac = veget(ji,jv)/veget_max(ji,jv) IF ( (.NOT. natural(jv)) .AND. (vegstress_old(ji,jv) .LT. irrig_threshold(jv)) .AND. & & (transpot(ji,jv)*tempfrac + evapot_corr(ji)*(1-tempfrac) .GT. precip_rain(ji)) ) THEN irrig_demand_ratio(ji,jv) = MIN( irrig_dosmax, irrig_fulfill(jv) * & & ( transpot(ji,jv)*tempfrac + evapot_corr(ji)*(1-tempfrac) & & - precip_rain(ji) ) ) * veget_max(ji,jv) ENDIF ! since irrigated fraction is the same across pfts on the same grid, no need to consider ELSE ! flooding IF ( (.NOT. natural(jv)) .AND. (vegstress_old(ji,jv) .LT. irrig_threshold(jv)) ) THEN irrig_demand_ratio(ji,jv) = MIN( irrig_dosmax, MAX( zero, soil_deficit(ji,jv) ) ) * veget_max(ji,jv) ENDIF ENDIF ENDIF ENDDO IF ( SUM(irrig_demand_ratio(ji,:)) .GT. zero ) THEN irrig_demand_ratio(ji,:) = irrig_demand_ratio(ji,:) / SUM(irrig_demand_ratio(ji,:)) ENDIF ENDDO ! WRITE(numout,*) 'irrig_demand_ratio(1,:): ',irrig_demand_ratio(1,:) ! WRITE(numout,*) 'irrig xwang: deficit(1,:): ',transpot(1,:) - precip_rain(1) ! WRITE(numout,*) 'irrig xwang: veget(1,:): ', veget(1,:) ! WRITE(numout,*) 'irrig xwang: veget_max(1,:): ',veget_max(1,:) ! WRITE(numout,*) 'irrig xwang: irrigation(1): ',irrigation(1) !!! end ratio_irrig, Xuhui CALL hydrolc_soil(kjpindex, vevapnu, precisol, returnflow, reinfiltration, irrigation, irrig_demand_ratio, veget_max, tot_melt, mx_eau_var, & ! added irrig_demand_ratio, veget_max, for crop irrigation & veget, tot_bare_soil, ruu_ch, transpir,& & gqsb, bqsb, dsg, dss, rsol, drysoil_frac, hdry, dsp, runoff, run_off_tot, drainage, humrel, & & vegstress, shumdiag, litterhumdiag, irrig_fin) ! added irrig_fin by xuhui DO ji = 1,kjpindex DO jv = 2,nvm IF (.NOT. natural(jv)) THEN soil_deficit(ji,jv) = MAX( zero, irrig_fulfill(jv) * mx_eau_var(ji) - bqsb(ji,jv) - gqsb(ji,jv) ) ENDIF ENDDO ENDDO ! computes horizontal diffusion between the water reservoirs IF ( ok_hdiff ) THEN CALL hydrolc_hdiff(kjpindex, veget, tot_bare_soil, ruu_ch, gqsb, bqsb, dsg, dss, dsp) ENDIF ! If we check the water balance, we end with the comparison of total water change and fluxes IF (check_waterbal) THEN CALL hydrolc_waterbal(kjpindex, index, veget, totfrac_nobio, qsintveg, snow, snow_nobio,& & precip_rain, precip_snow, returnflow, reinfiltration, irrigation, tot_melt, vevapwet, transpir, vevapnu, vevapsno,& & vevapflo, floodout, run_off_tot, drainage ) ENDIF !! 2. Output IF (almaoutput) THEN CALL hydrolc_alma(kjpindex, index, qsintveg, snow, snow_nobio, soilwet) ENDIF CALL xios_orchidee_send_field("runoff",run_off_tot/dt_sechiba) CALL xios_orchidee_send_field("drainage",drainage/dt_sechiba) CALL xios_orchidee_send_field("precip_rain",precip_rain/dt_sechiba) CALL xios_orchidee_send_field("precip_snow",precip_snow/dt_sechiba) CALL xios_orchidee_send_field("irrig_fin",irrig_fin*one_day/dt_sechiba) CALL xios_orchidee_send_field("qsintveg",qsintveg) CALL xios_orchidee_send_field("qsintveg_tot",SUM(qsintveg(:,:),dim=2)) CALL xios_orchidee_send_field("precisol",precisol/dt_sechiba) IF (do_floodplains) CALL xios_orchidee_send_field("floodout",floodout/dt_sechiba) CALL xios_orchidee_send_field("humrel",humrel) CALL xios_orchidee_send_field("qsintmax",qsintmax) CALL xios_orchidee_send_field("irrig_rat",irrig_demand_ratio) histvar(:)=(precip_rain(:)-SUM(precisol(:,:),dim=2)) CALL xios_orchidee_send_field("prveg",histvar/dt_sechiba) histvar(:)=zero DO jv = 1, nvm DO ji = 1, kjpindex IF ( vegtot(ji) .GT. zero ) THEN !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN histvar(ji)=histvar(ji)+tot_bare_soil(ji)/vegtot(ji)*MAX((0.1-dss(ji,jv))*wmax_veg(jv), zero) ELSE histvar(ji)=histvar(ji)+veget(ji,jv)/vegtot(ji)*MAX((0.1-dss(ji,jv))*wmax_veg(jv), zero) ENDIF ENDIF ENDDO ENDDO CALL xios_orchidee_send_field("humtot_top",histvar) ! mrsos in output name CALL xios_orchidee_send_field("humtot",mean_bqsb(:)+mean_gqsb(:)) ! Total soil moisture CALL xios_orchidee_send_field("bqsb",mean_bqsb) CALL xios_orchidee_send_field("gqsb",mean_gqsb) CALL xios_orchidee_send_field("dss",dss) IF (ok_explicitsnow) THEN CALL xios_orchidee_send_field("snowdz",snowdz) ELSE CALL xios_orchidee_send_field("snowdz",snowdepth) END IF CALL xios_orchidee_send_field("tot_melt",tot_melt/dt_sechiba) IF (almaoutput) THEN CALL xios_orchidee_send_field("soilwet",soilwet) CALL xios_orchidee_send_field("delsoilmoist",delsoilmoist) CALL xios_orchidee_send_field("delswe",delswe) CALL xios_orchidee_send_field("delintercept",delintercept) END IF IF ( .NOT. almaoutput ) THEN CALL histwrite_p(hist_id, 'dss', kjit, dss, kjpindex*nvm, indexveg) CALL histwrite_p(hist_id, 'bqsb', kjit, mean_bqsb, kjpindex, index) CALL histwrite_p(hist_id, 'bqsb_pft', kjit, bqsb, kjpindex*nvm, indexveg) CALL histwrite_p(hist_id, 'gqsb', kjit, mean_gqsb, kjpindex, index) CALL histwrite_p(hist_id, 'runoff', kjit, run_off_tot, kjpindex, index) ! this is surface runoff = 5% of total runoff CALL histwrite_p(hist_id, 'runoff_pft', kjit, runoff, kjpindex*nvm,indexveg) CALL histwrite_p(hist_id, 'drainage', kjit, drainage, kjpindex, index) ! this 95% of total runoff IF ( river_routing .AND. do_floodplains ) THEN CALL histwrite_p(hist_id, 'floodout', kjit, floodout, kjpindex, index) ENDIF CALL histwrite_p(hist_id, 'precisol', kjit, precisol, kjpindex*nvm, indexveg) CALL histwrite_p(hist_id, 'rain', kjit, precip_rain, kjpindex, index) CALL histwrite_p(hist_id, 'snowf', kjit, precip_snow, kjpindex, index) CALL histwrite_p(hist_id, 'qsintmax', kjit, qsintmax, kjpindex*nvm, indexveg) CALL histwrite_p(hist_id, 'qsintveg', kjit, qsintveg, kjpindex*nvm, indexveg) CALL histwrite_p(hist_id, 'humrel', kjit, humrel, kjpindex*nvm, indexveg) ! this the transpiration stress factor CALL histwrite_p(hist_id, 'vegstress', kjit, vegstress, kjpindex*nvm, indexveg) ! CALL histwrite_p(hist_id, 'irrig_fin', kjit, irrig_fin, kjpindex*nvm, indexveg) ! irrigation applications CALL histwrite_p(hist_id, 'soil_deficit', kjit, soil_deficit, kjpindex*nvm, indexveg) ! ! CALL histwrite_p(hist_id, 'irrig_ratio', kjit, irrig_demand_ratio, kjpindex*nvm, indexveg) !irrigation demande ratio !! The output for "CMIP5" is handled here, assuming that fluxes in kg m^{-2} s^{-1} !! But the transformation below on mrro, mrros and prveg lead to fluxes that are 48 times too small !*** histvar(:)=zero DO jv = 1, nvm DO ji = 1, kjpindex IF ( vegtot(ji) .GT. zero ) THEN !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN histvar(ji)=histvar(ji)+tot_bare_soil(ji)/vegtot(ji)*MAX((0.1-dss(ji,jv))*wmax_veg(jv), zero) ELSE histvar(ji)=histvar(ji)+veget(ji,jv)/vegtot(ji)*MAX((0.1-dss(ji,jv))*wmax_veg(jv), zero) ENDIF ENDIF ENDDO ENDDO ! this is soil moisture in the top 10 cms CALL histwrite_p(hist_id, 'mrsos', kjit, histvar, kjpindex, index) ! this is total soil moisture histvar(:)=mean_bqsb(:)+mean_gqsb(:) CALL histwrite_p(hist_id, 'mrso', kjit, histvar, kjpindex, index) CALL histwrite_p(hist_id, 'mrros', kjit, run_off_tot, kjpindex, index) histvar(:)=run_off_tot(:)+drainage(:) CALL histwrite_p(hist_id, 'mrro', kjit, histvar, kjpindex, index) histvar(:)=(precip_rain(:)-SUM(precisol(:,:),dim=2)) CALL histwrite_p(hist_id, 'prveg', kjit, histvar, kjpindex, index) CALL histwrite_p(hist_id, 'snowmelt',kjit,snowmelt,kjpindex,index) ELSE ! almaoutput=true CALL histwrite_p(hist_id, 'Snowf', kjit, precip_snow, kjpindex, index) CALL histwrite_p(hist_id, 'Rainf', kjit, precip_rain, kjpindex, index) ! surface runoff = 5% of total runoff CALL histwrite_p(hist_id, 'Qs', kjit, run_off_tot, kjpindex, index) ! drainage = 95% of total runoff CALL histwrite_p(hist_id, 'Qsb', kjit, drainage, kjpindex, index) CALL histwrite_p(hist_id, 'Qsm', kjit, snowmelt, kjpindex, index) CALL histwrite_p(hist_id, 'DelSoilMoist', kjit, delsoilmoist, kjpindex, index) CALL histwrite_p(hist_id, 'DelSWE', kjit, delswe, kjpindex, index) CALL histwrite_p(hist_id, 'DelIntercept', kjit, delintercept, kjpindex, index) CALL histwrite_p(hist_id, 'SoilMoist', kjit, tot_watsoil_end, kjpindex, index) CALL histwrite_p(hist_id, 'SoilWet', kjit, soilwet, kjpindex, index) ! this the transpiration stress factor CALL histwrite_p(hist_id, 'humrel', kjit, humrel, kjpindex*nvm, indexveg) CALL histwrite_p(hist2_id, 'vegstress', kjit, vegstress, kjpindex*nvm, indexveg) CALL histwrite_p(hist2_id, 'irrig_fin', kjit, irrig_fin, kjpindex*nvm, indexveg) CALL histwrite_p(hist_id, 'RootMoist', kjit, tot_watsoil_end, kjpindex, index) CALL histwrite_p(hist_id, 'SubSnow', kjit, vevapsno, kjpindex, index) CALL histwrite_p(hist_id, 'SnowDepth', kjit, snowdepth, kjpindex, index) ENDIF IF ( hist2_id > 0 ) THEN IF ( .NOT. almaoutput ) THEN CALL histwrite_p(hist2_id, 'dss', kjit, dss, kjpindex*nvm, indexveg) CALL histwrite_p(hist2_id, 'bqsb', kjit, mean_bqsb, kjpindex, index) CALL histwrite_p(hist2_id, 'gqsb', kjit, mean_gqsb, kjpindex, index) CALL histwrite_p(hist2_id, 'runoff', kjit, run_off_tot, kjpindex, index) CALL histwrite_p(hist2_id, 'drainage', kjit, drainage, kjpindex, index) IF ( river_routing .AND. do_floodplains ) THEN CALL histwrite_p(hist2_id, 'floodout', kjit, floodout, kjpindex, index) ENDIF CALL histwrite_p(hist2_id, 'precisol', kjit, precisol, kjpindex*nvm, indexveg) CALL histwrite_p(hist2_id, 'rain', kjit, precip_rain, kjpindex, index) CALL histwrite_p(hist2_id, 'snowf', kjit, precip_snow, kjpindex, index) CALL histwrite_p(hist2_id, 'qsintmax', kjit, qsintmax, kjpindex*nvm, indexveg) CALL histwrite_p(hist2_id, 'qsintveg', kjit, qsintveg, kjpindex*nvm, indexveg) CALL histwrite_p(hist2_id, 'humrel', kjit, humrel, kjpindex*nvm, indexveg) CALL histwrite_p(hist2_id, 'snowmelt',kjit,snowmelt,kjpindex,index) IF (check_waterbal) THEN CALL histwrite_p(hist2_id, 'TotWater', kjit, tot_water_end, kjpindex, index) CALL histwrite_p(hist2_id, 'TotWaterFlux', kjit, tot_flux, kjpindex, index) ENDIF histvar(:)=zero DO jv = 1, nvm DO ji = 1, kjpindex IF ( vegtot(ji) .GT. zero ) THEN !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN histvar(ji)=histvar(ji)+tot_bare_soil(ji)/vegtot(ji)*MAX((0.1-dss(ji,jv))*wmax_veg(jv), zero) ELSE histvar(ji)=histvar(ji)+veget(ji,jv)/vegtot(ji)*MAX((0.1-dss(ji,jv))*wmax_veg(jv), zero) ENDIF ENDIF ENDDO ENDDO CALL histwrite_p(hist2_id, 'mrsos', kjit, histvar, kjpindex, index) histvar(:)=run_off_tot(:)+drainage(:) CALL histwrite_p(hist2_id, 'mrro', kjit, histvar, kjpindex, index) ! this is total soil moisture histvar(:)=mean_bqsb(:)+mean_gqsb(:) CALL histwrite_p(hist2_id, 'mrso', kjit, histvar, kjpindex, index) CALL histwrite_p(hist2_id, 'mrros', kjit, run_off_tot, kjpindex, index) ELSE CALL histwrite_p(hist2_id, 'Snowf', kjit, precip_snow, kjpindex, index) CALL histwrite_p(hist2_id, 'Rainf', kjit, precip_rain, kjpindex, index) CALL histwrite_p(hist2_id, 'Qs', kjit, run_off_tot, kjpindex, index) CALL histwrite_p(hist2_id, 'Qsb', kjit, drainage, kjpindex, index) CALL histwrite_p(hist2_id, 'Qsm', kjit, snowmelt, kjpindex, index) CALL histwrite_p(hist2_id, 'DelSoilMoist', kjit, delsoilmoist, kjpindex, index) CALL histwrite_p(hist2_id, 'DelSWE', kjit, delswe, kjpindex, index) CALL histwrite_p(hist2_id, 'DelIntercept', kjit, delintercept, kjpindex, index) CALL histwrite_p(hist2_id, 'SoilMoist', kjit, tot_watsoil_end, kjpindex, index) CALL histwrite_p(hist2_id, 'SoilWet', kjit, soilwet, kjpindex, index) CALL histwrite_p(hist2_id, 'RootMoist', kjit, tot_watsoil_end, kjpindex, index) CALL histwrite_p(hist2_id, 'SubSnow', kjit, vevapsno, kjpindex, index) CALL histwrite_p(hist2_id, 'SnowDepth', kjit, snowdepth, kjpindex, index) ENDIF ENDIF IF (printlev>=3) WRITE (numout,*) ' hydrolc_main Done ' END SUBROUTINE hydrolc_main !! ================================================================================================================================ !! SUBROUTINE : hydrolc_finalize !! !>\BRIEF !! !! DESCRIPTION : This subroutine writes the module variables and variables calculated in hydrolc to restart file !! !! MAIN OUTPUT VARIABLE(S) : !! !! REFERENCE(S) : !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_finalize( kjit, kjpindex, rest_id, snow, & snow_age, snow_nobio, snow_nobio_age, humrel, & vegstress, qsintveg, snowrho, snowtemp, & snowdz, snowheat, snowgrain, & drysoil_frac, rsol, shumdiag ) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT(in) :: kjit !! Current time step number (unitless) INTEGER(i_std), INTENT(in) :: kjpindex !! Domain size (number of grid cells) (unitless) INTEGER(i_std),INTENT (in) :: rest_id !! Restart file identifier REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: snow !! Snow water equivalent REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: snow_age !! Snow age (days) REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (in) :: snow_nobio !! Snow water equivalent on nobio areas REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (in) :: snow_nobio_age !! Snow age on ice, lakes, ... (days) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: humrel !! Soil moisture stress factor on transpiration and !! bare soil evaporation (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: vegstress !! Vegetation moisture stress (only for vegetation !! growth) (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: qsintveg !! Amount of water in the canopy interception !! reservoir @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(in) :: snowrho !! Snow density REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(in) :: snowtemp !! Snow temperature REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(in) :: snowdz !! Snow layer thickness REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(in) :: snowheat !! Snow heat content REAL(r_std), DIMENSION (kjpindex,nsnow), INTENT(in) :: snowgrain !! Snow grain size REAL(r_std),DIMENSION (kjpindex),INTENT(in) :: drysoil_frac REAL(r_std),DIMENSION (kjpindex),INTENT(in) :: rsol REAL(r_std),DIMENSION (kjpindex,nbdl),INTENT(in) :: shumdiag !_ ================================================================================================================================ IF (printlev>=3) WRITE (numout,*) ' we have to complete restart file with HYDROLOGIC variables ' CALL restput_p(rest_id, 'humrel', nbp_glo, nvm, 1, kjit, humrel, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'vegstress', nbp_glo, nvm, 1, kjit, vegstress, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'snow', nbp_glo, 1, 1, kjit, snow, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'snow_age', nbp_glo, 1, 1, kjit, snow_age, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'snow_nobio', nbp_glo, nnobio, 1, kjit, snow_nobio, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'snow_nobio_age', nbp_glo, nnobio, 1, kjit, snow_nobio_age, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'bqsb', nbp_glo, nvm, 1, kjit, bqsb, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'gqsb', nbp_glo, nvm, 1, kjit, gqsb, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'dsg', nbp_glo, nvm, 1, kjit, dsg, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'dsp', nbp_glo, nvm, 1, kjit, dsp, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'dss', nbp_glo, nvm, 1, kjit, dss, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'hdry', nbp_glo, 1, 1, kjit, hdry, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'qsintveg', nbp_glo, nvm, 1, kjit, qsintveg, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'resdist', nbp_glo, nvm, 1, kjit, resdist, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'drysoil_frac', nbp_glo, 1, 1, kjit, drysoil_frac, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'rsol', nbp_glo, 1, 1, kjit, rsol, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'shumdiag', nbp_glo, nbdl, 1, kjit, shumdiag, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'mean_gqsb', nbp_glo, 1, 1, kjit, mean_gqsb, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'mean_bqsb', nbp_glo, 1, 1, kjit, mean_bqsb, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'mx_eau_var', nbp_glo, 1, 1, kjit, mx_eau_var, 'scatter', nbp_glo, index_g) CALL restput_p(rest_id, 'vegtot', nbp_glo, 1, 1, kjit, vegtot, 'scatter', nbp_glo, index_g) ! Write variables for explictsnow module to restart file IF (ok_explicitsnow) THEN CALL explicitsnow_finalize ( kjit, kjpindex, rest_id, snowrho, & snowtemp, snowdz, snowheat, snowgrain) END IF END SUBROUTINE hydrolc_finalize !! ================================================================================================================================ !! SUBROUTINE : hydrolc_init !! !>\BRIEF This routine drives the initialisation of the water budget calculations. !! !! DESCRIPTION : The following sequences are performed : !! - Setting ok_hdiff (default is false) for horizontal diffusion between soil columns !! - Dynamic allocation of arrays that are local to module hydrolc !! - Initializing prognostic variables from input restart file !! - Default attribution is performed in case the model is started without a restart file !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLE(S) : humrel, vegstress,snow, snow_age, snow_nobio, snow_nobio_age, qsintveg !! !! REFERENCE(S) : None !! !! FLOWCHART11 : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_init(kjit, kjpindex, index, rest_id, & veget, tot_bare_soil, humrel, vegstress, & shumdiag, & snow, snow_age, snow_nobio, snow_nobio_age, & qsintveg, & snowdz, snowgrain, snowrho, snowtemp, & snowheat, drysoil_frac, rsol) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT (in) :: kjit !! Current time step number (unitless) INTEGER(i_std), INTENT (in) :: kjpindex !! Domain size (number of grid cells) (unitless) INTEGER(i_std),DIMENSION (kjpindex), INTENT (in) :: index !! Indices of the land grid points on the map !! (unitless) INTEGER(i_std), INTENT (in) :: rest_id !! _Restart_ file identifier (unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: veget !! Grid-cell fraction effectively covered by !! vegetation for each PFT, except for soil !! (0-1, unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: tot_bare_soil !! Total evaporating bare soil fraction !! 0.2 Output variables REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (out) :: humrel !! Soil moisture stress factor on transpiration !! and bare soil evaporation (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (out) :: vegstress !! Vegetation moisture stress (only for !! vegetation growth) (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nbdl), INTENT (out) :: shumdiag !! Mean relative soil moisture in the different !! levels used by thermosoil.f90 (0-1, unitless) REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: snow !! Snow water equivalent @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: snow_age !! Snow age (days) REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (out):: snow_nobio !! Snow water equivalent on nobio areas !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (out):: snow_nobio_age !! Snow age on ice, lakes, ... (days) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (out) :: qsintveg !! Amount of water in the canopy interception !! reservoir @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nsnow),INTENT(out) :: snowdz !! Snow depth REAL(r_std),DIMENSION (kjpindex,nsnow),INTENT(out) :: snowgrain !! Snow grain size REAL(r_std),DIMENSION (kjpindex,nsnow),INTENT(out) :: snowheat !! Snow heat content REAL(r_std),DIMENSION (kjpindex,nsnow),INTENT(out) :: snowtemp !! Snow temperature REAL(r_std),DIMENSION (kjpindex,nsnow),INTENT(out) :: snowrho !! Snow density REAL(r_std),DIMENSION (kjpindex),INTENT(out) :: drysoil_frac REAL(r_std),DIMENSION (kjpindex),INTENT(out) :: rsol !! Resistance to bare soil evaporation !! 0.3 Modified variables !! 0.4 Local variables INTEGER(i_std) :: ier !! To receive error flag during allocation INTEGER(i_std) :: ji,jv,ik !! Indices for grid-cells, PFTs, and grid-cells !! (unitless) REAL(r_std), DIMENSION (kjpindex,nvm) :: zdsp, tmpdss !! Ancillary variables for initializing dsp !! and dss (m) REAL(r_std), ALLOCATABLE, DIMENSION (:,:) :: dsp_g !! Ancillary variable for initializing dsp (m) !! dss (m) REAL(r_std), DIMENSION(kjpindex) :: a_subgrd !! Diagnosed subgrid fraction of saturated soil in !! the top layer, to calculate hdry (0-1, unitless) CHARACTER(LEN=80) :: var_name !! To store variables names for I/O !_ ================================================================================================================================ !! 1. Setting ok_hdiff for horizontal diffusion between soil columns !Config Key = HYDROL_OK_HDIFF !Config Desc = do horizontal diffusion? !Config If = OK_SECHIBA and .NOT.(HYDROL_CWRR) !Config Def = n !Config Help = If TRUE, then water can diffuse horizontally between !Config the PFTs' water reservoirs. !Config Units = [FLAG] ok_hdiff = .FALSE. CALL getin_p('HYDROL_OK_HDIFF',ok_hdiff) !! 2. Make dynamic allocation with the good dimensions ! one dimension array allocation with possible restart value ALLOCATE (bqsb(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in bqsb allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF bqsb(:,:) = zero ALLOCATE (gqsb(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in gqsb allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF gqsb(:,:) = zero ALLOCATE (dsg(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in dsg allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF dsg(:,:) = zero ALLOCATE (dsp(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in dsp allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF dsp(:,:) = zero ! one dimension array allocation ALLOCATE (mean_bqsb(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in mean_bqsb allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF mean_bqsb(:) = zero ALLOCATE (mean_gqsb(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in mean_gqsb allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF mean_gqsb(:) = zero ALLOCATE (dss(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in dss allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF dss(:,:) = zero ALLOCATE (irrig_fin(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in irrig_fin allocation. We stop. We need kjpindex*nvm words = ',kjpindex*nvm STOP 'hydrolc_init' END IF irrig_fin(:,:) = zero ALLOCATE (hdry(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in hdry allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF hdry(:) = zero ALLOCATE (precisol(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in precisol allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF precisol(:,:) = zero ALLOCATE (gdrainage(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in precisol allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF gdrainage(:,:) = zero ALLOCATE (subsnowveg(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in subsnowveg allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF subsnowveg(:) = zero ALLOCATE (subsnownobio(kjpindex,nnobio),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in subsnownobio allocation. We stop. We need kjpindex*nnobio words = ', & kjpindex*nnobio STOP 'hydrolc_init' END IF subsnownobio(:,:) = zero ALLOCATE (snowmelt(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in snowmelt allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF snowmelt(:) = zero ALLOCATE (icemelt(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in icemelt allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF icemelt(:) = zero ALLOCATE (subsinksoil(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in subsinksoil allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (mx_eau_var(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in mx_eau_var allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF mx_eau_var(:) = zero ALLOCATE (ruu_ch(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in ruu_ch allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ruu_ch(:) = zero ALLOCATE (vegtot(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in vegtot allocation. We stop. We need kjpindex words = ',kjpindex*nvm STOP 'hydrolc_init' END IF vegtot(:) = zero ALLOCATE (resdist(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in resdist allocation. We stop. We need kjpindex words = ',kjpindex*nvm STOP 'hydrolc_init' END IF resdist(:,:) = zero ALLOCATE (runoff(kjpindex,nvm),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in runoff allocation. We stop. We need kjpindex words = ',kjpindex*nvm STOP 'hydrolc_init' END IF runoff(:,:) = zero ! If we check the water balance we need two more variables IF ( check_waterbal ) THEN ALLOCATE (tot_water_beg(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in tot_water_beg allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (tot_water_end(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in tot_water_end allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (tot_flux(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in tot_flux allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrol_init' END IF ENDIF ! If we use the almaoutputs we need four more variables IF ( almaoutput ) THEN ALLOCATE (tot_watveg_beg(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in tot_watveg_beg allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (tot_watveg_end(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in tot_watveg_end allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (tot_watsoil_beg(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in tot_watsoil_beg allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (tot_watsoil_end(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in tot_watsoil_end allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (delsoilmoist(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in delsoilmoist allocation. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (delintercept(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in delintercept. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (delswe(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in delswe. We stop. We need kjpindex words = ',kjpindex STOP 'hydrolc_init' ENDIF ALLOCATE (snow_beg(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in snow_beg allocation. We stop. We need kjpindex words =',kjpindex STOP 'hydrolc_init' END IF ALLOCATE (snow_end(kjpindex),stat=ier) IF (ier.NE.0) THEN WRITE (numout,*) ' error in snow_end allocation. We stop. We need kjpindex words =',kjpindex STOP 'hydrolc_init' END IF ENDIF !! 3. Initialization of hydrologic variables: !! 3.a Read data from restart input file (opened by sechiba_init) !! for HYDROLOGIC processes IF (printlev>=3) WRITE (numout,*) ' we have to read a restart file for HYDROLOGIC variables' var_name= 'snow' CALL ioconf_setatt_p('UNITS', 'kg/m^2') CALL ioconf_setatt_p('LONG_NAME','Snow mass') CALL restget_p (rest_id, var_name, nbp_glo, 1 , 1, kjit, .TRUE., snow, "gather", nbp_glo, index_g) var_name= 'snow_age' CALL ioconf_setatt_p('UNITS', 'd') CALL ioconf_setatt_p('LONG_NAME','Snow age') CALL restget_p (rest_id, var_name, nbp_glo, 1 , 1, kjit, .TRUE., snow_age, "gather", nbp_glo, index_g) var_name= 'snow_nobio' CALL ioconf_setatt_p('UNITS', 'kg/m^2') CALL ioconf_setatt_p('LONG_NAME','Snow on other surface types') CALL restget_p (rest_id, var_name, nbp_glo, nnobio , 1, kjit, .TRUE., snow_nobio, "gather", nbp_glo, index_g) var_name= 'snow_nobio_age' CALL ioconf_setatt_p('UNITS', 'd') CALL ioconf_setatt_p('LONG_NAME','Snow age on other surface types') CALL restget_p (rest_id, var_name, nbp_glo, nnobio , 1, kjit, .TRUE., snow_nobio_age, "gather", nbp_glo, index_g) var_name= 'humrel' CALL ioconf_setatt_p('UNITS', '-') CALL ioconf_setatt_p('LONG_NAME','Soil moisture stress') CALL restget_p (rest_id, var_name, nbp_glo, nvm, 1, kjit, .TRUE., humrel, "gather", nbp_glo, index_g) var_name= 'vegstress' CALL ioconf_setatt_p('UNITS', '-') CALL ioconf_setatt_p('LONG_NAME','Vegetation growth moisture stress') CALL restget_p (rest_id, var_name, nbp_glo, nvm, 1, kjit, .TRUE., vegstress, "gather", nbp_glo, index_g) var_name= 'bqsb' CALL ioconf_setatt_p('UNITS', 'kg/m^2') CALL ioconf_setatt_p('LONG_NAME','Deep soil moisture') CALL restget_p (rest_id, var_name, nbp_glo, nvm , 1, kjit, .TRUE., bqsb, "gather", nbp_glo, index_g) var_name= 'gqsb' CALL ioconf_setatt_p('UNITS', 'kg/m^2') CALL ioconf_setatt_p('LONG_NAME','Surface soil moisture') CALL restget_p (rest_id, var_name, nbp_glo, nvm , 1, kjit, .TRUE., gqsb, "gather", nbp_glo, index_g) var_name= 'dsg' CALL ioconf_setatt_p('UNITS', 'm') CALL ioconf_setatt_p('LONG_NAME','Depth of upper reservoir') CALL restget_p (rest_id, var_name, nbp_glo, nvm , 1, kjit, .TRUE., dsg, "gather", nbp_glo, index_g) var_name= 'dsp' CALL ioconf_setatt_p('UNITS', 'm') CALL ioconf_setatt_p('LONG_NAME','Depth to lower reservoir') CALL restget_p (rest_id, var_name, nbp_glo, nvm , 1, kjit, .TRUE., dsp, "gather", nbp_glo, index_g) var_name= 'dss' CALL ioconf_setatt_p('UNITS', 'm') CALL ioconf_setatt_p('LONG_NAME','Hauteur au dessus du reservoir de surface') CALL restget_p (rest_id, var_name, nbp_glo, nvm , 1, kjit, .TRUE., dss, "gather", nbp_glo, index_g) var_name= 'hdry' CALL ioconf_setatt_p('UNITS', 'm') CALL ioconf_setatt_p('LONG_NAME','Dry soil heigth in meters') CALL restget_p (rest_id, var_name, nbp_glo, 1 , 1, kjit, .TRUE., hdry, "gather", nbp_glo, index_g) var_name= 'qsintveg' CALL ioconf_setatt_p('UNITS', 'kg/m^2') CALL ioconf_setatt_p('LONG_NAME','Intercepted moisture') CALL restget_p (rest_id, var_name, nbp_glo, nvm, 1, kjit, .TRUE., qsintveg, "gather", nbp_glo, index_g) var_name= 'resdist' CALL ioconf_setatt_p('UNITS', '-') CALL ioconf_setatt_p('LONG_NAME','Distribution of reservoirs') CALL restget_p (rest_id, var_name, nbp_glo, nvm, 1, kjit, .TRUE., resdist, "gather", nbp_glo, index_g) ! Read drysoil_frac. It will be initalized later in hydrolc_var_init if the varaible is not find in restart file. CALL restget_p (rest_id, 'drysoil_frac', nbp_glo, 1 , 1, kjit, .TRUE., drysoil_frac, "gather", nbp_glo, index_g) ! Read rsol. It will be initalized later in hydrolc_var_init if the varaible is not find in restart file. CALL restget_p (rest_id, 'rsol', nbp_glo, 1 , 1, kjit, .TRUE., rsol, "gather", nbp_glo, index_g) ! shumdiag : initialization if not in restart file will be done in hydrolc_var_init CALL restget_p (rest_id, 'shumdiag', nbp_glo, nbdl , 1, kjit, .TRUE., shumdiag, "gather", nbp_glo, index_g) CALL restget_p (rest_id, 'mean_bqsb', nbp_glo, 1 , 1, kjit, .TRUE., mean_bqsb, "gather", nbp_glo, index_g) CALL restget_p (rest_id, 'mean_gqsb', nbp_glo, 1 , 1, kjit, .TRUE., mean_gqsb, "gather", nbp_glo, index_g) var_name= 'mx_eau_var' CALL ioconf_setatt_p('UNITS', '') CALL ioconf_setatt_p('LONG_NAME','') CALL restget_p (rest_id, var_name, nbp_glo, 1 , 1, kjit, .TRUE., mx_eau_var, "gather", nbp_glo, index_g) var_name= 'vegtot' CALL ioconf_setatt_p('UNITS', '') CALL ioconf_setatt_p('LONG_NAME','') CALL restget_p (rest_id, var_name, nbp_glo, 1 , 1, kjit, .TRUE., vegtot, "gather", nbp_glo, index_g) !! 3.b Assign default values if non were found in the restart file !Config Key = HYDROL_SNOW !Config Desc = Initial snow mass if not found in restart !Config If = OK_SECHIBA !Config Def = 0.0 !Config Help = The initial value of snow mass if its value is not found !Config in the restart file. This should only be used if the model is !Config started without a restart file. !Config Units = [kg/m^2] CALL setvar_p (snow, val_exp, 'HYDROL_SNOW', zero) !Config Key = HYDROL_SNOWAGE !Config Desc = Initial snow age if not found in restart !Config If = OK_SECHIBA !Config Def = 0.0 !Config Help = The initial value of snow age if its value is not found !Config in the restart file. This should only be used if the model is !Config started without a restart file. !Config Units = [days] CALL setvar_p (snow_age, val_exp, 'HYDROL_SNOWAGE', zero) !Config Key = HYDROL_SNOW_NOBIO !Config Desc = Initial snow amount on ice, lakes, etc. if not found in restart !Config If = OK_SECHIBA !Config Def = 0.0 !Config Help = The initial value of snow if its value is not found !Config in the restart file. This should only be used if the model is !Config started without a restart file. !Config Units = [m] CALL setvar_p (snow_nobio, val_exp, 'HYDROL_SNOW_NOBIO', zero) !Config Key = HYDROL_SNOW_NOBIO_AGE !Config Desc = Initial snow age on ice, lakes, etc. if not found in restart !Config If = OK_SECHIBA !Config Def = 0.0 !Config Help = The initial value of snow age if its value is not found !Config in the restart file. This should only be used if the model is !Config started without a restart file. !Config Units = [days] CALL setvar_p (snow_nobio_age, val_exp, 'HYDROL_SNOW_NOBIO_AGE', zero) !Config Key = HYDROL_HUMR !Config Desc = Initial soil moisture stress if not found in restart !Config If = OK_SECHIBA !Config Def = 1.0 !Config Help = The initial value of soil moisture stress if its value is not found !Config in the restart file. This should only be used if the model is !Config started without a restart file. !Config Units = [-] CALL setvar_p (humrel, val_exp,'HYDROL_HUMR', un) CALL setvar_p (vegstress, val_exp,'HYDROL_HUMR', un) !Config Key = HYDROL_BQSB !Config Desc = Initial restart deep soil moisture if not found in restart !Config If = OK_SECHIBA !Config Def = 999999. !Config Help = The initial value of deep soil moisture if its value is not found !Config in the restart file. This should only be used if the model is !Config started without a restart file. Default behaviour is a saturated soil. !Config Units = [kg/m^2] CALL setvar_p (bqsb, val_exp, 'HYDROL_BQSB', wmax_veg*zmaxh) !Config Key = HYDROL_GQSB !Config Desc = Initial upper soil moisture if not found in restart !Config If = OK_SECHIBA !Config Def = 0.0 !Config Help = The initial value of upper soil moisture if its value is not found !Config in the restart file. This should only be used if the model is !Config started without a restart file. !Config Units = [kg/m^2] CALL setvar_p (gqsb, val_exp, 'HYDROL_GQSB', zero) !Config Key = HYDROL_DSG !Config Desc = Initial upper reservoir depth if not found in restart !Config If = OK_SECHIBA !Config Def = 0.0 !Config Help = The initial value of upper reservoir depth if its value is not found !Config in the restart file. This should only be used if the model is !Config started without a restart file. !Config Units = [m] CALL setvar_p (dsg, val_exp, 'HYDROL_DSG', zero) !Config Key = HYDROL_QSV !Config Desc = Initial water on canopy if not found in restart !Config If = OK_SECHIBA !Config Def = 0.0 !Config Help = The initial value of moisture on canopy if its value !Config is not found in the restart file. This should only be used if !Config the model is started without a restart file. !Config Units = [kg/m^2] CALL setvar_p (qsintveg, val_exp, 'HYDROL_QSV', zero) !! 3.c Specific calculations to define default values for dry soil depths : dsp, dss, and hdry ! set inital value for dsp if needed !Config Key = HYDROL_DSP !Config Desc = Initial dry soil above upper reservoir if not found in restart !Config If = OK_SECHIBA !Config Def = 999999. !Config Help = The initial value of dry soil above upper reservoir if its value !Config is not found in the restart file. This should only be used if !Config the model is started without a restart file. The default behaviour !Config is to compute it from the variables above. Should be OK most of !Config the time. !Config Units = [m] ! ! Calculate temporary variable to use for initialiaion of dsp. ! This variable will only be used if no value is set in run.def DO jv = 1,nvm zdsp(:,jv) = zmaxh - bqsb(:,jv) / wmax_veg(jv) END DO CALL setvar_p(dsp, val_exp, 'HYDROL_DSP', zdsp) ! set inital value for dss DO jv = 1,nvm tmpdss(:,jv) = dsg(:,jv) - gqsb(:,jv) / wmax_veg(jv) END DO ! Initialize dss if it is not found in restart file IF ( ALL( dss(:,:) == val_exp ) ) THEN dss(:,:)=tmpdss(:,:) END IF ! set inital value for hdry if not found in restart file ! see hydrolc_soil, step 8.4 IF ( ALL( hdry(:) == val_exp ) ) THEN a_subgrd(:) = zero DO ji=1,kjpindex IF ( gqsb(ji,1)+bqsb(ji,1) .GT. zero ) THEN IF (.NOT. (dsg(ji,1).EQ. zero .OR. gqsb(ji,1).EQ.zero)) THEN ! Ajouts Nathalie - Fred - le 28 Mars 2006 a_subgrd(ji)=MIN(MAX(dsg(ji,1)-dss(ji,1),zero)/dsg_min,un) ENDIF ENDIF ENDDO ! Correction Nathalie - le 28 Mars 2006 - re-ecriture drysoil_frac/hdry - Fred Hourdin ! revu 22 novembre 2007 hdry(:) = a_subgrd(:)*dss(:,1) + (un-a_subgrd(:))*dsp(:,1) ENDIF ! There is no need to configure the initialisation of resdist. If not available it is the vegetation map IF ( MINVAL(resdist) .EQ. MAXVAL(resdist) .AND. MINVAL(resdist) .EQ. val_exp) THEN resdist(:,1) = tot_bare_soil(:) resdist(:,2:nvm) = veget(:,2:nvm) ENDIF !! 3.d Compute vegtot (remember that it is only frac_nobio + SUM(veget(,:)) that is equal to 1) IF (ALL(vegtot(:)==val_exp)) THEN DO ji = 1, kjpindex vegtot(ji) = SUM(veget(ji,2:nvm)) + tot_bare_soil(ji) ENDDO END IF ! Initialize variables for explictsnow module by reading restart file IF (ok_explicitsnow) THEN CALL explicitsnow_initialize( kjit, kjpindex, rest_id, snowrho, & snowtemp, snowdz, snowheat, snowgrain ) END IF IF (printlev>=3) WRITE (numout,*) ' hydrolc_init done ' END SUBROUTINE hydrolc_init !! ================================================================================================================================ !! SUBROUTINE : hydrolc_clear !! !>\BRIEF Deallocates arrays that were allocated in hydrolc_init and hydrolc_var_init. !! !! DESCRIPTION : None !! !! RECENT CHANGES : None !! !! MAIN OUTPUT VARIABLE(S) : None !! !! REFERENCE(S) : None !! !! FLOWCHART : None !!\n !_ ================================================================================================================================ SUBROUTINE hydrolc_clear() IF (ALLOCATED (bqsb)) DEALLOCATE (bqsb) IF (ALLOCATED (gqsb)) DEALLOCATE (gqsb) IF (ALLOCATED (dsg)) DEALLOCATE (dsg) IF (ALLOCATED (dsp)) DEALLOCATE (dsp) IF (ALLOCATED (mean_bqsb)) DEALLOCATE (mean_bqsb) IF (ALLOCATED (mean_gqsb)) DEALLOCATE (mean_gqsb) IF (ALLOCATED (irrig_fin)) DEALLOCATE (irrig_fin) IF (ALLOCATED (dss)) DEALLOCATE (dss) IF (ALLOCATED (hdry)) DEALLOCATE (hdry) IF (ALLOCATED (precisol)) DEALLOCATE (precisol) IF (ALLOCATED (gdrainage)) DEALLOCATE (gdrainage) IF (ALLOCATED (subsnowveg)) DEALLOCATE (subsnowveg) IF (ALLOCATED (subsnownobio)) DEALLOCATE (subsnownobio) IF (ALLOCATED (snowmelt)) DEALLOCATE (snowmelt) IF (ALLOCATED (icemelt)) DEALLOCATE (icemelt) IF (ALLOCATED (subsinksoil)) DEALLOCATE (subsinksoil) IF (ALLOCATED (mx_eau_var)) DEALLOCATE (mx_eau_var) IF (ALLOCATED (ruu_ch)) DEALLOCATE (ruu_ch) IF (ALLOCATED (vegtot)) DEALLOCATE (vegtot) IF (ALLOCATED (resdist)) DEALLOCATE (resdist) IF (ALLOCATED (tot_water_beg)) DEALLOCATE (tot_water_beg) IF (ALLOCATED (tot_water_end)) DEALLOCATE (tot_water_end) IF (ALLOCATED (tot_flux)) DEALLOCATE (tot_flux) IF (ALLOCATED (tot_watveg_beg)) DEALLOCATE (tot_watveg_beg) IF (ALLOCATED (tot_watveg_end)) DEALLOCATE (tot_watveg_end) IF (ALLOCATED (tot_watsoil_beg)) DEALLOCATE (tot_watsoil_beg) IF (ALLOCATED (tot_watsoil_end)) DEALLOCATE (tot_watsoil_end) IF (ALLOCATED (delsoilmoist)) DEALLOCATE (delsoilmoist) IF (ALLOCATED (delintercept)) DEALLOCATE (delintercept) IF (ALLOCATED (snow_beg)) DEALLOCATE (snow_beg) IF (ALLOCATED (snow_end)) DEALLOCATE (snow_end) IF (ALLOCATED (delswe)) DEALLOCATE (delswe) IF (ALLOCATED (runoff)) DEALLOCATE (runoff) END SUBROUTINE hydrolc_clear !! ================================================================================================================================ !! SUBROUTINE : hydrolc_var_init !! !>\BRIEF This routine initializes diagnostic hydrologic variables. !! !! DESCRIPTION : The following variables are assigned : !! - Soil characteristics : soil water capacities mx_eau_var and ruu_ch \f$(kg m^{-2})\f$ and \f$(kg m^{-3})\f$ !! - Initial values for diagnostic variables : mean_bqsb, mean_gqsb, mean_dsg, shumdiag, drysoil_frac, rsol, litterhumdiag !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLE(S) : rsol, drysoil_frac, mx_eau_var, ruu_ch, shumdiag, litterhumdiag !! !! REFERENCE(S) : None !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_var_init (kjpindex, veget, veget_max, tot_bare_soil, & rsol, drysoil_frac, mx_eau_var, ruu_ch, shumdiag) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT(in) :: kjpindex !! Domain size (number of grid cells) (unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: veget !! Grid-cell fraction effectively covered by vegetation for !! each PFT, except for soil (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: veget_max !! PFT fractions within grid-cells: max value of veget for !! vegetation PFTs and min value for bare soil (0-1, !! unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: tot_bare_soil !! Total evaporating bare soil fraction !! 0.2 Output variables REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: rsol !! Resistance to bare soil evaporation !! @tex ($s m^{-1}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: drysoil_frac !! Fraction of visible dry soil (0-1, unitless) REAL(r_std),DIMENSION (kjpindex), INTENT (inout) :: mx_eau_var !! Maximum water content of the soil !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: ruu_ch !! Volumetric soil water capacity !! @tex ($kg m^{-3}$) @endtex REAL(r_std),DIMENSION (kjpindex,nbdl), INTENT (inout):: shumdiag !! Mean relative soil moisture, diagnosed for !! thermosoil.f90 (0-1, unitless) !! 0.3 Modified variables !! 0.4 Local variables INTEGER(i_std) :: ji,jv, jd !! Indices for grid-cells, PFTs and diagnostic levels in !! the soil (unitless) REAL(r_std), DIMENSION(kjpindex) :: mean_dsg !! Mean Depth of the top layer, averaged over the soil !! columns (m) REAL(r_std) :: gtr, btr !! Ancillary variables to compute shumdiag (0-1, unitless) REAL(r_std), DIMENSION(nbdl+1) :: tmp_dl !! Temporary diagnostic levels in the soil (m) !_ ================================================================================================================================ !! 1. Vertical diagnostic levels to compute shumdiag (relative moisture for thermosoil) tmp_dl(1) = 0 tmp_dl(2:nbdl+1) = diaglev(1:nbdl) !! 2. Calculation of mx_eau_var and ruu_ch (soil water capacities) IF (ALL(mx_eau_var(:)==val_exp)) THEN mx_eau_var(:) = zero DO ji = 1,kjpindex DO jv = 1,nvm !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN mx_eau_var(ji) = mx_eau_var(ji) + tot_bare_soil(ji)*wmax_veg(jv)*zmaxh ELSE mx_eau_var(ji) = mx_eau_var(ji) + veget(ji,jv)*wmax_veg(jv)*zmaxh ENDIF END DO IF (vegtot(ji) .GT. zero) THEN mx_eau_var(ji) = mx_eau_var(ji)/vegtot(ji) ELSE ! lakes, ice, cities... mx_eau_var(ji) = mx_eau_nobio*zmaxh ENDIF END DO END IF !! Initialize ruu_ch ruu_ch(:) = mx_eau_var(:) / zmaxh !! 3.-4. Initial values of the mean soil layer depths and water contents and shumdiag IF (ALL(mean_bqsb(:)==val_exp) .OR. ALL(mean_gqsb(:)==val_exp) .OR. ALL(shumdiag(:,:)==val_exp)) THEN !! 3. Initial values of the mean soil layer depths and water contents ! could be done with SUM instruction but this kills vectorization mean_bqsb(:) = zero mean_gqsb(:) = zero mean_dsg(:) = zero DO jv = 1, nvm DO ji = 1, kjpindex mean_bqsb(ji) = mean_bqsb(ji) + resdist(ji,jv)*bqsb(ji,jv) mean_gqsb(ji) = mean_gqsb(ji) + resdist(ji,jv)*gqsb(ji,jv) mean_dsg(ji) = mean_dsg(ji) + resdist(ji,jv)*dsg(ji,jv) ENDDO ENDDO mean_dsg(:) = MAX( mean_dsg(:), mean_gqsb(:)/ruu_ch(:) ) DO ji = 1, kjpindex IF (vegtot(ji) .GT. zero) THEN mean_bqsb(ji) = mean_bqsb(ji)/vegtot(ji) mean_gqsb(ji) = mean_gqsb(ji)/vegtot(ji) mean_dsg(ji) = mean_dsg(ji)/vegtot(ji) ENDIF ENDDO !! 4. Initial value of shumdiag (see hydrolc_soil, 8.2 for details) DO jd = 1,nbdl DO ji = 1,kjpindex IF ( tmp_dl(jd+1) .LT. mean_dsg(ji)) THEN shumdiag(ji,jd) = mean_gqsb(ji)/mx_eau_var(ji) ELSE IF ( tmp_dl(jd) .LT. mean_dsg(ji)) THEN gtr = (mean_dsg(ji)-tmp_dl(jd))/(tmp_dl(jd+1)-tmp_dl(jd)) btr = 1 - gtr shumdiag(ji,jd) = gtr*mean_gqsb(ji)/mx_eau_var(ji) + & & btr*mean_bqsb(ji)/mx_eau_var(ji) ELSE shumdiag(ji,jd) = mean_bqsb(ji)/mx_eau_var(ji) ENDIF ENDIF shumdiag(ji,jd) = MAX(MIN(shumdiag(ji,jd), un), zero) ENDDO ENDDO END IF !! 5. Initialize drysoil_frac if it was not found in the restart file IF (ALL(drysoil_frac(:) == val_exp)) THEN drysoil_frac(:) = MIN(MAX(dss(:,1),zero)*10._r_std, un) END IF !! 6. Initial value of the resistance to bare soil evaporation (see hydrolc_soil, 8.4 for details) IF (ALL(rsol(:)==val_exp)) THEN rsol(:) = -un DO ji = 1, kjpindex IF (tot_bare_soil(ji) .GE. min_sechiba) THEN ! Correction Nathalie - le 28 mars 2006 - sur conseils Fred Hourdin ! on modifie le rsol pour que la resistance croisse subitement si on s'approche ! du fond. En gros, rsol=hdry*rsol_cste pour hdry < 1m70 !rsol(ji) = dss(ji,1) * rsol_cste !rsol(ji) = ( drysoil_frac(ji) + un/(10.*(zmaxh - drysoil_frac(ji))+1.e-10)**2 ) * rsol_cste rsol(ji) = ( hdry(ji) + un/(10.*(zmaxh - hdry(ji))+1.e-10)**2 ) * rsol_cste ENDIF ENDDO END IF IF (printlev>=3) WRITE (numout,*) ' hydrolc_var_init done ' END SUBROUTINE hydrolc_var_init !! ================================================================================================================================ !! SUBROUTINE : hydrolc_snow !! !>\BRIEF This routine computes accumulation, sublimation, snowmelt and snow ageing !! over vegetated and nobio (eg land-ice) areas. Snowdepth is then updated. !! !! DESCRIPTION : In this routine the snow-related processes accumulation, sublimation, !! melting and ageing are computed separately on vegetated and nobio areas. This subroutine !! is the first one among the ones that compute the physical processes. The water budgets !! of the interception reservoir and the soil are performed afterwards.\n !! !! - Values of the main parameters used in this routine are :\n !! tp_00=273.15K : freezing point\n !! snowcri=1.5\f$kg m^{-2}\f$ : critical snowmass for sublimation\n !! sneige=snowcri/1000._r_std : critical snowmass for snow melt\n !! maxmass_snow=3000 \f$kg m^{-2}\f$ (~ 10m snow) : critical snowmass for snow stock\n !! snow_trans=0.3 (\f$kg m^{-2}\f$) : critical constant for snow ageing\n !! max_snow_age=50 (days) : maximum snow age\n !! sn_dens=330 (\f$kg m^{-3}\f$) : snow density\n !! one_day=86400 (s) : one day, expressed in seconds... !! !! - Accumulation\n !! On the vegetated areas, the snow mass increases due to area-weighted snow !! precipitations precip_snow; on nobio areas, rain additionnaly converts into snow.\n !! !! - Sublimation\n !! Sublimation on vegetated and nobio areas is calculated as the area-weighed fraction !! of vevapsno (from enerbil). In case snow on vegetated areas is limited (less than snowcri) !! and a significant nobio area exists, the nobio area accomodates the whole sublimation !! vevapsno. The nobio area also accomodates the possible excess sublimation from vegetated !! areas, which otherwise goes into bare soil evaporation. In this case vevapsno is updated.\n !! !! - Melting\n !! Over vegetated and nobio areas, snowmelt occurs if the calculated soil temperature !! temp_soil_new(ji) exceeds the freezing point tp_00. The energy required to warm up the soil !! surface above tp_00 is converted into melting, according to the following equation : !! \latexonly !! \input{hydrolcsnow1.tex} !! \endlatexonly !! \n !! with soilcap the soil heat capacity @tex ($J K^{-1}$) @endtex and chalfu0 the latent heat of !! fusion.\n !! A special case occurs in areas with snowmass exceeding maxmass_snow, where !! all the snow in excess of maxmass_snow adds to the total melting tot_melt. !! This excess melting is considered as additionnal snowmelt for vegetated areas !! and as ice_melt for nobio areas.\n !! !! - Ageing\n !! Over vegetated areas, during the time step dt_radia (usually 1800 s), the snow age is !! incremented by a d_age calculated as follow: !! \latexonly !! \input{hydrolcsnow2.tex} !! \endlatexonly !! \n !! Over nobio areas and at subfreezing temperatures, snow ageing is limited by very !! slow snow metamorphism, hence d_age is reduced as follow: !! \latexonly !! \input{hydrolcsnow3.tex} !! \endlatexonly !! \n !! Scientific reference for this parametrization choice is obviously missing ! !! At the end of the routine the snowheight is diagnosed using the fixed !! snow density sn_dens. !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLES: !! for vegetated and nobio areas respectively:\n !! snow(kjpindex) and snow_nobio(kjpindex)\n !! snow_age(kjpindex) and snow_nobio_age(kjpindex)\n !! for the whole grid-cell:\n !! vevapnu(kjpindex) !! vevapsno(kjpindex) !! tot_melt(kjpindex) !! snowdepth(kjpindex) !! !! REFERENCES : None !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_snow (kjpindex, precip_rain, precip_snow , temp_sol_new, soilcap,& & frac_nobio, totfrac_nobio, vevapnu, vevapsno, snow, snow_age, snow_nobio, snow_nobio_age, & & tot_melt, snowdepth) !! 0. Variable and parameter declaration !! 0.1 Input variabless INTEGER(i_std), INTENT(in) :: kjpindex !! Domain size (unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: precip_rain !! Rainfall @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: precip_snow !! Snow precipitation @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: temp_sol_new !! New soil temperature (K) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: soilcap !! Soil heat capacity @tex ($J K^{-1}$) @endtex REAL(r_std), DIMENSION (kjpindex,nnobio), INTENT(in) :: frac_nobio !! Fraction of continental ice, lakes, ... !! (unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: totfrac_nobio !! Total fraction of continental ice+lakes+ ... !! (unitless) !! 0.2 Output variables REAL(r_std), DIMENSION (kjpindex), INTENT(out) :: tot_melt !! Total melt @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(out) :: snowdepth !! Snow depth (m) !! 0.3 Modified variables REAL(r_std), DIMENSION (kjpindex), INTENT(inout) :: vevapnu !! Bare soil evaporation @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(inout) :: vevapsno !! Snow evaporation @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(inout) :: snow !! Snow mass @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(inout) :: snow_age !! Snow age (days) REAL(r_std), DIMENSION (kjpindex,nnobio), INTENT(inout) :: snow_nobio !! Snomass on nobio areas !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nnobio), INTENT(inout) :: snow_nobio_age !! Snow age on ice, lakes, ...(days) !! 0.4 Local variables INTEGER(i_std) :: ji, jv !! indices (unitless) REAL(r_std), DIMENSION (kjpindex) :: d_age !! Snow age change (days) REAL(r_std), DIMENSION (kjpindex) :: xx !! temporary REAL(r_std) :: snowmelt_tmp !! temporary @tex ($kg m^{-2}$) @endtex REAL(r_std) :: snow_d1k !! The amount of snow that corresponds to a 1K cooling LOGICAL, DIMENSION (kjpindex) :: warnings LOGICAL :: any_warning !_ ================================================================================================================================ !! 1. initialisation DO jv = 1, nnobio DO ji=1,kjpindex subsnownobio(ji,jv) = zero ENDDO ENDDO DO ji=1,kjpindex subsnowveg(ji) = zero snowmelt(ji) = zero icemelt(ji) = zero tot_melt(ji) = zero ENDDO !! 2. On vegetation ! 2.1. It is snowing DO ji=1,kjpindex snow(ji) = snow(ji) + (un - totfrac_nobio(ji))*precip_snow(ji) ENDDO DO ji=1,kjpindex ! 2.2. Sublimation - separate between vegetated and no-veget fractions ! Care has to be taken as we might have sublimation from the ! the frac_nobio while there is no snow on the rest of the grid. IF ( snow(ji) > snowcri ) THEN subsnownobio(ji,iice) = frac_nobio(ji,iice)*vevapsno(ji) subsnowveg(ji) = vevapsno(ji) - subsnownobio(ji,iice) ELSE ! Correction Nathalie - Juillet 2006. ! On doit d'abord tester s'il existe un frac_nobio! ! Pour le moment je ne regarde que le iice IF ( frac_nobio(ji,iice) .GT. min_sechiba) THEN subsnownobio(ji,iice) = vevapsno(ji) subsnowveg(ji) = zero ELSE subsnownobio(ji,iice) = zero subsnowveg(ji) = vevapsno(ji) ENDIF ENDIF ENDDO warnings(:) = .FALSE. any_warning = .FALSE. DO ji=1,kjpindex ! 2.2.1 Check that sublimation on the vegetated fraction is possible. IF (subsnowveg(ji) .GT. snow(ji)) THEN ! What could not be sublimated goes into bare soil evaporation ! Nathalie - Juillet 2006 - il faut avant tout tester s'il existe du ! frac_nobio sur ce pixel pour eviter de puiser dans le sol! IF ( frac_nobio(ji,iice) .GT. min_sechiba) THEN subsnownobio(ji,iice) = subsnownobio(ji,iice) + (subsnowveg(ji) - snow(ji)) ELSE vevapnu(ji) = vevapnu(ji) + (subsnowveg(ji) - snow(ji)) warnings(ji) = .TRUE. any_warning = .TRUE. ENDIF ! Sublimation is thus limited to what is available subsnowveg(ji) = snow(ji) snow(ji) = zero vevapsno(ji) = subsnowveg(ji) + subsnownobio(ji,iice) ELSE snow(ji) = snow(ji) - subsnowveg(ji) ENDIF ENDDO IF ( any_warning ) THEN WRITE(numout,*)' ATTENTION on prend de l eau au sol nu sur au moins un point car evapsno est trop fort!' !!$ DO ji=1,kjpindex !!$ IF ( warnings(ji) ) THEN !!$ WRITE(numout,*)' ATTENTION on prend de l eau au sol nu car evapsno est trop fort!' !!$ WRITE(numout,*)' ',ji,' vevapnu (en mm/jour) = ',vevapnu(ji)*one_day/dt_sechiba !!$ ENDIF !!$ ENDDO ENDIF warnings(:) = .FALSE. any_warning = .FALSE. DO ji=1,kjpindex ! 2.3. snow melt only if temperature positive IF (temp_sol_new(ji).GT.tp_00) THEN IF (snow(ji).GT.sneige) THEN snowmelt(ji) = (un - frac_nobio(ji,iice))*(temp_sol_new(ji) - tp_00) * soilcap(ji) / chalfu0 ! 2.3.1 enough snow for melting or not IF (snowmelt(ji).LT.snow(ji)) THEN snow(ji) = snow(ji) - snowmelt(ji) ELSE snowmelt(ji) = snow(ji) snow(ji) = zero END IF ELSEIF (snow(ji).GE.zero) THEN ! 2.3.2 not enough snow snowmelt(ji) = snow(ji) snow(ji) = zero ELSE ! 2.3.3 negative snow - now snow melt snow(ji) = zero snowmelt(ji) = zero warnings(ji) = .TRUE. any_warning = .TRUE. END IF ENDIF ENDDO IF ( any_warning ) THEN DO ji=1,kjpindex IF ( warnings(ji) ) THEN WRITE(numout,*) 'hydrolc_snow: WARNING! snow was negative and was reset to zero for point ',ji,'. ' ENDIF ENDDO ENDIF !! 2.4 Snow melts above a threshold ! Ice melt only if there is more than a given mass : maxmass_snow, ! But the snow cannot melt more in one time step to what corresponds to ! a 1K cooling. This will lead to a progressive melting of snow above ! maxmass_snow but it is needed as a too strong cooling can destabilise the model. DO ji=1,kjpindex IF ( snow(ji) .GT. maxmass_snow ) THEN snow_d1k = un * soilcap(ji) / chalfu0 snowmelt(ji) = snowmelt(ji) + MIN((snow(ji) - maxmass_snow),snow_d1k) snow(ji) = snow(ji) - snowmelt(ji) IF ( printlev >= 3 ) WRITE (numout,*) "Snow was above maxmass_snow (", maxmass_snow,") and we melted ", snowmelt(ji) ENDIF END DO !! 3. On Land ice DO ji=1,kjpindex !! 3.1. It is snowing snow_nobio(ji,iice) = snow_nobio(ji,iice) + frac_nobio(ji,iice)*precip_snow(ji) + & & frac_nobio(ji,iice)*precip_rain(ji) !! 3.2. Sublimation - was calculated before it can give us negative snow_nobio but that is OK ! Once it goes below a certain values (-maxmass_snow for instance) we should kill ! the frac_nobio(ji,iice) ! snow_nobio(ji,iice) = snow_nobio(ji,iice) - subsnownobio(ji,iice) !! 3.3. snow melt only for continental ice fraction snowmelt_tmp = zero IF (temp_sol_new(ji) .GT. tp_00) THEN ! 3.3.1 If there is snow on the ice-fraction it can melt snowmelt_tmp = frac_nobio(ji,iice)*(temp_sol_new(ji) - tp_00) * soilcap(ji) / chalfu0 IF ( snowmelt_tmp .GT. snow_nobio(ji,iice) ) THEN snowmelt_tmp = MAX( zero, snow_nobio(ji,iice)) ENDIF snowmelt(ji) = snowmelt(ji) + snowmelt_tmp snow_nobio(ji,iice) = snow_nobio(ji,iice) - snowmelt_tmp ENDIF !! 3.4 Snow melts over a threshold ! Ice melt only if there is more than a given mass : maxmass_snow, ! But the snow cannot melt more in one time step to what corresponds to ! a 1K cooling. This will lead to a progressive melting of snow above ! maxmass_snow but it is needed as a too strong cooling can destabilise the model. ! IF ( snow_nobio(ji,iice) .GT. maxmass_snow ) THEN snow_d1k = un * soilcap(ji) / chalfu0 icemelt(ji) = MIN((snow_nobio(ji,iice) - maxmass_snow),snow_d1k) snow_nobio(ji,iice) = snow_nobio(ji,iice) - icemelt(ji) IF ( printlev >= 3 ) WRITE (numout,*) "Snow was above maxmass_snow ON ICE (", maxmass_snow,") and we melted ", icemelt(ji) ENDIF END DO !! 4. On other surface types - not done yet IF ( nnobio .GT. 1 ) THEN WRITE(numout,*) 'WE HAVE',nnobio-1,' SURFACE TYPES I DO NOT KNOW' CALL ipslerr_p (3,'hydrolc_snow', '', & & 'CANNOT TREAT SNOW ON THESE SURFACE TYPES', '') ENDIF !! 5. computes total melt (snow and ice) DO ji = 1, kjpindex tot_melt(ji) = icemelt(ji) + snowmelt(ji) ENDDO !! 6. computes snow age on veg and ice (for albedo) DO ji = 1, kjpindex !! 6.1 Snow age on vegetation IF (snow(ji) .LE. zero) THEN snow_age(ji) = zero ELSE snow_age(ji) =(snow_age(ji) + (un - snow_age(ji)/max_snow_age) * dt_sechiba/one_day) & & * EXP(-precip_snow(ji) / snow_trans) ENDIF !! 6.2 Snow age on ice ! age of snow on ice: a little bit different because in cold regions, we really ! cannot negect the effect of cold temperatures on snow metamorphism any more. IF (snow_nobio(ji,iice) .LE. zero) THEN snow_nobio_age(ji,iice) = zero ELSE d_age(ji) = ( snow_nobio_age(ji,iice) + & & (un - snow_nobio_age(ji,iice)/max_snow_age) * dt_sechiba/one_day ) * & & EXP(-precip_snow(ji) / snow_trans) - snow_nobio_age(ji,iice) IF (d_age(ji) .GT. zero ) THEN xx(ji) = MAX( tp_00 - temp_sol_new(ji), zero ) xx(ji) = ( xx(ji) / 7._r_std ) ** 4._r_std d_age(ji) = d_age(ji) / (un+xx(ji)) ENDIF snow_nobio_age(ji,iice) = MAX( snow_nobio_age(ji,iice) + d_age(ji), zero ) ENDIF ENDDO !! 7. Diagnose the depth of the snow layer DO ji = 1, kjpindex snowdepth(ji) = snow(ji) /sn_dens ENDDO IF (printlev>=3) WRITE (numout,*) ' hydrolc_snow done ' END SUBROUTINE hydrolc_snow !! ================================================================================================================================ !! SUBROUTINE : hydrolc_canop !! !>\BRIEF This routine computes the water budget of the canopy interception reservoir. !! !! DESCRIPTION : The first sequence is to withdraw interception loss from the interception !! reservoir, with independent values for each PFT. The reservoir loading happens afterwards. !! Rain falls uniformly over the PFTs. It uniformly loads the canopy interception !! reservoir of each PFT, up to the interception capacity, but a fraction of rainfall always falls to the ground. !! Throughfall is thus comprised of the fraction that always falls through, plus the remining fraction of rainfall that !! exceeds the interception capacity, the interception loss having been removed. !! \latexonly !! \input{interception.tex} !! \endlatexonly !! !! IMPORTANT NOTE : Bare soil treatment is complex in hydrolc : !! - veget_max(:,1) is the fraction of bare soil from the "annual" vegetation map !! - veget(:,1) is not the fraction of vegetation over bare soil but the total fraction of bare soil in the grid-cell !! (including the bare soil fractions over the vegetation PFTs). !! *** A diagram should be added in the spatial entry of the "umbrella" !! - For interception to be zero on bare soil, we thus need to impose qsintmax(:,1)=0 !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLE(S) : precisol (throughfall), qsintveg (amount of water in the canopy interception reservoir) !! !! REFERENCE(S) : None !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_canop (kjpindex, precip_rain, vevapwet, veget, qsintmax, tot_bare_soil, qsintveg, precisol) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT(in) :: kjpindex !! Domain size (number of grid cells) (unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: precip_rain !! Rainfall @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(in) :: vevapwet !! Interception loss over each PFT !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(in) :: veget !! Grid-cell fraction effectively covered by !! vegetation for each PFT, except for soil !! (0-1, unitless) REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(in) :: qsintmax !! Maximum amount of water in the canopy !! interception reservoir @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: tot_bare_soil !! Total evaporating bare soil fraction !! 0.2 Output variables REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(out) :: precisol !! Throughfall @tex ($kg m^{-2}$) @endtex !! 0.3 Modified variables REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: qsintveg !! Amount of water in the canopy interception !! reservoir @tex ($kg m^{-2}$) @endtex !! 0.4 Local variabless INTEGER(i_std) :: ji, jv !! Grid-cell and PFT indices (unitless) REAL(r_std), DIMENSION (kjpindex,nvm) :: zqsintvegnew !! Temporary variable for intercepted water !! amount @tex ($kg m^{-2}$) @endtex !_ ================================================================================================================================ ! calcul de qsintmax a prevoir a chaque pas de temps ! dans ini_sechiba ! boucle sur les points continentaux ! calcul de qsintveg au pas de temps suivant ! par ajout du flux interception loss ! calcule par enerbil en fonction ! des calculs faits dans diffuco ! calcul de ce qui tombe sur le sol ! avec accumulation dans precisol ! essayer d'harmoniser le traitement du sol nu ! avec celui des differents types de vegetation ! fait si on impose qsintmax ( ,1) = 0.0 ! ! loop for continental subdomain ! ! ! 1. evaporation off the continents ! ! 1.1 The interception loss is take off the canopy. DO jv=1,nvm qsintveg(:,jv) = qsintveg(:,jv) - vevapwet(:,jv) END DO ! 1.2 It is raining : precip_rain is shared for each vegetation ! type ! sum (veget (1,nvm)) must be egal to 1-totfrac_nobio. ! iniveget computes veget each day ! DO jv=1,nvm ! Correction Nathalie - Juin 2006 - une partie de la pluie arrivera toujours sur le sol ! sorte de throughfall supplementaire !qsintveg(:,jv) = qsintveg(:,jv) + veget(:,jv) * precip_rain(:) !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN qsintveg(:,jv) = qsintveg(:,jv) + tot_bare_soil(:) * ((1-throughfall_by_pft(jv))*precip_rain(:)) ELSE qsintveg(:,jv) = qsintveg(:,jv) + veget(:,jv) * ((1-throughfall_by_pft(jv))*precip_rain(:)) ENDIF END DO ! ! 1.3 Limits the effect and sum what receives soil ! precisol(:,:) = zero DO jv=1,nvm DO ji = 1, kjpindex zqsintvegnew(ji,jv) = MIN (qsintveg(ji,jv),qsintmax(ji,jv)) ! correction throughfall Nathalie - Juin 2006 !precisol(ji,jv) = qsintveg(ji,jv ) - zqsintvegnew (ji,jv) !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN precisol(ji,jv) = (tot_bare_soil(ji)*throughfall_by_pft(jv)*precip_rain(ji)) + qsintveg(ji,jv ) - zqsintvegnew (ji,jv) ELSE precisol(ji,jv) = (veget(ji,jv)*throughfall_by_pft(jv)*precip_rain(ji)) + qsintveg(ji,jv ) - zqsintvegnew (ji,jv) ENDIF ENDDO ENDDO ! ! 1.4 swap qsintveg to the new value ! DO jv=1,nvm qsintveg(:,jv) = zqsintvegnew (:,jv) END DO IF (printlev>=3) WRITE (numout,*) ' hydrolc_canop done ' END SUBROUTINE hydrolc_canop !! ================================================================================================================================ !! SUBROUTINE : hydrolc_vegupd !! !>\BRIEF This subroutines works at adapting the distribution of water !! in the soil and interception reservoirs between the different soil columns when the vegetation !! fraction of the PFTs (veget) has changed in slowproc. !! !! DESCRIPTION : Different vegetation changes are allowed in ORCHIDEE:\n !! - veget_max can be updated annually in slowproc (dynamic vegetation or prescribed vegetation change)\n !! - veget can be updated daily in slowproc (because of changes in veget_max or depending on LAI) !! !! This subroutine aims at adapting the distribution of water among the different liquid water reservoirs !! (interception reservoir and soil moisture) after these changes of veget : !! - the variable veget holds the "new" vegetation map !! - the variable resdist holds the previous vegetation map !! *** I see no flag or time step dependance to control the call to vegupd : is it called at each time step ? !! !! The principle is that PFTs where "veget" has shrunk keep the same water contents in kg.m^{-2}, !! whereas the water contents are increased in PFTs where "veget" has grown. !! *** I still have questions about redistribution to interception reservoirs which have shrunk !! *** and about thresholding to the reservoirs' capacities (is it ensured that the capacities are not exceeded ?) !! You may note that this occurs after evaporation and so on have been computed. It is not a !! problem as a new vegetation fraction will start with humrel=0 and thus will have no evaporation. !! If this is not the case it should have been caught above. !! !! IMPORTANT NOTE : the definition of veget is not simple : !! - for the non-bare soil PFTs (iv > 2), veget is the fraction effectively covered by !! vegetation : veget \f$\le\f$ veget_max\n !! - for the bare soil PFT (iv=1), veget holds the fraction of bare soil, from all !! PFTs : veget(:,1) \f$\ge\f$ veget_max(:,1)\n !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLE(S) : qsintveg, gqsb, bqsb, dsg, dss, dsp, resdist !! !! REFERENCE(S) : None !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_vegupd(kjpindex, veget, tot_bare_soil, ruu_ch, qsintveg, gqsb, bqsb, dsg, dss, dsp, resdist) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT(in) :: kjpindex !! Domain size (number of grid cells) (unitless) REAL(r_std), DIMENSION (kjpindex, nvm), INTENT(in) :: veget !! Grid-cell fraction effectively covered by vegetation !! for each PFT, except for soil (0-1, unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: tot_bare_soil !! Total evaporating bare soil fraction REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: ruu_ch !! Volumetric soil water capacity !! @tex ($kg m^{-3}$) @endtex !! 0.2 Output variables !! 0.3 Modified variables REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (inout) :: qsintveg !! Water on vegetation due to interception REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: gqsb !! Water content in the top layer !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: bqsb !! Water content in the bottom layer !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: dsg !! Depth of the top layer (m) REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: dss !! Depth of dry soil at the top, whether in the top or !! bottom layer (m) REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: dsp !! Depth of dry soil in the bottom layer plus depth of !! top layer (m) REAL(r_std), DIMENSION (kjpindex, nvm), INTENT(inout) :: resdist !! Previous values of "veget" (0-1, unitless) !! 0.4 Local variables INTEGER(i_std) :: ji,jv !! Grid-cell and PFT indices (unitless) REAL(r_std),DIMENSION (kjpindex,nvm) :: qsintveg2 !! Ancillary qsintveg @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm) :: bdq, gdq !! Changes in surface and bottom soil layer water !! content @tex ($kg m^{-2}; positive$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm) :: qsdq !! Changes in interception reservoir water content !! @tex ($kg m^{-2}; positive$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm) :: vmr !! Variation of "veget" since previous values !! (-1,1; unitless) REAL(r_std), DIMENSION(kjpindex) :: gtr !! Total water mass to redistribute between the top !! layers of a grid-cell @tex ($kg m^{-2}; positive) !! @ endtex REAL(r_std), DIMENSION(kjpindex) :: btr !! Total water mass to redistribute between the bottom !! layers of a grid-cell @tex ($kg m^{-2}; positive) !! @ endtex REAL(r_std), DIMENSION(kjpindex) :: vtr !! Total fraction over which "veget" has decreased !! (dimensionless; positive) REAL(r_std), DIMENSION(kjpindex) :: qstr !! Total water mass to redistribute between the !! interception reservoirs of a grid-cell !! @tex ($kg m^{-2}; positive$) @endtex REAL(r_std), DIMENSION(kjpindex) :: fra !! Weight for redistribution (dimensionless; negative) REAL(r_std), DIMENSION(kjpindex) :: vegchtot !! Total change of "veget" in the grid-point !! @tex ($kg m^{-2}$) @endtex REAL(r_std), PARAMETER :: EPS1 = EPSILON(un) !! Very small (scalar) *** why not use min_sechiba ? !_ ================================================================================================================================ !! 1. vmr is the change in veget in the different PFTs ! vmr is the change in veget in the different PFTs ! (dimensionless; negative if the new "veget" is smaller, i.e. if the PFT has shrunk) ! By construction, the algebraic sum of vmr in a grid-cell is zero DO jv = 1, nvm DO ji = 1, kjpindex !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN IF ( ABS(tot_bare_soil(ji)-resdist(ji,jv)) .GT. EPS1 ) THEN vmr(ji,jv) = tot_bare_soil(ji)-resdist(ji,jv) ELSE vmr(ji,jv) = zero ENDIF ELSE IF ( ABS(veget(ji,jv)-resdist(ji,jv)) .GT. EPS1 ) THEN vmr(ji,jv) = veget(ji,jv)-resdist(ji,jv) ELSE vmr(ji,jv) = zero ENDIF ENDIF !! 2. qsintveg2 is the intercepted water in mm ! qsintveg2 is the intercepted water in mmif the total volume ! was redistributed over the previous "veget" fractions ! This the distribution of intercepted water that needs to be ! changed if "veget" changes IF (resdist(ji,jv) .GT. zero) THEN qsintveg2(ji,jv) = qsintveg(ji,jv)/resdist(ji,jv) ELSE qsintveg2(ji,jv) = zero ENDIF ENDDO ENDDO !! 3. vegchtot is the total change of "veget" in the grid-points ! vegchtot is the total change of "veget" in the grid-points, ! integrated over the PFTs (vegchtot in kg m^{-2}) ! It is the sum of the absolute values of changes, it may thus ! be larger than 1 : it serves as a flag of change in each grid-point vegchtot(:) = zero DO jv = 1, nvm DO ji = 1, kjpindex vegchtot(ji) = vegchtot(ji) + ABS( vmr(ji,jv) ) ENDDO ENDDO !! 4. In the grid-points with "veget" change, we define changes in water content DO jv = 1, nvm DO ji = 1, kjpindex IF ( vegchtot(ji) .GT. zero ) THEN ! change in surface soil layer water content @tex ($kg m^{-2}$) @endtex gdq(ji,jv) = ABS(vmr(ji,jv)) * gqsb(ji,jv) ! change in bottom soil layer water content @tex ($kg m^{-2}$) @endtex bdq(ji,jv) = ABS(vmr(ji,jv)) * bqsb(ji,jv) ! change in interception reservoir water content @tex ($kg m^{-2}$) @endtex qsdq(ji,jv) = ABS(vmr(ji,jv)) * qsintveg2(ji,jv) ENDIF ENDDO ENDDO !! 5. Total water mass to redistribute in a grid-point = sum of water changes from PFTs where "veget" decreases ! Calculate the total water mass that we need to redistribute by grid-point, for each water reservoir ! We sum up the water changes from PFTs where "veget" decreases : this is the water that needs to be redistributed ! vtr is the total fraction over which "veget" has decreased (> 0) ! By construction, it is balanced by the total fraction where "veget" has increased gtr(:) = zero btr(:) = zero qstr(:) = zero vtr(:) = zero ! ! DO jv = 1, nvm DO ji = 1, kjpindex IF ( ( vegchtot(ji) .GT. zero ) .AND. ( vmr(ji,jv) .LT. zero ) ) THEN gtr(ji) = gtr(ji) + gdq(ji,jv) btr(ji) = btr(ji) + bdq(ji,jv) qstr(ji) = qstr(ji) + qsdq(ji,jv) ! vtr is necessarily le 0 since we enter here only if vmr <0 vtr(ji) = vtr(ji) - vmr(ji,jv) ENDIF ENDDO ENDDO !! 6. Put the water to redistribute from the PFTs that "shrank" into the PFTs that "growed" ! In doing so, water contents are kept constant in PFTs that shrank, and they increase in PFTs that growed ! fra is the weight for that redistribution, scaled to vtr which is the total amount to redistribute ! *** Feasability of the redistribution : it doesn't seem to be checked ??? ! *** In the soil, if the water capacities are constant between PFTs, it's OK ;this is the default for wmax_veg in ! *** constantes_veg.f90 ! *** But qsintmax is different between PFTsand also evolves in time : how is this managed ??? DO jv = 1, nvm DO ji = 1, kjpindex ! "veget" changed IF ( vegchtot(ji) .GT. zero .AND. ABS(vtr(ji)) .GT. EPS1) THEN ! negative when vmr positive, thus in the condition below fra(ji) = vmr(ji,jv) / vtr(ji) ! the PFT growed, thus its water contents must be updated IF ( vmr(ji,jv) .GT. zero) THEN !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN IF (tot_bare_soil(ji) .GT. zero) THEN gqsb(ji,jv) = (resdist(ji,jv)*gqsb(ji,jv) + fra(ji)*gtr(ji))/tot_bare_soil(ji) bqsb(ji,jv) = (resdist(ji,jv)*bqsb(ji,jv) + fra(ji)*btr(ji))/tot_bare_soil(ji) ENDIF ELSE IF (veget(ji,jv) .GT. zero) THEN gqsb(ji,jv) = (resdist(ji,jv)*gqsb(ji,jv) + fra(ji)*gtr(ji))/veget(ji,jv) bqsb(ji,jv) = (resdist(ji,jv)*bqsb(ji,jv) + fra(ji)*btr(ji))/veget(ji,jv) ENDIF ENDIF qsintveg(ji,jv) = qsintveg(ji,jv) + fra(ji)* qstr(ji) ELSE ! vmr negative *** I don't understand why we remove water from the interception reservoir in PFTs which shrank qsintveg(ji,jv) = qsintveg(ji,jv) - qsdq(ji,jv) ENDIF ! Then we update the soil layers depths. ! But we do not change dss, so that the redistribution does directly affect transpiration ! constantes : min_sechiba = 1.E-8_r_std IF (gqsb(ji,jv) .LT. min_sechiba) THEN dsg(ji,jv) = zero ELSE dsg(ji,jv) = (dss(ji,jv) * ruu_ch(ji) + gqsb(ji,jv)) & / ruu_ch(ji) ENDIF dsp(ji,jv) = zmaxh - bqsb(ji,jv) / ruu_ch(ji) ENDIF ENDDO ENDDO !! 7. We update resdist for the next "veget" change !MM veget(:,1) BUG ??!!!!!!!!!!! resdist(:,1) = tot_bare_soil(:) DO jv = 2, nvm resdist(:,jv) = veget(:,jv) ENDDO !! 8. Where vegetation fraction is zero, set water to that of bare soil. ! This does not create any additional water. DO jv = 2, nvm DO ji = 1, kjpindex IF ( veget(ji,jv) .LT. EPS1 ) THEN gqsb(ji,jv) = gqsb(ji,1) bqsb(ji,jv) = bqsb(ji,1) dsg(ji,jv) = dsg(ji,1) dss(ji,jv) = dss(ji,1) dsp(ji,jv) = dsp(ji,1) ENDIF ENDDO ENDDO END SUBROUTINE hydrolc_vegupd !! ================================================================================================================================ !! SUBROUTINE : hydrolc_flood !! !>\BRIEF this routine computes the evolution of the surface reservoir (floodplain) !! !! DESCRIPTION : !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLE(S) : floodout !! !! REFERENCE(S) : Same as for module hydrolc !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_flood (kjpindex, vevapnu, vevapflo, flood_frac, flood_res, floodout) ! input scalar INTEGER(i_std), INTENT(in) :: kjpindex ! input fields REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: flood_frac !! Fraction of floodplains in grid box ! modified fields REAL(r_std), DIMENSION (kjpindex), INTENT(out) :: floodout !! Flux to take out from floodplains REAL(r_std), DIMENSION (kjpindex), INTENT(inout) :: flood_res !! Floodplains reservoir estimate REAL(r_std), DIMENSION (kjpindex), INTENT(inout) :: vevapnu !! Bare soil evaporation REAL(r_std), DIMENSION (kjpindex), INTENT(inout) :: vevapflo !! Floodplains evaporation ! local declaration INTEGER(i_std) :: ji, jst, jv !! indices REAL(r_std) :: k_m !! conductivity in the soil REAL(r_std) :: temp !! !_ ================================================================================================================================ !- !- 1. Take out vevapflo from the reservoir and transfer the remaining to vevapnu !- DO ji = 1,kjpindex temp = MIN(flood_res(ji), vevapflo(ji)) flood_res(ji) = flood_res(ji) - temp vevapnu(ji) = vevapnu(ji) + vevapflo(ji) - temp vevapflo(ji) = temp ENDDO !- !- 2. Compute the total flux from floodplain floodout (transfered to routing) !- DO ji = 1,kjpindex floodout(ji) = vevapflo(ji) - flood_frac(ji) * SUM(precisol(ji,:)) ENDDO !- !- 3. Discriminate between precip over land and over floodplain !- DO jv=1, nvm DO ji = 1,kjpindex precisol(ji,jv) = precisol(ji,jv) * (1 - flood_frac(ji)) ENDDO ENDDO IF (printlev>=3) WRITE (numout,*) ' hydrolc_flood done' END SUBROUTINE hydrolc_flood !! ================================================================================================================================ !! SUBROUTINE : hydrolc_soil !! !>\BRIEF This routines computes the soil water budget and the related soil water !! fluxes and soil moisture diagnostics using the two-layer Choisnel scheme. !! !! DESCRIPTION : !! !! 1. Main processes: The Choisnel scheme relies on two soil layers. !! As show in the figure below, the upper one has a variable depth !! and can disappear after dry spells. It is created by infiltration (of throughfall or snow melt), !! in which case the layer is saturated. If this top layer is already present, infiltration can either !! fill it or make it deeper (Ducoudré et al., 1993). !! \latexonly !! \includegraphics[scale = 0.5]{choisnelvariables.pdf} !! \endlatexonly !! !! In this framework, most water fluxes updating soil moisture act from top:\n !! - throughfall, melted snow and ice, and irrigation increase soil moisture (of the top layer if present); !! - transpiration and bare soil evaporation reduce soil moisture (of the top layer if present); !! - return flow from rivers increases bottom soil moisture. \n !! !! Soil moisture stress on bare soil evaporation and transpiration (for diffuco), vegetation growth and !! litter processes (for stomate), proceed respectively via a soil resistance (rsol), and three soil !! moisture stress factor (humrel, vegstress, and litterhumdiag), which are all controlled by the !! height of dry soil at the top of soil: \n !! - Soil moisture stress factor on transpiration and bare soil evaporation: humrel = \f$U_s\f$ \n !! \latexonly !! \input{humrel.tex} !! \endlatexonly \n !! - Resistance to bare soil evaporation: rsol = \f$r_\mathrm{soil}\f$ \n !! \latexonly !! \input{rsol.tex} !! \endlatexonly !! !! Runoff is only produced when the entire soil column is saturated, as in the bucket !! scheme of Manabe (1969). Drainage at the bottom of soil and surface runoff are only diagnosed, !! mostly for use in the routing module, using a constant 95% - 5% redistribution (Ngo-Duc et al., 2005). !! Internal drainage is allowed from the top to the bottom layer, following Ducharne et al. (1998). !! \latexonly !! \input{gdrainage.tex} !! \endlatexonly !! !! Irrigation (de Rosnay et al., 2003) and return flow are optional inflows, calculated by the !! routing scheme (Ngo-Duc et al., 2005; Guimberteau, 2010). !! !! 2. Subgrid variability: !! The subgrid variability of soil is described by introducing as many soil columns as PFTs !! (de Rosnay & Polcher, 1998). The water budget is performed independently in each PFT/soil !! column, but the bottom soil moisture is merged between all PFTs at the end of the calculations. !! Therefore, vegetation withdraws from a shared bottom moisture (grid-cell weighted average). !! There can also be horizontal diffusion between the top layers, if the flag ok_hdiff is true (the default value !! is false). This is performed in the subroutine hydrolc_hdiff, call after the present subroutine. !! !! The areas of each soil column are defined by veget (the vegetation fraction of the PFTs), !! and not by veget_max (the maximum area of the PFT defined annually in slowproc). !! As veget can change at a daily time step, a redistribution of water between the soil !! columns is required : this is done in hydrolc_vegupd. !! !! 3. Water budget issues : !! Different issues can arise when solving the above processes : !! - negative total soil moisture (tracked using flag warning, but no action taken, cf. 4) !! - dsg > dsp after merging the bottom layers, solved iteratively (6.2) !! - we may also have a pathological behavior of rsol if hdry > dpu_cste (8.4) !! !! 4. Diagnostics for other subroutines: humrel for diffuco (7.1), vegstress for stomate (8.1), !! shumdiag for stomate (8.2), drysoil_frac for condveg (8.3), rsol for diffuco (8.4), !! litterhumdiag for stomate (8.5). !! !! MAIN OUTPUT VARIABLE(S) : rsol, drysoil_frac, hdry, !! run_off_tot (surface runoff), drainage, humrel, vegstress, shumdiag, litterhumdiag !! gqsb, bqsb, dsg, dss, dsp !! !! REFERENCE(S) : !! - Ducoudré, N, Laval, K & Perrier, A, 1993. SECHIBA, a new set of parameterisations !! of the hydrologic exchanges at the land-atmosphere interface within the LMD Atmospheric General !! Circulation Model. Journal of Climate, 6, pp. 248-273. !! - Ducharne, A. Laval, K. and Polcher, J. (1998) Sensitivity of the hydrological cycle to the parameterization !! of soil hydrology in a GCM. Climate Dynamics, 14:307-327. !! - de Rosnay, P. and Polcher J. (1998) Modeling root water uptake in a complex land surface scheme coupled !! to a GCM. Hydrology and Earth System Sciences, 2(2-3):239-256. !! - de Rosnay, P., Polcher, J., Laval, K. et Sabre, M. (2003). Integrated parameterization of irrigation in !! the land surface model ORCHIDEE. Validation over Indian Peninsula. Geophys. Res. Lett, 30(19):HLS2-1 - !! HLS2-4. !! - Ngo-Duc, T., J. Polcher, and K. Laval (2005), A 53-year forcing data set for land surface models, !! J. Geophys. Res., 110, D06116. !! - ALMA : http://www.lmd.jussieu.fr/~polcher/ALMA/ !! - Ducoudré, N. (1990). Sensibilite du climat simule a la parametrisation des echanges de vapeur d'eau entre !! la biosphere et l'atmosphere. These de Doctorat, Université Paris 6. !! - Ducharne A (1997). Le cycle de l'eau : modelisation de l'hydrologie continentale, etude de ses interactions !! avec le climat, These de Doctorat, Université Paris 6. !! - de Rosnay, P. (1999). Representation des interactions sol-plante-atmosphere dans le modele de circulation generale !! du LMD. These de doctorat, Université Paris 6. !! - Guimberteau, M, 2010. Modelisation de l'hydrologie continentale et influences de l'irrigation sur le cycle de l'eau, !! These de doctorat, Université Paris 6. !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_soil(kjpindex, vevapnu, precisol, returnflow, reinfiltration, irrigation, irrig_demand_ratio, veget_max, tot_melt, mx_eau_var, & !added irrig_demand_ratio, veget_max, for crop irrigation, xuhui & veget, tot_bare_soil, ruu_ch, transpir,& & gqsb, bqsb, dsg, dss, rsol, drysoil_frac, hdry, dsp, runoff, run_off_tot, drainage, & & humrel, vegstress, shumdiag, litterhumdiag, irrig_fin) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT(in) :: kjpindex !! Domain size (number of grid cells) (unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: vevapnu !! Bare soil evaporation @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(in) :: precisol !! Throughfall @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: returnflow !! Routed water which comes back into the soil !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: reinfiltration !! Water returning to the top reservoir REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: irrigation !! Irrigation water applied to soils !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex, nvm), INTENT(in) :: irrig_demand_ratio !! ratio of irrigation water applied for each pft REAL(r_std), DIMENSION (kjpindex, nvm), INTENT(in) :: veget_max !! REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: tot_melt !! Total melt @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: mx_eau_var !! Maximum water content of the soil !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex, nvm), INTENT(in) :: veget !! Grid-cell fraction effectively covered by vegetation !! for each PFT, except for soil (0-1, unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: tot_bare_soil !! Total evaporating bare soil fraction REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: ruu_ch !! Volumetric soil water capacity !! @tex ($kg m^{-3}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(in) :: transpir !! Transpiration over each PFT @tex ($kg m^{-2}$) @endtex !! 0.2 Output variables REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(out) :: runoff !! runoff for each pft REAL(r_std), DIMENSION (kjpindex), INTENT(out) :: run_off_tot !! Diagnosed surface runoff @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex), INTENT(out) :: drainage !! Diagnosed drainage at the bottom of soil !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex, nvm), INTENT(out) :: humrel !! Soil moisture stress factor on transpiration and bare !! soil evaporation (0-1, unitless) ! Relative humidity REAL(r_std), DIMENSION (kjpindex, nvm), INTENT(out) :: vegstress !! Vegetation moisture stress (only for vegetation !! growth) (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nbdl), INTENT (out) :: shumdiag !! Mean relative soil moisture in the different levels !! used by thermosoil.f90 (0-1, unitless) REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: litterhumdiag !! Litter humidity factor (0-1, unitless), used in !! stomate REAL(r_std), DIMENSION (kjpindex), INTENT(out) :: rsol !! Resistance to bare soil evaporation (s m^{-1}) REAL(r_std), DIMENSION (kjpindex), INTENT(out) :: drysoil_frac !! Fraction of visible dry soil (0-1, unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(out) :: hdry !! Mean top dry soil height (m) version beton REAL(r_std), DIMENSION (kjpindex, nvm), INTENT(out) :: irrig_fin !! application of irrigation water for each pft(mm) !! 0.3 Modified variables REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout):: gqsb !! Water content in the top layer !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout):: bqsb !! Water content in the bottom layer !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout):: dsg !! Depth of the top layer (m) REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout):: dss !! Depth of dry soil at the top, whether in the top or !! bottom layer (m) REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout):: dsp !! Depth of dry soil in the bottom layer plus depth of !! top layer (m) !! 0.4 Local variables INTEGER(i_std) :: ji,jv, jd !! Indices for grid-cells, PFTs and diagnostic levels in !! the soil (unitless) ! REAL(r_std), DIMENSION(kjpindex,nvm) :: runoff !! Total runoff @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION(kjpindex) :: zhumrel_lo !! Soil moisture stress factors on transpiration for the !! bottom and top layers (0-1, unitless) REAL(r_std), DIMENSION(kjpindex) :: zhumrel_up !! Soil moisture stress factors on transpiration for the !! bottom and top layers (0-1, unitless) REAL(r_std), DIMENSION(kjpindex,nvm) :: zeflux !! Evaporation to be withdrawn from soil !! @tex ($kg m^{-2}) @endtex ! *** why divided by veget ? REAL(r_std), DIMENSION(kjpindex,nvm) :: zpreci !! Throughfall @tex ($kg m^{-2}$) @endtex !! ! *** why divided by veget ? LOGICAL, DIMENSION(kjpindex,nvm) :: warning !! To track negative total soil moisture cases in soil !! columns (true/false) REAL(r_std) :: gtr, btr !! Fractions of top and botttom soil layers to the !! different diagnostic soil layers (0-1, unitless) REAL(r_std), DIMENSION(kjpindex) :: mean_dsg !! Mean depth of water in top soil layer (m) LOGICAL :: OnceMore !! To repeat the correction to solve dsg > dsp after !! diffusion between the bottom layers (true/false) INTEGER(i_std), PARAMETER :: nitermax = 100 !! Maximum number of iterations to dsg > dsp after !! diffusion between the bottom layers (unitless) INTEGER(i_std) :: niter !! Counter of iterations to solve dsg > dsp after !! diffusion between the bottom layers (unitless) INTEGER(i_std) :: nbad !! Number of negative total soil moisture cases !! (unitless); this is before diffusion between the !! bottom layers, cf. "warning" *** LOGICAL, DIMENSION(kjpindex,nvm) :: lbad !! Tags "bad" PFTs where dsg > dsp after diffusion !! between the bottom layers (true/false) LOGICAL, DIMENSION(kjpindex) :: lbad_ij !! Tags "bad" grid-points where at least one PFT exhibits !! dsg > dsp after diffusion between the bottom layers !! (true/false) REAL(r_std) :: gqseuil !! Ancillary variables to compute drainage between the !! two soil layers @tex ($kg m^{-2}$) @endtex REAL(r_std) :: eausup !! Ancillary variables to compute drainage between the !! two soil layers @tex ($kg m^{-2}$) @endtex REAL(r_std) :: wd1 !! Ancillary variables to compute drainage between the !! two soil layers @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION(nbdl+1) :: tmp_dl !! Temporary diagnostic levels in the soil (m) REAL(r_std), DIMENSION(kjpindex,nvm) :: a_subgrd !! Diagnosed subgrid fraction of saturated soil in the !! top layer, to calculate hdry (0-1, unitless) !_ ================================================================================================================================ !! 1. Preliminary calculations !! We define input and output fluxes at the soil surface, for each PFT !! The input flux is throughfall. !! The ouput flux is the total evaporation withdrawn from the soil (transpiration and bare soil evaporation, BSE) ! *** I don't understand why the fluxes are divided by veget if they are in kg.m^{-2} within each PFT *** DO jv=1,nvm DO ji = 1, kjpindex !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN IF ( tot_bare_soil(ji) .GT. zero ) THEN zeflux(ji,jv) = transpir(ji,jv)/tot_bare_soil(ji) zpreci(ji,jv) = precisol(ji,jv)/tot_bare_soil(ji) ELSE zeflux(ji,jv) = zero zpreci(ji,jv) = zero ENDIF ELSE IF ( veget(ji,jv) .GT. zero ) THEN zeflux(ji,jv) = transpir(ji,jv)/veget(ji,jv) zpreci(ji,jv) = precisol(ji,jv)/veget(ji,jv) ELSE zeflux(ji,jv) = zero zpreci(ji,jv) = zero ENDIF ENDIF ENDDO ENDDO !! For bare soil evaporation, we need to distinguish two cases. !! This should only apply if there is vegetation but we do not test this case. !! Case 1 - if bare soil is present, BSE is extracted from the bare soil fraction DO ji = 1, kjpindex IF ( (vegtot(ji) .GT. zero) .AND. (tot_bare_soil(ji) .GT. min_sechiba) ) THEN zeflux(ji,1) = vevapnu(ji)/tot_bare_soil(ji) ENDIF ENDDO !! Case 2 - if bare soil is not present, BSE is uniformly redistributed among the vegetation fractions !! This case is possible because of transfers (snow for instance). !MM veget(:,1) BUG ??!!!!!!!!!!! !! DO jv = 2, nvm !! DO ji = 1, kjpindex !! IF ( (vegtot(ji) .GT. zero) .AND. (tot_bare_soil(ji) .LE. min_sechiba)& !! & .AND. (veget(ji,jv) .GT. min_sechiba)) THEN !! zeflux(ji,jv) = zeflux(ji,jv) + vevapnu(ji)/vegtot(ji) !!! ENDIF !! ENDDO !! ENDDO ! Temporary diagnostic levels in the soil to diagnose shumdiag tmp_dl(1) = 0 tmp_dl(2:nbdl+1) = diaglev(1:nbdl) !! 2. Updating soil moisture !! We update soil moisture: !! The top soil moisture reacts to evaporation, throughfall, snow and ice melt, and inflow from irrigation !! The bottom soil moisture can receive returnflow from routing.f90 DO jv=1,nvm DO ji=1,kjpindex ! Evaporated water is taken out of the ground gqsb(ji,jv) = gqsb(ji,jv) - zeflux(ji,jv) ! ! 1.2 Add snow and ice melt, troughfall from vegetation, reinfiltration and irrigation. ! IF(vegtot(ji) .NE. zero) THEN ! snow and ice melt, reinfiltration and troughfall from vegetation gqsb(ji,jv) = gqsb(ji,jv) + zpreci(ji,jv) + (tot_melt(ji)+reinfiltration(ji))/vegtot(ji) ! We take care to add the irrigation only to the vegetated part if possible ! IF (ABS(vegtot(ji)-tot_bare_soil(ji)) .LE. min_sechiba) THEN ! vegtot == bare_soil ! gqsb(ji,jv) = gqsb(ji,jv) + irrigation(ji)/vegtot(ji) ! we only irrigated the crop pfts IF (irrig_demand_ratio(ji,jv) .GT. zero) THEN ! WRITE(numout,*) "irrig_demand_ratio (", ji, ", ", jv, "): ", irrig_demand_ratio(ji,jv) irrig_fin(ji,jv) = irrigation(ji)*irrig_demand_ratio(ji,jv)/veget_max(ji,jv) gqsb(ji,jv) = gqsb(ji,jv) + irrig_fin(ji,jv) ! bqsb(ji,jv) = bqsb(ji,jv) + irrig_fin(ji,jv) ENDIF ELSE ! no vegetation, : we only add irrigation in the PFTs where vegetation can grow IF ( jv > 1 ) THEN ! Only add the irrigation to the upper soil if there is a reservoir. ! Without this the water evaporates right away. IF ( gqsb(ji,jv) > zero ) THEN ! gqsb(ji,jv) = gqsb(ji,jv) + irrigation(ji)/(vegtot(ji)-tot_bare_soil(ji)) IF (irrig_demand_ratio(ji,jv) .GT. zero) THEN ! WRITE(numout,*) "irrig_demand_ratio (", ji, ", ", jv, "): ", irrig_demand_ratio(ji,jv) irrig_fin(ji,jv) = irrigation(ji)*irrig_demand_ratio(ji,jv)/veget_max(ji,jv) gqsb(ji,jv) = gqsb(ji,jv) + irrig_fin(ji,jv) ! bqsb(ji,jv) = bqsb(ji,jv) + irrig_fin(ji,jv) ! we always inject irrigation water into lower layer ENDIF ELSE IF (irrig_demand_ratio(ji,jv) .GT. zero) THEN ! WRITE(numout,*) "irrig_demand_ratio (", ji, ", ", jv, "): ", irrig_demand_ratio(ji,jv) irrig_fin(ji,jv) = irrigation(ji)*irrig_demand_ratio(ji,jv)/veget_max(ji,jv) bqsb(ji,jv) = bqsb(ji,jv) + irrig_fin(ji,jv) ENDIF ! bqsb(ji,jv) = bqsb(ji,jv) + irrigation(ji)/(vegtot(ji)-tot_bare_soil(ji)) ENDIF ENDIF ENDIF ! We add the water returning from rivers to the lower reservoir. bqsb(ji,jv) = bqsb(ji,jv) + returnflow(ji)/vegtot(ji) ENDIF END DO ENDDO !! 3. We compute runoff and adjust the soil layers' depth and water content !! The depth of top dry soil, dss, is of particular importance as it controls the soil moisture stresses !! to transpiration and BSE runoff(:,:) = zero warning(:,:) = .FALSE. DO jv=1,nvm DO ji = 1, kjpindex !! 3.1 Soil moisture in excess of total water holding capacity runs off runoff(ji,jv) = MAX(gqsb(ji,jv) + bqsb(ji,jv) - mx_eau_var(ji), zero) !! 3.2 If the soil is saturated (runoff is generated): no top layer; dss = dsp IF (mx_eau_var(ji) .LE. (gqsb(ji,jv) + bqsb(ji,jv))) THEN ! gqsb(ji,jv) = zero dsg(ji,jv) = zero bqsb(ji,jv) = mx_eau_var(ji) dsp(ji,jv) = zero dss(ji,jv) = dsp (ji,jv) ELSEIF ((gqsb(ji,jv) + bqsb(ji,jv)).GE.zero) THEN !! 3.3 Else, if the top layer holds more water than allowed by its depth, the top layer deepens !! The top layer is saturated, so that dss=0. !! In this case, dsp is useless, and is not updated, !! even if bqsb has changed because of irrigation and return flow. IF (gqsb(ji,jv) .GT. dsg(ji,jv) * ruu_ch(ji)) THEN ! dsg(ji,jv) = gqsb(ji,jv) / ruu_ch(ji) dss(ji,jv) = zero ELSEIF (gqsb(ji,jv) .GT. zero ) THEN !! 3.4 If the top layer is not saturated, its total depth does not change and we only update its dry soil depth !! In this case, dsp is useless, and is not updated, !! even if bqsb has changed because of irrigation and return flow. ! dss(ji,jv) = ((dsg(ji,jv) * ruu_ch(ji)) - gqsb(ji,jv)) / ruu_ch(ji) ELSE !! 3.5 If the top layer's moisture is negative, it vanishes and the required moisture is withdrawn from the bottom layer !! dsp is updated accordingly, and defines the depth of top dray soil dss. ! bqsb(ji,jv) = bqsb(ji,jv) + gqsb(ji,jv) dsp(ji,jv) = zmaxh - bqsb(ji,jv) / ruu_ch(ji) ! dsp>dpu if bqsb<0 *** we can be here with bsqb<0 and bqsb+gqsb>0 gqsb(ji,jv) = zero dsg(ji,jv) = zero dss(ji,jv) = dsp(ji,jv) END IF ELSE !! 3.6 If the total soil moisture is negative: we keep track of the problem for further warning. !! In this extreme case of dry soil, the top layer is absent. !! The top dry soil depth, dsp, is equal to the soil depth. !! But we keep the negative moisture for water budget closure, and assign it to the bottom layer. ! Ceci ne devrait jamais arriver plus d'une fois par point. C-a-d une fois la valeur negative ! atteinte les flux doivent etre nuls. On ne signale que ce cas donc. ! *** But this is obviously not the case in CMIP5 runs *** ! *** Also, I don't see the use of conditionning upon zeflux(ji,jv) .GT. zero : negative moisture is always a problem ! IF ( ( zeflux(ji,jv) .GT. zero ) .AND. & ( gqsb(ji,jv) + bqsb(ji,jv) .LT. -1.e-10 ) ) THEN warning(ji,jv) = .TRUE. ! WRITE (numout,*) 'WARNING! Soil Moisture will be negative' ! WRITE (numout,*) 'ji, jv = ', ji,jv ! WRITE (numout,*) 'mx_eau_var = ', mx_eau_var(ji) ! WRITE (numout,*) 'veget, resdist =', veget(ji,jv), resdist(ji,jv) ! WRITE (numout,*) 'bqsb = ', bqsb(ji,jv) ! WRITE (numout,*) 'gqsb = ', gqsb(ji,jv) ! WRITE (numout,*) 'dss = ', dss(ji,jv) ! WRITE (numout,*) 'dsg = ', dsg(ji,jv) ! WRITE (numout,*) 'dsp = ', dsp(ji,jv) ! WRITE (numout,*) 'humrel = ', humrel(ji, jv) ! WRITE (numout,*) 'Soil evaporation = ', zeflux(ji,jv) ! WRITE (numout,*) 'input = ',precisol(ji, jv), tot_melt(ji) ! WRITE (numout,*) '============================' ENDIF bqsb(ji,jv) = gqsb(ji,jv) + bqsb(ji,jv) ! this will be negative dsp(ji,jv) = zmaxh gqsb(ji,jv) = zero dsg(ji,jv) = zero dss(ji,jv) = dsp(ji,jv) ENDIF ENDDO ENDDO !! 4. If there are some PFTs with negative moisture, it is written in the run log nbad = COUNT( warning(:,:) .EQV. .TRUE. ) IF ( nbad .GT. 0 ) THEN WRITE(numout,*) 'hydrolc_soil: WARNING! Soil moisture was negative at', & nbad, ' points:' !DO jv = 1, nvm ! DO ji = 1, kjpindex ! IF ( warning(ji,jv) ) THEN ! WRITE(numout,*) ' ji,jv = ', ji,jv ! WRITE (numout,*) 'mx_eau_var = ', mx_eau_var(ji) ! WRITE (numout,*) 'veget, resdist =', veget(ji,jv), resdist(ji,jv) ! WRITE (numout,*) 'bqsb = ', bqsb(ji,jv) ! WRITE (numout,*) 'gqsb = ', gqsb(ji,jv) ! WRITE (numout,*) 'runoff = ',runoff(ji,jv) ! WRITE (numout,*) 'dss = ', dss(ji,jv) ! WRITE (numout,*) 'dsg = ', dsg(ji,jv) ! WRITE (numout,*) 'dsp = ', dsp(ji,jv) ! WRITE (numout,*) 'humrel = ', humrel(ji, jv) ! WRITE (numout,*) 'Soil evaporation = ', zeflux(ji,jv) ! WRITE (numout,*) 'Soil precipitation = ',zpreci(ji,jv) ! WRITE (numout,*) 'input = ',precisol(ji, jv), tot_melt(ji) ! WRITE (numout,*) 'returnflow = ',returnflow(ji) ! WRITE (numout,*) '============================' ! ENDIF ! ENDDO !ENDDO ENDIF !! 5. Top layers that are very large or very dry can be deadlock situations for the Choisnel scheme !! Top layers that are very large or that hold a tiny amount of water . !! They are handled here. IF (printlev>=3) WRITE(numout,*) 'hydro_soil 2.0 : Resolve deadlocks' DO jv=1,nvm DO ji=1,kjpindex !! 5.1 If the top layer is almost dry, we merge the two layers IF ( ABS(dsp(ji,jv)-dsg(ji,jv)) .LT. min_sechiba ) THEN ! min_sechiba = 1.e-8 (constantes.f90) bqsb(ji,jv) = bqsb(ji,jv) + gqsb(ji,jv) dsp(ji,jv) = zmaxh - bqsb(ji,jv) / ruu_ch(ji) ! *** can this make dsp > dpu_cste gqsb(ji,jv) = zero dsg(ji,jv) = zero dss(ji,jv) = dsp(ji,jv) ENDIF !! 5.2 Internal drainage from the top to the bottom layer !! Much faster when the relative moisture of the top layer exceeds 75\% of the water holding capacity. !! The parameters are exp_drain = 1.5, min_drain = 0.002 mm/h and max_drain = 0.2 mm/h gqseuil = min_sechiba * deux * ruu_ch(ji) ! min_sechiba = 1.e-8 (constantes.f90) eausup = dsg(ji,jv) * ruu_ch(ji) wd1 = .75*eausup IF (eausup .GT. gqseuil) THEN ! dsg > 2.e-8 m gdrainage(ji,jv) = min_drain * (gqsb(ji,jv)/eausup) IF ( gqsb(ji,jv) .GE. wd1 .AND. dsg(ji,jv) .GT. 0.10 ) THEN gdrainage(ji,jv) = gdrainage(ji,jv) + & (max_drain-min_drain)*((gqsb(ji,jv)-wd1) / (eausup-wd1))**exp_drain ENDIF gdrainage(ji,jv)=MIN(gdrainage(ji,jv), MAX(gqsb(ji,jv), zero)) ELSE gdrainage(ji,jv)=zero ! *** why not remove the top layer in that case ?? ENDIF ! gqsb(ji,jv) = gqsb(ji,jv) - gdrainage(ji,jv) bqsb(ji,jv) = bqsb(ji,jv) + gdrainage(ji,jv) dsg(ji,jv) = dsg(ji,jv) - gdrainage(ji,jv) / ruu_ch(ji) dsp(ji,jv) = zmaxh - bqsb(ji,jv)/ruu_ch(ji) ! *** this line shouldn't make dsp>dpu_cste ENDDO ENDDO !! 6. We want the vegetation to share a common bottom moisture: !! Thus, we must account for moisture diffusion between the soil columns. IF (printlev>=3) WRITE(numout,*) 'hydrolc_soil 3.0 : Vertical diffusion' !! 6.1 Average of bottom and top moisture over the "veget" fractions mean_bqsb(:) = zero mean_gqsb(:) = zero DO jv = 1, nvm DO ji = 1, kjpindex IF ( vegtot(ji) .GT. zero ) THEN !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN mean_bqsb(ji) = mean_bqsb(ji) + tot_bare_soil(ji)/vegtot(ji)*bqsb(ji,jv) mean_gqsb(ji) = mean_gqsb(ji) + tot_bare_soil(ji)/vegtot(ji)*gqsb(ji,jv) ELSE mean_bqsb(ji) = mean_bqsb(ji) + veget(ji,jv)/vegtot(ji)*bqsb(ji,jv) mean_gqsb(ji) = mean_gqsb(ji) + veget(ji,jv)/vegtot(ji)*gqsb(ji,jv) ENDIF ENDIF ENDDO ENDDO OnceMore = .TRUE. niter = 0 lbad_ij(:)=.TRUE. DO WHILE ( OnceMore .AND. ( niter .LT. nitermax ) ) ! nitermax prevents infinite loops (should actually never occur) niter = niter + 1 !!!! we test disabling the average of soil columns !! !! 6.2 We assign the mean value in all the soil columns in a grid-cell !! DO jv = 1, nvm !! DO ji = 1, kjpindex !! IF (lbad_ij(ji)) THEN !!!MM veget(:,1) BUG ??!!!!!!!!!!! !! IF (jv .EQ. 1) THEN !! IF (tot_bare_soil(ji).GT.zero) THEN !! ! !! bqsb(ji,jv) = mean_bqsb(ji) !! dsp(ji,jv) = zmaxh - bqsb(ji,jv)/ruu_ch(ji) !! ENDIF !! ELSE IF ( veget(ji,jv) .GT. zero ) THEN !! ! !! bqsb(ji,jv) = mean_bqsb(ji) !! dsp(ji,jv) = zmaxh - bqsb(ji,jv)/ruu_ch(ji) ! *** can this line make dsp>dpu_cste ? !! ENDIF !! ENDIF !! !! ENDDO !! ENDDO !! 6.3 Iterative adjustment if top layer larger than new average dsp !! After averaging the bottom moistures, dsp becomes the mean depth of soil that is not filled by bottom moisture. !! In "bad" points where dsg > dsp, we merge the two soil layers. !! This adjustment needs to be done iteratively (WHILE loop) !! We diagnose the bad points where dsg>dsp !MM veget(:,1) BUG ??!!!!!!!!!!! !!$ lbad(:,:) = ( ( dsp(:,:) .LT. dsg(:,:) ) .AND. & !!$ ( dsg(:,:) .GT. zero ) .AND. & !!$ ( veget(:,:) .GT. zero ) ) lbad(:,:) = ( ( dsp(:,:) .LT. dsg(:,:) ) .AND. & ( dsg(:,:) .GT. zero ) ) DO jv = 1, nvm DO ji = 1, kjpindex IF (jv .EQ. 1) THEN lbad(ji,jv) = lbad(ji,jv) .AND. ( tot_bare_soil(ji) .GT. zero ) ELSE lbad(ji,jv) = lbad(ji,jv) .AND. ( veget(ji,jv) .GT. zero ) ENDIF ENDDO ENDDO !! If there are no such points, we'll do no further iteration IF ( COUNT( lbad(:,:) ) .EQ. 0 ) OnceMore = .FALSE. DO ji = 1, kjpindex IF (COUNT(lbad(ji,:)) == 0 ) lbad_ij(ji)=.FALSE. ENDDO !! In the bad PFTs, we merge the two soil layers. DO jv = 1, nvm !YM ! ! ! DO ji = 1, kjpindex ! IF ( veget(ji,jv) .GT. zero ) THEN ! ! ! bqsb(ji,jv) = mean_bqsb(ji) ! dsp(ji,jv) = zmaxh - bqsb(ji,jv)/ruu_ch(ji) ! ENDIF ! ! ! ENDDO ! DO ji = 1, kjpindex IF ( lbad(ji,jv) ) THEN ! runoff(ji,jv) = runoff(ji,jv) + & MAX( bqsb(ji,jv) + gqsb(ji,jv) - mx_eau_var(ji), zero) ! bqsb(ji,jv) = MIN( bqsb(ji,jv) + gqsb(ji,jv), mx_eau_var(ji)) ! gqsb(ji,jv) = zero dsp(ji,jv) = zmaxh - bqsb(ji,jv)/ruu_ch(ji) ! *** could this line make dsp>dpu_cste ? ! *** set a max to dpu_cste to be sure ! dss(ji,jv) = dsp(ji,jv) dsg(ji,jv) = zero ENDIF ENDDO ENDDO !! New average of bottom and top moisture over the "veget" fractions, for the next iteration mean_bqsb(:) = zero mean_gqsb(:) = zero DO jv = 1, nvm DO ji = 1, kjpindex IF ( vegtot(ji) .GT. zero ) THEN !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN mean_bqsb(ji) = mean_bqsb(ji) + tot_bare_soil(ji)/vegtot(ji)*bqsb(ji,jv) mean_gqsb(ji) = mean_gqsb(ji) + tot_bare_soil(ji)/vegtot(ji)*gqsb(ji,jv) ELSE mean_bqsb(ji) = mean_bqsb(ji) + veget(ji,jv)/vegtot(ji)*bqsb(ji,jv) mean_gqsb(ji) = mean_gqsb(ji) + veget(ji,jv)/vegtot(ji)*gqsb(ji,jv) ENDIF ENDIF ENDDO ENDDO ENDDO ! end while, but no warning if nitermax has been reached *** !! 7. Compute total runoff from all soil columns and partition it into drainage and surface runoff ! *** why isn't run_off_tot divided by vegtot ? IF (printlev>=3) WRITE(numout,*) 'hydrolc_soil 4.0: Computes total runoff' !! 7.1 Average total runoff run_off_tot(:) = zero DO ji = 1, kjpindex IF ( vegtot(ji) .GT. zero ) THEN run_off_tot(ji) = runoff(ji,1)*tot_bare_soil(ji) + SUM(runoff(ji,2:nvm)*veget(ji,2:nvm)) ELSE run_off_tot(ji) = tot_melt(ji) + irrigation(ji) + reinfiltration(ji) ENDIF ENDDO !! 7.2 Diagnose drainage and surface runoff (95% and 5%) drainage(:) = 0.95 * run_off_tot(:) run_off_tot(:) = run_off_tot(:) - drainage(:) ! *** from now on, we lost track of total runoff ! *** the name "run_off_tot" is VERY misleading !! 8. Diagnostics which are needed to carry information to other modules: IF (printlev>=3) WRITE(numout,*) 'hydro_soil 5.0: Diagnostics' ! Reset dsg if necessary WHERE (gqsb(:,:) .LE. zero) dsg(:,:) = zero ! Average moisture profile for shumdiag DO ji=1,kjpindex mean_dsg(ji) = mean_gqsb(ji)/ruu_ch(ji) ! mean depth of water in top layer in meters ENDDO !! 8.1 Moisture stress factors on vegetation (humrel and vegstress) !! Moisture stress factors on vegetation: !! - "humrel" on transpiration (for condveg) exponentially decreases with top dry soil depth; !! the decay factor is the one of root density with depth (from 1 to 8 depending on PFTs), !! following de Rosnay and Polcher (1998) !! - "vegstress" on vegetation growth (for stomate) IF (printlev>=3) WRITE(numout,*) 'hydro_soil 6.0 : Moisture stress' a_subgrd(:,:) = zero DO jv = 1, nvm DO ji=1,kjpindex ! ! computes relative surface humidity ! ! Only use the standard formulas if total soil moisture is larger than zero. ! Else stress functions are set to zero. ! This will avoid that large negative soil moisture accumulate over time by the ! the creation of small skin reservoirs which evaporate quickly. ! IF ( gqsb(ji,jv)+bqsb(ji,jv) .GT. zero ) THEN ! IF (dsg(ji,jv).EQ. zero .OR. gqsb(ji,jv).EQ.zero) THEN humrel(ji,jv) = EXP( - humcste(jv) * zmaxh * (dsp(ji,jv)/zmaxh) ) dsg(ji,jv) = zero ! humrel = 0 if dsp is larger than its value at the wilting point, or if the bottom layer's soil is negative ! *** the condition based on qwilt (= 5.0) doesn't make much sense: (i) the Choisnel scheme works in available ! *** moisture, i.e. above wilting point (Ducharne & Laval, 2000), so that the moisture at withing point is ZERO; ! *** (ii) with the chosen values in constantes_soil.f90, qwilt/ruu_ch is around 0.033 and dpu_cste-qwilt/ruu_ch ! *** is around dpu IF (dsp(ji,jv).GT.(zmaxh - min_sechiba) .OR. bqsb(ji,jv).LT.zero) THEN humrel(ji,jv) = zero ENDIF vegstress(ji,jv) = humrel(ji,jv) ELSE !! 8.1.2 If there are two soil layers, we need the "transpiring" fraction "a_subgrd" !! We compute humrel as the average of the values defined by dss and dsp. !! The weights depend on "a_subgrd", which is defined by redistributing the top layer's !! moisture in a virtual layer of depth dsg_min (set to 1 mm in hydrolc), !! what defines a totally dry and a totally saturated fraction (a_subgrd): !! - if the top layer's moisture > 1mm, then a_subgrd=1, and the humrel is normally deduced from dss only !! - if the top layer's moisture is very small, a_subgrd decreases from 1 to 0 as the top layer's moisture !! vanishes, and it serves to describe a smooth transition to the case where the top soil layer has !! vanished and humrel depends on dsp. !! \latexonly !! \includegraphics[scale = 1]{asubgrid.pdf} !! \endlatexonly ! zhumrel_lo(ji) = EXP( - humcste(jv) * dsp(ji,jv)) zhumrel_up(ji) = EXP( - humcste(jv) * dss(ji,jv)) a_subgrd(ji,jv)=MIN(MAX(dsg(ji,jv)-dss(ji,jv),zero)/dsg_min,un) humrel(ji,jv)=a_subgrd(ji,jv)*zhumrel_up(ji)+(un-a_subgrd(ji,jv))*zhumrel_lo(ji) !! As we need a slower variable for vegetation growth, vegstress is computed differently from humrel. ! *** la formule ci-dessous est d'un empirisme absolu : on ajoute deux stresses, on en retranche un autre...???? ! que veut dire slower variable ?? vegstress(ji,jv) = zhumrel_lo(ji) + zhumrel_up(ji) - EXP( - humcste(jv) * dsg(ji,jv) ) ENDIF ELSE !! 8.1.3 If total moisture is negative, the two moisture stress factors are set to zero. !! This should avoid that large negative soil moisture accumulate over time because of small skin layers !! which transpire quickly. ! *** Yet, CMIP5 exhibits such behaviors => because of rsol ?? or other reasons ?? The routing shouldn't ! *** create such situations, but couldn't some patches here or there ??? humrel(ji,jv) = zero vegstress(ji,jv) = zero ENDIF ! ENDDO ENDDO !! Calculates the water limitation factor. humrel(:,:) = MAX( min_sechiba, MIN( humrel(:,:)/0.5, un )) !! 8.2 Mean relative soil moisture in the diagnostic soil levels: shumdiag (for thermosoil) !! It is deduced from the mean moisture and depth of the two soil layers in the grid cell, !! depending on how the soil diagnostic levels intersect the two mean soil depths DO jd = 1,nbdl DO ji = 1, kjpindex IF ( tmp_dl(jd+1) .LT. mean_dsg(ji)) THEN ! mean_dsg = mean depth of water in top layer in meters ! If the diagnostic soil level entirely fits into the mean top soil layer depth, they have the same ! relative moisture shumdiag(ji,jd) = mean_gqsb(ji)/mx_eau_var(ji) ELSE IF ( tmp_dl(jd) .LT. mean_dsg(ji)) THEN ! If the diagnostic soil level intersects both soil layers, its relative moisture is the weighted ! mean of the ones of two soil layers gtr = (mean_dsg(ji)-tmp_dl(jd))/(tmp_dl(jd+1)-tmp_dl(jd)) btr = 1 - gtr shumdiag(ji,jd) = gtr*mean_gqsb(ji)/mx_eau_var(ji) + & & btr*mean_bqsb(ji)/mx_eau_var(ji) ELSE ! If the diagnostic soil level entirely fits into the mean bottom soil layer depth, ! they have the same relative moisture shumdiag(ji,jd) = mean_bqsb(ji)/mx_eau_var(ji) ENDIF ENDIF shumdiag(ji,jd) = MAX(MIN(shumdiag(ji,jd), un), zero) ENDDO ENDDO !! 8.3 Fraction of visibly dry soil in the bare soil fraction for soil albedo !! if we want to account for its dependance on soil moisture in condveg. !! We redistribute the top layer's moisture in a virtual layer of depth 0.1 m, !! what defines a totally saturated and a totally dry fraction (drysoil_frac). !! The latter is thus 1 if dss > 0.1 m. drysoil_frac(:) = MIN(MAX(dss(:,1),zero)*10._r_std, un) !! 8.4 Resistance to bare soil evaporation !! This resistance increases with the height of top dry soil, described by hdry. !! It depends on both dss and dsp (dry soil heights) in the bare soil fraction, !! and, as for the soil moisture stress factor on transpiration (humrel), !! we use "a_subgrd" (see 8.1.2) to describe a smooth transition between cases !! when the top layer's moisture > 1mm and hdry=dss and cases when the top layer's !! has vanished and hdy=dsp. !! The relationship between rsol and dry soil height has been changed since !! de Rosnay and Polcher (1998), to make rsol becomes VERY large when hdry !! gets close to dpu_cste !! Owing to this non-linear dependance, BSE tends to zero when the depth of dry reaches dpu_cste. ! *** if hdry > dpu (several cases might lead to this pathological situation), ! *** we shift to the other limb of the hyperbolic function, and rsol decreases towards hdry*rsol_cste ! *** can this explain the accumulation of very negative soil moisture in arid zones in CMIP5 ??? ! *** COULD'NT WE SIMPLY SET THAT hdry CANNOT EXCEED dpu_cste ??? hdry(:) = a_subgrd(:,1)*dss(:,1) + (un-a_subgrd(:,1))*dsp(:,1) rsol(:) = -un DO ji = 1, kjpindex IF (tot_bare_soil(ji) .GE. min_sechiba) THEN ! Correction Nathalie - le 28 mars 2006 - sur conseils Fred Hourdin ! on modifie le rsol pour que la resistance croisse subitement si on s'approche ! du fond. En gros, rsol=hdry*rsol_cste pour hdry < 1m70 !rsol(ji) = dss(ji,1) * rsol_cste rsol(ji) = ( hdry(ji) + un/(10.*(zmaxh - hdry(ji))+1.e-10)**2 ) * rsol_cste ENDIF ENDDO !! 8.5 Litter humidity factor, used in stomate !! It varies from 1 when mean top dry soil height is 0, and decreases as mean top dry soil height increases litterhumdiag(:) = EXP( - hdry(:) / hcrit_litter ) ! hcrit_litter=0.08_r_std !! Special case of it has just been raining a few drops: the top layer exists, but its height !! is ridiculously small and the mean top dry soil height is almost zero: we assume a dry litter WHERE ( ( hdry(:) .LT. min_sechiba ) .AND. & ! constantes : min_sechiba = 1.E-8_r_std ( mean_dsg(:) .GT. min_sechiba ) .AND. ( mean_dsg(:) .LT. 5.E-4 ) ) litterhumdiag(:) = zero ENDWHERE IF (printlev>=3) WRITE (numout,*) ' hydrolc_soil done ' END SUBROUTINE hydrolc_soil SUBROUTINE hydrolc_waterbal_init (kjpindex, qsintveg, snow, snow_nobio) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT (in) :: kjpindex !! Domain size (number of grid cells) (unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: qsintveg !! Amount of water in the canopy interception !! reservoir @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: snow !! Snow water equivalent @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nnobio), INTENT(in) :: snow_nobio !! Snow water equivalent on nobio areas !! @tex ($kg m^{-2}$) @endtex !! 0.4 Local variables INTEGER(i_std) :: ji, jv, jn REAL(r_std),DIMENSION (kjpindex) :: watveg !! Total amount of intercepted water in a grid-cell REAL(r_std),DIMENSION (kjpindex) :: sum_snow_nobio !! Total amount of snow from the "nobio" fraction !! in a grid-cell @tex ($kg m^{-2}$) @endtex !_ ================================================================================================================================ !! 1. We initialize the total amount of water in terrestrial grid-cells at the beginning of the first time step tot_water_beg(:) = zero watveg(:) = zero sum_snow_nobio(:) = zero DO jv = 1, nvm watveg(:) = watveg(:) + qsintveg(:,jv) ENDDO DO jn = 1, nnobio ! nnobio=1 sum_snow_nobio(:) = sum_snow_nobio(:) + snow_nobio(:,jn) ENDDO DO ji = 1, kjpindex tot_water_beg(ji) = (mean_bqsb(ji) + mean_gqsb(ji))*vegtot(ji) + & & watveg(ji) + snow(ji) + sum_snow_nobio(ji) ENDDO tot_water_end(:) = tot_water_beg(:) END SUBROUTINE hydrolc_waterbal_init !! ================================================================================================================================ !! SUBROUTINE : hydrolc_waterbal !! !>\BRIEF This subroutine checks the water balance closure in each terrestrial grid-cell !! over a time step. !! !! DESCRIPTION : The change in total water amount over the time step must equal the algebraic sum of the !! water fluxes causing the change, integrated over the timestep. The equality is checked to some precision, !! set for double precision calculations (REAL*8). Note that this precision depends on the time step. !! This verification does not make much sense in REAL*4 as the precision is the same as some of the fluxes. !! The computation is only done over the soil area, as over glaciers (and lakes?) we do not have !! water conservation. !! *** The above sentence is not consistent with what I understand from the code, since snow_nobio is accounted for. !! *** what is the value of epsilon(1) ? !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLE(S) : None !! !! REFERENCE(S) : None !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_waterbal (kjpindex, index, veget, totfrac_nobio, qsintveg, snow, snow_nobio,& & precip_rain, precip_snow, returnflow, reinfiltration, irrigation, tot_melt, vevapwet, transpir, vevapnu,& & vevapsno, vevapflo, floodout, run_off_tot, drainage) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT (in) :: kjpindex !! Domain size (number of grid cells) (unitless) INTEGER(i_std),DIMENSION (kjpindex), INTENT (in) :: index !! Indices of the points on the map REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: veget !! Grid-cell fraction effectively covered by !! vegetation for each PFT, except for soil !! (0-1, unitless) REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: totfrac_nobio !! Total fraction of terrestrial ice+lakes+... !! (0-1, unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: qsintveg !! Amount of water in the canopy interception !! reservoir @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: snow !! Snow water equivalent @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nnobio), INTENT(inout):: snow_nobio !! Snow water equivalent on nobio areas !! @tex ($kg m^{-2}$) @endtex ! Ice water balance REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: precip_rain !! Rainfall @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: precip_snow !! Snowfall @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: returnflow !! Routed water which comes back into the soil !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: reinfiltration !! Water returning from routing to the top reservoir REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: irrigation !! Irrigation water applied to soils !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: tot_melt !! Total melt @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: vevapwet !! Interception loss over each PFT !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: transpir !! Transpiration over each PFT !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: vevapnu !! Bare soil evaporation @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: vevapflo !! Floodplains evaporation REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: vevapsno !! Snow evaporation @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: floodout !! Outflow from floodplains REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: run_off_tot !! Diagnosed surface runoff @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: drainage !! Diagnosed rainage at the bottom of soil !! @tex ($kg m^{-2}$) @endtex !! 0.2 Output variables !! 0.3 Modified variables !! 0.4 Local variables INTEGER(i_std) :: ji, jv, jn !! Grid-cell, PFT and "nobio" fraction indices !! (unitless) REAL(r_std) :: allowed_err !! Allowed error in the water budget closure !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex) :: watveg !! Total amount of intercepted water in a grid-cell !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex) :: delta_water !! Change in total water amount !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex) :: tot_flux !! Algebraic sum of the water fluxes integrated over !! the timestep @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex) :: sum_snow_nobio !! Total amount of snow from the "nobio" fraction !! in a grid-cell @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex) :: sum_vevapwet !! Sum of interception loss in the grid-cell !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex) :: sum_transpir !! Sum of transpiration in the grid-cell !! @tex ($kg m^{-2}$) @endtex !_ ================================================================================================================================ !! 1. We check the water balance : this is done at the end of a time step tot_water_end(:) = zero !! 1.1 If the "nobio" fraction does not complement the "bio" fraction, we issue a warning !! If the "nobio" fraction (ice, lakes, etc.) does not complement the "bio" fraction (vegetation and bare soil), !! we do not need to go any further, and we output a warning ! *** how are oceans treated ? DO ji = 1, kjpindex ! Modif Nathalie ! IF ( (un - (totfrac_nobio(ji) + vegtot(ji))) .GT. EPSILON(un) ) THEN IF ( (un - (totfrac_nobio(ji) + vegtot(ji))) .GT. (100*EPSILON(un)) ) THEN WRITE(numout,*) 'HYDROL problem in vegetation or frac_nobio on point ', ji WRITE(numout,*) 'totfrac_nobio : ', totfrac_nobio(ji) WRITE(numout,*) 'vegetation fraction : ', vegtot(ji) !STOP 'in hydrolc_waterbal' ENDIF ENDDO !! 1.2 We calculate the total amount of water in grid-cells at the end the time step watveg(:) = zero sum_vevapwet(:) = zero sum_transpir(:) = zero sum_snow_nobio(:) = zero !cdir NODEP DO jv = 1,nvm watveg(:) = watveg(:) + qsintveg(:,jv) sum_vevapwet(:) = sum_vevapwet(:) + vevapwet(:,jv) sum_transpir(:) = sum_transpir(:) + transpir(:,jv) ENDDO !cdir NODEP DO jn = 1,nnobio sum_snow_nobio(:) = sum_snow_nobio(:) + snow_nobio(:,jn) ENDDO !cdir NODEP DO ji = 1, kjpindex tot_water_end(ji) = (mean_bqsb(ji) + mean_gqsb(ji))*vegtot(ji) + & & watveg(ji) + snow(ji) + sum_snow_nobio(ji) ENDDO !! 2.3 Calculate the change in total water amount during the time step !! Calculate the change in total water amount during the time, stepand the algebraic sum !! of the water fluxes supposed to cause the total water amount change. !! If the model conserves water, they should be equal, since the fluxes are used in their integrated form, !! over the time step dt_sechiba, with a unit of kg m^{-2}. DO ji = 1, kjpindex delta_water(ji) = tot_water_end(ji) - tot_water_beg(ji) tot_flux(ji) = precip_rain(ji) + precip_snow(ji) + returnflow(ji) + reinfiltration(ji) + irrigation(ji) - & & sum_vevapwet(ji) - sum_transpir(ji) - vevapnu(ji) - vevapsno(ji) - vevapflo(ji) + & & floodout(ji)- run_off_tot(ji) - drainage(ji) ENDDO !! 1.4 We do the check, given some minimum required precision !! This is a wild guess and corresponds to what works on an IEEE machine under double precision (REAL*8). !! If the water balance is not closed at this precision, we issue a warning with some diagnostics. allowed_err = 50000*EPSILON(un) ! *** how much is epsilon(1) ? where is it defined ? DO ji = 1, kjpindex IF ( ABS(delta_water(ji)-tot_flux(ji)) .GT. allowed_err ) THEN WRITE(numout,*) 'HYDROL does not conserve water. The erroneous point is : ', ji WRITE(numout,*) 'The error in mm/d is :', (delta_water(ji)-tot_flux(ji))/dt_sechiba*one_day, & & ' and in mm/dt : ', delta_water(ji)-tot_flux(ji) WRITE(numout,*) 'delta_water : ', delta_water(ji), ' tot_flux : ', tot_flux(ji) WRITE(numout,*) 'Actual and allowed error : ', ABS(delta_water(ji)-tot_flux(ji)), allowed_err WRITE(numout,*) 'vegtot : ', vegtot(ji) WRITE(numout,*) 'precip_rain : ', precip_rain(ji) WRITE(numout,*) 'precip_snow : ', precip_snow(ji) WRITE(numout,*) 'Water from irrigation, floodplains:', reinfiltration(ji), returnflow(ji), irrigation(ji) WRITE(numout,*) 'Total water in soil :', mean_bqsb(ji) + mean_gqsb(ji) WRITE(numout,*) 'Water on vegetation :', watveg(ji) WRITE(numout,*) 'Snow mass :', snow(ji) WRITE(numout,*) 'Snow mass on ice :', sum_snow_nobio(ji) WRITE(numout,*) 'Melt water :', tot_melt(ji) WRITE(numout,*) 'evapwet : ', vevapwet(ji,:) WRITE(numout,*) 'transpir : ', transpir(ji,:) WRITE(numout,*) 'evapnu, evapsno, evapflo : ', vevapnu(ji), vevapsno(ji), vevapflo(ji) WRITE(numout,*) 'floodout : ', floodout(ji) WRITE(numout,*) 'drainage : ', drainage(ji) !STOP 'in hydrolc_waterbal' ENDIF ENDDO !! 2. Transfer the total water amount at the end of the current timestep to the begining of the next one tot_water_beg = tot_water_end END SUBROUTINE hydrolc_waterbal !! ================================================================================================================================ !! SUBROUTINE : hydrolc_alma_init !! !>\BRIEF Initialize variables needed in hydrolc_alma !! !! DESCRIPTION : None !! !! RECENT CHANGE(S) : None !! !! REFERENCE(S) : None !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_alma_init (kjpindex, index, qsintveg, snow, snow_nobio) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT (in) :: kjpindex !! Domain size (number of grid cells) (unitless) INTEGER(i_std),DIMENSION (kjpindex), INTENT (in) :: index !! Indices of the points on the map (unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: qsintveg !! Amount of water in the canopy interception reservoir !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: snow !! Snow water equivalent @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (in):: snow_nobio !! Snow water equivalent on nobio areas !! @tex ($kg m^{-2}$) @endtex !! 0.4 Local variabless INTEGER(i_std) :: ji !! Grid-cell indices (unitless) REAL(r_std) :: watveg !! Total amount of intercepted water in a grid-cell !! @tex ($kg m^{-2}$) @endtex !_ ================================================================================================================================ !! 1. Initialize water in terrestrial grid-cells at the beginning of the first time step !! Initialize the amounts of water in terrestrial grid-cells at the beginning of the first time step, !! for the three water reservoirs (interception, soil and snow). tot_watveg_beg(:) = zero tot_watsoil_beg(:) = zero snow_beg(:) = zero DO ji = 1, kjpindex watveg = SUM(qsintveg(ji,:)) tot_watveg_beg(ji) = watveg tot_watsoil_beg(ji) = mean_bqsb(ji) + mean_gqsb(ji) snow_beg(ji) = snow(ji)+ SUM(snow_nobio(ji,:)) ENDDO tot_watveg_end(:) = tot_watveg_beg(:) tot_watsoil_end(:) = tot_watsoil_beg(:) snow_end(:) = snow_beg(:) END SUBROUTINE hydrolc_alma_init !! ================================================================================================================================ !! SUBROUTINE : hydrolc_alma !! !>\BRIEF This routine computes diagnostic variables required under the ALMA standards: !! changes in water amounts over the time steps (in the soil, snow and interception reservoirs); total water amount !! at the end of the time steps; soil relative humidity. !! !! DESCRIPTION : None !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLE(S) : !! - soilwet: mean relative humidity of soil in the grid-cells (0-1, unitless) !! - delsoilmoist, delswe, delintercept: changes in water amount during the time step @tex ($kg m^{-2}$) @endtex, !! for the three water reservoirs (soil,snow,interception) !! - tot_watsoil_end: total water amount at the end of the time steps aincluding the three water resrevoirs !! @tex ($kg m^{-2}$) @endtex. !! !! REFERENCE(S) : None !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_alma (kjpindex, index, qsintveg, snow, snow_nobio, soilwet) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT (in) :: kjpindex !! Domain size (number of grid cells) (unitless) INTEGER(i_std),DIMENSION (kjpindex), INTENT (in) :: index !! Indices of the points on the map (unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: qsintveg !! Amount of water in the canopy interception reservoir !! @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: snow !! Snow water equivalent @tex ($kg m^{-2}$) @endtex REAL(r_std),DIMENSION (kjpindex,nnobio), INTENT (in):: snow_nobio !! Snow water equivalent on nobio areas !! @tex ($kg m^{-2}$) @endtex !! 0.2 Output variables REAL(r_std),DIMENSION (kjpindex), INTENT (out) :: soilwet !! Mean relative humidity of soil in the grid-cells !! (0-1, unitless) !! 0.3 Modified variables !! 0.4 Local variabless INTEGER(i_std) :: ji !! Grid-cell indices (unitless) REAL(r_std) :: watveg !! Total amount of intercepted water in a grid-cell !! @tex ($kg m^{-2}$) @endtex !_ ================================================================================================================================ !! 1. We calculate the required variables at the end of each time step tot_watveg_end(:) = zero tot_watsoil_end(:) = zero snow_end(:) = zero delintercept(:) = zero delsoilmoist(:) = zero delswe(:) = zero DO ji = 1, kjpindex watveg = SUM(qsintveg(ji,:)) tot_watveg_end(ji) = watveg tot_watsoil_end(ji) = mean_bqsb(ji) + mean_gqsb(ji) snow_end(ji) = snow(ji)+ SUM(snow_nobio(ji,:)) ! delintercept(ji) = tot_watveg_end(ji) - tot_watveg_beg(ji) delsoilmoist(ji) = tot_watsoil_end(ji) - tot_watsoil_beg(ji) delswe(ji) = snow_end(ji) - snow_beg(ji) ! ENDDO !! 2. Transfer the total water amount at the end of the current timestep to the begining of the next one. tot_watveg_beg = tot_watveg_end tot_watsoil_beg = tot_watsoil_end snow_beg(:) = snow_end(:) !! 3. We calculate the mean relative humidity of soil in the grid-cells DO ji = 1,kjpindex IF ( mx_eau_var(ji) > 0 ) THEN soilwet(ji) = tot_watsoil_end(ji) / mx_eau_var(ji) ELSE soilwet(ji) = zero ENDIF ENDDO END SUBROUTINE hydrolc_alma !! ================================================================================================================================ !! SUBROUTINE : hydrolc_hdiff !! !>\BRIEF This subroutine performs horizontal diffusion of water between each PFT/soil column, !! if the flag ok_hdiff is true. !! !! DESCRIPTION : The diffusion is realized on the water contents of both the top and bottom !! soil layers, but the bottom soil layers share the same soil moisture since the end of hydrolc_soil (step 6). !! This subroutine thus only modifies the moisture of the top soil layer. !! \latexonly !! \input{hdiff.tex} !! \endlatexonly !! !! RECENT CHANGE(S) : None !! !! MAIN OUTPUT VARIABLE(S) : gqsb, bqsb, dsg, dss, dsp !! !! REFERENCE(S) : None !! !! FLOWCHART : None !! \n !_ ================================================================================================================================ SUBROUTINE hydrolc_hdiff(kjpindex, veget, tot_bare_soil, ruu_ch, gqsb, bqsb, dsg, dss, dsp) !! 0. Variable and parameter declaration !! 0.1 Input variables INTEGER(i_std), INTENT (in) :: kjpindex !! Domain size (number of grid cells) (unitless) REAL(r_std),DIMENSION (kjpindex,nvm), INTENT (in) :: veget !! Grid-cell fraction effectively covered by !! vegetation for each PFT, except for soil !! (0-1, unitless) REAL(r_std), DIMENSION (kjpindex), INTENT(in) :: tot_bare_soil !! Total evaporating bare soil fraction REAL(r_std),DIMENSION (kjpindex), INTENT (in) :: ruu_ch !! Volumetric soil water capacity !! @tex ($kg m^{-3}$) @endtex !! 0.2 Output variables !! 0.3 Modified variables REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: gqsb !! Water content in the top layer !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: bqsb !! Water content in the bottom layer !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: dsg !! Depth of the top layer (m) REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: dss !! Depth of dry soil at the top, whether in the top !! or bottom layer (m) REAL(r_std), DIMENSION (kjpindex,nvm), INTENT(inout) :: dsp !! Depth of dry soil in the bottom layer plus depth !! of top layer (m) !! 0.4 Local variables REAL(r_std), DIMENSION (kjpindex) :: bqsb_mean !! Mean value of bqsb in each grid-cell !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex) :: gqsb_mean !! Mean value of gqsb in each grid-cell !! @tex ($kg m^{-2}$) @endtex REAL(r_std), DIMENSION (kjpindex) :: dss_mean !! Mean value of dss in each grid-cell (m) REAL(r_std), DIMENSION (kjpindex) :: vegtot !! Total fraction of grid-cell covered by PFTs (bare !! soil + vegetation) (0-1, unitless) ! *** this variable is declared at the module level REAL(r_std) :: x !! Coefficient of diffusion by time step !! (0-1, unitless) INTEGER(i_std) :: ji,jv !! Indices for grid-cells and PFTs (unitless) REAL(r_std), SAVE :: tau_hdiff !! Time scale for horizontal water diffusion (s) !$OMP THREADPRIVATE(tau_hdiff) LOGICAL, SAVE :: lstep_init=.TRUE. !! Flag to set tau_hdiff at the first time step !$OMP THREADPRIVATE(lstep_init) !_ ================================================================================================================================ !! 1. First time step: we assign a value to the time scale for horizontal water diffusion (in seconds) IF ( lstep_init ) THEN !Config Key = HYDROL_TAU_HDIFF !Config Desc = time scale (s) for horizontal diffusion of water !Config Def = one_day !Config If = HYDROL_OK_HDIFF !Config Help = Defines how fast diffusion occurs horizontally between !Config the individual PFTs' water reservoirs. If infinite, no !Config diffusion. !Config Units = [seconds] tau_hdiff = one_day ! 86400 s CALL getin_p('HYDROL_TAU_HDIFF',tau_hdiff) WRITE (numout,*) 'Hydrol: Horizontal diffusion, tau (s)=',tau_hdiff lstep_init = .FALSE. ENDIF !! 2. We calculate mean values of bqsb, gqsb and dss over the grid-cell ("bio" fraction). ! Calculate mean values of bqsb, gqsb and dss over the grid-cell ("bio" fraction) ! This could be done with SUM instruction but this kills vectorization ! *** We compute here vegtot=SUM(veget), but it is already defined at a higher level (declared in the module) *** bqsb_mean(:) = zero gqsb_mean(:) = zero dss_mean(:) = zero vegtot(:) = zero ! DO jv = 1, nvm DO ji = 1, kjpindex !MM veget(:,1) BUG ??!!!!!!!!!!! IF (jv .EQ. 1) THEN bqsb_mean(ji) = bqsb_mean(ji) + tot_bare_soil(ji)*bqsb(ji,jv) gqsb_mean(ji) = gqsb_mean(ji) + tot_bare_soil(ji)*gqsb(ji,jv) dss_mean(ji) = dss_mean(ji) + tot_bare_soil(ji)*dss(ji,jv) vegtot(ji) = vegtot(ji) + tot_bare_soil(ji) ELSE bqsb_mean(ji) = bqsb_mean(ji) + veget(ji,jv)*bqsb(ji,jv) gqsb_mean(ji) = gqsb_mean(ji) + veget(ji,jv)*gqsb(ji,jv) dss_mean(ji) = dss_mean(ji) + veget(ji,jv)*dss(ji,jv) vegtot(ji) = vegtot(ji) + veget(ji,jv) ENDIF ENDDO ENDDO DO ji = 1, kjpindex IF (vegtot(ji) .GT. zero) THEN bqsb_mean(ji) = bqsb_mean(ji)/vegtot(ji) gqsb_mean(ji) = gqsb_mean(ji)/vegtot(ji) dss_mean(ji) = dss_mean(ji)/vegtot(ji) ENDIF ENDDO !! 3. Relax PFT values towards grid-cell mean !! Relax values towards mean : the diffusion is proportional to the deviation to the mean, !! and inversely proportional to the timescale tau_hdiff !! We change the moisture of two soil layers, but also the depth of dry in the top soil layer. !! Therefore, we need to accordingly adjust the top soil layer depth !! and the dry soil depth above the bottom moisture (dsp). ! *** This sequence does not seem to be fully consistent with the variable definitions, ! *** especially for the dry soil depths dss and dsp: ! *** (i) is the "diffusion" of dss correct is some PFTs only have one soil layer (dss=dsp), ! *** given that hydrolc_soil acted to merge the bottom soil moistures bqsb ! *** (ii) if gqsb is very small, we let the top layer vanish, but dss is not updated to dsp ! ! *** Also, it would be make much more sense to perform the diffusion in hydrolc_soil, when the ! *** bottom soil moistures are homogenized. It would benefit from the iterative consistency ! *** check between the dsg and dsp, and it would prevent from doing some calculations twice. ! *** Finally, it would be better to keep the water balance calculation for the real end of the ! *** hydrological processes. ! ! *** FORTUNATELY, the default value of ok_hdiff is false (hydrolc_init.f90) x = MAX( zero, MIN( dt_sechiba/tau_hdiff, un ) ) DO jv = 1, nvm DO ji = 1, kjpindex ! *** bqsb does not change as bqsb(ji,jv)=bqsb_mean(ji) since hydrolc_soil, step 6 bqsb(ji,jv) = (un-x) * bqsb(ji,jv) + x * bqsb_mean(ji) gqsb(ji,jv) = (un-x) * gqsb(ji,jv) + x * gqsb_mean(ji) ! *** is it meaningful to apply the diffusion equation to dss ? dss(ji,jv) = (un-x) * dss(ji,jv) + x * dss_mean(ji) IF (gqsb(ji,jv) .LT. min_sechiba) THEN dsg(ji,jv) = zero ! *** in this case, we should also set dss to dsp (defined below) ELSE dsg(ji,jv) = (dss(ji,jv) * ruu_ch(ji) + gqsb(ji,jv)) / ruu_ch(ji) ENDIF dsp(ji,jv) = zmaxh - bqsb(ji,jv) / ruu_ch(ji) ! no change here since bqsb does not change ENDDO ENDDO END SUBROUTINE hydrolc_hdiff END MODULE hydrolc
{"hexsha": "a1540f8dd85d4f423868ae2674c50199d197d261", "size": 213320, "ext": "f90", "lang": "FORTRAN", "max_stars_repo_path": "test/examples_large/ORCHIDEE_hydrolc.f90", "max_stars_repo_name": "mbdevpl/open-fortran-parser-xml", "max_stars_repo_head_hexsha": "127f4ec2ba7cd06eb010794560eb8e4b9494fdfe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-08-01T03:11:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T13:11:43.000Z", "max_issues_repo_path": "test/examples_large/ORCHIDEE_hydrolc.f90", "max_issues_repo_name": "mbdevpl/open-fortran-parser-xml", "max_issues_repo_head_hexsha": "127f4ec2ba7cd06eb010794560eb8e4b9494fdfe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2017-08-08T12:26:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T14:27:39.000Z", "max_forks_repo_path": "test/examples_large/ORCHIDEE_hydrolc.f90", "max_forks_repo_name": "mbdevpl/open-fortran-parser-xml", "max_forks_repo_head_hexsha": "127f4ec2ba7cd06eb010794560eb8e4b9494fdfe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-04-04T08:08:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T13:23:59.000Z", "avg_line_length": 54.9793814433, "max_line_length": 216, "alphanum_fraction": 0.5393774611, "num_tokens": 57929}
module VermontTerrestrialPassageTool using ArchGDAL using DelimitedFiles using GeoData using Omniscape using Shapefile using Statistics include("utils.jl") include("main.jl") include("consts.jl") export compute_all_culverts end
{"hexsha": "d6d0d2943d5f50faa30aba936871f95e915277a2", "size": 232, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/VermontTerrestrialPassageTool.jl", "max_stars_repo_name": "csp-inc/VermontTerrestrialPassageTool.jl", "max_stars_repo_head_hexsha": "9c5273012bcdb77241ec6caddf2bc02c99c4e817", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/VermontTerrestrialPassageTool.jl", "max_issues_repo_name": "csp-inc/VermontTerrestrialPassageTool.jl", "max_issues_repo_head_hexsha": "9c5273012bcdb77241ec6caddf2bc02c99c4e817", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/VermontTerrestrialPassageTool.jl", "max_forks_repo_name": "csp-inc/VermontTerrestrialPassageTool.jl", "max_forks_repo_head_hexsha": "9c5273012bcdb77241ec6caddf2bc02c99c4e817", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.6470588235, "max_line_length": 36, "alphanum_fraction": 0.8318965517, "num_tokens": 61}
/**************************************************************************** * hipipe library * Copyright (c) 2017, Cognexa Solutions s.r.o. * Copyright (c) 2018, Iterait a.s. * Author(s) Filip Matzner * * This file is distributed under the MIT License. * See the accompanying file LICENSE.txt for the complete license agreement. ****************************************************************************/ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE run_graph_test #include "../core/common.hpp" #include <hipipe/tensorflow/load_graph.hpp> #include <hipipe/tensorflow/run_graph.hpp> #include <boost/test/unit_test.hpp> namespace htf = hipipe::tensorflow; BOOST_AUTO_TEST_CASE(test_simple_run) { auto sess = load_graph("transpose_add_one_2_3_net.pb"); // prepare inputs std::vector<std::string> input_names = {"input"}; std::tuple<std::vector<float>> input_data = {{0, 1, 2, 3, 4, 5}}; std::vector<std::vector<long>> input_shapes = {{2, 3}}; std::vector<std::string> output_names = {"output"}; // prepare outputs std::tuple<std::vector<float>> output_data; std::vector<std::vector<long>> output_shapes; // run graph std::tie(output_data, output_shapes) = htf::run_graph<float>(*sess, input_names, input_data, input_shapes, output_names); // test output shape BOOST_TEST(output_shapes.size() == 1); BOOST_TEST(output_shapes[0][0] == 3); BOOST_TEST(output_shapes[0][1] == 2); // test output data test_ranges_equal(std::get<0>(output_data), std::vector<float>{1, 4, 2, 5, 3, 6}); }
{"hexsha": "3a624e818493180be0319f99347f08d5b0f56f15", "size": 1603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensorflow/run_graph.cpp", "max_stars_repo_name": "iterait/hipipe", "max_stars_repo_head_hexsha": "c2a6cc13857dce93e5ae3f76a86e8f029ca3f921", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T09:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T12:35:09.000Z", "max_issues_repo_path": "test/tensorflow/run_graph.cpp", "max_issues_repo_name": "iterait/hipipe", "max_issues_repo_head_hexsha": "c2a6cc13857dce93e5ae3f76a86e8f029ca3f921", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-09-26T13:55:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-28T13:47:04.000Z", "max_forks_repo_path": "test/tensorflow/run_graph.cpp", "max_forks_repo_name": "iterait/hipipe", "max_forks_repo_head_hexsha": "c2a6cc13857dce93e5ae3f76a86e8f029ca3f921", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3958333333, "max_line_length": 88, "alphanum_fraction": 0.6144728634, "num_tokens": 404}
subroutine difu(icreep ,timest ,lundia ,nst ,icx , & & icy ,j ,nmmaxj ,nmmax ,kmax , & & lstsci ,lstsc ,lsal ,ltem ,lsecfl , & & lsec ,lsed ,lsts ,norow ,irocol , & & kcs ,kcu ,kfs ,kfu ,kfv , & & kadu ,kadv ,s0 ,s1 ,hu , & & hv ,dps ,qxk ,qyk ,qzk , & & guu ,gvv ,guv ,gvu ,gsqs , & & rbnd ,sigdif ,sigmol ,r0 ,r1 , & & sour ,sink ,ws ,sedtyp ,thick , & & sig ,dicuv ,vicww ,dsdksi ,dsdeta , & & dtdksi ,dtdeta ,aak ,bbk ,cck , & & bdddx ,bddx ,bdx ,bux ,buux , & & buuux ,uvdwk ,vvdwk ,areau ,areav , & & aakl ,bbkl ,cckl ,ddkl , & & eqmbcsand ,eqmbcmud ,seddif ,volum0 ,volum1 , & & rscale ,bruvai ,gdp ) !----- GPL --------------------------------------------------------------------- ! ! Copyright (C) Stichting Deltares, 2011-2016. ! ! This program is free software: you can redistribute it and/or modify ! it under the terms of the GNU General Public License as published by ! the Free Software Foundation version 3. ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License ! along with this program. If not, see <http://www.gnu.org/licenses/>. ! ! contact: [email protected] ! Stichting Deltares ! P.O. Box 177 ! 2600 MH Delft, The Netherlands ! ! All indications and logos of, and references to, "Delft3D" and "Deltares" ! are registered trademarks of Stichting Deltares, and remain the property of ! Stichting Deltares. All rights reserved. ! !------------------------------------------------------------------------------- ! $Id: difu.f90 5717 2016-01-12 11:35:24Z mourits $ ! $HeadURL: https://svn.oss.deltares.nl/repos/delft3d/tags/6686/src/engines_gpl/flow2d3d/packages/kernel/src/compute/difu.f90 $ !!--description----------------------------------------------------------------- ! ! Function: Computes transport in the u, v and w-direction. ! Implicit in the u- and w-direction, explicit in ! v-direction. ! Sinks are treated implicitly and sources explicit- ! y. A special approach is used for the hori- ! ontal diffusion to avoid artificial creeping. ! Method used: Reference : On the approximation of horizontal ! gradients in sigma co-ordinates for bathymetry ! with steep bottom slopes (G.S. Stelling and J. ! van Kester - International Journal for Methods ! in Fluids, Vol. 18 1994) ! - Horizontal Advection in U-direction : ! implicit, higher order upwind ! - Horizontal Advection in V-direction : ! explicit, central scheme ! - Horizontal Diffusion : ! 3D: explicit, along Z-planes ! 2D: implicit in U-direction ! explicit in V-direction ! - Option: horizontal diffusion strictly horizontal ! using special filter ! - Vertical Advection : ! implicit, central scheme ! - Vertical Diffusion : implicit ! - Sources are integrated explicitly. ! - Sinks are integrated implicitly. ! Comment: For the Thatcher Harleman boundaries the boundary ! points for outflow are reflected from the inner ! points; for inflow the boundary conditions are ! used (see also thahbc.for). ! !!--pseudo code and references-------------------------------------------------- ! NONE !!--declarations---------------------------------------------------------------- use precision use mathconsts use flow2d3d_timers use globaldata use dfparall use sediment_basics_module ! implicit none ! type(globdat),target :: gdp ! ! The following list of pointer parameters is used to point inside the gdp structure ! include 'flow_steps_f.inc' integer , pointer :: iro integer , pointer :: mfg integer , pointer :: nfg integer , pointer :: nudge real(fp) , pointer :: ck real(fp) , pointer :: dicoww real(fp) , pointer :: eps real(fp) , pointer :: hdt real(fp) , pointer :: vicmol real(fp) , pointer :: xlo ! ! Global variables ! integer , intent(in) :: icreep ! Description and declaration in tricom.igs integer :: icx !! Increment in the X-dir., if ICX= NMAX !! then computation proceeds in the X- !! dir. If icx=1 then computation pro- !! ceeds in the Y-dir. integer :: icy !! Increment in the Y-dir. (see ICX) integer :: j !! Begin pointer for arrays which have !! been transformed into 1D arrays. !! Due to the shift in the 2nd (M-) !! index, J = -2*NMAX + 1 integer :: kmax ! Description and declaration in esm_alloc_int.f90 integer :: lsal ! Description and declaration in dimens.igs integer , intent(in) :: lsec ! Description and declaration in dimens.igs integer :: lsecfl ! Description and declaration in dimens.igs integer :: lsed ! Description and declaration in esm_alloc_int.f90 integer , intent(in) :: lsts ! Description and declaration in dimens.igs integer , intent(in) :: lstsc ! Description and declaration in dimens.igs integer :: lstsci ! Description and declaration in esm_alloc_int.f90 integer :: ltem ! Description and declaration in dimens.igs integer :: lundia ! Description and declaration in inout.igs integer :: nmmax ! Description and declaration in dimens.igs integer :: nmmaxj ! Description and declaration in dimens.igs integer :: norow ! Description and declaration in esm_alloc_int.f90 integer , intent(in) :: nst integer, dimension(5, norow) :: irocol ! Description and declaration in esm_alloc_int.f90 integer, dimension(gdp%d%nmlb:gdp%d%nmub) :: kcs ! Description and declaration in esm_alloc_int.f90 integer, dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: kcu ! Description and declaration in esm_alloc_int.f90 integer, dimension(gdp%d%nmlb:gdp%d%nmub) :: kfs ! Description and declaration in esm_alloc_int.f90 integer, dimension(gdp%d%nmlb:gdp%d%nmub) :: kfu ! Description and declaration in esm_alloc_int.f90 integer, dimension(gdp%d%nmlb:gdp%d%nmub) :: kfv ! Description and declaration in esm_alloc_int.f90 integer, dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: kadu ! Description and declaration in esm_alloc_int.f90 integer, dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: kadv ! Description and declaration in esm_alloc_int.f90 integer, dimension(lsed) , intent(in) :: sedtyp !! sediment type: 0=total/1=noncoh/2=coh logical , intent(in) :: eqmbcsand ! Description and declaration in morpar.igs logical , intent(in) :: eqmbcmud ! Description and declaration in morpar.igs real(fp) , intent(in) :: timest !! Half Integration time step [sec.] real(prec), dimension(gdp%d%nmlb:gdp%d%nmub) :: dps ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) :: gsqs ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) :: guu ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) :: guv ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) :: gvu ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) :: gvv ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: hu ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: hv ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) :: s0 ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) :: s1 ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) :: bruvai ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) , intent(in) :: vicww ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) , intent(in) :: qzk ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax, lsed), intent(in) :: seddif ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax, lsed) :: ws ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: aak !! Internal work array (in CUCNP & UZD) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: bbk !! Internal work array (in CUCNP & UZD) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: bdddx !! Internal work array, implicit coup- !! ling of concentration in (N,M,K) !! with layer concentration in (N,M-3,K) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: bddx !! Internal work array, implicit coup- !! ling of concentration in (N,M,K) !! with layer concentration in (N,M-2,K) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: bdx !! Internal work array, implicit coup- !! ling of concentration in (N,M,K) !! with layer concentration in (N,M-1,K) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: buuux !! Internal work array, implicit coup- !! ling of concentration in (N,M,K) !! with layer concentration in (N,M+3,K) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: buux !! Internal work array, implicit coup- !! ling of concentration in (N,M,K) !! with layer concentration in (N,M+2,K) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: bux !! Internal work array, implicit coup- !! ling of concentration in (N,M,K) !! with layer concentration in (N,M+1,K) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: cck !! Internal work array (in CUCNP & UZD) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax+2) :: dicuv ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: dsdeta ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: dsdksi ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: dtdeta ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: dtdksi ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: areau real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: areav real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: qxk ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: qyk ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: rscale ! Internal work array, row scaling parameter in difu real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: volum0 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: volum1 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: uvdwk !! Internal work array for Jac.iteration real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: vvdwk !! Internal work array for Jac.iteration real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax, lstsci) :: aakl !! Internal work array, lower diagonal !! tridiagonal matrix, implicit coupling !! of concentration in (N,M,K) with con- !! centration in (N,M,K-1) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax, lstsci) :: bbkl !! Internal work array, main diagonal !! tridiagonal matrix, implicit coupling !! of concentration in (N,M,K) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax, lstsci) :: cckl !! Internal work array, upper diagonal !! tridiagonal matrix, implicit coupling !! of concentration in (N,M,K) with con- !! centration in (N,M,K+1) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax, lstsci) :: ddkl !! Internal work array, diagonal space !! at (N,M,K,L) real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax, lstsci) :: r0 ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax, lstsci) :: r1 ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax, lstsci) :: sink ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax, lstsci) :: sour ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(kmax) :: sig ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(kmax) :: thick ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(kmax, max(lstsc, 1), 2, norow) , intent(in) :: rbnd ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(lstsci) :: sigdif ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(lstsci) , intent(in) :: sigmol ! Description and declaration in esm_alloc_real.f90 ! ! Local variables ! integer :: nmsta integer :: ddb integer :: iad1 integer :: iad2 integer :: iad3 integer :: ic integer :: icxy integer :: iter integer :: itr integer :: j1 integer :: j2 integer :: j3 integer :: jj integer :: k integer :: kfw integer :: l integer :: ll integer :: ls integer :: lst integer :: maskval integer :: mf integer :: ml integer :: n integer :: ndm integer :: nhystp integer :: nm integer :: nmd integer :: nmdd integer :: nmf integer :: nmfu integer :: nml integer :: nmlu integer, dimension(10) :: nms integer :: nmu integer :: nmuu integer :: nnudge integer :: num real(fp) :: adza real(fp) :: adzc real(fp) :: bi real(fp) :: cl real(fp) :: cr real(fp) :: d0k ! Internal work array real(fp) :: ddzc real(fp) :: difiwe real(fp) :: difl real(fp) :: difr real(fp) :: diz1 real(fp) :: epsitr ! Maximum value of relative error and absolute error of iteration process real(fp) :: flux real(fp) :: h0 real(fp) :: h0i real(fp) :: h0new real(fp) :: h0old real(fp), dimension(10) :: mu real(fp) :: nudgefac real(fp) :: qxu real(fp) :: qyv real(fp) :: qzw real(fp) :: rb real(fp), external :: reddic real(fp) :: rp real(fp) :: sqrtbv real(fp) :: timesti ! inverse of time step real(fp) :: tnudge real(fp) :: tsg character(20) :: errtxt integer :: nm_pos ! indicating the array to be exchanged has nm index at the 2nd place, e.g., dbodsd(lsedtot,nm) ! !! executable statements ------------------------------------------------------- ! eps => gdp%gdconst%eps vicmol => gdp%gdphysco%vicmol dicoww => gdp%gdphysco%dicoww iro => gdp%gdphysco%iro xlo => gdp%gdturcoe%xlo ck => gdp%gdturcoe%ck mfg => gdp%gdparall%mfg nfg => gdp%gdparall%nfg nudge => gdp%gdnumeco%nudge hdt => gdp%gdnumeco%hdt ! ! INITIALISATION ! ddb = gdp%d%ddbound icxy = max(icx, icy) nm_pos = 1 ! ! INITIALIZE ! call timer_start(timer_difu_ini, gdp) ! ! Initialise arrays aak - cck for all (nm,k) ! aak = 0.0_fp buuux = 0.0_fp buux = 0.0_fp bux = 0.0_fp bdx = 0.0_fp bddx = 0.0_fp bdddx = 0.0_fp cck = 0.0_fp ! timesti = 1.0_fp / timest do k = 1, kmax do nm = 1, nmmax if (kfs(nm) == 1) then bbk(nm, k) = volum1(nm, k) * timesti else bbk(nm, k) = 1.0_fp if (lsec > 0) r0(nm, k, lsecfl) = 0.0_fp endif enddo enddo do l = 1, lstsci if (lsec==2 .and. l==lsecfl) then cycle endif do k = 1, kmax do nm = 1, nmmax if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then ddkl(nm, k, l) = volum0(nm, k) * r0(nm, k, l) * timesti else ddkl(nm, k, l) = r0(nm, k, l) endif enddo enddo enddo call timer_stop(timer_difu_ini, gdp) ! ! CONTRIBUTION OF ADVECTION IN X-DIRECTION ! call timer_start(timer_difu_horadv, gdp) do k = 1, kmax ! ! CONTRIBUTION TO VOLUME NM AND NMU ! nmd = -icx nmdd = -icx - icx nmu = icx nmuu = icx + icx do nm = 1, nmmax nmd = nmd + 1 nmdd = nmdd + 1 nmu = nmu + 1 nmuu = nmuu + 1 qxu = qxk(nm, k)/6.0_fp if (qxu > 0.0) then iad1 = kfu(nm) *kadu(nm, k) iad2 = iad1*kfu(nmd) *kadu(nmd, k) iad3 = iad2*kfu(nmdd)*kadu(nmdd, k) ! j1 = 6*iad1 + 3*iad2 + iad3 j2 = - 3*iad2 - 2*iad3 j3 = iad3 ! bbk (nm , k) = bbk (nm , k) + qxu*j1 bdx (nm , k) = bdx (nm , k) + qxu*j2 bddx (nm , k) = bddx (nm , k) + qxu*j3 bdx (nmu, k) = bdx (nmu, k) - qxu*j1 bddx (nmu, k) = bddx (nmu, k) - qxu*j2 bdddx(nmu, k) = bdddx(nmu, k) - qxu*j3 else iad1 = kfu(nm) * kadu(nm , k) iad2 = iad1 * kfu(nmu) * kadu(nmu , k) iad3 = iad2 * kfu(nmuu) * kadu(nmuu, k) ! j1 = 6*iad1 + 3*iad2 + iad3 j2 = - 3*iad2 - 2*iad3 j3 = iad3 ! bux (nm , k) = bux (nm , k) + qxu*j1 buux (nm , k) = buux (nm , k) + qxu*j2 buuux(nm , k) = buuux(nm , k) + qxu*j3 bbk (nmu, k) = bbk (nmu, k) - qxu*j1 bux (nmu, k) = bux (nmu, k) - qxu*j2 buux (nmu, k) = buux (nmu, k) - qxu*j3 endif enddo enddo ! ! CONTRIBUTION OF ADVECTION IN Y-DIRECTION ! do l = 1, lstsci if (lsec==2 .and. l==lsecfl) then cycle endif do k = 1, kmax ! ! CONTRIBUTION TO VOLUME NM AND NUM ! ndm = -icy num = icy do nm = 1, nmmax ndm = ndm + 1 num = num + 1 qyv = qyk(nm, k) iad1 = kfv(nm)*kadv(nm, k) iad2 = iad1*kfv(num)*kadv(num, k)*kfv(ndm)*kadv(ndm, k) if (qyv > 0.0_fp) then d0k = 0.5_fp*qyv*( (2*iad1 - iad2)*r0(nm , k, l) & & + iad2 *r0(num, k, l)) else d0k = 0.5_fp*qyv*( (2*iad1 - iad2)*r0(num, k, l) & & + iad2 *r0(nm , k, l)) endif if (kcs(nm) == 1) ddkl(nm , k, l) = ddkl(nm , k, l) - d0k if (kcs(num) == 1) ddkl(num, k, l) = ddkl(num, k, l) + d0k enddo enddo enddo call timer_stop(timer_difu_horadv, gdp) ! ! ! Explicit algoritm (call DIFACR) leads to extra stablity criterium ! DT <= (DX**2)/(2*DICUV) ! ! This diffusion part (loop 410) is constituent independent. ! The value of SIGDIF(L) = 0.7 (see TKECOF) for all LSTSCI ! call timer_start(timer_difu_hordiff, gdp) if (icreep==0 .or. kmax==1) then ! ! HORIZONTAL DIFFUSION IN X-DIRECTION ALONG SIGMA PLANES ! do k = 1, kmax ! ! CONTRIBUTION TO VOLUME NM AND NMU ! nmu = icx do nm = 1, nmmax nmu = nmu + 1 if (kfu(nm)*kadu(nm, k) /= 0) then difl = dicuv(nm, k) difr = dicuv(nmu, k) flux = 0.5*(difl + difr)/(0.7*gvu(nm)) maskval = max(0, 2 - abs(kcs(nm))) bbk(nm, k) = bbk(nm, k) + areau(nm, k)*flux*maskval bux(nm, k) = bux(nm, k) - areau(nm, k)*flux*maskval maskval = max(0, 2 - abs(kcs(nmu))) bbk(nmu, k) = bbk(nmu, k) + areau(nm, k)*flux*maskval bdx(nmu, k) = bdx(nmu, k) - areau(nm, k)*flux*maskval endif enddo enddo ! ! HORIZONTAL DIFFUSION IN Y-DIRECTION ALONG SIGMA PLANES ! do l = 1, lstsci if (lsec==2 .and. l==lsecfl) then cycle endif do k = 1, kmax ! ! CONTRIBUTION TO VOLUME NM AND NUM ! num = icy do nm = 1, nmmax num = num + 1 if (kfv(nm)*kadv(nm, k) /= 0) then cl = r0(nm, k, l) difl = dicuv(nm, k) cr = r0(num, k, l) difr = dicuv(num, k) flux = 0.5_fp*(cr - cl)*(difl + difr)/(0.7*guv(nm)) maskval = max(0, 2 - abs(kcs(nm))) ddkl(nm, k, l) = ddkl(nm, k, l) + areav(nm, k)*flux*maskval maskval = max(0, 2 - abs(kcs(num))) ddkl(num, k, l) = ddkl(num, k, l) - areav(nm, k)*flux*maskval endif enddo enddo enddo else ! ! Explicit algoritm (call DIFACR) leads to extra stablity criterium ! dt <= (dx**2)/(2*dicuv) ! ! HORIZONTAL DIFFUSION ALONG Z-PLANES (only if KMAX > 1 and Anti Creep) ! call difacr(icx ,icy ,j ,nmmaxj ,nmmax , & & kmax ,lstsci ,lsal ,ltem ,kcs , & & kfu ,kfv ,kadu ,kadv ,s0 , & & dps ,r0 ,ddkl ,guu ,gvv , & & guv ,gvu ,thick ,sig ,dicuv , & & sigdif ,dsdksi ,dtdksi ,dsdeta ,dtdeta , & & gdp ) endif call timer_stop(timer_difu_hordiff, gdp) call timer_start(timer_difu_vertadv, gdp) if (kmax > 1) then do k = 1, kmax - 1 if (k==1 .or. k==kmax - 1) then kfw = 1 else kfw = 0 endif do nm = 1, nmmax ! ! ADVECTION IN VERTICAL DIRECTION; W*DC/DZ ! if (kfs(nm) == 1) then qzw = qzk(nm, k) if (qzw > 0.0) then adza = 0.5_fp*qzw*(1 - kfw) adzc = 0.5_fp*qzw*(1 + kfw) else adza = 0.5_fp*qzw*(1 + kfw) adzc = 0.5_fp*qzw*(1 - kfw) endif aak(nm, k + 1) = aak(nm, k + 1) + adza bbk(nm, k + 1) = bbk(nm, k + 1) + adzc bbk(nm, k ) = bbk(nm, k ) - adza cck(nm, k ) = cck(nm, k ) - adzc endif enddo enddo endif do l = 1, lstsci if (lsec==2 .and. l==lsecfl) then cycle endif do k = 1, kmax do nm = 1, nmmax aakl(nm, k, l) = aak(nm, k) bbkl(nm, k, l) = bbk(nm, k) cckl(nm, k, l) = cck(nm, k) enddo enddo enddo call timer_stop(timer_difu_vertadv, gdp) ! ! DIFFUSION IN VERTICAL DIRECTION ! call timer_start(timer_difu_vertdiff, gdp) if (kmax > 1) then do l = 1, lstsci ! ! l = sediment: ls > 0 ! else : ls = 0 ! ls = 0 if ((l>max(lsal, ltem)) .and. (l<=lsts)) ls = l - max(lsal, ltem) do k = 1, kmax - 1 tsg = 0.5_fp * (thick(k) + thick(k+1)) do nm = 1, nmmax if (kfs(nm) == 1) then h0 = max(0.1_fp, s0(nm) + real(dps(nm),fp)) h0i = 1.0_fp / h0 ! ! Internal wave contribution ! sqrtbv = max(0.0_fp, bruvai(nm, k)) sqrtbv = sqrt(sqrtbv) difiwe = 0.2_fp * sqrtbv * xlo**2 if (ls > 0) then ! ! sediment constituent: ! No dicoww-restriction in reddic ! diz1 = vicmol/sigmol(l) + difiwe + seddif(nm, k, ls)/sigdif(l) else ! ! all other constituents: ! dicoww-restriction is moved from TURCLO to here (in reddic) ! vicww is used instead of dicww ! diz1 = vicmol/sigmol(l) + reddic(difiwe + vicww(nm,k)/sigdif(l), gdp) endif ddzc = gsqs(nm) * diz1 * h0i / tsg aakl(nm, k+1, l) = aakl(nm, k+1, l) - ddzc bbkl(nm, k+1, l) = bbkl(nm, k+1, l) + ddzc bbkl(nm, k , l) = bbkl(nm, k , l) + ddzc cckl(nm, k , l) = cckl(nm, k , l) - ddzc endif enddo enddo enddo endif call timer_stop(timer_difu_vertdiff, gdp) ! ! Include settling velocities and Dirichlet BC for sediments in ! matrices AAKL/BBKL/CCKL/DDKL ! if (lsed > 0) then call timer_start(timer_difu_difws, gdp) call dif_ws(j ,nmmaxj ,nmmax ,kmax ,lsal , & & ltem ,lstsci ,lsed ,kcs ,kfs , & & gsqs ,ws ,aakl ,bbkl ,cckl , & & gdp ) call timer_stop(timer_difu_difws, gdp) endif ! ! SET VALUES IN OPEN BOUNDARY POINTS (IN PART. FOR Y-DIRECTION) ! On open boundary no seconday flow (=> loop over LSTSC) ! call timer_start(timer_difu_bounopen, gdp) do nm = 1, nmmax if (kcs(nm) == 2) then do l = 1, lstsc do k = 1, kmax ddkl(nm, k, l) = r0(nm, k, l) aakl(nm, k, l) = 0.0_fp bbkl(nm, k, l) = 1.0_fp cckl(nm, k, l) = 0.0_fp enddo enddo endif enddo ! ! BOUNDARY CONDITIONS ! On open boundary no seconday flow (=> loop over LSTSC) ! do ic = 1, norow n = irocol(1, ic) mf = irocol(2, ic) - 1 ml = irocol(3, ic) nmf = (n + ddb)*icy + (mf + ddb)*icx - icxy nml = (n + ddb)*icy + (ml + ddb)*icx - icxy nmfu = nmf + icx nmlu = nml + icx ! ! IMPLEMENTATION OF BOUNDARY CONDITIONS ! if (kcu(nmf) == 1) then do k = 1, kmax do l = 1, lstsc ddkl(nmf, k, l) = rbnd(k, l, 1, ic) enddo enddo endif if (kcu(nml) == 1) then do k = 1, kmax do l = 1, lstsc ddkl(nmlu, k, l) = rbnd(k, l, 2, ic) enddo enddo endif ! ! optional Neumann boundary condition for suspended sediment fractions ! lst = max(lsal, ltem) do l = 1, lsed ll = lst + l if ((eqmbcsand .and. sedtyp(l) == SEDTYP_NONCOHESIVE_SUSPENDED) .or. & & (eqmbcmud .and. sedtyp(l) == SEDTYP_COHESIVE) ) then if (kcu(nmf) == 1) then do k = 1, kmax ddkl(nmf, k, ll) = max(0.0_fp, r0(nmfu, k, ll)) enddo endif if (kcu(nml) == 1) then do k = 1, kmax ddkl(nmlu, k, ll) = max(0.0_fp, r0(nml, k, ll)) enddo endif endif enddo enddo call timer_stop(timer_difu_bounopen, gdp) do l = 1, lstsci ! ! SOURCES AND SINK TERMS ! ! SINKS ARE TREATED IMPLICITLY ! call timer_start(timer_difu_sourcesink, gdp) if (lsec==2 .and. l==lsecfl) then ! ! secondary flow (equilibrium equals to new intensity) ! start-up problems SINK might be 0.0 when ! UMOD = 0.0 in SECRHS ! do k = 1, kmax do nm = 1, nmmax if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then h0new = s1(nm) + real(dps(nm),fp) if (abs(sink(nm,k,l)*h0new) > eps) then h0old = s0(nm) + real(dps(nm),fp) r1(nm, k, l) = sour(nm, k, l)*h0old/(sink(nm, k, l)*h0new) else r1(nm, k, l) = 0.0_fp endif endif enddo enddo else do k = 1, kmax do nm = 1, nmmax if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then bbkl(nm, k, l) = bbkl(nm, k, l) + sink(nm, k, l)*volum1(nm, k) ddkl(nm, k, l) = ddkl(nm, k, l) + sour(nm, k, l)*volum0(nm, k) endif enddo enddo ! ! set concentrations in dry points and in open boundary points ! do k = 1, kmax do nm = 1, nmmax if ((kfs(nm)==0 .and. kcs(nm)==1) .or. kcs(nm)==2) then r1(nm, k, l) = ddkl(nm, k, l) endif enddo enddo endif call timer_stop(timer_difu_sourcesink, gdp) ! if (l == lsecfl) then ! ! boundary conditions secondary flow (spiral motion intensity) ! call timer_start(timer_difu_secbou, gdp) call secbou(j ,nmmaxj ,kmax ,icx ,icy , & & lstsci ,lsecfl ,kfu ,irocol ,norow , & & s0 ,s1 ,dps ,r1 ,sour , & & sink ,gdp ) call timer_stop(timer_difu_secbou, gdp) if (lsec == 2) then ! ! exchange r1 with neighbours for parallel runs ! call dfexchg ( r1(:,:,l), 1, kmax, dfloat, nm_pos, gdp ) ! cycle endif endif ! ! DD code added: ! ! left hand-side is now set by Delft3D-FLOW instead of the mapper ! call timer_start(timer_difu_lhs, gdp) do nm = 1, nmmax if (kcs(nm) == 3 ) then do k = 1, kmax aakl(nm,k,l) = 0.0_fp bbkl(nm,k,l) = 1.0_fp cckl(nm,k,l) = 0.0_fp ddkl(nm,k,l) = r0(nm,k,l) enddo endif enddo call timer_stop(timer_difu_lhs, gdp) ! ! ! D3dFlow_Build_ADI_Conc: poke the coupling equations into system ! nhystp = nxtstp(d3dflow_build_adi_conc, gdp) ! ! DD code added end ! !***SCALE ROWS OF MATRIX/RIGHT HAND SIDE VECTOR ! ! Store scale factor in array rscale ! They are used for the constituent independent flux arrays b[d/u][d/u][d/u]x ! call timer_start(timer_difu_rowsc, gdp) do k = 1, kmax do nm = 1, nmmax if (kfs(nm)==1) then rscale(nm, k) = 1.0_fp / bbkl(nm, k, l) aakl (nm, k, l) = aakl(nm, k, l) * rscale(nm, k) bbkl (nm, k, l) = 1.0_fp cckl (nm, k, l) = cckl(nm, k, l) * rscale(nm, k) ddkl (nm, k, l) = ddkl(nm, k, l) * rscale(nm, k) endif enddo enddo call timer_stop(timer_difu_rowsc, gdp) ! !***SOLUTION PROCEDURE SYSTEM OF EQUATIONS ! ! Division by the pivot for k=1 is not needed anymore ! because of row scaling ! call timer_start(timer_difu_solve1, gdp) do nm = 1, nmmax if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then do k = 2, kmax bi = 1.0_fp/(bbkl(nm, k, l) - aakl(nm, k, l)*cckl(nm, k - 1, l)) bbkl(nm, k, l) = bi cckl(nm, k, l) = cckl(nm, k, l)*bi enddo endif enddo call timer_stop(timer_difu_solve1, gdp) ! ! ITERATION LOOP ! call timer_start(timer_difu_solve2, gdp) iter = 0 do k = 1, kmax do nm = 1, nmmax if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then r1(nm, k, l) = r0(nm, k, l) uvdwk(nm, k) = r0(nm, k, l) endif enddo enddo call timer_stop(timer_difu_solve2, gdp) ! ! exchange r1 with neighbours for parallel runs ! call dfexchg ( r1(:,:,l), 1, kmax, dfloat, nm_pos, gdp ) ! ! assure that loop starts at point of correct color in own subdomain ! if (mod(mfg+nfg,2) == 1) then ! red points nmsta = 1 else ! black points nmsta = 2 endif ! ! DD code added: ! ! ! (re)solve system of equations ! 111 continue gdp%dd%difuiter = gdp%dd%difuiter + 1 ! ! DD code added end ! 1100 continue iter = iter + 1 ! ! ITERATIVE SOLUTION METHOD USING CHECKERBOARD JACOBI ! IN HORIZONTAL DIRECTION ! itr = 0 ! ! set concentrations in coupling points ! call timer_start(timer_difu_solve3, gdp) do k = 1, kmax do nm = 1, nmmax if (kcs(nm) == 3) then r1(nm, k, l) = ddkl(nm, k, l) endif enddo enddo call timer_stop(timer_difu_solve3, gdp) if(icx == 1) then call timer_start(timer_difu_solve4u, gdp) else call timer_start(timer_difu_solve6v, gdp) end if ! ! loop starts at red or black point depending on own subdomain ! nmsta = 3 - nmsta ! do k = 1, kmax do nm = nmsta, nmmax, 2 ! ! COMPUTE RIGHT HAND SIDE ! ( CHECK FOR KCS TO AVOID AN ARRAY INDEX OUT OF BOUNDS ) ! if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then uvdwk(nm, k) = bdddx(nm, k) * r1(nm - icx - icx - icx, k, l) & & + bddx (nm, k) * r1(nm - icx - icx, k, l) & & + bdx (nm, k) * r1(nm - icx, k, l) & & + bux (nm, k) * r1(nm + icx, k, l) & & + buux (nm, k) * r1(nm + icx + icx, k, l) & & + buuux(nm, k) * r1(nm + icx + icx + icx, k, l) uvdwk(nm, k) = ddkl(nm, k, l) - rscale(nm, k)*uvdwk(nm, k) endif enddo enddo if(icx == 1) then call timer_stop(timer_difu_solve4u, gdp) call timer_start(timer_difu_solve5u, gdp) else call timer_stop(timer_difu_solve6v, gdp) call timer_start(timer_difu_solve7v, gdp) end if do nm = nmsta, nmmax, 2 if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then vvdwk(nm, 1) = uvdwk(nm, 1)*bbkl(nm, 1, l) endif enddo do k = 2, kmax do nm = nmsta, nmmax, 2 if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then vvdwk(nm,k) = (uvdwk(nm,k) - aakl(nm,k,l)*vvdwk(nm,k-1)) * bbkl(nm,k,l) endif enddo enddo do k = kmax - 1, 1, -1 do nm = nmsta, nmmax, 2 if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then vvdwk(nm, k) = vvdwk(nm, k) - cckl(nm, k, l) *vvdwk(nm, k + 1) endif enddo enddo ! ! CHECK FOR CONVERGENCE ! do k = 1, kmax do nm = nmsta, nmmax, 2 if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then epsitr = max(1.e-8_fp, 0.5e-3*abs(r1(nm, k, l))) if (abs(vvdwk(nm, k) - r1(nm, k, l)) > epsitr) itr = 1 r1(nm, k, l) = vvdwk(nm, k) endif enddo enddo if(icx == 1) then call timer_stop(timer_difu_solve5u, gdp) call timer_start(timer_difu_solve4u, gdp) else call timer_stop(timer_difu_solve7v, gdp) call timer_start(timer_difu_solve6v, gdp) end if ! call dfexchg ( r1(:,:,l), 1, kmax, dfloat, nm_pos, gdp ) ! ! loop starts at point of other color now (black respectively red) ! nmsta = 3 - nmsta ! do k = 1, kmax do nm = nmsta, nmmax, 2 ! ! COMPUTE RIGHT HAND SIDE ! if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then uvdwk(nm, k) = bdddx(nm, k) * r1(nm - icx - icx - icx, k, l) & & + bddx (nm, k) * r1(nm - icx - icx, k, l) & & + bdx (nm, k) * r1(nm - icx, k, l) & & + bux (nm, k) * r1(nm + icx, k, l) & & + buux (nm, k) * r1(nm + icx + icx, k, l) & & + buuux(nm, k) * r1(nm + icx + icx + icx, k, l) uvdwk(nm, k) = ddkl(nm, k, l) - rscale(nm, k)*uvdwk(nm, k) endif enddo enddo if(icx == 1) then call timer_stop(timer_difu_solve4u, gdp) call timer_start(timer_difu_solve5u, gdp) else call timer_stop(timer_difu_solve6v, gdp) call timer_start(timer_difu_solve7v, gdp) end if do nm = nmsta, nmmax, 2 if (kfs(nm)==1 .and. kcs(nm) == 1) then vvdwk(nm, 1) = uvdwk(nm, 1)*bbkl(nm, 1, l) endif enddo do k = 2, kmax do nm = nmsta, nmmax, 2 if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then vvdwk(nm, k) = (uvdwk(nm,k) - aakl(nm,k,l)*vvdwk(nm,k-1)) * bbkl(nm,k,l) endif enddo enddo do k = kmax - 1, 1, -1 do nm = nmsta, nmmax, 2 if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then vvdwk(nm, k) = vvdwk(nm, k) - cckl(nm, k, l) *vvdwk(nm, k + 1) endif enddo enddo ! ! CHECK FOR CONVERGENCE ! do k = 1, kmax do nm = nmsta, nmmax, 2 if ( (kfs(nm)==1) .and. (kcs(nm)==1) ) then epsitr = max(1.e-8_fp, 0.5e-3*abs(r1(nm, k, l))) if (abs(vvdwk(nm, k) - r1(nm, k, l)) > epsitr) itr = 1 r1(nm, k, l) = vvdwk(nm, k) endif enddo enddo if(icx == 1) then call timer_stop(timer_difu_solve5u, gdp) else call timer_stop(timer_difu_solve7v, gdp) end if call dfexchg ( r1(:,:,l), 1, kmax, dfloat, nm_pos, gdp ) ! ! determine global maximum of 'itr' over all nodes ! Note: this enables to synchronize the iteration process ! call dfreduce_gdp( itr, 1, dfint, dfmax, gdp ) ! if (itr>0 .and. iter<50) goto 1100 ! if (gdp%gdflwpar%flwoutput%iteroutputsteps >= gdp%gdinttim%ntstep) then write (lundia, '(3(a,i0))') 'difu(ntstep,l,iter):',gdp%gdinttim%ntstep, ' ', l, ' ',iter endif if (iter >= 50) then write (errtxt, '(i0,a,i0)') l, ' ', nst call prterr(lundia ,'S206' ,trim(errtxt) ) endif ! ! DD code added: ! ! ! D3dFlow_Solve_ADI_Conc: Check for convergence ! nhystp = nxtstp(d3dflow_solve_adi_conc, gdp) if (nhystp == d3dflow_solve_adi_conc) goto 111 ! ! DD code added end ! ! Nudging of constituents at open boundaries ! if (nudge==1) then ! Nudging layer nnudge = 4 nudgefac = 10.0_fp tnudge = hdt mu(1) = max(hdt / tnudge, 1.0_fp) do jj = 2, nnudge mu(jj) = mu(jj-1) / nudgefac enddo ! do nm = 1, nmmax nmu = nm + icx nmd = nm - icx if (kcs(nmd) == 2 .and. kcs(nm) == 1 ) then nms(1) = nm do jj = 2, nnudge nms(jj) = nms(jj-1) + icx enddo do jj = 1, nnudge do k = 1, kmax if (r1(nmd, k, l )>1.0e-6) then rb = r1(nmd, k, l ) rp = r1(nms(jj), k, l) r1(nms(jj), k, l) = rp + mu(jj)*(rb-rp) r0(nms(jj), k, l) = r1(nms(jj), k, l) endif enddo enddo endif if (kcs(nmu) == 2 .and. kcs(nm) == 1) then nms(1) = nm do jj = 2, nnudge nms(jj) = nms(jj-1) - icx enddo do jj = 1, nnudge do k = 1, kmax if (r1(nmu, k, l )>1.0e-6) then rb = r1(nmu, k, l ) rp = r1(nms(jj), k, l) r1(nms(jj), k, l) = rp + mu(jj)*(rb-rp) r0(nms(jj), k, l) = r1(nms(jj), k, l) endif enddo enddo endif enddo endif ! enddo end subroutine difu
{"hexsha": "1d7ca2ec6776a1f20d8beeff045e7dabc98a884c", "size": 49066, "ext": "f90", "lang": "FORTRAN", "max_stars_repo_path": "docker/water/delft3d/tags/v6686/src/engines_gpl/flow2d3d/packages/kernel/src/compute/difu.f90", "max_stars_repo_name": "liujiamingustc/phd", "max_stars_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-06T03:01:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:02:55.000Z", "max_issues_repo_path": "docker/water/delft3d/tags/v6686/src/engines_gpl/flow2d3d/packages/kernel/src/compute/difu.f90", "max_issues_repo_name": "liujiamingustc/phd", "max_issues_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docker/water/delft3d/tags/v6686/src/engines_gpl/flow2d3d/packages/kernel/src/compute/difu.f90", "max_forks_repo_name": "liujiamingustc/phd", "max_forks_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3475046211, "max_line_length": 136, "alphanum_fraction": 0.4258549709, "num_tokens": 13986}
from vpython import * from cubes.configs import * from cubes.cube import * from cubes.util import * from time import time import numpy as np def smooth_step(x): """ Smooth interpolation function """ return 0.5 - np.cos(x * pi) / 2 class Cube3D(Cube): """ Initialize the cube structure Shuffle and copy the cube if necessary Initialize cubes for the 3D representation """ def __init__(self, cube_dict=solved_cube_dict, shuffle=False, n_shuffles=200, record=False, do_copy=False, fps=fps_def, move_time=move_time_def, wait_time=wait_time_def, colors_dict=colors_dict_def): super().__init__(cube_dict, shuffle, n_shuffles, record, do_copy) # Initialize boxes self.base_box_list = [] self.box_dict, self.base_box_dict = self.init_graphics_cube(colors_dict) # New cube to store and rotate the box objects self.box_cube = Cube(self.box_dict, shuffle=False, do_copy=False) # Visual parameters self.fps = fps self.move_time = move_time self.wait_time = wait_time """ Create all the boxes necessary to represent the cube """ def init_graphics_cube(self, colors_dict=colors_dict_def): cube_dict = self.cube_dict box_dict = {} base_box_dict = {dir_name: [] for dir_name in direction_names} # For each face for face_name, dir in direction_dict.items(): face_dict = {} # For each piece of the face for box_name in cube_dict[face_name]: box_face_list = [] # Compute the offset of the piece v = dir if box_name != face_name: for c in box_name: v = v + direction_dict[c] # For each sticker in the piece for i, box_face_type in enumerate(cube_dict[face_name][box_name]): # Get the name of the sticker if i == 0: box_face_name = face_name else: box_face_name = box_name[i - 1] # Create a cube for the sticker box_obj = box(pos=v + direction_dict[box_face_name] * box_height, length=1 - box_margin, height=1 - box_margin, width=1 - box_margin, color=colors_dict[box_face_type]) box_face_list.append(box_obj) face_dict[box_name] = box_face_list # Create a base cube for the piece base_box = box( pos=v, length=1, height=1, width=1, color=base_color) # Store this base cube self.base_box_list.append(base_box) for dir_name in direction_names: if dir_name in face_name + box_name: base_box_dict[dir_name].append(base_box) box_dict[face_name] = face_dict return box_dict, base_box_dict """ Make the appropriate animation for the given move """ def move(self, move, n=1, record=True, step_func=smooth_step): super().move(move, n, record) # Prepare arguments if type(move) == tuple: move, n = move n %= 4 if n == 0 or not record: return # Prepare variables cubes = self.get_cubes_from_move(move) base_cubes = self.get_base_cubes_from_move(move) axis = direction_dict[move[0]] t0, rotated = time(), 0 t = n if n <= 2 else -1 # Animate all cubes while time() - t0 <= self.move_time * np.abs(t): rate(self.fps) rotation = pi / 2 * step_func((time() - t0) / self.move_time / t) * t for cube in cubes + base_cubes: cube.rotate( angle=rotation - rotated, axis=axis, origin=vector(0, 0, 0) ) rotated = rotation # Finish rotation rotation = pi / 2 * t for cube in cubes: cube.rotate( angle=rotation - rotated, axis=axis, origin=vector(0, 0, 0) ) # Undo base rotations for cube in base_cubes: cube.rotate( angle=-rotated, axis=axis, origin=vector(0, 0, 0) ) # Wait t0 = time() while time() - t0 < self.wait_time: rate(self.fps) # Update graphics cube self.box_cube.move(move, n, record) """ Return a list of the cubes that should rotate on a given move """ def get_cubes_from_move(self, move): c = self.box_cube.cube_dict if move == "U" or move == "D": c = self.box_cube.cube_dict[move] return c["F"] + c["R"] + c["B"] + c["L"] + c[move] + c["FR"] + c["RB"] + c["BL"] + c["LF"] elif move == "F": return c["U"]["F"] + c["L"]["F"] + c["D"]["F"] + c["F"]["R"] + \ c["U"]["LF"] + c["D"]["LF"] + c["D"]["FR"] + c["U"]["FR"] + c[move][move] elif move == "R": return c["U"]["R"] + c["F"]["R"] + c["D"]["R"] + c["R"]["B"] + \ c["U"]["FR"] + c["D"]["FR"] + c["D"]["RB"] + c["U"]["RB"] + c[move][move] elif move == "B": return c["U"]["B"] + c["R"]["B"] + c["D"]["B"] + c["B"]["L"] + \ c["U"]["RB"] + c["D"]["RB"] + c["D"]["BL"] + c["U"]["BL"] + c[move][move] elif move == "L": return c["U"]["L"] + c["B"]["L"] + c["D"]["L"] + c["L"]["F"] + \ c["U"]["BL"] + c["D"]["BL"] + c["D"]["LF"] + c["U"]["LF"] + c[move][move] elif move == "UD": return c["F"]["R"] + c["R"]["B"] + c["B"]["L"] + c["L"]["F"] + \ c["F"]["F"] + c["R"]["R"] + c["B"]["B"] + c["L"]["L"] elif move == "FB": return c["U"]["L"] + c["D"]["L"] + c["D"]["R"] + c["U"]["R"] + \ c["U"]["U"] + c["L"]["L"] + c["D"]["D"] + c["R"]["R"] elif move == "RL": return c["U"]["F"] + c["D"]["F"] + c["D"]["B"] + c["U"]["B"] + \ c["U"]["U"] + c["F"]["F"] + c["D"]["D"] + c["B"]["B"] else: all_stickers = [] for k in c: for kk in c[k]: if type(c[k][kk]) is list: all_stickers += c[k][kk] else: all_stickers.append(c[k][kk]) return all_stickers """ Return a list of the base cubes that should rotate on a given move """ def get_base_cubes_from_move(self, move): if len(move) == 1: return self.base_box_dict[move] elif move[0] != move[1]: return [cube for cube in self.base_box_list if cube not in self.base_box_dict[move[0]] and cube not in self.base_box_dict[move[1]]] else: return self.base_box_dict["U"] + self.base_box_dict["D"] + self.get_base_cubes_from_move("UD")
{"hexsha": "86e7168fb5792e92bab81e59daa74a183d8ba426", "size": 7397, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/cubes/cube_3d.py", "max_stars_repo_name": "pabloqb2000/py-rubik_solver", "max_stars_repo_head_hexsha": "c1cf83fa62b6ff0dce9859fe59296c85a57f8d3f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-09-11T14:44:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T00:51:02.000Z", "max_issues_repo_path": "src/cubes/cube_3d.py", "max_issues_repo_name": "pabloqb2000/py-rubik_solver", "max_issues_repo_head_hexsha": "c1cf83fa62b6ff0dce9859fe59296c85a57f8d3f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cubes/cube_3d.py", "max_forks_repo_name": "pabloqb2000/py-rubik_solver", "max_forks_repo_head_hexsha": "c1cf83fa62b6ff0dce9859fe59296c85a57f8d3f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-12T02:29:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-18T13:39:46.000Z", "avg_line_length": 36.6188118812, "max_line_length": 110, "alphanum_fraction": 0.4659997296, "include": true, "reason": "import numpy", "num_tokens": 1847}
[STATEMENT] lemma ZfunD: "Zfun f F \<Longrightarrow> 0 < r \<Longrightarrow> eventually (\<lambda>x. norm (f x) < r) F" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>Zfun f F; 0 < r\<rbrakk> \<Longrightarrow> \<forall>\<^sub>F x in F. norm (f x) < r [PROOF STEP] by (simp add: Zfun_def)
{"llama_tokens": 123, "file": null, "length": 1}
#!/usr/bin/env python # coding: utf-8 import numpy as np import pandas as pd import tempfile import argparse import os from tabulate import tabulate import pickle header = '''data_nef_MELD_{} save_nef_nmr_meta_data _nef_nmr_meta_data.sf_category nef_nmr_meta_data _nef_nmr_meta_data.sf_framecode nef_nmr_meta_data _nef_nmr_meta_data.format_name nmr_exchange_format _nef_nmr_meta_data.format_version 1.1 _nef_nmr_meta_data.program_name MELD-NEF _nef_nmr_meta_data.program_version 1.0 _nef_nmr_meta_data.creation_date 2020-03-31 _nef_nmr_meta_data.uuid MELD-NEF_2020-03-31 _nef_nmr_meta_data.coordinate_file_name . loop_ _nef_program_script.program_name _nef_program_script.script_name MELD MELD-NEF stop_ save_ ''' def parse_args(): #in line argument parser with help ''' Parse arguments for the program from command line ''' parser = argparse.ArgumentParser() parser.add_argument('-nef', type=str, help='NEF input file') parser.add_argument('-out', type=str, help='NEF output file name',default='MELD.nef') parser.add_argument('-directory', type=str, help='Where to place the files',default='.') return(parser.parse_args()) class NEF_system: '''This will be an object keeping track of all the blocks that compose the NEF file. We will have a list telling us block orders and a dictionary to map to each block''' def __init__(self, filename, directory): '''Start the system keeping track of the original file and processing all blocks inside''' self.block_order = [] self.block_content = {} self.block_types = {} self.active = [] self.original_file = filename self.directory = directory self.get_blocks(filename) def add_block(self,block): '''Given a block object, we insert it into the global NEF system''' if block.name: block_naming = "_".join([block.type,block.name]) else: block_naming = block.type self.block_order.append(block_naming) self.block_content[block_naming] = block try: self.block_types[block.type].append(block) except: self.block_types[block.type] = [block] def get_blocks(self,file_name): '''open a nef file and get the blocks from the file. Input: a string as file name. Return: a list of all the blocks(also a list). In one block list, lines are elements in the list. ''' all_blocks = [] block = [] logic = False with open(file_name, 'r') as fin: for line in fin: line_strip = '{}\n'.format(line.strip()) if 'save_\n' in line_strip: logic = False self.add_block(NEF_block(block)) block = [] if 'save_nef_' in line_strip: logic = True if logic: block.append(line_strip) def write(self,file_name='MELD_test1.nef'): '''write the whole NEF pipeline. The first block will change from whatever we were given to know that it has been hadnled by our MELD pipeline. For all other blocks, we will only print the ones that are active. If no block has been set as active, it should print all''' txt = "" txt += header.format(file_name) if len(self.active) < 1: self.active = self.block_order[1:] for block_name in self.active: #update the output object self.block_content[block_name].write() #and set it to our txt txt += self.block_content[block_name].output txt += ' save_\n' with open(file_name,'w') as fo: fo.write(txt) def sequence(self): '''NEF.block_content['molecular_system'].loop_type_data['_nef_sequence'] This has a pandas kind of structure. index/chain/sequence/residue/linking/residue/cis ''' data = self.block_content['molecular_system'].loop_type_data['_nef_sequence'] chains = data.chain_code.unique() self.chains = chains self.sequence = {} self.sequence_names = [] for chain in chains: residues = data.residue_name[data.chain_code == chain].values # Add caps. This will fail if not a protein. TODO: make more general residues[0] = 'N{}'.format(residues[0]) residues[-1] = 'C{}'.format(residues[-1]) with open('{}/sequence_{}.dat'.format(self.directory,chain),'w') as fo: fo.write(" ".join(residues)) fo.write("\n") self.sequence['sequence_{}'.format(chain)] = " ".join(residues) self.sequence_names.append('sequence_{}'.format(chain)) class NEF_block: '''Each block is refered to by the save_nef_[type]_[name] keyworkd. Inside the block each _nef_[type] has several attributes. Then some of those attributes have a corresponding loop_ structure, where first the headers of that attribute name are given, and then the information as a table. We want to create the same structure for all blocks''' def __init__(self,block): '''Each block should have the original data before processing. Attributes: _raw: contains the original data type: the type of block we are dealing with name: if present will help distinguish between different blocks with same type attributes: the list of keywords this particular block has. These will effectively be the keys to dictionaries containing such data ''' self._raw = block self.attributes = {} self.attributes_ordered = [] self.loop_type = [] self.loop_type_headers = {} self.loop_type_data = {} self.type = None self.name = None self.header = None self.process_type(block[0].rstrip()) self.block_from_raw() def process_type(self,header): '''Gets the type of data in this block as well as the name for this type if any Will return None otherwise. Block header has this format: save_nef_[type]_[name]''' if ('list' in header): tmp = header.split('list_') self.type = "_".join(tmp[0].split('_')[2:]) + 'list' self.name = tmp[1] elif ('spectrum' in header): tmp = header.split('spectrum_') self.type = "_".join(tmp[0].split('_')[2:]) + 'spectrum' self.name = tmp[1] else: self.type = "_".join(header.split('_')[2:]) self.name = None self.header = header print(self.name,self.type,self.header) def process_attributes(self,data): '''First part of the block. Tells us about the attributes in this block''' for line in data.split('\n'): if self.type in line and not 'save_' in line: result = line.split('{}.'.format(self.type)) result = result[1].split() self.attributes_ordered.append(result[0]) self.attributes[result[0]] = result[1].rstrip() else: # Empty lines pass print(self.type,self.attributes_ordered) def process_loop(self,data): '''Each loop has headers and then values. We will likely create a pandas structure''' headers = [] txt = "" loop_type = None header = None #print('processing loop') for line in data.split('\n'): if '_nef_' in line: [loop_type, header] = line.split('.') headers.append(header) elif line.strip(): #this is the table if ('stop_' or 'save_') in line: pass else: txt += '{}\n'.format(line) else: pass #print(headers) #print(txt) #write a temporary file and read into a pandas data frame with open('tmp.txt','w') as fo: fo.write("{}\n".format(" ".join(headers))) fo.write(txt) self.loop_type.append(loop_type) self.loop_type_headers[loop_type] = headers self.loop_type_data[loop_type] = pd.read_csv('tmp.txt',sep=" ",skipinitialspace=True) def block_from_raw(self): '''Give the initial block structure as specified in the nef file. All blocks start with the header, then the properties in that header, then the tables of data for each specific property (keyword loop_) Will generate one big text and then split into loop regions. The first one has the attributes for this block The next ones (if any) have the table information -- all blocks have at least one loop_ keyword ''' block = "".join(self._raw) data = block.split('loop_') for i,loop in enumerate(data): #print(i) #print(loop) if i < 1: self.process_attributes(loop) else: self.process_loop(loop) def write(self): '''Each block object should be able to write itself. First the attributes, then each loop''' self.output = '{}\n\n'.format(self.header) for attribute in self.attributes_ordered: self.output += ' _nef_{}.{} {}'.format(self.type, attribute, self.attributes[attribute]) self.output += '\n' self.output += '\n' #Now process the loops for loop_type in self.loop_type: self.output += ' loop_\n' #Handle all the headers for loop_header in self.loop_type_headers[loop_type]: self.output += ' {}.{}\n'.format(loop_type,loop_header) self.output += '\n' #Use pandas to write out a formatted table of the data in the loop #Note that we have the formatters option to tells us how to write! formatterslist #If each loop type has a formatting option we just have to define all of them somewhere at the #beginning and then the output will always be exact! #For now i'm just going to do standard formatting self.loop_type_data[loop_type] #prepend 7 white spaces to the data frame self.output += '\n' df = self.loop_type_data[loop_type] df[df.columns[0]] = ' ' + df[df.columns[0]].astype(str) #self.output += df.to_string(header=False, justify='match-parent',index=False) self.output += tabulate(df, showindex=False, tablefmt='plain') #Finish the loop self.output += '\n stop_\n\n' #Finish the block self.output += "\n\n" ''' Example: #This is an example of how to use the block object all_blocks = get_blocks('CCPN_Commented_Example.nef') a = NEF_block(all_blocks[0]) print('loop type: ',a.loop_type) print('loop type headerse',a.loop_type_headers[' _nef_program_script']) print('loop type data', a.loop_type_data[' _nef_program_script']) #This is an example of how to use the NEF_system class, which reads and processes all blocks NEF = NEF_system('CCPN_Commented_Example.nef') #we need the block order to write out file in same order print(NEF.block_order) #This will group all types together in case we want all the noesy for example, and will return a list of the #block objects print(NEF.block_types.keys()) print(NEF.block_content['molecular_system'].loop_type_headers) print(NEF.block_types['distance_restraint_list']) print(NEF.block_content['molecular_system'].loop_type) print(NEF.block_content['molecular_system'].loop_type_headers) print(NEF.block_content['molecular_system'].loop_type_data[' _nef_sequence'].to_string(header=False)) NEF.block_content['molecular_system'].loop_type_data[' _nef_sequence'] NEF.write() for i in NEF.block_content.keys(): print(i,NEF.block_content[i].attributes_ordered) ''' def save_object(obj, filename): with open(filename, 'wb') as output: # Overwrites any existing file. pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) def main(): args = parse_args() #Work in a temporary directory if args.directory == '.': args.directory = os.getcwd() with tempfile.TemporaryDirectory() as tmpdirname: os.chdir(tmpdirname) NEF = NEF_system(args.nef,args.directory) print(NEF.block_content['molecular_system'].loop_type_data['_nef_sequence']) NEF.sequence() #Now save the object in a way we can use for MELD save_object(NEF, '{}/{}.pkl'.format(args.directory,args.out)) #And save a NEF file NEF.write(file_name='{}/{}'.format(args.directory,args.out)) if __name__ == '__main__': #Python way to execute main() main()
{"hexsha": "30d7c13ff330b83433c9f4a89eae54e0599628e9", "size": 13294, "ext": "py", "lang": "Python", "max_stars_repo_path": "MELD_NEF_Classes.py", "max_stars_repo_name": "alberto99/MELDNMRParser", "max_stars_repo_head_hexsha": "cabffff5dcb6fbc9ff01446367659d42ce236644", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MELD_NEF_Classes.py", "max_issues_repo_name": "alberto99/MELDNMRParser", "max_issues_repo_head_hexsha": "cabffff5dcb6fbc9ff01446367659d42ce236644", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MELD_NEF_Classes.py", "max_forks_repo_name": "alberto99/MELDNMRParser", "max_forks_repo_head_hexsha": "cabffff5dcb6fbc9ff01446367659d42ce236644", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4219653179, "max_line_length": 116, "alphanum_fraction": 0.6035053408, "include": true, "reason": "import numpy", "num_tokens": 2995}
[STATEMENT] lemma cxt_inv: "\<lbrakk> cxt_to_stmt E c = c' ; \<And> p q. c' \<noteq> Seq p q \<rbrakk> \<Longrightarrow> E = [] \<and> c' = c" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>cxt_to_stmt E c = c'; \<And>p q. c' \<noteq> p ;; q\<rbrakk> \<Longrightarrow> E = [] \<and> c' = c [PROOF STEP] by (metis cxt_to_stmt.simps(1) cxt_to_stmt.simps(2) neq_Nil_conv)
{"llama_tokens": 181, "file": "Dependent_SIFUM_Type_Systems_Language", "length": 1}
import bw2data as bd import numpy as np from scipy.stats import norm import stats_arrays as sa # Local files from .constants import air_molecular_weight, atmosphere_total_mass, substances_data def get_uncertain_flows(time_horizon=100, verbose=False): method = ('IPCC 2013', 'climate change', 'GWP {}a'.format(time_horizon)) bw_method = bd.Method(method) act_names = { bd.get_activity(flow[0])['name'] for flow in bw_method.load() if "Carbon dioxide" not in bd.get_activity(flow[0])['name'] # GWP=1, no uncertainties by definition and "Carbon monoxide" not in bd.get_activity(flow[0])['name'] # Add manually as uniformly distributed and "Nitric oxide" not in bd.get_activity(flow[0])['name'] # Assume not enought data for uncertainties and "VOC" not in bd.get_activity(flow[0])['name'] # Assume not enought data for uncertainties } delta_std_multiplier_dict = {} for i,act_name in enumerate(act_names): _, delta_std_multiplier_dict[act_name] = compute_delta_std_multiplier(act_name, time_horizon, verbose, i + 1) flows_list = [] for flow in bw_method.load(): act = bd.get_activity(flow[0]) if 'Carbon dioxide' in act['name']: flows_list.append(flow) elif 'Carbon monoxide' in act['name']: if ', fossil' in act['name'] or ', from soil or biomass stock' in act['name']: oxidation = 1.5714 elif ', non-fossil' in act['name']: oxidation = 0 gwp_nominal = flow[1] min_ = 2 + oxidation max_ = 3.3 + oxidation flow_uncertain = ( flow[0], # flow key = (database, code) { 'amount': gwp_nominal, 'minimum': min_, 'maximum': max_, 'uncertainty type': sa.UniformUncertainty.id, # assumption from the ipcc report } ) flows_list.append(flow_uncertain) else: try: gwp_nominal = flow[1] ghg_std = gwp_nominal * delta_std_multiplier_dict[act['name']] flow_uncertain = ( flow[0], # flow key = (database, code) { 'amount': gwp_nominal, # static value of gwp 'uncertainty type': sa.NormalUncertainty.id, # assumption from the ipcc report 'loc': gwp_nominal, # mean value that is equal to the static one 'scale': ghg_std, # standard deviation } ) flows_list.append(flow_uncertain) except: flows_list.append(flow) return flows_list # Conversion from ppbv (part per billion), page 8SM-15 ppbv_to_kg = lambda x_molecular_weight: (air_molecular_weight/x_molecular_weight*1e9/atmosphere_total_mass) # Compute function f uncertainty given derivatives d = partial_df/partial_dx*delta_x, and normalize compute_delta_f = lambda nominal_value, *d: np.sqrt(np.sum(np.power(d,2))) / nominal_value # General expression for AGWP, equation 8.SM.9 # A - radiative efficiency, [W/m2/ppb] # tau - lifetime, [yr] # H - time horizon, [yr] # mult - multiplier specific to each substance, in many cases is equal to 1 compute_agwp_general = lambda tau, A, H, mult: A*tau*(1-np.exp(-H/tau)) * mult # Print computed +-delta_x uncertainty values as percentage of the expected value \bar{x} # for a 90% confidence interval and its standard deviation def print_uncertainties(i, x_name, x_delta, x_std): if not np.isnan(x_delta): print( "{:3} {}\n delta = {:6.3f}%, std = {:5.3f}*mean".format(i, x_name, x_delta*100, x_std) ) else: print( "{:3} {}\n NO DATA".format(i, x_name) ) # Compute standard deviation x_std given +-delta_x values for confidence interval with a certain confidence level conf_interval_to_std = lambda conf_level, conf_interval: conf_interval / norm.ppf(0.5 + conf_level / 2) def compute_co2_agwp(time_horizon): # 1. Carbon dioxide, AGWP expression is not general, instead taken from equation 8.SM.23 # Constants are from Joos et al, 2013, https://doi.org/10.5194/acp-13-2793-2013 # time_horizon is given in years M_co2 = 44.01 A_co2 = 1.37e-5 * ppbv_to_kg(M_co2) delta_A_co2 = 0.1 if time_horizon==20: I_co2 = 14.2 delta_I_co2 = (16.3-12.2)/2/I_co2 elif time_horizon==100: I_co2 = 52.4 delta_I_co2 = (65.2-39.5)/2/I_co2 elif time_horizon==500: I_co2 = 184 delta_I_co2 = (235-132)/2/I_co2 else: print('Choose time horizon of 20, 100 or 500 years') return co2_agwp = A_co2*I_co2 co2_ddelta_A = I_co2*delta_A_co2*A_co2 co2_ddelta_I = A_co2*delta_I_co2*I_co2 co2_delta_agwp = compute_delta_f(co2_agwp, co2_ddelta_A, co2_ddelta_I) conf_level = 0.9 co2_std_agwp = conf_interval_to_std(conf_level, co2_delta_agwp) return co2_delta_agwp, co2_std_agwp, co2_agwp # Uncertainty values for AGWP, chapter 8.SM.12, equation 8.SM.24 # delta values for A and tau are taken from table 8.SM.12 compute_gwp = lambda x_agwp, co2_agwp: x_agwp/co2_agwp compute_dgwp_dA = lambda tau, A, H, mult, co2_agwp, delta_A: \ mult * tau / co2_agwp * (1 - np.exp(-H/tau)) * delta_A*A compute_dgwp_dtau = lambda tau, A, H, mult, co2_agwp, delta_tau: \ mult * A / co2_agwp * (1 - np.exp(-H/tau) - H/tau*np.exp(-H/tau) ) * delta_tau*tau compute_dgwp_dgwpco2 = lambda x_agwp, co2_agwp, co2_delta_agwp: \ 1 / co2_agwp**2 * x_agwp * co2_delta_agwp*co2_agwp def compute_delta_std_gwp(tau, A, H, delta_A, delta_tau, mult=1, *dgwp_dy): co2_delta_agwp, co2_std_agwp, co2_agwp = compute_co2_agwp(H) x_agwp = compute_agwp_general (tau, A, H, mult) x_gwp = compute_gwp(x_agwp, co2_agwp) x_dgwp_dA = compute_dgwp_dA (tau, A, H, mult, co2_agwp, delta_A) x_dgwp_dtau = compute_dgwp_dtau(tau, A, H, mult, co2_agwp, delta_tau) x_dgwp_dgwpco2 = compute_dgwp_dgwpco2(x_agwp, co2_agwp, co2_delta_agwp) x_delta_gwp = compute_delta_f( x_gwp, x_dgwp_dA, x_dgwp_dtau, x_dgwp_dgwpco2, *dgwp_dy, ) conf_level = 0.9 x_std_multiplier_gwp = conf_interval_to_std(conf_level, x_delta_gwp) return x_delta_gwp, x_std_multiplier_gwp def get_substance_data(substance_name, time_horizon): if substance_name in ["Methane", "Methane, fossil", 'Methane, from soil or biomass stock']: # Assume that fossil methane and methane from soil or biomass stock are the same # see Bourgault G (2020). Implementation of impact assessment methods in the ecoinvent database version 3.7.1. dict_ = substances_data['Methane'] else: dict_ = substances_data[substance_name] M = dict_.get("Molecular weight") tau = dict_.get("Lifetime") A = dict_.get("Radiative efficiency") * ppbv_to_kg(M) if substance_name in ['Methane', "Methane, fossil", 'Methane, from soil or biomass stock', "Methane, non-fossil"]: # For all CH4 flows f1 = dict_.get("f1") # due to effects on ozone f2 = dict_.get("f2") # due to stratospheric H2O mult = 1 + f1 + f2 elif substance_name=="Dinitrogen monoxide": f1 = dict_.get("f1") # due to effects on ozone f2 = dict_.get("f2") # due to stratospheric H2O dict_methane = substances_data["Methane"] # TODO or non-fossil?? M_ch4 = dict_methane.get("Molecular weight") A_ch4 = dict_methane.get("Radiative efficiency") * ppbv_to_kg(M_ch4) _, _, co2_agwp = compute_co2_agwp(time_horizon) mult = 1 - 0.36 * (1 + f1 + f2) * A_ch4 / A else: mult = 1 return tau, A, mult def compute_substance_agwp_gwp(substance_name, time_horizon): co2_delta_agwp, co2_std_agwp, co2_agwp = compute_co2_agwp(time_horizon) tau, A, mult = get_substance_data(substance_name, time_horizon) x_agwp = compute_agwp_general(tau, A, time_horizon, mult) x_gwp = compute_gwp(x_agwp, co2_agwp) return x_agwp, x_gwp def compute_delta_std_multiplier(substance_name, time_horizon, verbose=True, i='-->'): try: tau, A, mult = get_substance_data(substance_name, time_horizon) if substance_name in ["Methane", "Methane, fossil", 'Methane, from soil or biomass stock']: # Assume that fossil methane and methane from soil or biomass stock are the same # see Bourgault G (2020). Implementation of impact assessment methods in the ecoinvent database version 3.7.1. dict_ = substances_data['Methane'] else: dict_ = substances_data[substance_name] delta_tau = dict_.get("Lifetime delta", 0.2) delta_A = dict_.get("Radiative efficiency delta", 0.1) if substance_name in ['Methane', "Methane, fossil", 'Methane, from soil or biomass stock', "Methane, non-fossil"]: # For all CH4 flows f1 = dict_.get("f1") # due to effects on ozone f2 = dict_.get("f2") # due to stratospheric H2O delta_f1 = dict_.get("delta_f1") delta_f2 = dict_.get("delta_f2") _, _, co2_agwp = compute_co2_agwp(time_horizon) ch4_dgwp_df1 = A * tau / co2_agwp * (1 - np.exp(-time_horizon / tau)) * delta_f1 * f1 ch4_dgwp_df2 = A * tau / co2_agwp * (1 - np.exp(-time_horizon / tau)) * delta_f2 * f2 x_delta_gwp, x_std_multiplier_gwp = compute_delta_std_gwp( tau, A, time_horizon, delta_A, delta_tau, mult, ch4_dgwp_df1, ch4_dgwp_df2, ) elif substance_name=="Dinitrogen monoxide": f1 = dict_.get("f1") # due to effects on ozone f2 = dict_.get("f2") # due to stratospheric H2O delta_f1 = dict_.get("delta_f1") delta_f2 = dict_.get("delta_f2") dict_methane = substances_data["Methane"] M_ch4 = dict_methane.get("Molecular weight") A_ch4 = dict_methane.get("Radiative efficiency") * ppbv_to_kg(M_ch4) RE_ch4 = A_ch4 RE_n2o = A _, _, co2_agwp = compute_co2_agwp(time_horizon) n2o_dgwp_df1 = -0.36 * RE_ch4 / RE_n2o * A * tau / co2_agwp * (1 - np.exp(-time_horizon / tau)) * delta_f1 * f1 n2o_dgwp_df2 = -0.36 * RE_ch4 / RE_n2o * A * tau / co2_agwp * (1 - np.exp(-time_horizon / tau)) * delta_f2 * f2 x_delta_gwp, x_std_multiplier_gwp = compute_delta_std_gwp( tau, A, time_horizon, delta_A, delta_tau, mult, n2o_dgwp_df1, n2o_dgwp_df2 ) else: x_delta_gwp, x_std_multiplier_gwp = compute_delta_std_gwp( tau, A, time_horizon, delta_A, delta_tau, mult, ) if verbose: print_uncertainties(i, substance_name, x_delta_gwp, x_std_multiplier_gwp) return x_delta_gwp, x_std_multiplier_gwp except: if verbose: print_uncertainties(i, substance_name, np.nan, np.nan) return np.nan, np.nan
{"hexsha": "a48992b3004e3cd44cb75679d302b2e6fd07b1c5", "size": 11226, "ext": "py", "lang": "Python", "max_stars_repo_path": "gwp_uncertainties/gwp_computations.py", "max_stars_repo_name": "aleksandra-kim/bw_gwp_uncertainties", "max_stars_repo_head_hexsha": "de428c60b2ff54def15f976657ebf55823ccb86d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-20T19:59:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T19:59:45.000Z", "max_issues_repo_path": "gwp_uncertainties/gwp_computations.py", "max_issues_repo_name": "aleksandra-kim/gwp_uncertainties", "max_issues_repo_head_hexsha": "de428c60b2ff54def15f976657ebf55823ccb86d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gwp_uncertainties/gwp_computations.py", "max_forks_repo_name": "aleksandra-kim/gwp_uncertainties", "max_forks_repo_head_hexsha": "de428c60b2ff54def15f976657ebf55823ccb86d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.0081967213, "max_line_length": 123, "alphanum_fraction": 0.6306787814, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3310}
\section{PWGrid version 1} \subsection{The implementation: {\tt PWGrid\_01.jl}} The type definition \begin{juliacode} type PWGrid Ns::Array{Int64} LatVecs::Array{Float64,2} RecVecs::Array{Float64,2} Npoints::Int Ω::Float64 r::Array{Float64,2} G::Array{Float64,2} G2::Array{Float64} end \end{juliacode} The constructor \begin{juliacode} function PWGrid( Ns::Array{Int,1},LatVecs::Array{Float64,2} ) Npoints = prod(Ns) RecVecs = 2*pi*inv(LatVecs') Ω = det(LatVecs) R,G,G2 = init_grids( Ns, LatVecs, RecVecs ) return PWGrid( Ns, LatVecs, RecVecs, Npoints, Ω, R, G, G2 ) end \end{juliacode} Mapping between half of the sampling points to the negative ones \begin{juliacode} function mm_to_nn(mm::Int,S::Int) if mm > S/2 return mm - S else return mm end end \end{juliacode} Initialization of real space and reciprocal space grid points \begin{juliacode} function init_grids( Ns, LatVecs, RecVecs ) Npoints = prod(Ns) r = Array(Float64,3,Npoints) ip = 0 for k in 0:Ns[3]-1 for j in 0:Ns[2]-1 for i in 0:Ns[1]-1 ip = ip + 1 r[1,ip] = LatVecs[1,1]*i/Ns[1] + LatVecs[2,1]*j/Ns[2] + LatVecs[3,1]*k/Ns[3] r[2,ip] = LatVecs[1,2]*i/Ns[1] + LatVecs[2,2]*j/Ns[2] + LatVecs[3,2]*k/Ns[3] r[3,ip] = LatVecs[1,3]*i/Ns[1] + LatVecs[2,3]*j/Ns[2] + LatVecs[3,3]*k/Ns[3] end end end # G = Array(Float64,3,Npoints) G2 = Array(Float64,Npoints) ip = 0 for k in 0:Ns[3]-1 for j in 0:Ns[2]-1 for i in 0:Ns[1]-1 gi = mm_to_nn( i, Ns[1] ) gj = mm_to_nn( j, Ns[2] ) gk = mm_to_nn( k, Ns[3] ) ip = ip + 1 G[1,ip] = RecVecs[1,1]*gi + RecVecs[2,1]*gj + RecVecs[3,1]*gk G[2,ip] = RecVecs[1,2]*gi + RecVecs[2,2]*gj + RecVecs[3,2]*gk G[3,ip] = RecVecs[1,3]*gi + RecVecs[2,3]*gj + RecVecs[3,3]*gk G2[ip] = G[1,ip]^2 + G[2,ip]^2 + G[3,ip]^2 end end end return r,G,G2 end \end{juliacode} \subsection{Testing the {\tt PWGrid\_01}} Include files: \begin{juliacode} include("../common/PWGrid_v01.jl") include("../common/gen_lattice.jl") \end{juliacode} Main driver \begin{juliacode} function test_main_hexagonal() # call these functions for other types of lattice #LL = 16.0*diagm([1.0, 1.0, 1.0]) # cubic #LL = gen_lattice_fcc(16.0) # face-centered cubic #LL = gen_lattice_bcc(16.0) # body-centered cubic Ns = [10, 10, 20] LL = gen_lattice_hexagonal(10.0, coa=2.0) pw = PWGrid( Ns, LL ) atpos = pw.r println(pw.LatVecs) println(pw.RecVecs) write_XSF("R_grid_hexagonal.xsf", LL, atpos) Rec = pw.RecVecs*Ns[1]/2.0 atpos = pw.G write_XSF("G_grid_hexagonal.xsf", LL, atpos, molecule=true) for ii = 1:3 @printf("LatVecLen %d %18.10f\n", ii, norm(pw.LatVecs[ii,:])) end @printf("Ratio coa: %18.10f\n", norm(pw.LatVecs[1,:])/norm(pw.LatVecs[3,:])) @printf("\n") for ii = 1:3 @printf("RecVecLen %d %18.10f\n", ii, norm(pw.RecVecs[ii,:])) end @printf("Ratio coa: %18.10f\n", norm(pw.RecVecs[1,:])/norm(pw.RecVecs[3,:])) end \end{juliacode}
{"hexsha": "890c23178c50e7e7a1b8d37e67fe95dcb3aee533", "size": 3007, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "PW/annotated/PWGrid_01.tex", "max_stars_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_stars_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-01-03T02:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T13:30:20.000Z", "max_issues_repo_path": "PW/annotated/PWGrid_01.tex", "max_issues_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_issues_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PW/annotated/PWGrid_01.tex", "max_forks_repo_name": "f-fathurrahman/ffr-ElectronicStructure.jl", "max_forks_repo_head_hexsha": "35dca9831bfc6a3e49bb0f3a5872558ffce4b211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-23T06:58:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T00:54:28.000Z", "avg_line_length": 22.9541984733, "max_line_length": 80, "alphanum_fraction": 0.6291985367, "num_tokens": 1321}
*DECK SCOEF SUBROUTINE SCOEF (YH, YP, NCOMP, NROWB, NFC, NIC, B, BETA, COEF, + INHOMO, RE, AE, BY, CVEC, WORK, IWORK, IFLAG, NFCC) C***BEGIN PROLOGUE SCOEF C***SUBSIDIARY C***PURPOSE Subsidiary to BVSUP C***LIBRARY SLATEC C***TYPE SINGLE PRECISION (SCOEF-S, DCOEF-D) C***AUTHOR Watts, H. A., (SNLA) C***DESCRIPTION C C ********************************************************************** C INPUT TO SCOEF C ********************************************************************** C C YH = Matrix of homogeneous solutions. C YP = Vector containing particular solution. C NCOMP = Number of components per solution vector. C NROWB = First dimension of B in calling program. C NFC = Number of base solution vectors. C NFCC = 2*NFC for the special treatment of complex valued C equations. Otherwise, NFCC=NFC. C NIC = Number of specified initial conditions. C B = Boundary condition matrix at X = Xfinal. C BETA = Vector of nonhomogeneous boundary conditions at X = Xfinal. C 1 - Nonzero particular solution C INHOMO = 2 - Zero particular solution C 3 - Eigenvalue problem C RE = Relative error tolerance C AE = Absolute error tolerance C BY = Storage space for the matrix B*YH C CVEC = Storage space for the vector BETA-B*YP C WORK = Real array of internal storage. Dimension must be .GE. C NFCC*(NFCC+4) C IWORK = Integer array of internal storage. Dimension must be .GE. C 3+NFCC C C ********************************************************************** C OUTPUT FROM SCOEF C ********************************************************************** C C COEF = Array containing superposition constants. C IFLAG = Indicator of success from SUDS in solving the C boundary equations C = 0 Boundary equations are solved C = 1 Boundary equations appear to have many solutions C = 2 Boundary equations appear to be inconsistent C = 3 For this value of an eigenparameter, the boundary C equations have only the zero solution. C C ********************************************************************** C C Subroutine SCOEF solves for the superposition constants from the C linear equations defined by the boundary conditions at X = Xfinal. C C B*YP + B*YH*COEF = BETA C C ********************************************************************** C C***SEE ALSO BVSUP C***ROUTINES CALLED SDOT, SUDS, XGETF, XSETF C***COMMON BLOCKS ML5MCO C***REVISION HISTORY (YYMMDD) C 750601 DATE WRITTEN C 890531 Changed all specific intrinsics to generic. (WRB) C 890831 Modified array declarations. (WRB) C 890921 Realigned order of variables in certain COMMON blocks. C (WRB) C 891214 Prologue converted to Version 4.0 format. (BAB) C 900328 Added TYPE section. (WRB) C 910722 Updated AUTHOR section. (ALS) C***END PROLOGUE SCOEF C DIMENSION YH(NCOMP,*),YP(*),B(NROWB,*),BETA(*), 1 COEF(*),BY(NFCC,*),CVEC(*),WORK(*),IWORK(*) C COMMON /ML5MCO/ URO,SRU,EPS,SQOVFL,TWOU,FOURU,LPAR C C SET UP MATRIX B*YH AND VECTOR BETA - B*YP C C***FIRST EXECUTABLE STATEMENT SCOEF NCOMP2=NCOMP/2 DO 7 K = 1,NFCC DO 1 J = 1,NFC L=J IF (NFC .NE. NFCC) L=2*J-1 1 BY(K,L) = SDOT(NCOMP,B(K,1),NROWB,YH(1,J),1) IF (NFC .EQ. NFCC) GO TO 3 DO 2 J=1,NFC L=2*J BYKL=SDOT(NCOMP2,B(K,1),NROWB,YH(NCOMP2+1,J),1) BY(K,L)=SDOT(NCOMP2,B(K,NCOMP2+1),NROWB,YH(1,J),1) - BYKL 2 CONTINUE 3 GO TO (4,5,6), INHOMO C CASE 1 4 CVEC(K) = BETA(K) - SDOT(NCOMP,B(K,1),NROWB,YP,1) GO TO 7 C CASE 2 5 CVEC(K) = BETA(K) GO TO 7 C CASE 3 6 CVEC(K) = 0. 7 CONTINUE CONS=ABS(CVEC(1)) BYS=ABS(BY(1,1)) C C ********************************************************************** C SOLVE LINEAR SYSTEM C IFLAG=0 MLSO=0 IF (INHOMO .EQ. 3) MLSO=1 KFLAG = 0.5 * LOG10(EPS) CALL XGETF(NF) CALL XSETF(0) 10 CALL SUDS(BY,COEF,CVEC,NFCC,NFCC,NFCC,KFLAG,MLSO,WORK,IWORK) IF (KFLAG .NE. 3) GO TO 13 KFLAG=1 IFLAG=1 GO TO 10 13 IF (KFLAG .EQ. 4) IFLAG=2 CALL XSETF(NF) IF (NFCC .EQ. 1) GO TO 25 IF (INHOMO .NE. 3) RETURN IF (IWORK(1) .LT. NFCC) GO TO 17 IFLAG=3 DO 14 K=1,NFCC 14 COEF(K)=0. COEF(NFCC)=1. NFCCM1=NFCC-1 DO 15 K=1,NFCCM1 J=NFCC-K L=NFCC-J+1 GAM=SDOT(L,BY(J,J),NFCC,COEF(J),1)/(WORK(J)*BY(J,J)) DO 15 I=J,NFCC 15 COEF(I)=COEF(I)+GAM*BY(J,I) RETURN 17 DO 20 K=1,NFCC KI=4*NFCC+K 20 COEF(K)=WORK(KI) RETURN C C ********************************************************************** C TESTING FOR EXISTENCE AND UNIQUENESS OF BOUNDARY-VALUE PROBLEM C SOLUTION IN A SCALAR CASE C 25 BN = 0. UN = 0. YPN=0. DO 30 K = 1,NCOMP UN = MAX(UN,ABS(YH(K,1))) YPN=MAX(YPN,ABS(YP(K))) 30 BN = MAX(BN,ABS(B(1,K))) BBN = MAX(BN,ABS(BETA(1))) IF (BYS .GT. 10.*(RE*UN + AE)*BN) GO TO 35 BRN = BBN / BN * BYS IF (CONS .GE. 0.1*BRN .AND. CONS .LE. 10.*BRN) IFLAG=1 IF (CONS .GT. 10.*BRN) IFLAG=2 IF (CONS .LE. RE*ABS(BETA(1))+AE + (RE*YPN+AE)*BN) IFLAG=1 IF (INHOMO .EQ. 3) COEF(1)=1. RETURN 35 IF (INHOMO .NE. 3) RETURN IFLAG=3 COEF(1)=1. RETURN END
{"hexsha": "c53d812c3bbb6eef1123f0c47045a8adc9102279", "size": 5511, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "slatec/src/scoef.f", "max_stars_repo_name": "andremirt/v_cond", "max_stars_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slatec/src/scoef.f", "max_issues_repo_name": "andremirt/v_cond", "max_issues_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slatec/src/scoef.f", "max_forks_repo_name": "andremirt/v_cond", "max_forks_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0, "max_line_length": 72, "alphanum_fraction": 0.5363817819, "num_tokens": 1894}
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.HITs.Truncation.FromNegOne where open import Cubical.HITs.Truncation.FromNegOne.Base public open import Cubical.HITs.Truncation.FromNegOne.Properties public
{"hexsha": "fdbb77ecd12a49b7635e67c6a865c42578a19d8d", "size": 224, "ext": "agda", "lang": "Agda", "max_stars_repo_path": "Cubical/HITs/Truncation/FromNegOne.agda", "max_stars_repo_name": "bijan2005/univalent-foundations", "max_stars_repo_head_hexsha": "737f922d925da0cd9a875cb0c97786179f1f4f61", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cubical/HITs/Truncation/FromNegOne.agda", "max_issues_repo_name": "bijan2005/univalent-foundations", "max_issues_repo_head_hexsha": "737f922d925da0cd9a875cb0c97786179f1f4f61", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cubical/HITs/Truncation/FromNegOne.agda", "max_forks_repo_name": "bijan2005/univalent-foundations", "max_forks_repo_head_hexsha": "737f922d925da0cd9a875cb0c97786179f1f4f61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-22T02:02:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T02:02:01.000Z", "avg_line_length": 37.3333333333, "max_line_length": 64, "alphanum_fraction": 0.8080357143, "num_tokens": 60}
################################################################################ # interHapLabels function # # Author: Heidi Lischer # Date: 10.2008 ################################################################################ interHapLabels <- function(xmlText){ tagData2 <- as.character(xmlText) tagData3 <- strsplit(tagData2, "\n") tagMatrix <- as.matrix(as.data.frame(tagData3)) tagMatrix <- gsub(":", " ", tagMatrix) tagMatrix <- gsub(" + ", "\t", tagMatrix) # trim white space tagMatrix <- subset(tagMatrix, tagMatrix[,1] != "") #trim empty lines Names <- strsplit(tagMatrix, "\t") InterHapLabels <- as.matrix(as.data.frame(Names)[2,]) return(InterHapLabels) }
{"hexsha": "f913e9408a79d6ae0bafaea3655ab04eae4534c9", "size": 735, "ext": "r", "lang": "R", "max_stars_repo_path": "code/tools/arlequin/arlecore_linux/Rfunctions/interHapLabels.r", "max_stars_repo_name": "kibet-gilbert/co1_metaanalysis", "max_stars_repo_head_hexsha": "1089cc03bc4dbabab543a8dadf49130d8e399665", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-01T05:57:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-01T05:57:08.000Z", "max_issues_repo_path": "code/tools/arlequin/arlecore_linux/Rfunctions/interHapLabels.r", "max_issues_repo_name": "kibet-gilbert/co1_metaanalysis", "max_issues_repo_head_hexsha": "1089cc03bc4dbabab543a8dadf49130d8e399665", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/tools/arlequin/arlecore_linux/Rfunctions/interHapLabels.r", "max_forks_repo_name": "kibet-gilbert/co1_metaanalysis", "max_forks_repo_head_hexsha": "1089cc03bc4dbabab543a8dadf49130d8e399665", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-01T06:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-01T06:15:56.000Z", "avg_line_length": 28.2692307692, "max_line_length": 81, "alphanum_fraction": 0.4829931973, "num_tokens": 169}
[STATEMENT] lemma Spy_not_see_NB: "[| A \<notin> bad; B \<notin> bad |] ==> Nprg \<in> Always {s. Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s & (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) --> Nonce NB \<notin> analz (spies s)}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>A \<notin> bad; B \<notin> bad\<rbrakk> \<Longrightarrow> Nprg \<in> Always {s. Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s)} [PROOF STEP] apply ns_induct [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. (C = Ba \<longrightarrow> A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) 2. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa 3. \<And>s A' A2 Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A' Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A2\<rbrace>) \<in> set s; Nonce NBa \<notin> used s\<rbrakk> \<Longrightarrow> (A2 \<in> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa \<and> NB \<noteq> NBa \<and> Nonce NB \<notin> analz (knows Spy s)) \<and> (A2 \<notin> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s)) 4. \<And>s A3 B' Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A3 Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A3\<rbrace>) \<in> set s; Says B' A3 (Crypt (pubK A3) \<lbrace>Nonce NAa, Nonce NBa\<rbrace>) \<in> set s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. (C = Ba \<longrightarrow> A = A3 \<longrightarrow> NB \<noteq> NBa) \<and> Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NBa [PROOF STEP] apply (simp_all (no_asm_simp) add: all_conj_distrib) [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) 2. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa 3. \<And>s A' A2 Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A' Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A2\<rbrace>) \<in> set s; Nonce NBa \<notin> used s\<rbrakk> \<Longrightarrow> (A2 \<in> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa \<and> NB \<noteq> NBa \<and> Nonce NB \<notin> analz (knows Spy s)) \<and> (A2 \<notin> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s)) 4. \<And>s A3 B' Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A3 Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A3\<rbrace>) \<in> set s; Says B' A3 (Crypt (pubK A3) \<lbrace>Nonce NAa, Nonce NBa\<rbrace>) \<in> set s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (A = A3 \<longrightarrow> NB \<noteq> NBa) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NBa [PROOF STEP] txt\<open>NS3: because NB determines A\<close> [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) 2. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa 3. \<And>s A' A2 Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A' Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A2\<rbrace>) \<in> set s; Nonce NBa \<notin> used s\<rbrakk> \<Longrightarrow> (A2 \<in> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa \<and> NB \<noteq> NBa \<and> Nonce NB \<notin> analz (knows Spy s)) \<and> (A2 \<notin> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s)) 4. \<And>s A3 B' Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A3 Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A3\<rbrace>) \<in> set s; Says B' A3 (Crypt (pubK A3) \<lbrace>Nonce NAa, Nonce NBa\<rbrace>) \<in> set s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (A = A3 \<longrightarrow> NB \<noteq> NBa) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NBa [PROOF STEP] prefer 4 [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>s A3 B' Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A3 Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A3\<rbrace>) \<in> set s; Says B' A3 (Crypt (pubK A3) \<lbrace>Nonce NAa, Nonce NBa\<rbrace>) \<in> set s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (A = A3 \<longrightarrow> NB \<noteq> NBa) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NBa 2. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) 3. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa 4. \<And>s A' A2 Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A' Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A2\<rbrace>) \<in> set s; Nonce NBa \<notin> used s\<rbrakk> \<Longrightarrow> (A2 \<in> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa \<and> NB \<noteq> NBa \<and> Nonce NB \<notin> analz (knows Spy s)) \<and> (A2 \<notin> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s)) [PROOF STEP] apply (blast dest: unique_NB) [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) 2. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa 3. \<And>s A' A2 Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A' Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A2\<rbrace>) \<in> set s; Nonce NBa \<notin> used s\<rbrakk> \<Longrightarrow> (A2 \<in> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa \<and> NB \<noteq> NBa \<and> Nonce NB \<notin> analz (knows Spy s)) \<and> (A2 \<notin> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s)) [PROOF STEP] txt\<open>NS2: by freshness and unicity of NB\<close> [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) 2. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa 3. \<And>s A' A2 Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A' Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A2\<rbrace>) \<in> set s; Nonce NBa \<notin> used s\<rbrakk> \<Longrightarrow> (A2 \<in> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa \<and> NB \<noteq> NBa \<and> Nonce NB \<notin> analz (knows Spy s)) \<and> (A2 \<notin> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s)) [PROOF STEP] prefer 3 [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>s A' A2 Ba NAa NBa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Says A' Ba (Crypt (pubK Ba) \<lbrace>Nonce NAa, Agent A2\<rbrace>) \<in> set s; Nonce NBa \<notin> used s\<rbrakk> \<Longrightarrow> (A2 \<in> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa \<and> NB \<noteq> NBa \<and> Nonce NB \<notin> analz (knows Spy s)) \<and> (A2 \<notin> bad \<longrightarrow> (B = Ba \<and> A = A2 \<and> NA = NAa \<and> NB = NBa \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s)) 2. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) 3. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa [PROOF STEP] apply (blast intro: no_nonce_NS1_NS2_reachable) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) 2. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa [PROOF STEP] txt\<open>NS1: by freshness\<close> [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) 2. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa [PROOF STEP] prefer 2 [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>s Ba NAa. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); Nonce NAa \<notin> used s\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> NB \<noteq> NAa 2. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) [PROOF STEP] apply blast [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) [PROOF STEP] txt\<open>Fake\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>s Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; s \<in> reachable Nprg; Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (knows Spy s); X \<in> synth (analz (knows Spy s))\<rbrakk> \<Longrightarrow> (B = Spy \<and> A = Ba \<and> Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace> = X \<or> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB\<rbrace>) \<in> set s) \<and> (A = Spy \<longrightarrow> Crypt (pubK Ba) (Nonce NB) \<noteq> X) \<and> (\<forall>C. Says A C (Crypt (pubK C) (Nonce NB)) \<notin> set s) \<longrightarrow> Nonce NB \<notin> analz (insert X (knows Spy s)) [PROOF STEP] apply spy_analz [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
{"llama_tokens": 11201, "file": null, "length": 14}
# -*- coding: utf-8 -*- #========================================== # Title: util.py # Author: Binxin Ru and Ahsan Alvi # Date: 20 August 2019 # Link: https://arxiv.org/abs/1906.08878 #========================================== from typing import Tuple import numpy as np def add_hallucinations_to_x_and_y(bo, old_x, old_y, x_new, fixed_dim_vals=None) \ -> Tuple[np.ndarray, np.ndarray]: """Add hallucinations to the data arrays. Parameters ---------- old_x Current x values old_y Current y values x_new Locations at which to use the async infill procedure. If x_busy is None, then nothing happens and the x and y arrays are returned Returns ------- augmented_x (np.ndarray), augmented_y (list or np.ndarray) """ if x_new is None: x_out = old_x y_out = old_y else: if isinstance(x_new, list): x_new = np.vstack(x_new) if fixed_dim_vals is not None: if fixed_dim_vals.ndim == 1: # row vector fixed_dim_vals = np.vstack([fixed_dim_vals] * len(x_new)) assert len(fixed_dim_vals) == len(x_new) x_new = np.hstack(( fixed_dim_vals, x_new )) x_out = np.vstack((old_x, x_new)) fake_y = make_hallucinated_data(bo, x_new, bo.async_infill_strategy) y_out = np.vstack((old_y, fake_y)) return x_out, y_out def make_hallucinated_data(bo, x: np.ndarray, strat: str) -> np.ndarray: """Returns fake y-values based on the chosen heuristic Parameters ---------- x Used to get the value for the kriging believer. Otherwise, this sets the number of values returned bo Instance of BayesianOptimization strat string describing the type of hallucinated data. Choices are: 'constant_liar_min', 'constant_liar_median', 'kriging_believer', 'posterior_simple' Returns ------- y : np.ndarray Values for the desired heuristic """ if strat == 'constant_liar_min': if x is None: y = np.atleast_2d(bo.y_min) else: y = np.array([bo.y_min] * len(x)).reshape(-1, 1) elif strat == 'constant_liar_median': if x is None: y = np.atleast_2d(bo.y_min) else: y = np.array([bo.y_min] * len(x)).reshape(-1, 1) elif strat == 'kriging_believer': y = bo.surrogate.predict(x)[0] elif strat == 'posterior_simple': mu, var = bo.surrogate.predict(x) y = np.random.multivariate_normal(mu.flatten(), np.diag(var.flatten())) \ .reshape(-1, 1) elif strat == 'posterior_full': mu, var = bo.surrogate.predict(x, full_cov=True) y = np.random.multivariate_normal(mu.flatten(), var).reshape(-1, 1) else: raise NotImplementedError return y
{"hexsha": "6e1ce39236517ddd8add2e4ed3432963bd4fc2e7", "size": 2977, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/bayesopt/util.py", "max_stars_repo_name": "ChangYong-Oh/CoCaBO_code", "max_stars_repo_head_hexsha": "d7eab8c8419de8df68355f1e410b8c4b4e697e44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-01-20T13:58:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:22:32.000Z", "max_issues_repo_path": "utils/bayesopt/util.py", "max_issues_repo_name": "ChangYong-Oh/CoCaBO_code", "max_issues_repo_head_hexsha": "d7eab8c8419de8df68355f1e410b8c4b4e697e44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-06-08T22:24:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:49:58.000Z", "max_forks_repo_path": "utils/bayesopt/util.py", "max_forks_repo_name": "ChangYong-Oh/CoCaBO_code", "max_forks_repo_head_hexsha": "d7eab8c8419de8df68355f1e410b8c4b4e697e44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-06-15T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T12:50:26.000Z", "avg_line_length": 28.3523809524, "max_line_length": 81, "alphanum_fraction": 0.5656701377, "include": true, "reason": "import numpy", "num_tokens": 747}
# Copyright - Transporation, Bots, and Disability Lab - Carnegie Mellon University # Released under MIT License """ Convert Functions for roslibpy """ import numpy as np import base64 import sys import logging logging.basicConfig() def _get_encoding_information(encoding): if encoding == 'bgra8': return 4, np.uint8 elif encoding == 'bgr8': return 3, np.uint8 elif encoding == 'mono8': return 1, np.uint8 def image_to_numpy(image_msg_dict, desire_encoding='passthrough'): """ Convert sensor_msgs/Image (in dict form) to a numpy array """ # if image_msg_dict['encoding'] != 'bgra8': # raise NotImplementedError("Unable to convert other image besides bgra8") num_channel, dtype = _get_encoding_information(image_msg_dict['encoding']) buffer = base64.b64decode(image_msg_dict['data']) data_arr = np.frombuffer(buffer, dtype) data_arr = np.reshape( data_arr, (image_msg_dict['height'], image_msg_dict['width'], num_channel)) # now we convert it if desire_encoding == 'bgr8' and image_msg_dict['encoding'] == 'bgra8': data_arr = data_arr[:, :, 0:3] return data_arr, image_msg_dict['header'] def numpy_to_image(image_numpy, encoding_name="bgr8", header=None): """ Convert a numpy array to sensor_msgs/Image (in dict form) only works with bgra8 """ image_dict = dict() # the header image_dict['header'] = header image_shape = np.shape(image_numpy) image_dict['width'] = image_shape[1] image_dict['height'] = image_shape[0] image_num_channels = image_shape[2] if len(image_shape) >= 3 else 1 # put in the data if sys.version_info >= (3, 0): buffer = (memoryview(image_numpy.copy())).tobytes() # literally translate it to string including b'' encoded_str = str(base64.b64encode(buffer)) # remove the b' in front and ' in of the string literal. encoded_str = encoded_str[2:-1] image_dict['data'] = encoded_str else: # the copy here will make the image to have a continous buffer in the memory buffer = np.getbuffer(image_numpy.copy()) image_dict['data'] = base64.b64encode(buffer) image_dict['encoding'] = encoding_name image_dict['is_bigendian'] = 0 image_dict['step'] = image_shape[1] * image_num_channels return image_dict
{"hexsha": "2341f34b64ccd6a300739731b72130ee5aecee57", "size": 2381, "ext": "py", "lang": "Python", "max_stars_repo_path": "alloy/ros/roslibpy.py", "max_stars_repo_name": "CMU-TBD/alloy", "max_stars_repo_head_hexsha": "cf66738e044613fb274bd1b159864a7600e15cb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alloy/ros/roslibpy.py", "max_issues_repo_name": "CMU-TBD/alloy", "max_issues_repo_head_hexsha": "cf66738e044613fb274bd1b159864a7600e15cb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alloy/ros/roslibpy.py", "max_forks_repo_name": "CMU-TBD/alloy", "max_forks_repo_head_hexsha": "cf66738e044613fb274bd1b159864a7600e15cb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1392405063, "max_line_length": 84, "alphanum_fraction": 0.6732465351, "include": true, "reason": "import numpy", "num_tokens": 598}
# coding: utf-8 import logging import sys import time import numpy as np import pytest import ray.cluster_utils from ray._private.test_utils import ( client_test_enabled, SignalActor, ) if client_test_enabled(): from ray.util.client import ray else: import ray logger = logging.getLogger(__name__) def test_task_arguments_inline_bytes_limit(ray_start_cluster_enabled): cluster = ray_start_cluster_enabled cluster.add_node( num_cpus=1, resources={"pin_head": 1}, _system_config={ "max_direct_call_object_size": 100 * 1024, # if task_rpc_inlined_bytes_limit is greater than # max_grpc_message_size, this test fails. "task_rpc_inlined_bytes_limit": 18 * 1024, "max_grpc_message_size": 20 * 1024, }, ) cluster.add_node(num_cpus=1, resources={"pin_worker": 1}) ray.init(address=cluster.address) @ray.remote(resources={"pin_worker": 1}) def foo(ref1, ref2, ref3): return ref1 == ref2 + ref3 @ray.remote(resources={"pin_head": 1}) def bar(): # if the refs are inlined, the test fails. # refs = [ray.put(np.random.rand(1024) for _ in range(3))] # return ray.get( # foo.remote(refs[0], refs[1], refs[2])) return ray.get( foo.remote( np.random.rand(1024), # 8k np.random.rand(1024), # 8k np.random.rand(1024), ) ) # 8k ray.get(bar.remote()) # This case tests whether gcs-based actor scheduler works properly with # a normal task co-existed. def test_schedule_actor_and_normal_task(ray_start_cluster_enabled): cluster = ray_start_cluster_enabled cluster.add_node( memory=1024 ** 3, _system_config={"gcs_actor_scheduling_enabled": True} ) ray.init(address=cluster.address) cluster.wait_for_nodes() @ray.remote(memory=600 * 1024 ** 2, num_cpus=0.01) class Foo: def method(self): return 2 @ray.remote(memory=600 * 1024 ** 2, num_cpus=0.01) def fun(singal1, signal_actor2): signal_actor2.send.remote() ray.get(singal1.wait.remote()) return 1 singal1 = SignalActor.remote() signal2 = SignalActor.remote() o1 = fun.remote(singal1, signal2) # Make sure the normal task is executing. ray.get(signal2.wait.remote()) # The normal task is blocked now. # Try to create actor and make sure this actor is not created for the time # being. foo = Foo.remote() o2 = foo.method.remote() ready_list, remaining_list = ray.wait([o2], timeout=2) assert len(ready_list) == 0 and len(remaining_list) == 1 # Send a signal to unblock the normal task execution. ray.get(singal1.send.remote()) # Check the result of normal task. assert ray.get(o1) == 1 # Make sure the actor is created. assert ray.get(o2) == 2 # This case tests whether gcs-based actor scheduler works properly # in a large scale. def test_schedule_many_actors_and_normal_tasks(ray_start_cluster): cluster = ray_start_cluster node_count = 10 actor_count = 50 each_actor_task_count = 50 normal_task_count = 1000 node_memory = 2 * 1024 ** 3 for i in range(node_count): cluster.add_node( memory=node_memory, _system_config={"gcs_actor_scheduling_enabled": True} if i == 0 else {}, ) ray.init(address=cluster.address) cluster.wait_for_nodes() @ray.remote(memory=100 * 1024 ** 2, num_cpus=0.01) class Foo: def method(self): return 2 @ray.remote(memory=100 * 1024 ** 2, num_cpus=0.01) def fun(): return 1 normal_task_object_list = [fun.remote() for _ in range(normal_task_count)] actor_list = [Foo.remote() for _ in range(actor_count)] actor_object_list = [ actor.method.remote() for _ in range(each_actor_task_count) for actor in actor_list ] for object in ray.get(actor_object_list): assert object == 2 for object in ray.get(normal_task_object_list): assert object == 1 # This case tests whether gcs actor scheduler distributes actors # in a balanced way if using `SPREAD` policy. @pytest.mark.parametrize("args", [[5, 20], [5, 3]]) def test_actor_distribution_balance(ray_start_cluster_enabled, args): cluster = ray_start_cluster_enabled node_count = args[0] actor_count = args[1] for i in range(node_count): cluster.add_node( memory=1024 ** 3, _system_config={"gcs_actor_scheduling_enabled": True} if i == 0 else {}, ) ray.init(address=cluster.address) cluster.wait_for_nodes() @ray.remote(memory=100 * 1024 ** 2, num_cpus=0.01, scheduling_strategy="SPREAD") class Foo: def method(self): return ray.worker.global_worker.node.unique_id actor_distribution = {} actor_list = [Foo.remote() for _ in range(actor_count)] for actor in actor_list: node_id = ray.get(actor.method.remote()) if node_id not in actor_distribution.keys(): actor_distribution[node_id] = [] actor_distribution[node_id].append(actor) if node_count >= actor_count: assert len(actor_distribution) == actor_count for node_id, actors in actor_distribution.items(): assert len(actors) == 1 else: assert len(actor_distribution) == node_count for node_id, actors in actor_distribution.items(): assert len(actors) <= int(actor_count / node_count) # This case tests whether RequestWorkerLeaseReply carries normal task resources # when the request is rejected (due to resource preemption by normal tasks). def test_worker_lease_reply_with_resources(ray_start_cluster_enabled): cluster = ray_start_cluster_enabled cluster.add_node( memory=2000 * 1024 ** 2, num_cpus=1, _system_config={ "gcs_resource_report_poll_period_ms": 1000000, "gcs_actor_scheduling_enabled": True, }, ) node2 = cluster.add_node(memory=1000 * 1024 ** 2, num_cpus=1) ray.init(address=cluster.address) cluster.wait_for_nodes() @ray.remote(memory=1500 * 1024 ** 2, num_cpus=0.01) def fun(signal): signal.send.remote() time.sleep(30) return 0 signal = SignalActor.remote() fun.remote(signal) # Make sure that the `fun` is running. ray.get(signal.wait.remote()) @ray.remote(memory=800 * 1024 ** 2, num_cpus=0.01) class Foo: def method(self): return ray.worker.global_worker.node.unique_id foo1 = Foo.remote() o1 = foo1.method.remote() ready_list, remaining_list = ray.wait([o1], timeout=10) # If RequestWorkerLeaseReply carries normal task resources, # GCS will then schedule foo1 to node2. Otherwise, # GCS would keep trying to schedule foo1 to # node1 and getting rejected. assert len(ready_list) == 1 and len(remaining_list) == 0 assert ray.get(o1) == node2.unique_id if __name__ == "__main__": import os import pytest if os.environ.get("PARALLEL_CI"): sys.exit(pytest.main(["-n", "auto", "--boxed", "-vs", __file__])) else: sys.exit(pytest.main(["-sv", __file__]))
{"hexsha": "0bda228682f4c17f72575843529b6586900a48d8", "size": 7318, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/ray/tests/test_advanced_5.py", "max_stars_repo_name": "jianoaix/ray", "max_stars_repo_head_hexsha": "1701b923bc83905f8961c06a6a173e3eba46a936", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/ray/tests/test_advanced_5.py", "max_issues_repo_name": "jianoaix/ray", "max_issues_repo_head_hexsha": "1701b923bc83905f8961c06a6a173e3eba46a936", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/ray/tests/test_advanced_5.py", "max_forks_repo_name": "jianoaix/ray", "max_forks_repo_head_hexsha": "1701b923bc83905f8961c06a6a173e3eba46a936", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3651452282, "max_line_length": 84, "alphanum_fraction": 0.6500409948, "include": true, "reason": "import numpy", "num_tokens": 1836}
#include <boost/log/sinks/basic_sink_frontend.hpp>
{"hexsha": "53c787c860d9565abaa498078196dfb7f23b03ee", "size": 51, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/boost_log_sinks_basic_sink_frontend.hpp", "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_issues_repo_path": "src/boost_log_sinks_basic_sink_frontend.hpp", "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_forks_repo_path": "src/boost_log_sinks_basic_sink_frontend.hpp", "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "avg_line_length": 25.5, "max_line_length": 50, "alphanum_fraction": 0.8235294118, "num_tokens": 11}
import numpy as np import tensorflow as tf from sklearn.ensemble import IsolationForest class EarlyStoppingBeforeOverfit(tf.keras.callbacks.Callback): """ """ def __init__(self, patience=15, min_acc=0.95): super(EarlyStoppingBeforeOverfit, self).__init__() self.min_acc = min_acc self.patience = patience # best_weights to store the weights at which the minimum loss occurs. self.best_weights = None def on_train_begin(self, logs=None): self.stopped_epoch = 0 self.wait = 0 self.lowest_point = 1 def on_epoch_end(self, epoch, logs=None): current = logs.get("accuracy") if (current < self.min_acc) or self.wait == self.patience - 1: self.model.stop_training = True self.model.set_weights(self.best_weights) else: if current <= self.lowest_point: self.stopped_epoch = epoch self.best_weights = self.model.get_weights() self.wait = 0 self.lowest_point = current else: self.wait += 1 def on_train_end(self, logs=None): if self.stopped_epoch > 0: print("Epoch %05d: early stopping" % (self.stopped_epoch + 1)) def sample_enrichment_IF(r_seed, target_data, sample_size): np.random.seed(r_seed) domain_max = target_data.max(axis=0) domain_min = target_data.min(axis=0) domain_dim = target_data.shape[1] sample_enri = np.random.random(size=(sample_size, domain_dim)) domain_gap = (domain_max - domain_min) * 1.2 domain_mean = (domain_max + domain_min) / 2 for dim_idx in range(domain_dim): sample_enri[:, dim_idx] = sample_enri[:, dim_idx] * domain_gap[ dim_idx] + domain_mean[dim_idx] - domain_gap[dim_idx] / 2 clf = IsolationForest(random_state=r_seed, max_samples=0.9).fit(target_data) sample_coef = clf.score_samples(sample_enri) sample_coef -= sample_coef.min() sample_coef /= sample_coef.max() print(np.unique(sample_coef).shape) return sample_enri, np.squeeze(sample_coef) class aosr_risk(tf.keras.losses.Loss): def __init__(self, model, x_q, x_w, z_p_X, outlier_ratio, k): super().__init__(name='pq_risk') self.model = model self.x_q = x_q self.x_w = x_w self.k = k self.z_p_X = z_p_X self.outlier_ratio = outlier_ratio def call(self, y_true, y_pred): Rs_all_hat = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred) y_t_pred = self.model(self.x_q) y_true_q = np.zeros(self.x_w.shape[0]) + self.k Rt_k_hat = tf.keras.losses.sparse_categorical_crossentropy(y_true_q, y_t_pred) Rt_k_hat = tf.math.multiply(tf.convert_to_tensor(self.x_w, dtype=tf.float32), Rt_k_hat) Rt_k_hat = tf.reduce_mean(Rt_k_hat) num_out = tf.math.argmax(self.model(self.z_p_X), axis=1) num_out = tf.reduce_sum(tf.cast(tf.equal(num_out, self.k), tf.int32)) num_out = tf.cast(num_out, tf.float32 ) outlier = self.z_p_X.shape[0] * self.outlier_ratio if num_out == 0: num_out = 0.00001 num_out = tf.stop_gradient(num_out) return Rs_all_hat + (outlier*1.0/(num_out*1.0))* Rt_k_hat
{"hexsha": "134b1b6c6674e64f977ddd5c3921921ec22451ed", "size": 3410, "ext": "py", "lang": "Python", "max_stars_repo_path": "exp_table2/aosr_utility.py", "max_stars_repo_name": "Anjin-Liu/Openset_Learning_AOSR", "max_stars_repo_head_hexsha": "8b9435dfd33abf5969122beddf07bf9314d0969a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2021-05-26T14:19:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T16:31:02.000Z", "max_issues_repo_path": "exp_table3/aosr_utility.py", "max_issues_repo_name": "fang-zhen/Openset_Learning_AOSR", "max_issues_repo_head_hexsha": "979ee07cf632eb9b64bc982c4d223cb08de1c943", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exp_table3/aosr_utility.py", "max_forks_repo_name": "fang-zhen/Openset_Learning_AOSR", "max_forks_repo_head_hexsha": "979ee07cf632eb9b64bc982c4d223cb08de1c943", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-05-26T14:50:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T06:28:55.000Z", "avg_line_length": 34.4444444444, "max_line_length": 95, "alphanum_fraction": 0.6246334311, "include": true, "reason": "import numpy", "num_tokens": 854}
from scipy.signal import butter, lfilter, resample, firwin, decimate from sklearn.decomposition import FastICA, PCA from sklearn import preprocessing import numpy as np import pandas as np import matplotlib.pyplot as plt import scipy import pandas as pd class SpectrogramImage: """ Plot spectrogram for each channel and convert it to numpy image array. """ def __init__(self, size=(224, 224, 4)): self.size = size def get_name(self): return 'img-spec-{}'.format(self.size) def drop_zeros(self, df): return df[(df.T != 0).any()] def apply(self, data): data = pd.DataFrame(data.T) data = self.drop_zeros(data) channels = [] for col in data.columns: plt.ioff() _, _, _, _ = plt.specgram(data[col], NFFT=2048, Fs=240000/600, noverlap=int((240000/600)*0.005), cmap=plt.cm.spectral) plt.axis('off') plt.savefig('spec.png', bbox_inches='tight', pad_inches=0) plt.close() im = scipy.misc.imread('spec.png', mode='RGB') im = scipy.misc.imresize(im, (224, 224, 3)) channels.append(im) return channels class UnitScale: """ Scale across the last axis. """ def get_name(self): return 'unit-scale' def apply(self, data): return preprocessing.scale(data, axis=data.ndim - 1) class UnitScaleFeat: """ Scale across the first axis, i.e. scale each feature. """ def get_name(self): return 'unit-scale-feat' def apply(self, data): return preprocessing.scale(data, axis=0) class FFT: """ Apply Fast Fourier Transform to the last axis. """ def get_name(self): return "fft" def apply(self, data): axis = data.ndim - 1 return np.fft.rfft(data, axis=axis) class ICA: """ apply ICA experimental! """ def __init__(self, n_components=None): self.n_components = n_components def get_name(self): if self.n_components != None: return "ICA%d" % (self.n_components) else: return 'ICA' def apply(self, data): # apply pca to each ica = FastICA() data = ica.fit_transform(da) return data class Resample: """ Resample time-series data. """ def __init__(self, sample_rate): self.f = sample_rate def get_name(self): return "resample%d" % self.f def apply(self, data): axis = data.ndim - 1 if data.shape[-1] > self.f: return resample(data, self.f, axis=axis) return data class Magnitude: """ Take magnitudes of Complex data """ def get_name(self): return "mag" def apply(self, data): return np.absolute(data) class LPF: """ Low-pass filter using FIR window """ def __init__(self, f): self.f = f def get_name(self): return 'lpf%d' % self.f def apply(self, data): nyq = self.f / 2.0 cutoff = min(self.f, nyq - 1) h = firwin(numtaps=101, cutoff=cutoff, nyq=nyq) # data[ch][dim0] # apply filter over each channel for j in range(len(data)): data[j] = lfilter(h, 1.0, data[j]) return data class Mean: """ extract channel means """ def get_name(self): return 'mean' def apply(self, data): axis = data.ndim - 1 return data.mean(axis=axis) class Abs: """ extract channel means """ def get_name(self): return 'abs' def apply(self, data): return np.abs(data) class Stats: """ Subtract the mean, then take (min, max, standard_deviation) for each channel. """ def get_name(self): return "stats" def apply(self, data): # data[ch][dim] shape = data.shape out = np.empty((shape[0], 3)) for i in range(len(data)): ch_data = data[i] ch_data = data[i] - np.mean(ch_data) outi = out[i] outi[0] = np.std(ch_data) outi[1] = np.min(ch_data) outi[2] = np.max(ch_data) return out class Interp: """ Interpolate zeros max --> min * 1.0 NOTE: try different methods later """ def get_name(self): return "interp" def apply(self, data): # interps 0 data before taking log indices = np.where(data <= 0) data[indices] = np.max(data) data[indices] = (np.min(data) * 0.1) return data class Log10: """ Apply Log10 """ def get_name(self): return "log10" def apply(self, data): # interps 0 data before taking log indices = np.where(data <= 0) data[indices] = np.max(data) data[indices] = (np.min(data) * 0.1) return np.log10(data) class Slice: """ Take a slice of the data on the last axis. e.g. Slice(1, 48) works like a normal python slice, that is 1-47 will be taken """ def __init__(self, start, end): self.start = start self.end = end def get_name(self): return "slice%d-%d" % (self.start, self.end) def apply(self, data): s = [slice(None), ] * data.ndim s[-1] = slice(self.start, self.end) return data[s] class CorrelationMatrix: """ Calculate correlation coefficients matrix across all EEG channels. """ def get_name(self): return 'corr-mat' def apply(self, data): return upper_right_triangle(np.corrcoef(data)) # Fix everything below here class Eigenvalues: """ Take eigenvalues of a matrix, and sort them by magnitude in order to make them useful as features (as they have no inherent order). """ def get_name(self): return 'eigenvalues' def apply(self, data): w, v = np.linalg.eig(data) w = np.absolute(w) w.sort() return w class FreqCorrelation: """ Correlation in the frequency domain. First take FFT with (start, end) slice options, then calculate correlation co-efficients on the FFT output, followed by calculating eigenvalues on the correlation co-efficients matrix. The output features are (fft, upper_right_diagonal(correlation_coefficients), eigenvalues) Features can be selected/omitted using the constructor arguments. """ def __init__(self, start, end, scale_option, with_fft=False, with_corr=True, with_eigen=True): self.start = start self.end = end self.scale_option = scale_option self.with_fft = with_fft self.with_corr = with_corr self.with_eigen = with_eigen assert scale_option in ('us', 'usf', 'none') assert with_corr or with_eigen def get_name(self): selections = [] if not self.with_corr: selections.append('nocorr') if not self.with_eigen: selections.append('noeig') if len(selections) > 0: selection_str = '-' + '-'.join(selections) else: selection_str = '' return 'freq-correlation-%d-%d-%s-%s%s' % (self.start, self.end, 'withfft' if self.with_fft else 'nofft', self.scale_option, selection_str) def apply(self, data): data1 = FFT().apply(data) data1 = Slice(self.start, self.end).apply(data1) data1 = Magnitude().apply(data1) data1 = Log10().apply(data1) data2 = data1 if self.scale_option == 'usf': data2 = UnitScaleFeat().apply(data2) elif self.scale_option == 'us': data2 = UnitScale().apply(data2) data2 = CorrelationMatrix().apply(data2) if self.with_eigen: w = Eigenvalues().apply(data2) out = [] if self.with_corr: data2 = upper_right_triangle(data2) out.append(data2) if self.with_eigen: out.append(w) if self.with_fft: data1 = data1.ravel() out.append(data1) for d in out: assert d.ndim == 1 return np.concatenate(out, axis=0) class TimeCorrelation: """ Correlation in the time domain. First downsample the data, then calculate correlation co-efficients followed by calculating eigenvalues on the correlation co-efficients matrix. The output features are (upper_right_diagonal(correlation_coefficients), eigenvalues) Features can be selected/omitted using the constructor arguments. """ def __init__(self, max_hz, scale_option, with_corr=True, with_eigen=True): self.max_hz = max_hz self.scale_option = scale_option self.with_corr = with_corr self.with_eigen = with_eigen assert scale_option in ('us', 'usf', 'none') assert with_corr or with_eigen def get_name(self): selections = [] if not self.with_corr: selections.append('nocorr') if not self.with_eigen: selections.append('noeig') if len(selections) > 0: selection_str = '-' + '-'.join(selections) else: selection_str = '' return 'time-correlation-r%d-%s%s' % (self.max_hz, self.scale_option, selection_str) def apply(self, data): # so that correlation matrix calculation doesn't crash for ch in data: if np.alltrue(ch == 0.0): ch[-1] += 0.00001 data1 = data if data1.shape[1] > self.max_hz: data1 = Resample(self.max_hz).apply(data1) if self.scale_option == 'usf': data1 = UnitScaleFeat().apply(data1) elif self.scale_option == 'us': data1 = UnitScale().apply(data1) data1 = CorrelationMatrix().apply(data1) if self.with_eigen: w = Eigenvalues().apply(data1) out = [] if self.with_corr: data1 = upper_right_triangle(data1) out.append(data1) if self.with_eigen: out.append(w) for d in out: assert d.ndim == 1 return np.concatenate(out, axis=0) class TimeFreqCorrelation: """ Combines time and frequency correlation, taking both correlation coefficients and eigenvalues. """ def __init__(self, start, end, max_hz, scale_option): self.start = start self.end = end self.max_hz = max_hz self.scale_option = scale_option assert scale_option in ('us', 'usf', 'none') def get_name(self): return 'time-freq-correlation-%d-%d-r%d-%s' % (self.start, self.end, self.max_hz, self.scale_option) def apply(self, data): data1 = TimeCorrelation(self.max_hz, self.scale_option).apply(data) data2 = FreqCorrelation(self.start, self.end, self.scale_option).apply(data) assert data1.ndim == data2.ndim return np.concatenate((data1, data2), axis=data1.ndim - 1) class FFTWithTimeFreqCorrelation: """ Combines FFT with time and frequency correlation, taking both correlation coefficients and eigenvalues. """ def __init__(self, start, end, max_hz, scale_option): self.start = start self.end = end self.max_hz = max_hz self.scale_option = scale_option def get_name(self): return 'fft-with-time-freq-corr-%d-%d-r%d-%s' % (self.start, self.end, self.max_hz, self.scale_option) def apply(self, data): data1 = TimeCorrelation(self.max_hz, self.scale_option).apply(data) data2 = FreqCorrelation(self.start, self.end, self.scale_option, with_fft=True).apply(data) assert data1.ndim == data2.ndim return np.concatenate((data1, data2), axis=data1.ndim - 1) def upper_right_triangle(matrix): indices = np.triu_indices_from(matrix) return np.asarray(matrix[indices]) def slidingWindow(sequence, window, step=1): for i in range(0, sequence.shape[1] - window + 1, step): yield sequence[:, i:i + window] def decimate(time_data): '''decimates by factor of 10''' return decimate(time_data, 10, 'fir', axis=1)
{"hexsha": "767f756df6c9b01fb861185b1d3f165d996d8fe9", "size": 12247, "ext": "py", "lang": "Python", "max_stars_repo_path": "transforms.py", "max_stars_repo_name": "A-Jacobson/iEEG_Seizure_Prediction", "max_stars_repo_head_hexsha": "bdee7f4aab72674e01af7ec254b5d6ec7f65e620", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "transforms.py", "max_issues_repo_name": "A-Jacobson/iEEG_Seizure_Prediction", "max_issues_repo_head_hexsha": "bdee7f4aab72674e01af7ec254b5d6ec7f65e620", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transforms.py", "max_forks_repo_name": "A-Jacobson/iEEG_Seizure_Prediction", "max_forks_repo_head_hexsha": "bdee7f4aab72674e01af7ec254b5d6ec7f65e620", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4514038877, "max_line_length": 130, "alphanum_fraction": 0.589613783, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 2990}
import numpy as np import sigpy as sp import math from subtle_data_crimes.functions import new_poisson import matplotlib.pyplot as plt # ===================== 2D Variable-density Sampling (based on Miki Lustig's Sparse MRI toolbox) ============================ def create_samp_mask(R, imSize, calib=[24, 24], mask_show_flag=0): print('gen PDF & sampling mask...') # Here we define the variable "poly_degree", which controls the shape of the PDF. # Strong variable density can be obtained with poly_degree =~5 # Weak variable density can be obtained with poly_degree = 50 # Extremeley weak variable density, which is almost (but not exactly) uniform random, is obtained with poly_dgree = 1000 if R == 10: poly_degree = 4.5 elif R == 8: poly_degree = 4 elif R == 6: poly_degree = 3 elif R == 5: poly_degree = 2.5 elif R == 4: poly_degree = 2 elif R == 3: poly_degree = 1.5 elif R == 2: poly_degree = 1.5 elif R > 10: poly_degree = 10 # works OK for R=6,8,10 without calib, but results are unstable pdf = genPDF(imSize, poly_degree, 1 / R) mask = genSampling(pdf, iter=10, tol=60, calib=calib) # mask = np.expand_dims(mask,axis=0) # add coils dim to mask if mask_show_flag == 1: # display sampling mask fig = plt.figure() plt.imshow(mask, cmap="gray") plt.axis('off') plt.title('R={}'.format(R)) plt.show() fname = 'mask_R{}'.format(R) fig.savefig(fname=fname) elif mask_show_flag == 2: # display mask & pdf # display sampling mask & PDF fig = plt.figure() plt.imshow(np.concatenate((mask, pdf), axis=1), cmap="gray") plt.axis('off') plt.title('sampling mask & pdf \n R={}'.format(R)) plt.show() fname = 'mask_and_PDF_R{}'.format(R) fig.savefig(fname=fname) return mask, pdf ############### genPDF ########################### def genPDF(imSize, p, pctg, distType=2, radius=0, disp=0): # This function generates a pdf for a 1d or 2d random sampling pattern # with polynomial variable density sampling # Input: # imSize - size of matrix or vector # p - power of polynomial # pctg - partial sampling factor e.g. 0.5 for half # distType - 1 or 2 for L1 or L2 distance measure # radius - radius of fully sampled center # disp - display output # Output: # pdf - the pdf # val - min sampling density # (c) Michael Lustig 2007. Converted from Matlab to Python by Efrat Shimron (2020) minval = 0 maxval = 1 val = 0.5 if len(imSize) == 2: # 2D case # sx = imSize(1); # sy = imSize(2); # PCTG = floor(pctg*sx*sy); sx = imSize[0] sy = imSize[1] PCTG = np.floor(pctg * sx * sy) x_co = np.linspace(-1, 1, sy) # coordinates y_co = np.linspace(-1, 1, sx) # coordinates x, y = np.meshgrid(x_co, y_co) if distType == 1: r = np.max(np.abs(x), np.abs(y)) else: r = np.sqrt(x ** 2 + y ** 2) r = r / np.max(np.abs(r.reshape(1, -1))) elif len(imSize) == 1: # 1D case sx = imSize[0] r = np.abs(np.linspace(-1, 1, sx)) # create PDF idx = np.where(r < radius) pdf = (1 - r) ** p + val pdf[pdf > 1] = 1 pdf[idx] = 1 while (1): val = minval / 2 + maxval / 2 pdf = (1 - r) ** p + val pdf[pdf > 1] = 1 pdf[idx] = 1 N = np.floor(np.sum(pdf)) if N > PCTG: # infeasible maxval = val if N < PCTG: # feasible, but not optimal minval = val if N == PCTG: # optimal break return pdf ############### genSampling ########################### def genSampling(pdf, iter, tol, calib=[1, 1]): # A monte-carlo algorithm to generate a sampling pattern with # minimum peak interference. The number of samples will be # sum(pdf) +- tol # # Inputs: # pdf - probability density function to choose samples from # iter - vector of min interferences measured each try # tol - the deviation from the desired number of samples in samples # Outputs: # mask - sampling pattern # (c) Michael Lustig 2007. # Converted from Matlab to Python by Efrat Shimron (2020) # print('inside genSampling') print('calib=', calib) pdf[pdf > 1] = 1 K = np.sum(pdf[::]) minIntr = np.array([1e99]) minIntrVec = np.zeros(pdf.shape) for n in range(iter): tmp = np.zeros(pdf.shape) while np.abs(np.sum(tmp[::]) - K) > tol: tmp = np.random.random(pdf.shape) < pdf TMP = np.fft.ifft2(tmp / pdf) if np.max(np.abs(TMP[1:-1])) < minIntr: minIntr = np.max(np.abs(TMP[1:-1])) minIntrVec = tmp mask = minIntrVec # add calibration area nx = mask.shape[-1] ny = mask.shape[-2] mask[int(ny / 2 - calib[-2] / 2):int(ny / 2 + calib[-2] / 2), int(nx / 2 - calib[-1] / 2):int(nx / 2 + calib[-1] / 2)] = 1 return mask # ############### Example for calling the above two functions: ########################### # imSize=np.array([128,128]) # #imSize=np.array([128]) # R_wanted = 6 # pctg = 1/R_wanted # p=3 # pdf,_ = genPDF(imSize,p,pctg) # mask = genSampling(pdf,iter=10,tol=60) # fig = plt.figure() # plt.imshow(abs(pdf)) # fig = plt.figure() # plt.imshow(mask)
{"hexsha": "58151f4d1b634b3b26644f2126dbb4f0f46ed993", "size": 5712, "ext": "py", "lang": "Python", "max_stars_repo_path": "subtle_data_crimes/crime_2_jpeg/Fig7/DL/utils/sampling_funcs.py", "max_stars_repo_name": "mikgroup/subtle_data_crimes", "max_stars_repo_head_hexsha": "210025d9cb8f92583f5f983be15af06b57cfea36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-12-12T02:32:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T02:26:26.000Z", "max_issues_repo_path": "subtle_data_crimes/crime_2_jpeg/Fig7/DL/utils/sampling_funcs.py", "max_issues_repo_name": "mikgroup/data_crimes", "max_issues_repo_head_hexsha": "210025d9cb8f92583f5f983be15af06b57cfea36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "subtle_data_crimes/crime_2_jpeg/Fig7/DL/utils/sampling_funcs.py", "max_forks_repo_name": "mikgroup/data_crimes", "max_forks_repo_head_hexsha": "210025d9cb8f92583f5f983be15af06b57cfea36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9949238579, "max_line_length": 126, "alphanum_fraction": 0.5339635854, "include": true, "reason": "import numpy", "num_tokens": 1660}
import gc import os import numpy as np import tensorflow as tf from tensorflow.contrib.image import translate as tf_translate from scipy.ndimage import gaussian_filter from utils.distance_measures import DistL2 from models.minibatch_wrapper import MinibatchWrapper from utils import saliency, dataset_imagenet from utils.util import find_img_centroid class StartingPointFinder: def __init__(self, bb_model, surr_model, imagenet_base_path, saliency_base_path, tf_session, batch_size=8): self.bb_model = MinibatchWrapper(bb_model, batch_size=batch_size) self.surr_model = MinibatchWrapper(surr_model, batch_size=batch_size) self.imagenet_base_path = imagenet_base_path self.saliency_base_path = saliency_base_path # TF graph for fast-ish random transforms self.tf_session = tf_session self.tf_img = None self.tf_centroid = None self.tf_resize = None self.tf_flip = None self.tf_centr_target = None self.tf_trans_out = None self.tf_shifted_centr_out = None self.init_transform_graph() def init_transform_graph(self): """ TF graph for random scale, flip, translate for a batch of images. """ img_shape = (299, 299, 3) with self.tf_session.as_default(): tf_img = tf.placeholder(dtype=tf.float32, shape=(None,) + img_shape) tf_centroid = tf.placeholder(dtype=tf.float32, shape=2) # Pixel coords of centroid tf_resize = tf.placeholder(dtype=tf.int32, shape=2) # resize: new_height, new_width tf_flip = tf.placeholder(dtype=tf.bool, shape=()) # flip horizontally: true/false tf_centr_target = tf.placeholder(dtype=tf.int32, shape=2) # translate img so centroid is at this location: y/x flipped = tf.cond(tf_flip, lambda: tf.image.flip_left_right(tf_img), lambda: tf_img) flipped_centr = tf_centroid * [1., 0.] flipped_centr += tf.cond(tf_flip, lambda: (img_shape[:2] - tf_centroid), lambda: tf_centroid) * [0., 1.] scaled = tf.image.resize_images(flipped, tf_resize, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) scaled_centr = flipped_centr * (tf.cast(tf_resize, tf.float32) / img_shape[:2]) padded = tf.image.pad_to_bounding_box(scaled, offset_height=0, offset_width=0, target_height=img_shape[0], target_width=img_shape[1]) padded_centr = scaled_centr to_shift = tf.cast(tf_centr_target, tf.float32) - padded_centr shifted_centr = padded_centr + to_shift to_shift = tf.ones([tf.shape(padded)[0], 2]) * to_shift # Tile into batch dimension shifted_img = tf_translate(padded, to_shift[:, ::-1], interpolation="BILINEAR") # For some weird reason this is xy and not yx self.tf_img = tf_img self.tf_centroid = tf_centroid self.tf_resize = tf_resize self.tf_flip = tf_flip self.tf_centr_target = tf_centr_target self.tf_trans_out = shifted_img self.tf_shifted_centr_out = shifted_centr def random_transform(self, imgs, centroid_start, centroid_orig): """ Randomly transforms a batch of images. An extra translation is added (centroid_start - centroid_orig), in an effort to try and align the saliency centroids of both starting point and original image. The basic idea was to have features of the adversarial class directly on top of features of the original, hopefully overwriting them with minimal perturbation required. :param imgs: A batch of images (b,h,w,c) :param centroid_start: Saliency centroid of the image(s). Only one centroid for the entire batch. :param centroid_orig: Saliency centroid of the image to attack. :return: transformed batch of images. """ rnd_resize = np.random.uniform(0.5, 1.0) rnd_resize = np.int32(np.round(rnd_resize * 299)) rnd_flip = np.random.uniform() < 0.5 rnd_shift = [np.random.randint(-75, 75), np.random.randint(-75, 75)] with self.tf_session.as_default(): imgs_trans, centroid_target_trans = self.tf_session.run([self.tf_trans_out, self.tf_shifted_centr_out], feed_dict={ self.tf_img: imgs, self.tf_centroid: centroid_start, self.tf_resize: [rnd_resize, rnd_resize], # Keep aspect ratio self.tf_flip: rnd_flip, self.tf_centr_target: centroid_orig + rnd_shift }) centroid_target_trans = np.int32(np.round(centroid_target_trans)) return imgs_trans, centroid_target_trans def load_saliency_mask(self, img_id): """ Loads a precalc'd saliency map from disk. Need to run precalc_saliency_maps first. """ filepath = os.path.join(self.saliency_base_path, str(img_id), "maps.npz") maps = np.load(filepath) # Use SmoothGrad normal and SmoothGrad Guided Backprop saliency_mask_normal = saliency.VisualizeImageGrayscale(maps["saliency_mask_normal_smooth"]) saliency_mask_gb = saliency.VisualizeImageGrayscale(maps["saliency_mask_gb_smooth"]) # Combine normal and GB masks. SmoothGrad GB has really good features, but often large areas in the background that don't matter. # Normal smooth doesn't have those, so we try to keep GB features, but remove background areas. saliency_mask_combined = np.copy(saliency_mask_gb) low_index = saliency_mask_normal < 0.05 saliency_mask_combined[low_index] = saliency_mask_normal[low_index] return saliency_mask_combined def find_start_from_saliency(self, X_orig, orig_id, y_target, target_ids): """ Creates a starting point for attacking an image using precalculated saliency information. :param X_orig: The original image to attack. :param orig_id: The image ID (in the X_val dataset) of the original. Needed for retrieving saliency maps. :param y_target: The target adversarial class label. :param target_ids: Image IDs (in the X_val dataset) of all images of the target class. :return: """ if len(target_ids) == 0: raise ValueError("No images of the target class!") print("There are {} images of the target class.".format(len(target_ids))) if len(target_ids) > 500: print("WARN: Large number of images of the target class! Do you have enough memory?") dm_l2 = DistL2().to_range_255() print("Loading precalc'd saliency maps...") X_target_all = dataset_imagenet.load_on_demand_X_val(self.imagenet_base_path, target_ids) saliency_target_all = np.empty(X_target_all.shape[:3], dtype=np.float32) centroid_target_all = np.empty((X_target_all.shape[0], 2), dtype=np.int32) # We run this function in a loop 5 times. Sometimes, but not often, we may randomly fail to construct a good starting point. # When this happens, we amplify and smoothen the saliency mask even further, resulting in a larger patch that is added to the image. # If we still fail 4 times, in the last try we set the mask to 100%. This is basically a fallback to a "closest image" strategy. found_start = False n_tries = 5 for i_try in range(n_tries): for i, img_id in enumerate(target_ids): saliency_mask_gray = self.load_saliency_mask(img_id) centroid_target_all[i, :] = find_img_centroid(saliency_mask_gray, min_mass_threshold=.5) # Save center of mass, can be [-1,-1] if empty # Amplify mask: # - Default: Amplify via sqrt and add smooth transitions via Gauss # - If previous tries didn't find anything: amplify even further. # - If last try: set mask to full img. if i_try >= 1: saliency_mask_gray = saliency_mask_gray ** 0.75 if i_try >= 2: saliency_mask_gray = saliency_mask_gray ** 0.75 if i_try >= 3: saliency_mask_gray += 0.1 * i_try if i_try == n_tries - 1: saliency_mask_gray = np.ones_like(saliency_mask_gray) saliency_mask_gray = saliency_mask_gray ** 0.55 saliency_mask_gray += 2. * gaussian_filter(saliency_mask_gray, sigma=1.0) np.clip(saliency_mask_gray, 0., 1., out=saliency_mask_gray) saliency_target_all[i, ...] = saliency_mask_gray saliency_orig = self.load_saliency_mask(orig_id) saliency_orig_color = np.tile(saliency_orig[:, :, np.newaxis], (1, 1, 3)) centroid_orig = find_img_centroid(saliency_orig, min_mass_threshold=.5) print("Original image's saliency centroid is at {}.".format(centroid_orig)) X_orig_mod = np.copy(np.float32(X_orig)) # Random seed: fix so the generated starting points are the same each time we run this. # HOWEVER, change the (fixed) seed for every subsequent try, so we don't retry the same transforms that didn't work before. np.random.seed(i_try) # Generate all candidates X_start_all = [] masks_all = [] img_ids_all = [] for i, img_id in enumerate(target_ids): print("Preparing target img {}...".format(img_id)) saliency_mask_color = np.tile(saliency_target_all[i, :, :, np.newaxis], (1, 1, 3)) X_target = X_target_all[i, ...] centroid_start = centroid_target_all[i, :] if centroid_start[0] < 0: print("WARN: Saliency mask is empty for this image. Skipping.") continue print("Target image's saliency centroid is at {}.".format(centroid_start)) # Do a lot of random transforms (zoom and rotate). n_trans_samples = 50 for i_trans_sample in range(n_trans_samples): # Do a random transform (scale, flip and shift) # - For an L2 attack, we want to create one small patch with strong features of the target. # This massively reduces the L2 distance of the starting point. X_start = np.copy(X_orig_mod) mask_sum = np.zeros_like(X_start) n_copies = 1 # If you want, you can also add multiple copies :) Should work well for L_inf attacks. for i_copy in range(n_copies): imgs = np.stack([X_target, saliency_mask_color]) imgs_trans, centroid_target_trans = self.random_transform(imgs, centroid_start=centroid_start, centroid_orig=centroid_orig) X_target_trans, saliency_map_trans = imgs_trans # Interpolate: Starting point = original + saliency*(target_img - original) diff = (np.float32(X_target_trans) - np.float32(X_start)) * saliency_map_trans X_start = np.clip(X_start + diff, 0., 255.) mask_sum = np.clip(mask_sum + saliency_map_trans, 0., 1.) X_start_all.append(X_start) masks_all.append(mask_sum) img_ids_all.append(img_id) # Remember the image id for logging purposes X_start_all = np.uint8(np.clip(np.round(np.array(X_start_all)), 0, 255)) masks_all = np.array(masks_all) img_ids_all = np.array(img_ids_all) # Get predictions from surrogate model and remove all starting points that are not adversarial on it. # This is a quick sanity check, so we don't waste too many calls on the black box model. preds_all = self.surr_model.batch_predictions(X_start_all) adv_filter = np.argmax(preds_all, axis=1) == y_target print("{} of {} starting points are adversarial for the surrogate.".format(np.sum(adv_filter), len(X_start_all))) X_start_all = X_start_all[adv_filter] masks_all = masks_all[adv_filter] img_ids_all = img_ids_all[adv_filter] # Calculate distance for remaining images. Lower is better. score_all = np.empty(X_start_all.shape[0]) for i in range(X_start_all.shape[0]): score_all[i] = dm_l2.calc(X_start_all[i, ...], X_orig) # Sort ascending by distance, and try them one by one on the black box. The first to succeed is picked. sort_indices = np.argsort(score_all) for i, ind in enumerate(sort_indices): X_best = X_start_all[ind] mask_best = masks_all[ind] img_id_best = img_ids_all[ind] pred = self.bb_model.predictions(X_best) if np.argmax(pred) == y_target: found_start = True print("Found a valid starting point (no. {}).".format(i)) break if found_start: break else: print("None of the starting points were adversarial on the black box model.") print("Reducing mask strength, retry no. {}".format(i_try+1)) gc.collect() if not found_start: # This should only happen if not even the clean images worked. raise ValueError("Could not find a starting point - at all.") # Mask: features of target class AND original features (allow to perturb both). Also scale it between [0,1] for the BBA. mask_best = np.maximum(mask_best, saliency_orig_color) mask_best /= np.max(mask_best) dist = dm_l2.calc(X_orig, X_best) print("Picked img with d_l2 of {:.3f}. Used features from image id {}.".format(dist, img_id_best)) print("Dimensionality of search space: {}".format(np.sum(mask_best))) return np.uint8(np.clip(np.round(X_best), 0., 255.)), mask_best, img_id_best
{"hexsha": "7ebd9fe264e36fbf306a04603ddc626fe83b1347", "size": 14391, "ext": "py", "lang": "Python", "max_stars_repo_path": "starting_point_finder.py", "max_stars_repo_name": "ttbrunner/blackbox_starting_points", "max_stars_repo_head_hexsha": "7d489cc712a3ee53bfd630ce2830bf643feecb0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-07-14T05:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T16:11:53.000Z", "max_issues_repo_path": "starting_point_finder.py", "max_issues_repo_name": "ttbrunner/blackbox_starting_points", "max_issues_repo_head_hexsha": "7d489cc712a3ee53bfd630ce2830bf643feecb0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "starting_point_finder.py", "max_forks_repo_name": "ttbrunner/blackbox_starting_points", "max_forks_repo_head_hexsha": "7d489cc712a3ee53bfd630ce2830bf643feecb0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-09T20:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-09T20:55:25.000Z", "avg_line_length": 52.9080882353, "max_line_length": 155, "alphanum_fraction": 0.6263636995, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3243}
function tapas_validate_data(data) %% Check that data complies with the inferface. % % [email protected] % copyright (C) 2016 % if ~isstruct(data) error('tapas:validate:data', 'data is not a structure') end if ~isfield(data, 'y') error('tapas:validate:data', 'data lacks field y'); end if ~isfield(data, 'u') error('tapas:validate:data', 'data lacks field u'); end end
{"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/tools/ti/tapas_validate_data.m"}
abstract Initializer type NormalInit <: Initializer mu :: AbstractFloat sd :: AbstractFloat function NormalInit(mu=0.0, sd=1.0) new(mu, sd) end end type UniformInit <: Initializer min :: AbstractFloat max :: AbstractFloat function UniformInit(min=0.0, max=1.0) new(min, max) end end function initialize(T::DataType, mapdim::Tuple, init::UniformInit) data = rand(T, mapdim) data -= T(init.min) data /= T(init.max-init.min) end function initialize(T::DataType, mapdim::Tuple, init::NormalInit) data = convert(Array{T},randn(mapdim)) data *= T(init.sd) data += T(init.mu) end
{"hexsha": "d2a9863fb3ade191aaf299ba6ce4bfc0586c258c", "size": 650, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/initializer.jl", "max_stars_repo_name": "peakbook/BlockMatchingSOMs.jl", "max_stars_repo_head_hexsha": "e70d20a4e6dce296f6b489a3344090e97db1085d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-05T22:27:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-05T22:27:36.000Z", "max_issues_repo_path": "src/initializer.jl", "max_issues_repo_name": "peakbook/BlockMatchingSOMs.jl", "max_issues_repo_head_hexsha": "e70d20a4e6dce296f6b489a3344090e97db1085d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/initializer.jl", "max_forks_repo_name": "peakbook/BlockMatchingSOMs.jl", "max_forks_repo_head_hexsha": "e70d20a4e6dce296f6b489a3344090e97db1085d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9677419355, "max_line_length": 66, "alphanum_fraction": 0.6492307692, "num_tokens": 183}
import matplotlib.pyplot as plt from numpy import * import Model def read_data_from_file(filename): file = open(filename, "r") file.readline() data = file.readlines() x_true, y_true = [], [] for line in data: temp = line.split(",") x_true.append(int(temp[0])) y_true.append(int(temp[1][:-1])) return x_true, y_true x_true, y_true = read_data_from_file("data.csv") x_train = x_true[0:25] y_train = y_true[0:25] x_test = x_true[25:] y_test = y_true[25:] learning_rate = 0.00001 iterations = 10 momentum = 0 model = Model.Model(0, 0) validation_loss_graph = [] train_loss_graph = [] iter = [] for i in range(30): model.optimize(x_train, y_train, learning_rate, momentum) train_loss = model.calculate_cost(x_train, y_train) test_loss = model.calculate_cost(x_test, y_test) train_loss_graph.append(train_loss) validation_loss_graph.append(test_loss) iter.append(i) print ("Train Loss : ", train_loss, " Test Loss : ", test_loss) plt.plot(iter,train_loss_graph) plt.xlabel('Iterations') plt.ylabel('Loss') plt.title('Train Loss Graph') plt.show() plt.plot(iter,validation_loss_graph) plt.xlabel('Iterations') plt.ylabel('Loss') plt.title('Validation Loss Graph') plt.show()
{"hexsha": "eb165e96358ce4fa0a45b5fc31956ef3d361a997", "size": 1358, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW1/Experiment1.py", "max_stars_repo_name": "efkandurakli/Pattern-Recognition-Homewoks", "max_stars_repo_head_hexsha": "0d24a2c5d38fb70b02313ea6c1b8342bdcfa4495", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW1/Experiment1.py", "max_issues_repo_name": "efkandurakli/Pattern-Recognition-Homewoks", "max_issues_repo_head_hexsha": "0d24a2c5d38fb70b02313ea6c1b8342bdcfa4495", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW1/Experiment1.py", "max_forks_repo_name": "efkandurakli/Pattern-Recognition-Homewoks", "max_forks_repo_head_hexsha": "0d24a2c5d38fb70b02313ea6c1b8342bdcfa4495", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4102564103, "max_line_length": 70, "alphanum_fraction": 0.6421207658, "include": true, "reason": "from numpy", "num_tokens": 337}
import os import sys import numpy as np BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = BASE_DIR DATA_PATH = os.path.join(ROOT_DIR, 'data/') out_fname = ['rgbnss_trn', 'rgbnss_tst', 'depth_trn', 'depth_tst'] xtrn_list = [line.rstrip() for line in open(os.path.join(DATA_PATH, 'xtrn_list.txt'))] xtst_list = [line.rstrip() for line in open(os.path.join(DATA_PATH, 'xtst_list.txt'))] ytrn_list = [line.rstrip() for line in open(os.path.join(DATA_PATH, 'ytrn_list.txt'))] ytst_list = [line.rstrip() for line in open(os.path.join(DATA_PATH, 'ytst_list.txt'))] flist = [xtrn_list, xtst_list, ytrn_list, ytst_list] data_merged = [] for i in range(len(flist)): for f in flist[i]: data = np.load(DATA_PATH+f, allow_pickle=True) data_merged.append(data) data_stack = np.concatenate(data_merged, axis=0) np.save(DATA_PATH+'/'+out_fname[i], data_stack, allow_pickle=True) data_merged = []
{"hexsha": "d30ca922ec617070f128fb08b1254f810e36c951", "size": 931, "ext": "py", "lang": "Python", "max_stars_repo_path": "stack_all_data.py", "max_stars_repo_name": "yustisiardhitasari/sdbcnn", "max_stars_repo_head_hexsha": "5b591009c1576c6879bf883c6eec23b0b743d2cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-19T15:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T05:41:44.000Z", "max_issues_repo_path": "stack_all_data.py", "max_issues_repo_name": "yustisiardhitasari/sdbcnn", "max_issues_repo_head_hexsha": "5b591009c1576c6879bf883c6eec23b0b743d2cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stack_all_data.py", "max_forks_repo_name": "yustisiardhitasari/sdbcnn", "max_forks_repo_head_hexsha": "5b591009c1576c6879bf883c6eec23b0b743d2cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-02T04:35:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T14:56:43.000Z", "avg_line_length": 37.24, "max_line_length": 86, "alphanum_fraction": 0.7099892589, "include": true, "reason": "import numpy", "num_tokens": 268}
\section{Conclusion} \label{sec:conc} Blockchains have the potential to disrupt incumbent applications on the data sharing economy. In addition to this, the Transportation industry is going through a radical shift due to the new types of data and applications that have become available. For instance the proliferation of mobile phones has brought a surge in crowd-sourced data. Also widespread deployment of cheap hardware sensor networks combined with smart analysis and planning algorithms are able to utilize this data to create valuable new insights and applications that were not previously possible. By bringing the blockchain technology and designing it from the grounds up for Transportation applications, we have created the world's first blockchain specifically tailored for Transportation applications. Our mission is for Latitude to become the de-facto platform for all transportation applications by building the right constructs for trusted, privacy-aware, secure and verifiable data and computation sharing/enforcement. Our mission is to build Latitude to support applications across the planet and across different modes of transport. We are excited by how Latitude stands to disrupt existing applications such as Ride-sharing, Mapping, Location sharing and analytics and the driver-behavior industry (UBIs). The full-whitepaper shall contain a deeper dive into the mechanics of the Latitude blockchain including details on how the smart contract system, the cryptographic proofs and the datastore would function.
{"hexsha": "b2e8d0fc92d13be2a554aa2c87c5fd0f18aa7a54", "size": 1535, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "conclusion.tex", "max_stars_repo_name": "arunesh/latwp", "max_stars_repo_head_hexsha": "a84fff7e01cfea691a81024f13cd730bea6c8c05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conclusion.tex", "max_issues_repo_name": "arunesh/latwp", "max_issues_repo_head_hexsha": "a84fff7e01cfea691a81024f13cd730bea6c8c05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conclusion.tex", "max_forks_repo_name": "arunesh/latwp", "max_forks_repo_head_hexsha": "a84fff7e01cfea691a81024f13cd730bea6c8c05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.0952380952, "max_line_length": 123, "alphanum_fraction": 0.8351791531, "num_tokens": 271}
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed 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. import unittest import numpy as np from mars.session import new_session try: import sklearn from sklearn.metrics import pairwise_distances as sk_pairwise_distances from sklearn.exceptions import DataConversionWarning from sklearn.utils._testing import assert_warns except ImportError: sklearn = None from mars import tensor as mt from mars.learn.metrics import pairwise_distances from mars.tests.core import ExecutorForTest @unittest.skipIf(sklearn is None, 'scikit-learn not installed') class Test(unittest.TestCase): def setUp(self) -> None: self.session = new_session().as_default() self._old_executor = self.session._sess._executor self.executor = self.session._sess._executor = \ ExecutorForTest('numpy', storage=self.session._sess._context) def tearDown(self) -> None: self.session._sess._executor = self._old_executor def testPairwiseDistancesExecution(self): raw_x = np.random.rand(20, 5) raw_y = np.random.rand(21, 5) x = mt.tensor(raw_x, chunk_size=11) y = mt.tensor(raw_y, chunk_size=12) d = pairwise_distances(x, y) result = self.executor.execute_tensor(d, concat=True)[0] expected = sk_pairwise_distances(raw_x, raw_y) np.testing.assert_almost_equal(result, expected) # test precomputed d2 = d.copy() d2[0, 0] = -1 d2 = pairwise_distances(d2, y, metric='precomputed') with self.assertRaises(ValueError): _ = self.executor.execute_tensor(d2, concat=True)[0] # test cdist weight = np.random.rand(5) d = pairwise_distances(x, y, metric='wminkowski', p=3, w=weight) result = self.executor.execute_tensor(d, concat=True)[0] expected = sk_pairwise_distances(raw_x, raw_y, metric='wminkowski', p=3, w=weight) np.testing.assert_almost_equal(result, expected) # test pdist d = pairwise_distances(x, metric='hamming') result = self.executor.execute_tensor(d, concat=True)[0] expected = sk_pairwise_distances(raw_x, metric='hamming') np.testing.assert_almost_equal(result, expected) # test function metric m = lambda u, v: np.sqrt(((u-v)**2).sum()) d = pairwise_distances(x, y, metric=m) result = self.executor.execute_tensor(d, concat=True)[0] expected = sk_pairwise_distances(raw_x, raw_y, metric=m) np.testing.assert_almost_equal(result, expected) assert_warns(DataConversionWarning, pairwise_distances, x, y, metric='jaccard') with self.assertRaises(ValueError): _ = pairwise_distances(x, y, metric='unknown')
{"hexsha": "82f331067cbf449dccaf1ca643ded164e42d9dbf", "size": 3379, "ext": "py", "lang": "Python", "max_stars_repo_path": "mars/learn/metrics/pairwise/tests/test_pariwise_distances.py", "max_stars_repo_name": "tomzhang/mars-1", "max_stars_repo_head_hexsha": "6f1d85e37eb1b383251314cb0ba13e06288af03d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-25T13:51:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-25T13:51:16.000Z", "max_issues_repo_path": "mars/learn/metrics/pairwise/tests/test_pariwise_distances.py", "max_issues_repo_name": "tomzhang/mars-1", "max_issues_repo_head_hexsha": "6f1d85e37eb1b383251314cb0ba13e06288af03d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mars/learn/metrics/pairwise/tests/test_pariwise_distances.py", "max_forks_repo_name": "tomzhang/mars-1", "max_forks_repo_head_hexsha": "6f1d85e37eb1b383251314cb0ba13e06288af03d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7282608696, "max_line_length": 75, "alphanum_fraction": 0.6732761172, "include": true, "reason": "import numpy", "num_tokens": 756}
[STATEMENT] lemma set_attribute_get_attribute: "h \<turnstile> set_attribute ptr k v \<rightarrow>\<^sub>h h' \<Longrightarrow> h' \<turnstile> get_attribute ptr k \<rightarrow>\<^sub>r v" [PROOF STATE] proof (prove) goal (1 subgoal): 1. h \<turnstile> set_attribute ptr k v \<rightarrow>\<^sub>h h' \<Longrightarrow> h' \<turnstile> get_attribute ptr k \<rightarrow>\<^sub>r v [PROOF STEP] by(auto simp add: set_attribute_impl[unfolded a_set_attribute_def] get_attribute_impl[unfolded a_get_attribute_def] elim!: bind_returns_heap_E2 intro!: bind_pure_returns_result_I elim: element_put_get)
{"llama_tokens": 221, "file": "Core_DOM_common_Core_DOM_Functions", "length": 1}
# -*- coding: utf-8 -*- import numpy as np import statistics from skimage import filters, morphology, measure import matplotlib.pyplot as plt def kymo_to_coords(kymo, thres=15, pixel_length = 0.1833333): """ This function takes a kymograph and extract the membrane position from the image. Parameters ---------- kymo : array A kymograph. thres : integer, optional The largest membrane displacement allowed in a frame. The default is 15 pixels. pixel_length : integer, optional The pixel size. The default is 0.1833333. Returns ------- normalized_coords : list A list of coordinates in tuples where the lowest point is normalized to 0. filtered_coords : list A list of coordinates in tuples where extremas are filtered and replaced by the interpolated position between frames. """ smooth_kymo = filters.median(kymo > 0, morphology.disk(3)) # plt.imshow(smooth_kymo) # plt.show() sobel_kymo = filters.sobel(smooth_kymo) # plt.imshow(sobel_kymo) # plt.show() coords = [] coords.append(np.argmax(np.gradient(smooth_kymo[:,0]*1))) for time in range(1, sobel_kymo.shape[1]-1): local_max = np.argmax(sobel_kymo[:,time]) coords.append(local_max) coords.append(np.argmax(np.gradient(smooth_kymo[:,-1]*1))) # the following code replaces outliers with interpolated points filtered_coords = [] #save all the filtered points filtered_coords.append(coords[0]) for kk in range(1, len(coords)-1): z = coords[kk] z_before = coords[kk-1] z_after = coords[kk+1] if np.abs(z_before - z) > thres or np.abs(z_after - z) > thres: if kk < 3: new_coords = int(statistics.mean([coords[kk+1], coords[kk+2], coords[kk+3]])) filtered_coords.append(new_coords) if kk >= 3 and kk <= len(coords)-4: new_coords = int(statistics.mean([coords[kk+1], coords[kk+2], coords[kk+3], coords[kk-1], coords[kk-2], coords[kk-3]])) filtered_coords.append(new_coords) if kk > len(coords)-4: new_coords = int(statistics.mean([coords[kk-1],coords[kk-2],coords[kk-3]])) filtered_coords.append(new_coords) else: filtered_coords.append(z) filtered_coords.append(coords[-1]) # the following code normalize the coordinates to the lowest point normalized_coords = [] for jj in range(len(filtered_coords)): #norm_coords = filtered_coords[jj]*-1 + max(filtered_coords) norm_coords = (filtered_coords[jj]*-1 + max(filtered_coords)) * pixel_length normalized_coords.append(norm_coords) return normalized_coords, filtered_coords
{"hexsha": "9ddef7453170ff5287628ed61ad810197cbd1558", "size": 2784, "ext": "py", "lang": "Python", "max_stars_repo_path": "kymo_to_coords.py", "max_stars_repo_name": "ernestiu/Cell-spreading-analysis", "max_stars_repo_head_hexsha": "5a8807be9e25b6cc8cc4850f03810eacc48fe8e0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kymo_to_coords.py", "max_issues_repo_name": "ernestiu/Cell-spreading-analysis", "max_issues_repo_head_hexsha": "5a8807be9e25b6cc8cc4850f03810eacc48fe8e0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kymo_to_coords.py", "max_forks_repo_name": "ernestiu/Cell-spreading-analysis", "max_forks_repo_head_hexsha": "5a8807be9e25b6cc8cc4850f03810eacc48fe8e0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6666666667, "max_line_length": 135, "alphanum_fraction": 0.6436781609, "include": true, "reason": "import numpy", "num_tokens": 688}
import unittest import pytest import numpy as np import pickle from s2and.data import ANDData from s2and.model import Clusterer from s2and.featurizer import FeaturizationInfo, many_pairs_featurize from s2and.consts import LARGE_DISTANCE from sklearn.linear_model import LogisticRegression class TestClusterer(unittest.TestCase): def setUp(self): super().setUp() self.dummy_dataset = ANDData( "tests/dummy/signatures_incompatible.json", "tests/dummy/papers.json", clusters="tests/dummy/clusters.json", cluster_seeds={"1": {"2": "require"}}, altered_cluster_signatures=["1", "2"], name="dummy", load_name_counts=True, ) features_to_use = [ "affiliation_similarity", ] featurizer_info = FeaturizationInfo(features_to_use=features_to_use) np.random.seed(1) X = np.vstack([np.ones((100, 1)), np.random.uniform(0, 0.5, (100, 1))]) y = np.vstack([np.ones((100, 1)), np.zeros((100, 1))]).squeeze() clf = LogisticRegression().fit(X, y) self.dummy_clusterer = Clusterer( featurizer_info=featurizer_info, classifier=clf, n_jobs=1, use_cache=False, use_default_constraints_as_supervision=True, ) def test_predict_incremental(self): """ signature: first name 1: A 2: Alan 3: Alec 4: Alan 5: A A and Alec would be allowed normally. A and the first Alan are seeded in a cluster together. The only feature in this test is affiliation similarity, and (1,3) and (2,4) each have the same affiliation, and so the pairwise model would rate them as similar. Given all of this, the expected outcome is that, when we prevent new incompatibilities, Alec does not get added to the seeded cluster, but the second Alan does. When we do not prevent new incompatibilities, all the signatures should end up in a cluster together. """ block = ["3", "4"] output = self.dummy_clusterer.predict_incremental(block, self.dummy_dataset) expected_output = {"0": ["1", "2", "4"], "1": ["3"]} assert output == expected_output block = ["3", "4"] output = self.dummy_clusterer.predict_incremental( block, self.dummy_dataset, prevent_new_incompatibilities=False ) expected_output = {"0": ["1", "2", "3", "4"]} assert output == expected_output # NOTE: this behavior is expected given the current implementation, but is not ideal # because Alec and Alan were simultaneously added to the A cluster. Noting here in case # this issue comes up later so someone knows where to start. # It is testing that when the claimed cluster only contains signatures with a single character # first name, the added incompatibility rule does not prevent adding to the cluster self.dummy_dataset.altered_cluster_signatures = ["1", "5"] self.dummy_dataset.cluster_seeds_require = {"1": 0, "5": 0} block = ["3", "4"] output = self.dummy_clusterer.predict_incremental(block, self.dummy_dataset) expected_output = {"0": ["1", "5", "3", "4"]} assert output == expected_output
{"hexsha": "66579e70df0c64235d8dccafc00bc12f5eb65e1a", "size": 3368, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_cluster_incremental_incompatible.py", "max_stars_repo_name": "atypon/S2AND", "max_stars_repo_head_hexsha": "d1af114edf5941d0ec00f56b11508582e1091913", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2021-03-09T23:07:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T17:32:54.000Z", "max_issues_repo_path": "tests/test_cluster_incremental_incompatible.py", "max_issues_repo_name": "atypon/S2AND", "max_issues_repo_head_hexsha": "d1af114edf5941d0ec00f56b11508582e1091913", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-03-16T19:19:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T22:16:46.000Z", "max_forks_repo_path": "tests/test_cluster_incremental_incompatible.py", "max_forks_repo_name": "atypon/S2AND", "max_forks_repo_head_hexsha": "d1af114edf5941d0ec00f56b11508582e1091913", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-04-02T11:38:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:58:18.000Z", "avg_line_length": 40.0952380952, "max_line_length": 102, "alphanum_fraction": 0.6350950119, "include": true, "reason": "import numpy", "num_tokens": 791}
#!/usr/bin/env python # -*- coding: utf-8 -*- import openravepy import numpy import random from copy import deepcopy if not __openravepy_build_doc__: from openravepy import * from numpy import * class Node: def __init__(self, _input, id_in, parentid_in): self.config = _input self.id = id_in self.parentid = parentid_in def printme(self): print self.config[0], self.config[1], self.config[2], self.config[3], self.config[4], self.config[5], self.id, self.parentid def creatrandomdir(presentconfig, randomvector, step): _randomvector = array(randomvector) _presentconfig = array(presentconfig) randdir = step*(_randomvector-_presentconfig)/numpy.linalg.norm(_randomvector-_presentconfig) return randdir def rotaionnorm(config1, config2): return numpy.linalg.norm(matrix(config1)-matrix(config2)) def getclosenode(randconfig, allnode): dis_min = rotaionnorm(allnode[0].config, randconfig) index_min = 0 for i in range(len(allnode)): if abs(allnode[i].config[4]-randconfig[4]) > dis_min or abs(allnode[i].config[1]-randconfig[1]) > dis_min: continue dis_temp = numpy.linalg.norm(matrix(allnode[i].config)-matrix(randconfig)) if dis_temp < dis_min: dis_min = dis_temp index_min = i return index_min def Iscollision(env, robot, newconfig): robot.SetActiveDOFValues(newconfig) if env.CheckCollision(robot) is False: return 0 else: return 1 def IsTemination(presentconfig, goalconfig, step): if rotaionnorm(presentconfig, goalconfig) < step: return 1 return 0 def Creatpath(allnode, goalid, env, handles, robot): path = [] idpresent = goalid while True: path.append(allnode[idpresent].config.tolist()) Plotendeffector(handles, env, robot, allnode[idpresent].config, 1) if idpresent == 0: break else: idpresent = allnode[idpresent].parentid path.reverse() return path def GetEETransform(robot, activedofvalues=None): if activedofvalues != None: robot.SetActiveDOFValues(activedofvalues); manip = robot.GetActiveManipulator() return manip.GetEndEffectorTransform() def Plotendeffector(handles, env, robot, activedofvalues, choise): size = 5 transform = GetEETransform(robot, activedofvalues) if choise == 0: col = array(((0, 0, 1))) #size = 15 elif choise == 1: col = array(((1, 0, 0))) elif choise == 2: col = array(((0, 1, 0))) else: col = array(((0, 0, 0))) handles.append(env.plot3(points=array((transform[0][3], transform[1][3], transform[2][3])), pointsize = size, colors=col)) def Randconfig(tar_ratio, limit, goalconfig): if random.random() <= tar_ratio*1: randconfig = array(goalconfig) else: randconfig = array([random.uniform(limit[0][0], limit[0][1]), random.uniform(limit[1][0], limit[1][1]), random.uniform(limit[2][0], limit[2][1]), random.uniform(limit[3][0], limit[3][1]), random.uniform(-2*pi, 0), random.uniform(limit[5][0], limit[5][1])]) if random.random() <= tar_ratio: randconfig = array(goalconfig)+0.3*array([random.uniform(limit[0][0]-goalconfig[0], limit[0][1]-goalconfig[0]), random.uniform(limit[1][0]-goalconfig[1], limit[1][1]-goalconfig[1]), random.uniform(limit[2][0]-goalconfig[2], limit[2][1]-goalconfig[2]), random.uniform(limit[3][0]-goalconfig[3], limit[3][1]-goalconfig[3]), random.uniform(-pi-goalconfig[4], pi-goalconfig[4]), random.uniform(limit[5][0]-goalconfig[5], limit[5][1]-goalconfig[5])]) return randconfig def Smoothing(path_unsmooth, env, robot, ite_times, handles): path_smooth = deepcopy(path_unsmooth) for j in range(ite_times): index1 = random.randint(0, len(path_smooth)) index2 = random.randint(0, len(path_smooth)) if abs(index2-index1) < 2: continue dir = array(deepcopy(path_smooth[index1]))-array(deepcopy(path_smooth[index2])) step_smooth = 0.05*dir/numpy.linalg.norm(dir) presentconfig = array(deepcopy(path_smooth[index2])) + step_smooth flag_coll_free = 1 while numpy.linalg.norm(presentconfig-array(path_smooth[index1])) > 0.05: if Iscollision(env, robot, presentconfig) == 1: flag_coll_free = 0 break presentconfig += step_smooth if flag_coll_free == 1: del1 = min(index1, index2) del2 = max(index1, index2) del path_smooth[del1+1:del2] dir = array(deepcopy(path_smooth[del1+1]))-array(deepcopy(path_smooth[del1])) step_smooth = 0.05*dir/numpy.linalg.norm(dir) presentconfig = array(deepcopy(path_smooth[del1])) + step_smooth end_config = path_smooth[del1+1] while numpy.linalg.norm(presentconfig-array(end_config)) > 0.05: del1 = del1 + 1 path_smooth.insert(del1, presentconfig.tolist()) presentconfig = presentconfig + step_smooth for i in range(len(path_smooth)): Plotendeffector(handles, env, robot, path_smooth[i], 0) return path_smooth def RRTmainloop(env, robot, goalconfig, initialconfig, step, tar_ratio, handles, limit, ite_times): allnode = [] allnode.append(Node(array(deepcopy(initialconfig)), 0, 0)) id_presnt = 0 flag_terminate = 0 Plotendeffector(handles, env, robot, goalconfig, 1) while True: randconfig = Randconfig(tar_ratio, limit, goalconfig) id_par = getclosenode(randconfig, allnode) presentconfig = deepcopy(allnode[id_par].config) #Plotendeffector(handles, env, robot, randconfig.tolist(), 3) step_present = creatrandomdir(presentconfig, randconfig, step) while True: presentconfig = presentconfig + step_present if Iscollision(env, robot, presentconfig) == 0: id_presnt += 1 allnode.append(Node(deepcopy(presentconfig), id_presnt, id_par)) #if mod(id_presnt, 200) == 0: # print id_presnt id_par = id_presnt #Plotendeffector(handles, env, robot, presentconfig, 0) if IsTemination(presentconfig, goalconfig, step) == 1: goalid = id_presnt flag_terminate = 1 break if IsTemination(presentconfig, randconfig, step) == 1: break else: break if flag_terminate == 1: break path_unsmooth = Creatpath(allnode, goalid, env, handles, robot) path_smooth = Smoothing(path_unsmooth, env, robot, ite_times, handles) return path_smooth
{"hexsha": "c5bd2174ba11d708ebe4816cf5f4f785a2a3c928", "size": 7075, "ext": "py", "lang": "Python", "max_stars_repo_path": "RRT/rrt_fun.py", "max_stars_repo_name": "Simon0323/A-star-RRT-Motion-Planning", "max_stars_repo_head_hexsha": "3319a4da07b9a81fdc6ab64aeef119abb5aedd93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-02T02:52:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-02T02:52:23.000Z", "max_issues_repo_path": "RRT/rrt_fun.py", "max_issues_repo_name": "Simon0323/A-star-RRT-Motion-Planning", "max_issues_repo_head_hexsha": "3319a4da07b9a81fdc6ab64aeef119abb5aedd93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RRT/rrt_fun.py", "max_forks_repo_name": "Simon0323/A-star-RRT-Motion-Planning", "max_forks_repo_head_hexsha": "3319a4da07b9a81fdc6ab64aeef119abb5aedd93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-08T13:02:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T02:52:31.000Z", "avg_line_length": 39.5251396648, "max_line_length": 132, "alphanum_fraction": 0.6125795053, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1817}
// Copyright (c) 2012, Yahoo! Inc. All rights reserved. // Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. #include <tap/trivial.h> #include <gearbox/core/util.h> #include <gearbox/core/TempFile.h> using namespace Gearbox; #include "log4cxx/propertyconfigurator.h" #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> namespace bfs=boost::filesystem; #include <unistd.h> // mkstemp #include <errno.h> // errno #include <string> #include <iostream> using namespace std; int main() { chdir(TESTDIR); log4cxx::PropertyConfigurator::configure("../../../common/conf/stdout-logger.conf"); TEST_START(6); // create a "small" (1Mb) file of zeros TempFile small("/tmp/ffdigest.small"); small.close(); small.unlink(); OK( run("dd bs=1048576 count=1 if=/dev/zero of=" + small.name() + " 2> /dev/null") == 0 ); // create a "large" (64Mb) file of zeros TempFile large("/tmp/ffdigest.large"); large.close(); large.unlink(); OK( run("dd bs=1048576 count=64 if=/dev/zero of=" + large.name() + " 2> /dev/null") == 0 ); OK( digest_full( small.name() ) == "b6d81b360a5672d80c27430f39153e2c" ); OK( digest_full( large.name() ) == "7f614da9329cd3aebf59b91aadc30bf0" ); OK( digest_fast( small.name() ) == "b6d81b360a5672d80c27430f39153e2c" ); OK( digest_fast( large.name() ) == "0a9156c4e3c48ef827980639c4d1e263" ); TEST_END; }
{"hexsha": "e35b8394c24a7ecb6c0eef6d57a97414bdb5de8e", "size": 1468, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gearbox/t/core/ffdigest.t.cc", "max_stars_repo_name": "coryb/gearbox", "max_stars_repo_head_hexsha": "88027f2f101c2d1fab16093928963052b9d3294d", "max_stars_repo_licenses": ["Artistic-1.0-Perl", "BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-06-26T15:37:40.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-22T07:42:39.000Z", "max_issues_repo_path": "gearbox/t/core/ffdigest.t.cc", "max_issues_repo_name": "coryb/gearbox", "max_issues_repo_head_hexsha": "88027f2f101c2d1fab16093928963052b9d3294d", "max_issues_repo_licenses": ["Artistic-1.0-Perl", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gearbox/t/core/ffdigest.t.cc", "max_forks_repo_name": "coryb/gearbox", "max_forks_repo_head_hexsha": "88027f2f101c2d1fab16093928963052b9d3294d", "max_forks_repo_licenses": ["Artistic-1.0-Perl", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2340425532, "max_line_length": 95, "alphanum_fraction": 0.6716621253, "num_tokens": 453}
import numpy as np from flask import Flask, jsonify, request import pickle #model my_model = pickle.load(open('iris_model2.pkl', 'rb')) app = Flask(__name__) @app.route('/api', methods=['POST']) def make_predict(): #get data data = request.get_json(force=True) #transform/parse predict_request = [data['SepalLengthCm'], data['SepalWidthCm'], data['PetalLengthCm'], data['PetalWidthCm']] predict_request = np.array(predict_request).reshape(1, -1) #preds y_hat = my_model.predict(predict_request) #send back to browser output = {'y_hat': int(y_hat[0])} return jsonify(results=output) @app.route('/accuracy') def show_accuracy(): from sklearn.datasets import load_iris from sklearn.metrics import accuracy_score X, y = load_iris(return_X_y=True) y_pred = my_model.predict(X) return str(accuracy_score(y, y_pred)) if __name__ == '__main__': app.run(port = 9000, debug = True)
{"hexsha": "99e3fd6a4ec6768a5b8f3e33e66481c19064c5db", "size": 1009, "ext": "py", "lang": "Python", "max_stars_repo_path": "module3-adding-data-science-to-a-web-application/iris_model_app_two.py", "max_stars_repo_name": "nrvanwyck/DS-Unit-3-Sprint-3-Productization-and-Cloud", "max_stars_repo_head_hexsha": "186a2420ddaf0ca1b229982e05867b88d9c66fd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "module3-adding-data-science-to-a-web-application/iris_model_app_two.py", "max_issues_repo_name": "nrvanwyck/DS-Unit-3-Sprint-3-Productization-and-Cloud", "max_issues_repo_head_hexsha": "186a2420ddaf0ca1b229982e05867b88d9c66fd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module3-adding-data-science-to-a-web-application/iris_model_app_two.py", "max_forks_repo_name": "nrvanwyck/DS-Unit-3-Sprint-3-Productization-and-Cloud", "max_forks_repo_head_hexsha": "186a2420ddaf0ca1b229982e05867b88d9c66fd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8285714286, "max_line_length": 62, "alphanum_fraction": 0.6521308226, "include": true, "reason": "import numpy", "num_tokens": 252}
module day24 include("inputs.jl") ex = inputs.ex_d24() input = inputs.input_d24() # https://www.redblobgames.com/grids/hexagons/#coordinates-cube struct Tile # cube coordinates for hex grid (see link) x::Int y::Int z::Int end function parse_input(input) rgx = r"(ne|se|sw|nw|e|w)" return map(split(input, "\n")) do line [m.match for m in eachmatch(rgx, line)] end end # Part 1 function move(t::Tile, dir) dir == "e" && return Tile(t.x + 1, t.y - 1, t.z + 0) dir == "se" && return Tile(t.x + 0, t.y - 1, t.z + 1) dir == "sw" && return Tile(t.x - 1, t.y + 0, t.z + 1) dir == "w" && return Tile(t.x - 1, t.y + 1, t.z + 0) dir == "nw" && return Tile(t.x + 0, t.y + 1, t.z - 1) dir == "ne" && return Tile(t.x + 1, t.y + 0, t.z - 1) error("Direction unknown: $dir") end function setup_tiles(input) lines = parse_input(input) flipped = Dict{Tile, Bool}() # false = white for line in lines tile = Tile(0, 0, 0) for dir in line tile = move(tile, dir) end if haskey(flipped, tile) flipped[tile] = !flipped[tile] else flipped[tile] = true end end return flipped end part1(input) = setup_tiles(input) |> f->sum(values(f)) @assert part1(ex) == 10 @info "Day 24, Part 1 answer: $(part1(input))" # Part 2 get_neighs(t) = [ # Tile(t.x + 0, t.y + 0, t.z + 0) Tile(t.x + 1, t.y - 1, t.z + 0) Tile(t.x + 0, t.y - 1, t.z + 1) Tile(t.x - 1, t.y + 0, t.z + 1) Tile(t.x - 1, t.y + 1, t.z + 0) Tile(t.x + 0, t.y + 1, t.z - 1) Tile(t.x + 1, t.y + 0, t.z - 1) ] count_adj(tile, tiles) = sum([tiles[nei] for nei in get_neighs(tile) if nei ∈ keys(tiles)]) function exec(input, days=100) tiles = setup_tiles(input) for day in 1:days # get black tiles (used to determine candidates) blacks = [tile for (tile, color) in tiles if color == true] # create enough candidate tiles (don't forget to add curr tile, t) candidates = Set(Iterators.flatten([(t, get_neighs(t)...) for t in blacks])) # setup dictionary of tiles, colors for this iteration tiles = Dict{Tile, Bool}() for c in candidates tiles[c] = c ∈ blacks end # keep track of changing tiles for next iteration next_tiles = copy(tiles) for (tile, color) in tiles nb = count_adj(tile, tiles) if tiles[tile] && (nb == 0 || nb > 2) # println("flipped $tile to white") next_tiles[tile] = false elseif !tiles[tile] && nb == 2 # println("flipped ($tile, $(tiles[tile])) to black") next_tiles[tile] = true end end tiles = copy(next_tiles) # apply the rules at the end of the iteration # println("Day $day: ", count(values(tiles))) end return tiles end part2(input) = exec(input) |> t->sum(values(t)) @assert part2(ex) == 2208 @info "Day 24, Part 2 answer: $(part2(input))" end
{"hexsha": "81685e76ae7e8b529b74434be4aa9fb2ea921c59", "size": 3104, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/day_24.jl", "max_stars_repo_name": "danjburns/AdventOfCode2020", "max_stars_repo_head_hexsha": "2c7cb0d1cbc41960da26691d55a572b9806bdb32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day_24.jl", "max_issues_repo_name": "danjburns/AdventOfCode2020", "max_issues_repo_head_hexsha": "2c7cb0d1cbc41960da26691d55a572b9806bdb32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day_24.jl", "max_forks_repo_name": "danjburns/AdventOfCode2020", "max_forks_repo_head_hexsha": "2c7cb0d1cbc41960da26691d55a572b9806bdb32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.963963964, "max_line_length": 91, "alphanum_fraction": 0.5386597938, "num_tokens": 996}
\documentclass[]{book} \usepackage{lmodern} \usepackage{amssymb,amsmath} \usepackage{ifxetex,ifluatex} \usepackage{fixltx2e} % provides \textsubscript \ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \else % if luatex or xelatex \ifxetex \usepackage{mathspec} \else \usepackage{fontspec} \fi \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase} \fi % use upquote if available, for straight quotes in verbatim environments \IfFileExists{upquote.sty}{\usepackage{upquote}}{} % use microtype if available \IfFileExists{microtype.sty}{% \usepackage{microtype} \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts }{} \usepackage[margin=1in]{geometry} \usepackage{hyperref} \hypersetup{unicode=true, pdftitle={Lewis \& Clark BLT cluster}, pdfauthor={Watzek DI, etc.}, pdfborder={0 0 0}, breaklinks=true} \urlstyle{same} % don't use monospace font for urls \usepackage{natbib} \bibliographystyle{apalike} \usepackage{longtable,booktabs} \usepackage{graphicx,grffile} \makeatletter \def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi} \def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi} \makeatother % Scale images if necessary, so that they will not overflow the page % margins by default, and it is still possible to overwrite the defaults % using explicit options in \includegraphics[width, height, ...]{} \setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio} \IfFileExists{parskip.sty}{% \usepackage{parskip} }{% else \setlength{\parindent}{0pt} \setlength{\parskip}{6pt plus 2pt minus 1pt} } \setlength{\emergencystretch}{3em} % prevent overfull lines \providecommand{\tightlist}{% \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}} \setcounter{secnumdepth}{5} % Redefines (sub)paragraphs to behave more like sections \ifx\paragraph\undefined\else \let\oldparagraph\paragraph \renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}} \fi \ifx\subparagraph\undefined\else \let\oldsubparagraph\subparagraph \renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}} \fi %%% Use protect on footnotes to avoid problems with footnotes in titles \let\rmarkdownfootnote\footnote% \def\footnote{\protect\rmarkdownfootnote} %%% Change title format to be more compact \usepackage{titling} % Create subtitle command for use in maketitle \newcommand{\subtitle}[1]{ \posttitle{ \begin{center}\large#1\end{center} } } \setlength{\droptitle}{-2em} \title{Lewis \& Clark BLT cluster} \pretitle{\vspace{\droptitle}\centering\huge} \posttitle{\par} \author{Watzek DI, etc.} \preauthor{\centering\large\emph} \postauthor{\par} \predate{\centering\large\emph} \postdate{\par} \date{2018-02-19} \usepackage{booktabs} \begin{document} \maketitle { \setcounter{tocdepth}{1} \tableofcontents } \chapter*{About BLT}\label{about-blt} \addcontentsline{toc}{chapter}{About BLT} A description of BLT goes here. \section{About the Cluster}\label{about-the-cluster} content here\ldots{}. \chapter{Getting Connected}\label{getting-connected} \section{Accounts}\label{accounts} In order to gain access to the cluster, you first need an account. Contact the BLT Admins to request an account. NOTE: Once you receive a temporary password, please reset it within 5 days of gaining access to the system. \section{Getting on the network}\label{getting-on-the-network} The BLT cluster is quite isolated from LC's public-facing infrastructure. In order to connect to it, you will need a copy of Cisco AnyConnect secure mobility client, which is available to LC students, faculty, and staff HERE. If you are using Linux to connect to the cluster, the current version of Cisco AnyConnect will fail to install. Luckily, there is an open-source equivalent called OpenConnect, which installs as a menu option for debian and redhat based OSes. You will need to open your network settings and click the green plus button to add a new connection, and then select VPN when prompted. After that, put in \texttt{vpn.lclark.edu} for the gateway option and the same root CA certificate as you used when setting up LC secure. After you click save, it will ask for your LC id and password. After you have installed and started AnyConnect: \begin{enumerate} \def\labelenumi{\arabic{enumi}.} \tightlist \item Start a VPN session by typing \texttt{vpn.lclark.edu} in the text box and clicking ``connect'' \item When prompted, put in your LC username and password for access Now, your computer is connected to the same virtual network as the cluster. \end{enumerate} \section{Logging In}\label{logging-in} NOTE: In order to log in, you will need an SSH client. If you are using a Mac or Linux machine, you already have one. If you are using Windows, you will need to install PuTTY or similar. \begin{enumerate} \def\labelenumi{\arabic{enumi}.} \tightlist \item Open your SSH client \end{enumerate} \begin{itemize} \tightlist \item On Mac Press the space bar and command key at the same time. then type ``Terminal'' and hit return \item On Linux Open a terminal window \item On Windows Open PuTTY \end{itemize} \begin{enumerate} \def\labelenumi{\arabic{enumi}.} \setcounter{enumi}{1} \tightlist \item Log In! \end{enumerate} \begin{itemize} \tightlist \item On Mac or Linux type \texttt{ssh\ \textless{}lclark\ username\textgreater{}@mayo.blt.lclark.edu} and type your password when prompted \item On Windows Open PuTTY, set ``Host Name'' to mayo.blt.lclark.edu and click ``Open'', and follow the prompt. Congratulations! You have logged in to the BLT cluster! See Using the Cluster for more information about what you can do. \end{itemize} \chapter{Submitting Jobs}\label{submitting-jobs} \section{Checking Usage}\label{checking-usage} At any time, a user can check what the current availability of the cluster is by typing \texttt{SGE\_Avail} on their command line. The output will look something like this: \begin{verbatim} #HOST TOTRAM FREERAM TOTSLOTS Q QSLOTS QFREESLOTS QSTATUS QTYPE bacon 503.6 500.3 48 all.q 48 48 normal BP lettuce 503.6 500.2 48 all.q 48 48 normal BP tomato 503.6 500.2 48 all.q 48 48 normal BP \end{verbatim} \chapter{Technical Details}\label{technical-details} Now I'll teach you some crazy math, but I need to work it out first\ldots{} \bibliography{book.bib} \end{document}
{"hexsha": "19169839b95ff0711fb4b83344b1e701534451b4", "size": 6675, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "bookdown-start.tex", "max_stars_repo_name": "watzek/BLTdocs", "max_stars_repo_head_hexsha": "e21c8f809de6bf20d235ee7e4f4c6617df52bb53", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bookdown-start.tex", "max_issues_repo_name": "watzek/BLTdocs", "max_issues_repo_head_hexsha": "e21c8f809de6bf20d235ee7e4f4c6617df52bb53", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bookdown-start.tex", "max_forks_repo_name": "watzek/BLTdocs", "max_forks_repo_head_hexsha": "e21c8f809de6bf20d235ee7e4f4c6617df52bb53", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-25T22:22:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-25T22:22:42.000Z", "avg_line_length": 30.9027777778, "max_line_length": 102, "alphanum_fraction": 0.7337827715, "num_tokens": 1966}
PROGRAM SECEME C C CALCULATES AVERAGE VALUE OF 1/SQRT(ES) FOR SECONDARY C EMISSION FROM COPPER, SEAH, SURFACE SCIENCE 17,132-160,(1969) C DELE = .05 VAL1 = 0. VAL2 = 0. DO N = 1,1000 ES = .05*N FSR = 1 + (N.AND.1) Y = ES/(ES +.35)/(ES + 4.5)**1.6 VAL1 = VAL1 + DELE*FSR*Y VAL2 = VAL2 + DELE*FSR*Y/SQRT(ES) ENDDO PRINT*,'VAL1,VAL2,AVR SQRT(ES)',VAL1,VAL2,VAL1/VAL2 STOP END
{"hexsha": "e7164c9fb75d9e805c3badd47e11457c6356ab76", "size": 388, "ext": "for", "lang": "FORTRAN", "max_stars_repo_path": "WAVES_VMS_Fortran/PJK_Fortran/waves_dir/seceme_1.for", "max_stars_repo_name": "lynnbwilsoniii/Wind_Decom_Code", "max_stars_repo_head_hexsha": "ef596644fe0ed3df5ff3b462602e7550a04323e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WAVES_VMS_Fortran/PJK_Fortran/waves_dir/seceme_1.for", "max_issues_repo_name": "lynnbwilsoniii/Wind_Decom_Code", "max_issues_repo_head_hexsha": "ef596644fe0ed3df5ff3b462602e7550a04323e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WAVES_VMS_Fortran/PJK_Fortran/waves_dir/seceme_1.for", "max_forks_repo_name": "lynnbwilsoniii/Wind_Decom_Code", "max_forks_repo_head_hexsha": "ef596644fe0ed3df5ff3b462602e7550a04323e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4, "max_line_length": 63, "alphanum_fraction": 0.6365979381, "num_tokens": 205}
# Copyright 2017 Battelle Energy Alliance, LLC # # Licensed 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. """ Created on August 23, 2017 @author: wangc """ #External Modules------------------------------------------------------------------------------------ import numpy as np import os from collections import OrderedDict import itertools import copy #External Modules End-------------------------------------------------------------------------------- #Internal Modules------------------------------------------------------------------------------------ from utils import xmlUtils from utils import InputData, InputTypes import Files import Distributions import MetricDistributor from .PostProcessorInterface import PostProcessorInterface #Internal Modules End-------------------------------------------------------------------------------- class Metric(PostProcessorInterface): """ Metrics class. """ @classmethod def getInputSpecification(cls): """ Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls. """ inputSpecification = super(Metric, cls).getInputSpecification() featuresInput = InputData.parameterInputFactory("Features", contentType=InputTypes.StringListType) featuresInput.addParam("type", InputTypes.StringType) inputSpecification.addSub(featuresInput) targetsInput = InputData.parameterInputFactory("Targets", contentType=InputTypes.StringListType) targetsInput.addParam("type", InputTypes.StringType) inputSpecification.addSub(targetsInput) multiOutputInput = InputData.parameterInputFactory("multiOutput", contentType=InputTypes.StringType) inputSpecification.addSub(multiOutputInput) multiOutput = InputTypes.makeEnumType('MultiOutput', 'MultiOutputType', ['mean','max','min','raw_values']) multiOutputInput = InputData.parameterInputFactory("multiOutput", contentType=multiOutput) inputSpecification.addSub(multiOutputInput) weightInput = InputData.parameterInputFactory("weight", contentType=InputTypes.FloatListType) inputSpecification.addSub(weightInput) pivotParameterInput = InputData.parameterInputFactory("pivotParameter", contentType=InputTypes.StringType) inputSpecification.addSub(pivotParameterInput) metricInput = InputData.parameterInputFactory("Metric", contentType=InputTypes.StringType) metricInput.addParam("class", InputTypes.StringType, True) metricInput.addParam("type", InputTypes.StringType, True) inputSpecification.addSub(metricInput) return inputSpecification def __init__(self): """ Constructor @ In, None @ Out, None """ super().__init__() self.printTag = 'POSTPROCESSOR Metrics' self.dynamic = False # is it time-dependent? self.features = None # list of feature variables self.targets = None # list of target variables self.metricsDict = {} # dictionary of metrics that are going to be assembled self.multiOutput = 'mean'# defines aggregating of multiple outputs for HistorySet # currently allow mean, max, min, raw_values self.weight = None # 'mean' is provided for self.multiOutput, weights can be used # for each individual output when all outputs are averaged self.pivotParameter = None self.pivotValues = [] # assembler objects to be requested self.addAssemblerObject('Metric', InputData.Quantity.one_to_infinity) def __getMetricSide(self, metricDataName, currentInputs): """ Gets the metricDataName and stores it in inputDict. @ In, metricDataName, string, the name of the metric data to find in currentInputs @ In, currentInputs, list of inputs to the step. @ Out, metricData, (data, probability) or Distribution """ origMetricDataName = metricDataName metricData = None if metricDataName.count("|") == 2: #Split off the data name and if this is input or output. dataName, inputOrOutput, metricDataName = metricDataName.split("|") inputOrOutput = [inputOrOutput.lower()] else: dataName = None inputOrOutput = ['input','output'] for currentInput in currentInputs: inputType = None if hasattr(currentInput, 'type'): inputType = currentInput.type if dataName is not None and dataName != currentInput.name: continue if inputType in ['PointSet', 'HistorySet']: dataSet = currentInput.asDataset() metadata = currentInput.getMeta(pointwise=True) for ioType in inputOrOutput: if metricDataName in currentInput.getVars(ioType): if metricData is not None: self.raiseAnError(IOError, "Same feature or target variable " + metricDataName + "is found in multiple input objects") #Found the data, now put it in the return value. requestData = copy.copy(dataSet[metricDataName].values) if len(requestData.shape) == 1: requestData = requestData.reshape(-1,1) # If requested data are from input space, the shape will be (nSamples, 1) # If requested data are from history output space, the shape will be (nSamples, nTimeSteps) if 'ProbabilityWeight' in metadata: weights = metadata['ProbabilityWeight'].values else: # TODO is this correct sizing generally? weights = np.ones(requestData.shape[0]) metricData = (requestData, weights) elif isinstance(currentInput, Distributions.Distribution): if currentInput.name == metricDataName and dataName is None: if metricData is not None: self.raiseAnError(IOError, "Same feature or target variable " + metricDataName + "is found in multiple input objects") #Found the distribution, now put it in the return value metricData = currentInput if metricData is None: self.raiseAnError(IOError, "Feature or target variable " + origMetricDataName + " is not found") return metricData def inputToInternal(self, currentInputs): """ Method to convert an input object into the internal format that is understandable by this pp. @ In, currentInputs, list or DataObject, data object or a list of data objects @ Out, measureList, list of (feature, target), the list of the features and targets to measure the distance between """ if type(currentInputs) != list: currentInputs = [currentInputs] hasPointSet = False hasHistorySet = False #Check for invalid types for currentInput in currentInputs: inputType = None if hasattr(currentInput, 'type'): inputType = currentInput.type if isinstance(currentInput, Files.File): self.raiseAnError(IOError, "Input type '", inputType, "' can not be accepted") elif isinstance(currentInput, Distributions.Distribution): pass #Allowed type elif inputType == 'HDF5': self.raiseAnError(IOError, "Input type '", inputType, "' can not be accepted") elif inputType == 'PointSet': hasPointSet = True elif inputType == 'HistorySet': hasHistorySet = True if self.multiOutput == 'raw_values': self.dynamic = True if self.pivotParameter not in currentInput.getVars('indexes'): self.raiseAnError(IOError, self, 'Pivot parameter', self.pivotParameter,'has not been found in DataObject', currentInput.name) if not currentInput.checkIndexAlignment(indexesToCheck=self.pivotParameter): self.raiseAnError(IOError, "HistorySet", currentInput.name," is not syncronized, please use Interfaced PostProcessor HistorySetSync to pre-process it") pivotValues = currentInput.asDataset()[self.pivotParameter].values if len(self.pivotValues) == 0: self.pivotValues = pivotValues elif set(self.pivotValues) != set(pivotValues): self.raiseAnError(IOError, "Pivot values for pivot parameter",self.pivotParameter, "in provided HistorySets are not the same") else: self.raiseAnError(IOError, "Metric cannot process "+inputType+ " of type "+str(type(currentInput))) if self.multiOutput == 'raw_values' and hasPointSet and hasHistorySet: self.multiOutput = 'mean' self.raiseAWarning("Reset 'multiOutput' to 'mean', since both PointSet and HistorySet are provided as Inputs. Calculation outputs will be aggregated by averaging") measureList = [] for cnt in range(len(self.features)): feature = self.features[cnt] target = self.targets[cnt] featureData = self.__getMetricSide(feature, currentInputs) targetData = self.__getMetricSide(target, currentInputs) measureList.append((featureData, targetData)) return measureList def initialize(self, runInfo, inputs, initDict) : """ Method to initialize the pp. @ In, runInfo, dict, dictionary of run info (e.g. working dir, etc) @ In, inputs, list, list of inputs @ In, initDict, dict, dictionary with initialization options """ super().initialize(runInfo, inputs, initDict) for metricIn in self.assemblerDict['Metric']: self.metricsDict[metricIn[2]] = metricIn[3] def _handleInput(self, paramInput): """ Function to handle the parsed paramInput for this class. @ In, paramInput, ParameterInput, the already parsed input. @ Out, None """ super()._handleInput(paramInput) for child in paramInput.subparts: if child.getName() == 'Metric': if 'type' not in child.parameterValues.keys() or 'class' not in child.parameterValues.keys(): self.raiseAnError(IOError, 'Tag Metric must have attributes "class" and "type"') elif child.getName() == 'Features': self.features = child.value self.featuresType = child.parameterValues['type'] elif child.getName() == 'Targets': self.targets = child.value self.TargetsType = child.parameterValues['type'] elif child.getName() == 'multiOutput': self.multiOutput = child.value elif child.getName() == 'weight': self.weight = np.asarray(child.value) elif child.getName() == 'pivotParameter': self.pivotParameter = child.value else: self.raiseAnError(IOError, "Unknown xml node ", child.getName(), " is provided for metric system") if not self.features: self.raiseAnError(IOError, "XML node 'Features' is required but not provided") elif len(self.features) != len(self.targets): self.raiseAnError(IOError, 'The number of variables found in XML node "Features" is not equal the number of variables found in XML node "Targets"') def collectOutput(self, finishedJob, output): """ Function to place all of the computed data into the output object, (Files or DataObjects) @ In, finishedJob, object, JobHandler object that is in charge of running this postprocessor @ In, output, object, the object where we want to place our computed results @ Out, None """ evaluation = finishedJob.getEvaluation() outputDict = evaluation[1] # FIXED: writing directly to file is no longer an option! #if isinstance(output, Files.File): # availExtens = ['xml'] # outputExtension = output.getExt().lower() # if outputExtension not in availExtens: # self.raiseAMessage('Metric postprocessor did not recognize extension ".', str(outputExtension), '". The output will be dumped to a text file') # output.setPath(self._workingDir) # self.raiseADebug('Write Metric prostprocessor output in file with name: ', output.getAbsFile()) # self._writeXML(output, outputDict) if output.type in ['PointSet', 'HistorySet']: self.raiseADebug('Adding output in data object named', output.name) rlz = {} for key, val in outputDict.items(): newKey = key.replace("|","_") rlz[newKey] = val if self.dynamic: rlz[self.pivotParameter] = np.atleast_1d(self.pivotValues) output.addRealization(rlz) # add metadata xml = self._writeXML(output, outputDict) output._meta['MetricPP'] = xml elif output.type == 'HDF5': self.raiseAnError(IOError, 'Output type', str(output.type), 'is not yet implemented. Skip it') else: self.raiseAnError(IOError, 'Output type ', str(output.type), ' can not be used for postprocessor', self.name) def _writeXML(self,output,outputDictionary): """ Defines the method for writing the post-processor to the metadata within a data object @ In, output, DataObject, instance to write to @ In, outputDictionary, dict, dictionary stores importance ranking outputs @ Out, xml, xmlUtils.StaticXmlElement instance, written data in XML format """ if self.dynamic: outputInstance = xmlUtils.DynamicXmlElement('MetricPostProcessor', pivotParam=self.pivotParameter) else: outputInstance = xmlUtils.StaticXmlElement('MetricPostProcessor') if self.dynamic: for key, values in outputDictionary.items(): assert("|" in key) metricName, nodeName = key.split('|') for ts, pivotVal in enumerate(self.pivotValues): if values.shape[0] == 1: outputInstance.addScalar(nodeName, metricName,values[0], pivotVal=pivotVal) else: outputInstance.addScalar(nodeName, metricName,values[ts], pivotVal=pivotVal) else: for key, values in outputDictionary.items(): assert("|" in key) metricName, nodeName = key.split('|') if len(list(values)) == 1: outputInstance.addScalar(nodeName, metricName, values[0]) else: self.raiseAnError(IOError, "Multiple values are returned from metric '", metricName, "', this is currently not allowed") return outputInstance def run(self, inputIn): """ This method executes the postprocessor action. In this case, it computes all the requested statistical FOMs @ In, inputIn, object, object contained the data to process. (inputToInternal output) @ Out, outputDict, dict, Dictionary containing the results """ measureList = self.inputToInternal(inputIn) outputDict = {} assert(len(self.features) == len(measureList)) for metricInstance in self.metricsDict.values(): metricEngine = MetricDistributor.factory.returnInstance('MetricDistributor', metricInstance) for cnt in range(len(self.targets)): nodeName = (str(self.targets[cnt]) + '_' + str(self.features[cnt])).replace("|","_") varName = metricInstance.name + '|' + nodeName output = metricEngine.evaluate(measureList[cnt], weights=self.weight, multiOutput=self.multiOutput) outputDict[varName] = np.atleast_1d(output) return outputDict
{"hexsha": "dcf7dbc44b8c4a0b18e3ce5cd3d8b8f3c360df53", "size": 15558, "ext": "py", "lang": "Python", "max_stars_repo_path": "framework/Models/PostProcessors/Metric.py", "max_stars_repo_name": "FlanFlanagan/raven", "max_stars_repo_head_hexsha": "bd7fca18af94376a28e2144ba1da72c01c8d343c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 159, "max_stars_repo_stars_event_min_datetime": "2017-03-24T21:07:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:44:40.000Z", "max_issues_repo_path": "framework/Models/PostProcessors/Metric.py", "max_issues_repo_name": "FlanFlanagan/raven", "max_issues_repo_head_hexsha": "bd7fca18af94376a28e2144ba1da72c01c8d343c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1667, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "framework/Models/PostProcessors/Metric.py", "max_forks_repo_name": "wanghy-anl/raven", "max_forks_repo_head_hexsha": "ef1372364a2776385931763f2b28fdf2930c77b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 95, "max_forks_repo_forks_event_min_datetime": "2017-03-24T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:30:22.000Z", "avg_line_length": 47.8707692308, "max_line_length": 171, "alphanum_fraction": 0.6771435917, "include": true, "reason": "import numpy", "num_tokens": 3397}
function x = Adj_USFFT(n,y,omega,D,L,center) % USFFT_simple -- 1d adjoint unequispaced Fourier transform % Usage: % x = USFFT(n,y,omega,D,L,center) % Inputs: % n length of output x % y vector of length m, % omega vector of sampled frequencies (length m) % center 0 for unbiased FT, 1 otherwise % Outputs: % x vector of length n % Description: % Evaluates the adjoint of the FT % % If center = 0, % % x(t) = sum_{k} exp(i omega_k t) y(k), -n/2 <= t < n/2 % % If center = 1, % % x(t) = sum_{k} exp(i omega_k t) y(k), 0 <= t < n % % See Also % USFFT, USFT_simple, Evaluate_FT % Notes: % To work properly, D*n must be even % % By Emmanuel candes, 2003-2004 if nargin < 6, center = 0; end if nargin < 5, L = 4; end if nargin < 4, D = 16; end n2 = n/2; N = D*n; N2 = N/2; m = length(omega); if rem(L,2) == 1, L = L + 1; end % Nearest point calculations near_index = round(N *omega/(2*pi)); row = near_index + N/2 + 1; delta = omega - 2*pi*near_index/N; % Make matrix y(k) * delta(k)^l, l = 0, 1, ..., L-1 FA = repmat(y(:),1,L); for l = 2:L; FA(:,l) = FA(:,l-1) .* delta/(l-1); end % Sum entries corresponding to the same index F = zeros(N,L); for k = 1:m, F(row(k),:) = F(row(k),:) + FA(k,:); end % Take IFFT along columns X = ifft_mid0(F) * N; X = X((N2-n2+1):(N2+n2),:); t = -n2:(n2-1); tp = ones(n,L); for k = 2:L; tp(:,k) = tp(:,k-1) .* (i*t.'); end x = sum(X.*tp,2);
{"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/USFFT/Adj_USFFT.m"}
From Test Require Import tactic. Section FOFProblem. Variable Universe : Set. Variable UniverseElement : Universe. Variable wd_ : Universe -> Universe -> Prop. Variable col_ : Universe -> Universe -> Universe -> Prop. Variable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)). Variable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)). Variable col_triv_3 : (forall A B : Universe, col_ A B B). Variable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)). Variable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\ (col_ P Q A /\ (col_ P Q B /\ col_ P Q C))) -> col_ A B C)). Theorem pipo_6 : (forall A B C P Q I : Universe, ((wd_ P I /\ (wd_ I Q /\ (wd_ P Q /\ (wd_ I B /\ (wd_ B A /\ (wd_ I A /\ (wd_ P Q /\ (wd_ A B /\ (wd_ A C /\ (wd_ B C /\ (wd_ A P /\ (wd_ A Q /\ (wd_ B P /\ (wd_ B Q /\ (wd_ C P /\ (wd_ C Q /\ (col_ P I Q /\ (col_ I B A /\ col_ B P I)))))))))))))))))) -> col_ A P Q)). Proof. time tac. Qed. End FOFProblem.
{"author": "janicicpredrag", "repo": "Larus", "sha": "a095ca588fbb0e4a64a26d92946485bbf85e1e08", "save_path": "github-repos/coq/janicicpredrag-Larus", "path": "github-repos/coq/janicicpredrag-Larus/Larus-a095ca588fbb0e4a64a26d92946485bbf85e1e08/benchmarks/coq-problems/col-trans/col_trans_0888.v"}
import h5py import numpy as np import os from numpy.lib.shape_base import expand_dims import open3d as o3d import torch from torch.utils.data import Dataset from sklearn.neighbors import NearestNeighbors from scipy.spatial.distance import minkowski def farthest_subsample_points(pointcloud1, pointcloud2, num_subsampled_points=768): pointcloud1 = pointcloud1.T pointcloud2 = pointcloud2.T num_points = pointcloud1.shape[0] nbrs1 = NearestNeighbors(n_neighbors=num_subsampled_points, algorithm='auto', metric=lambda x, y: minkowski(x, y)).fit(pointcloud1) random_p1 = np.random.random(size=(1, 3)) + np.array([[500, 500, 500]]) * np.random.choice([1, -1, 1, -1]) idx1 = nbrs1.kneighbors(random_p1, return_distance=False).reshape((num_subsampled_points,)) nbrs2 = NearestNeighbors(n_neighbors=num_subsampled_points, algorithm='auto', metric=lambda x, y: minkowski(x, y)).fit(pointcloud2) random_p2 = random_p1 #np.random.random(size=(1, 3)) + np.array([[500, 500, 500]]) * np.random.choice([1, -1, 2, -2]) idx2 = nbrs2.kneighbors(random_p2, return_distance=False).reshape((num_subsampled_points,)) return pointcloud1[idx1, :].T, pointcloud2[idx2, :].T def jitter_pcd(pcd, sigma=0.01, clip=0.05): pcd += np.clip(sigma * np.random.randn(*pcd.shape), -1 * clip, clip) return pcd def random_pose(max_angle, max_trans): R = random_rotation(max_angle) t = random_translation(max_trans) return np.concatenate([np.concatenate([R, t], 1), [[0, 0, 0, 1]]], 0) def random_rotation(max_angle): axis = np.random.randn(3) axis /= np.linalg.norm(axis) angle = np.random.rand() * max_angle A = np.array([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]]) R = np.eye(3) + np.sin(angle) * A + (1 - np.cos(angle)) * np.dot(A, A) return R def random_translation(max_dist): t = np.random.randn(3) t /= np.linalg.norm(t) t *= np.random.rand() * max_dist return np.expand_dims(t, 1) class ModelNet40(Dataset): """docstring for ModelNet40""" def __init__(self, prefix, args): self.prefix = prefix self.gaussian_noise = args.gaussian_noise self.unseen = args.unseen self.partial = args.partial # self.filtering = args.filtering self.n_cpoints = 1024 self.n_ppoints = 768 self.max_angle = args.max_angle / 180 * np.pi self.max_trans = args.max_trans # self.use_ppf = args.use_ppf # self.use_fpfh = args.use_fpfh if self.prefix == "train": path = './data/ModelNet40_train.h5' elif self.prefix == "val": if args.small_angle: path = './data/ModelNet40_test_SmallAngle.h5' else: path = './data/ModelNet40_test.h5' f = h5py.File(path, 'r') self.data = np.array(f['data'][:].astype('float32')) self.label = np.squeeze(np.array(f['label'][:].astype('int64'))) print(self.data.shape, self.label.shape) if self.prefix == "val": self.src_cc = np.array(f['complete_src_clean'][:].astype('float32')) self.tgt_cc = np.array(f['complete_tgt_clean'][:].astype('float32')) self.src_cn = np.array(f['complete_src_noise'][:].astype('float32')) self.tgt_cn = np.array(f['complete_tgt_noise'][:].astype('float32')) self.src_pc = np.array(f['partial_src_clean'][:].astype('float32')) self.tgt_pc = np.array(f['partial_tgt_clean'][:].astype('float32')) self.src_pn = np.array(f['partial_src_noise'][:].astype('float32')) self.tgt_pn = np.array(f['partial_tgt_noise'][:].astype('float32')) self.transforms = np.array(f['transforms'][:].astype('float32')) f.close() if self.unseen: if self.prefix == "val": self.data = self.data[self.label>=20] self.src_cc = self.src_cc[self.label>=20] self.tgt_cc = self.tgt_cc[self.label>=20] self.src_cn = self.src_cn[self.label>=20] self.tgt_cn = self.tgt_cn[self.label>=20] self.src_pc = self.src_pc[self.label>=20] self.tgt_pc = self.tgt_pc[self.label>=20] self.src_pn = self.src_pn[self.label>=20] self.tgt_pn = self.tgt_pn[self.label>=20] self.transforms = self.transforms[self.label>=20] self.label = self.label[self.label>=20] elif self.prefix == "train": self.data = self.data[self.label<20] self.label = self.label[self.label<20] print(self.data.shape, self.label.shape) def __len__(self): return self.data.shape[0] def __getitem__(self, index): if self.prefix == "train": src = self.data[index][:self.n_cpoints] tgt = src transform = random_pose(self.max_angle, self.max_trans / 2) pose1 = random_pose(np.pi, self.max_trans) pose2 = transform @ pose1 src = src @ pose1[:3, :3].T + pose1[:3, 3] tgt = tgt @ pose2[:3, :3].T + pose2[:3, 3] src = np.random.permutation(src) tgt = np.random.permutation(tgt) if self.partial: src, tgt = farthest_subsample_points(src.T, tgt.T, num_subsampled_points=self.n_ppoints) src = src.T tgt = tgt.T if self.gaussian_noise: src = jitter_pcd(src) tgt = jitter_pcd(tgt) elif self.prefix == "val": if self.partial: if self.gaussian_noise: src = self.src_pn[index][:self.n_ppoints] tgt = self.tgt_pn[index][:self.n_ppoints] else: src = self.src_pc[index][:self.n_ppoints] tgt = self.tgt_pc[index][:self.n_ppoints] else: if self.gaussian_noise: src = self.src_cn[index][:self.n_cpoints] tgt = self.tgt_cn[index][:self.n_cpoints] else: src = self.src_cc[index][:self.n_cpoints] tgt = self.tgt_cc[index][:self.n_cpoints] transform = self.transforms[index] src = np.random.permutation(src) tgt = np.random.permutation(tgt) src = torch.from_numpy(src) tgt = torch.from_numpy(tgt) if self.prefix is not "test": transform = torch.from_numpy(transform) match_level = 1 rot_level = 1 return src, tgt, transform, match_level, rot_level else: return src, tgt
{"hexsha": "65fddea90094215400f8ea85d65c4f143087e9a8", "size": 6861, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/dataset.py", "max_stars_repo_name": "paul007pl/GMCNet", "max_stars_repo_head_hexsha": "ebe3005874ec6040ac6d2b2f4aee7aeb9b21e7ee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-12-16T03:20:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:38:00.000Z", "max_issues_repo_path": "src/dataset.py", "max_issues_repo_name": "paul007pl/GMCNet", "max_issues_repo_head_hexsha": "ebe3005874ec6040ac6d2b2f4aee7aeb9b21e7ee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-02-16T13:19:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T11:14:38.000Z", "max_forks_repo_path": "src/dataset.py", "max_forks_repo_name": "paul007pl/GMCNet", "max_forks_repo_head_hexsha": "ebe3005874ec6040ac6d2b2f4aee7aeb9b21e7ee", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9060773481, "max_line_length": 121, "alphanum_fraction": 0.5733858038, "include": true, "reason": "import numpy,from numpy,from scipy", "num_tokens": 1734}