PyTorch how to load a pre-trained model?

There are several approaches to recording (serializing) and loading (deserialize) patterns for inference in PyTorch.

For example you may need to load a model that is already trained and back up that comes from the internet. More recently I answered this question on a discussion forum https://discuss.pytorch.org/t/i-want-to-do-machine-learning-with-android/98753. I take advantage of this article to give some details.

SAVE AND LOAD OF A PRE-TRAINED MODE with load_state_dict

In PyTorch you can save a model by storing in its file its state_dict these are Python dictionaries, they can be easily recorded, updated, modified and restored, adding great modularity to PyTorch models and optimizers.

In my example:

ESPNet is backed up with this method

Website github.com

I managed to load the encoder model using the ESPNet class that makes a load_state_dict

import torch
model = ESPNet(20,encoderFile="espnet_p_2_q_8.pth", p=2, q=8)
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
traced_script_module.save("model.pt")

The exit is

Encode loaded!

Note that ESPNet uses the default GPU and that an adaptation in Model.py in https://github.com/sacmehta/ESPNet/tree/master/train was required by replacing:

self.encoder.load_state_dict(torch.load(encoderFile)

By:

self.encoder.load_state_dict(torch.load(encoderFile,map_location='cpu'))

Otherwise if you don’t make this adjustment don’t have the ability to launch on a GPU you’ll get the following error:

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location-torch.device ('cpu') to map your storages to the CPU.

BACKUP AND LOAD BY PYTORCH SCRIPT

Website pytorch.org

TorchScript is a way to create models that can be made that can be optimized from the PyTorch code.

Any TorchScript program can be saved from a Python process and loaded into a process where there is no Python dependency.

The code below allows you to save the pre-trained ESPNet model that was backed up by the classic torch.save method via the use of TorchScript.

import torch


model = ESPNet(20,encoderFile="espnet_p_2_q_8.pth", p=2, q=8)
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
#Exemple de save avec TorchScript
torch.jit.save(traced_script_module, "scriptmodel.pth")

An example for loader via TorchScript below:

import torch
model = torch.jit.load("scriptmodel.pth")

RESOURCES ON THE SUBJECT

Website pytorch.org

Website pytorch.org

Website stackoverflow.com

PyTorch ¿Cómo cargar un modelo previamente entrenado?

Existen varios enfoques para registrar (serializar) y cargar (deserializar) patrones de inferencia en PyTorch.

Por ejemplo, es posible que deba cargar un modelo que ya está entrenado y una copia de seguridad que proviene de Internet. Más recientemente respondí a esta pregunta en un foro de debate https://discuss.pytorch.org/t/i-want-to-do-machine-learning-with-android/98753. Aprovecho este artículo para dar algunos detalles.

GUARDA Y CARGA DE UN MODO PRE-TRAINED con load_state_dict

En PyTorch puedes guardar un modelo almacenando en su archivo sus state_dict estos son diccionarios Python, se pueden grabar, actualizar, modificar y restaurar fácilmente, añadiendo una gran modularidad a los modelos y optimizadores de PyTorch.

En mi ejemplo:

ESPNet está respaldado con este método

Website github.com

Me las arreglé para cargar el modelo de codificador utilizando la clase ESPNet que hace un load_state_dict

antorcha de importación
modelo - ESPNet(20,encoderFile"espnet_p_2_q_8.pth", p-2, q-8)
ejemplo - torch.rand (1, 3, 224, 224)
traced_script_module - torch.jit.trace (modelo, ejemplo)
traced_script_module.save ("model.pt")

La salida es

¡Codifica cargado!

Tenga en cuenta que ESPNet utiliza la GPU predeterminada y que se requería una adaptación en Model.py en https://github.com/sacmehta/ESPNet/tree/master/train reemplazando:

self.encoder.load_state_dict (torch.load (encoderFile)

Por:

self.encoder.load_state_dict (torch.load (encoderFile,map_location'cpu')

De lo contrario, si no realiza este ajuste no tiene la capacidad de iniciarse en una GPU, obtendrá el siguiente error:

RuntimeError: intentar deserializar un objeto en un dispositivo CUDA, pero torch.cuda.is_available() es False. Si se está ejecutando en una máquina solo para CPU, utilice torch.load con map_location-torch.device ('cpu') para asignar sus almacenamientos a la CPU.

COPIA DE SEGURIDAD Y CARGA POR SCRIPT PYTORCH

Website pytorch.org

TorchScript es una forma de crear modelos que se pueden crear que se pueden optimizar desde el código PyTorch.

Cualquier programa TorchScript se puede guardar desde un proceso de Python y cargarse en un proceso en el que no haya dependencia de Python.

El código siguiente le permite guardar el modelo ESPNet previamente entrenado que fue respaldado por el método clásico torch.save mediante el uso de TorchScript.

antorcha de importación

modelo - ESPNet(20,encoderFile"espnet_p_2_q_8.pth", p-2, q-8)
ejemplo - torch.rand (1, 3, 224, 224)
traced_script_module - torch.jit.trace (modelo, ejemplo)
#Exemple con TorchScript
torch.jit.save (traced_script_module, "scriptmodel.pth")

Un ejemplo para el cargador a través de TorchScript a continuación:

antorcha de importación
model - torch.jit.load ("scriptmodel.pth")

RECURSOS SOBRE EL TEMA

Website pytorch.org

Website pytorch.org

Website stackoverflow.com

PyTorch comment charger un modèle pré-entraîné ?

Il existe plusieurs approches pour enregistrer (sérialiser) et charger (désérialiser) des modèles pour l’inférence dans PyTorch.

Par exemple vous pouvez avoir besoin de charger un modèle qui est déjà entrainé et sauvegarder qui provient d’internet. Plus récemment j’ai répondu à cette question sur un forum de discussion Website discuss.pytorch.org. Je profite de cette article pour donner quelques détails.

SAVE ET LOAD D’UN MODE PRE-TRAINED avec load_state_dict

Dans PyTorch on peut sauvegarder un modèle en stockant dans son fichier son state_dict ce sont des dictionnaires Python, ils peuvent être facilement enregistrés, mis à jour, modifiés et restaurés, ajoutant une grande modularité aux modèles et optimiseurs PyTorch.

Dans mon exemple :

ESPNet est sauvegardé avec cette méthode

Website github.com

J’ai réussi à charger le modèle de l’encodeur en utilisant la classe ESPNet qui fait un load_state_dict

import torch
model = ESPNet(20,encoderFile="espnet_p_2_q_8.pth", p=2, q=8)
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
traced_script_module.save("model.pt")

La sortie est

Encoder loaded!

A noter que ESPNet utilise le GPU par défaut et qu’une adaptation dans Model.py dans Website github.com a été nécessaire en remplaçant :

self.encoder.load_state_dict(torch.load(encoderFile)

Par :

self.encoder.load_state_dict(torch.load(encoderFile,map_location='cpu'))

Sinon si vous ne faites pas cette adaptation n’avez pas la possibilité de lancer sur un GPU vous allez obtenir l’erreur suivante :

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU.

SAUVEGARDE ET LOAD PAR PYTORCH SCRIPT

Website pytorch.org

TorchScript est un moyen de créer des modèles sérialisables et optimisables à partir du code PyTorch.

Tout programme TorchScript peut être enregistré à partir d’un processus Python et chargé dans un processus où il n’y a pas de dépendance Python.

Le code ci-dessous permet de sauvegarder via l’utilisation de TorchScript le modèle pré-entraîné de ESPNet qui avait été sauvegardé par la méthode classique torch.save.

import torch


model = ESPNet(20,encoderFile="espnet_p_2_q_8.pth", p=2, q=8)
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
#Exemple de save avec TorchScript
torch.jit.save(traced_script_module, "scriptmodel.pth")

Un exemple pour loader via TorchScript ci-dessous :

import torch
model = torch.jit.load("scriptmodel.pth")

RESSOURCES SUR LE SUJET

Website pytorch.org

Website pytorch.org

Website stackoverflow.com

BCEWithLogitsLoss en PyTorch ¿cómo encontrar la implementación?

Me han preguntado recientemente sobre cómo encontrar el código BCEWithLogitsLoss (https://discuss.pytorch.org/t/implementation-of-binary-cross-entropy/98715/2) para una función llamada en PYTORCH con la función handle_torch_function me lleva algún tiempo entenderlo, y lo compartiré con usted si ayuda:

La pregunta era acerca de BCEWithLogitsLoss – BCELoss + sigmoid() ? Mi respuesta puede ser aplicable si desea analizar el código de todas las funciones que figura en el diccionario ret de https://github.com/pytorch/pytorch/blob/master/torch/overrides.py

BCEWithLogitsLoss es una combinación de BCELOSS + una capa sigmoid i. Esto es más estable numéricamente que el uso de un sigmoid simple seguido de un BCELoss ya que, al combinar las operaciones en una capa, aprovecha el truco log-sum-exp para la estabilidad numérica ver: Website en.wikipedia.org

  1. El código de la clase BCEWithLogitsLoss se puede encontrar en https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/loss.py
    def forward(self, input: Tensor, target: Tensor) -> Tensor:
        retorno F.binary_cross_entropy_with_logits (entrada, objetivo,
                                                  self.peso,
                                                  pos_weight-self.pos_weight,
                                                  reducción-auto.reducción)

El Oject F se importa de functionnal.py aquí : https://github.com/pytorch/pytorch/blob/master/torch/nn/functional.py

Encontrará la función llamada

def binary_cross_entropy_with_logits(entrada, destino, peso-Ninguno, size_average-Ninguno,
                                     reducir-Ninguno, reducción 'media', pos_weight-Ninguno):

Llama a la handle_torch_function en https://github.com/pytorch/pytorch/blob/master/torch/overrides.pyYou en
contrará una entrada de la función binary_cross_entropy_with_logits en el ret dictionnary que contiene todas las funciones que se pueden invalidar en pytorch. Esta
es la implementación de Python de torch_functionMore
información en https://github.com/pytorch/pytorch/issues/24015

A continuación, el código al que se llama está
en el Filehttps://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/Loss.cpp de C++

Tensor binary_cross_entropy_with_logits (const Tensor> entrada, const Tensor&, const Tensor&weight, const Tensor&pos_weight, int64_t 
...

LIENS DE RESSOURCES :

Website pytorch.org

Website discuss.pytorch.org

Website stackoverflow.com

Website www.semicolonworld.com

https://128mots.com/index.php/en/2020/04/10/build-an-application-decentralises-full-stack-not-a-not-ethereum-blockchain-dapp-en-plus-de-128-words-part-3-2/

BCEWithLogitsLoss Pytorch – Python Class

BCEWithLogitsLoss voici quelques explications complémentaire sur l’utilisation de Binary Cross-Entropy Loss avec Pytorch en python.

On m’a demandé récemment comment trouver le code de Binary Cross-Entropy Loss(https://discuss.pytorch.org/t/implementation-of-binary-cross-entropy/98715/2) pour une fonction appelée dans PYTORCH avec la fonction handle_torch_function.

C’est une combinaison de BCELOSS + une couche Sigmoid. C’est plus stable numériquement que l’utilisation d’un Sigmoid suivie d’un BCELoss comme, ici on tire parti de l’astuce log-sum-exp pour la stabilité numérique voir: https://en.wikipedia.org/wiki/LogSumExp

Bcewithlogitsloss : quelques explications

  1. Le code de la classe se trouve dans https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/loss.py
   def forward(self, input: Tensor, target: Tensor) -> Tensor:
        return F.binary_cross_entropy_with_logits(input, target,
                                                  self.weight,
                                                  pos_weight=self.pos_weight,
                                                  reduction=self.reduction)

Le F oject est importé de functionnal.py ici : https://github.com/pytorch/pytorch/blob/master/torch/nn/functional.py

Vous trouverez la fonction appelée

def binary_cross_entropy_with_logits(input, target, weight=None, size_average=None,
                                     reduce=None, reduction='mean', pos_weight=None):

Il appelle le handle_torch_function dans Website github.com
On trouve une entrée de la fonction binary_cross_entropy_with_logits dans le dictionnaire ret qui contiennent toutes les fonctions qui peuvent être overridé dans pytorch. Il s’agit de l’implémentation Python de torch_function plus d’informations dans https://github.com/pytorch/pytorch/issues/24015

Ensuite, le code appelé est dans le C++
Filehttps://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/Loss.cpp

Tensor binary_cross_entropy_with_logits(const Tensor& input, const Tensor& target, const Tensor& weight, const Tensor& pos_weight, int64_t 
...

LIENS DE RESSOURCES :

https://128mots.com/index.php/en/2020/04/10/build-an-application-decentralises-full-stack-not-a-not-ethereum-blockchain-dapp-en-plus-de-128-words-part-3-2/

Website pytorch.org

Liens internes

https://128mots.com/index.php/category/graphes/

https://128mots.com/index.php/category/python/

BCEWithLogitsLoss Pytorch with python

BCEWithLogitsLoss Here are some additional explanations on using Binary Cross-Entropy Loss with Pytorch in python.

Introduction

I have been asked recently on How to find the code BCEWithLogitsLoss (Website discuss.pytorch.org) for a function called in PYTORCH with the function handle_torch_function it takes me some time to understand it, and i will share it with you if it helps:

The question was about BCEWithLogitsLoss = BCELoss + sigmoid() ? My answer can be apply if you want to analyse the code of all the functions that figures in the ret dictionnary from Website github.com

BCEWithLogitsLoss is a combination of BCELOSS + a Sigmoid layer i. This is more numerically stable than using a plain Sigmoid followed by a BCELoss as, by combining the operations into one layer, it takes advantage of the log-sum-exp trick for numerical stability see : Website en.wikipedia.org

BCEWithLogitsLoss in details

  1. The code of the BCEWithLogitsLoss Class can be found in Website github.com
    def forward(self, input: Tensor, target: Tensor) -> Tensor:
        return F.binary_cross_entropy_with_logits(input, target,
                                                  self.weight,
                                                  pos_weight=self.pos_weight,
                                                  reduction=self.reduction)

The F oject is imported from functionnal.py here : Website github.com

You will find the function called

def binary_cross_entropy_with_logits(input, target, weight=None, size_average=None,
                                     reduce=None, reduction='mean', pos_weight=None):

It calls the handle_torch_function in Website github.com
You will find an entry of the function binary_cross_entropy_with_logits in the ret dictionnary wich contain every function that can be overriden in pytorch.
This is the Python implementation of torch_function
More info in Website github.com

Then the code called is in the C++ File
Website github.com

Tensor binary_cross_entropy_with_logits(const Tensor& input, const Tensor& target, const Tensor& weight, const Tensor& pos_weight, int64_t 
...

LIENS DE RESSOURCES :

Website pytorch.org

Website discuss.pytorch.org

Website stackoverflow.com

Website www.semicolonworld.com

https://128mots.com/index.php/en/2020/04/10/build-an-application-decentralises-full-stack-not-a-not-ethereum-blockchain-dapp-en-plus-de-128-words-part-3-2/

https://128mots.com/index.php/en/category/non-classe-en/

Mastering IBM COBOL Language – Part 1 – FREE TRAINING

This article follows my introduction to the COBOL language. I advise you to reread the first part that deals with the general principles of COBOL. Here: https://128mots.com/index.php/2020/10/07/ibm-cobol/ and English https://128mots.com/index.php/en/2020/10/07/ibm-cobol-3/ (IBM COBOL FREE TRAINING)

Here we discuss the general concepts of the structure of a COBOL program.

DATA DIVISION

All the data that will be used by the program is located in the Data Division. This is where all the memory allowances required by the program are taken care of. This division is optional.

FILE MANAGEMENT:

FILE SECTION describes data sent or from the system, especially files.

The SYNtax in COBOL is the following

DATA DIVISION.
FILE SECTION.
 FD/SD NameOfFile[RECORD CONTAINS intgr CHARACTERS] 
	[BLOCK CONTAINS intgr RECORDS] 
[DATA RECORD IS NameOfRecord].
	[RECORDING MODE IS {F/V/U/S}]

FD describes the files and SD the sorting files.

FILE IN INPUT

In FILE-CONTROL the statement will be:

           SELECT FMASTER ASSIGN FMASTER
                  FILE STATUS W-STATUS-FMASTER.

If the input file is indexed:
           SELECT FMASTER ASSIGN FMASTER
                  ORGANIZATION IS INDEXED
                  RECORD KEY IS FMASTER-KEY
                  FILE STATUS W-STATUS-FMASTER.

In this case at the file-SECTION level we will have:

      FMAITRE as an appetizer  
       FD FMAITRE.
       01 ENR-FMAITRE.
      Statements from the registration areas

At the JCL level the statement will be of the form:
ENTREE DD DSN-SAMPLE. INPUTF,DISP-SHR

FILE OUT

The JCL statement will then be:

OUTFILE DD DSN-SAMPLE. OUTPUTF,DISP(,CATLG,DELETE),
LRECL-150,RECFM-FB

RECFM specifies the characteristics of records with fixed length (F), variable length (V), variable length ASCII (D) or indefinite length (U). Records that are said to be blocked are described as FB, VB or DB.

OPENING AND CLOSING FILE IN PROCEDURE DIVISION

COBOL uses PROCEDURE DIVISION mechanisms to perform writing, closing and file openings.

Entry file opening:

OPEN INPUT FICENT

Opening the output file:

OPEN OUTPUT FICSOR

File closure:

CLOSE FICENT
CLOSE FICSOR

File playback:

READ ACTENR
AT END MOVE 'O' TO LAST-RECORD
END-READ

File writing

WRITE SOR-ENR

EXTERNAL LINKS TO RESOURCES (IBM COBOL FREE TRAINING)

Below are some links that I found interesting that also deal with file management with COBOL.

Example of IBM file management: https://www.ibm.com/support/knowledgecenter/en/SS6SGM_5.1.0/com.ibm.cobol51.aix.doc/PGandLR/ref/rpfio13e.html

REFM Format: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.2.0/com.ibm.zos.v2r2.idad400/d4037.htm

Tutorialspoint an article on file management https://www.tutorialspoint.com/cobol/cobol_file_handling.htm

COURSERA COBOL with VSCODE: Website www.coursera.org

MEDIUM an interesting article for COBOL beginners: https://medium.com/@yvanscher/7-cobol-examples-with-explanations-ae1784b4d576

Also on his blog: http://yvanscher.com/2018-08-01_7-cobol-examples-with-explanations–ae1784b4d576.html

Many example COBOL free tutorials and sample code: http://www.csis.ul.ie/cobol/examples/default.htm

GITHUB Awesome-cobol https://github.com/mickaelandrieu/awesome-cobol you

https://128mots.com/index.php/2020/10/07/ibm-cobol/

IBM COBOL FREE TRAINING

Masterización de IBM COBOL Language – Parte 1 – ENTRENAMIENTO GRATUITO

Este artículo sigue mi introducción al lenguaje COBOL. Le aconsejo que vuelva a leer la primera parte que trata de los principios generales de COBOL. Aquí: https://128mots.com/index.php/2020/10/07/ibm-cobol/ e inglés http://128mots.com/index.php/en/2020/10/07/ibm-cobol-3/ (IBM COBOL FREE TRAINING)

Aquí discutimos los conceptos generales de la estructura de un programa COBOL.

DIVISIÓN DE DATOS

Todos los datos que utilizará el programa se encuentran en la División de Datos. Aquí es donde se cuidan todas las asignaciones de memoria requeridas por el programa. Esta división es opcional.

GESTIÓN DE ARCHIVOS:

FILE SECTION describe los datos enviados o desde el sistema, especialmente los archivos.

El SYNtax en COBOL es el siguiente

DIVISION DE DATOS.
SECCIÓN DE ARCHIVO.
 FD/SD NameOfFile[RECORD CONTAINS intgr CHARACTERS] 
	[BLOCK CONTAINS intgr RECORDS] 
[DATA RECORD IS NameOfRecord].
	[RECORDING MODE IS {F/V/U/S}]

FD describe los archivos y SD los archivos de clasificación.

ARCHIVO EN ENTRADA

En FILE-CONTROL la sentencia será:

           SELECCIONE FMASTER ASSIGN FMASTER
                  ESTADO DEL ARCHIVO W-STATUS-FMASTER.

Si el archivo de entrada está indexado:
           SELECCIONE FMASTER ASSIGN FMASTER
                  ORGANIZACIÓN ESTÁ INDEXADA
                  LA CLAVE DE REGISTRO ES FMASTER-KEY
                  ESTADO DEL ARCHIVO W-STATUS-FMASTER.

En este caso a nivel de archivo-SECTION tendremos:

      FMAITRE como aperitivo  
       FD FMAITRE.
       01 ENR-FMAITRE.
      Declaraciones de las áreas de registro

En el nivel JCL, la declaración tendrá el siguiente formato:
ENTREE DD DSN-SAMPLE. INPUTF,DISP-SHR

ARCHIVO FUERA

La instrucción JCL será:

OUTFILE DD DSN-SAMPLE. OUTPUTF,DISP(,CATLG,DELETE),
LRECL-150,RECFM-FB

RECFM especifica las características de los registros con longitud fija (F), longitud variable (V), longitud variable ASCII (D) o longitud indefinida (U). Los registros que se dice que están bloqueados se describen como FB, VB o DB.

APERTURA Y CIERRE DE ARCHIVO EN LA DIVISIÓN DE PROCEDIMIENTOS

COBOL utiliza mecanismos PROCEDURE DIVISION para realizar aperturas de escritura, cierre y archivo.

Apertura del archivo de entrada:

FICENT DE ENTRADA ABIERTA

Abrir el archivo de salida:

SALIDA ABIERTA FICSOR

Cierre de archivo:

CLOSE FICENT
CLOSE FICSOR

Reproducción de archivos:

LEER ACTENR
AL FINAL MUEVA 'O' AL ÚLTIMO REGISTRO
FIN DE LECTURA

Escritura de archivos

ESCRIBIR SOR-ENR

ENLACES EXTERNOS A RECURSOS (IBM COBOL FREE TRAINING)

A continuación se muestran algunos enlaces que me pareció interesante que también se ocupan de la gestión de archivos con COBOL.

Ejemplo de gestión de archivos de IBM: https://www.ibm.com/support/knowledgecenter/en/SS6SGM_5.1.0/com.ibm.cobol51.aix.doc/PGandLR/ref/rpfio13e.html

Formato REFM: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.2.0/com.ibm.zos.v2r2.idad400/d4037.htm

Tutorialespunto un artículo sobre administración de https://www.tutorialspoint.com/cobol/cobol_file_handling.htm

COURSERA COBOL con VSCODE: https://www.coursera.org/lecture/cobol-programming-vscode/file-handling-YVlcf

MEDIUM un interesante artículo para principiantes de COBOL: https://medium.com/@yvanscher/7-cobol-examples-with-explanations-ae1784b4d576

También en su blog: http://yvanscher.com/2018-08-01_7-cobol-examples-with-explanations–ae1784b4d576.html

Muchos ejemplos de tutoriales gratuitos de COBOL y código de ejemplo: http://www.csis.ul.ie/cobol/examples/default.htm

GITHUB Awesome-cobol te https://github.com/mickaelandrieu/awesome-cobol

https://128mots.com/index.php/2020/10/07/ibm-cobol/

FORMACIÓN GRATUITA DE IBM COBOL

Apprendre COBOL – Tutorial pour apprendre le COBOL

Apprendre COBOL, ce tutorial présente les concepts généraux liés à la structure d’un programme en COBOL.

Apprendre COBOL – Introduction

Cette article fait suite à mon introduction au langage COBOL. Je vous conseille de relire la première partie qui traite des principes généraux de COBOL. Ici : https://128mots.com/index.php/2020/10/07/ibm-cobol/ et en anglais https://128mots.com/index.php/en/2020/10/07/ibm-cobol-3/

Nous traitons ici les concepts généraux liés à la structure d’un programme en COBOL.

DATA DIVISION

Toutes les données qui vont être utilisées par le programme sont situées dans la Data Division . C’est l’endroit où toutes les allocations de mémoire requises par le programme sont prises en charge. Cette division est facultative.

GESTION DES FICHIERS :

La FILE SECTION décrit les données envoyées ou provenant du système, en particulier les fichiers.

Lorsqu’on apprend COBOL la syntaxe est trèc importante. La syntaxe en COBOL est la suivante

DATA DIVISION.
FILE SECTION.
 FD/SD NameOfFile 
	[RECORD CONTAINS intgr CHARACTERS] 
	[BLOCK CONTAINS intgr RECORDS]
	[DATA RECORD IS NameOfRecord].
	[RECORDING MODE IS {F/V/U/S}]

FD décrit les fichiers et SD les fichiers de tri.

FICHIER EN ENTRÉE

En FILE-CONTROL la déclaration sera :

           SELECT FMASTER      ASSIGN FMASTER
                  FILE STATUS  W-STATUS-FMASTER.

Si le fichier d'entrée est indexée:
           SELECT FMASTER      ASSIGN FMASTER
                  ORGANIZATION IS INDEXED
                  RECORD KEY   IS FMASTER-KEY
                  FILE STATUS  W-STATUS-FMASTER..

Dans ce cas au niveau de la FILE-SECTION on va avoir :

      *    FMAITRE en entrée  
       FD  FMAITRE.
       01  ENR-FMAITRE.
      *    Déclarations des zones de l’enregistrement

Au niveau JCL la déclaration sera de la forme :
//ENTREE    DD DSN=SAMPLE.INPUTF,DISP=SHR

FICHIER EN SORTIE

La déclaration JCL sera alors :

//OUTFILE   DD DSN=SAMPLE.OUTPUTF,DISP=(,CATLG,DELETE),
//       LRECL=150,RECFM=FB

RECFM spécifie les caractéristiques des enregistrements avec longueur fixe (F), longueur variable (V), longueur variable ASCII (D) ou longueur indéfinie (U). Les enregistrements qui sont dit bloqués sont décrits comme FB, VB ou DB.

OUVERTURE ET FERMETURE FICHIER EN PROCEDURE DIVISION

COBOL utilise des mécanismes en PROCEDURE DIVISION pour effectuer des lecture écriture, fermeture et ouverture de fichier.

Ouverture de fichier d’entrée :

OPEN  INPUT               FICENT

Ouverture de fichier de sortie :

OPEN OUTPUT          FICSOR

Fermeture de fichier :

CLOSE FICENT
CLOSE FICSOR

Lecture de fichier:

READ ACTENR
AT END MOVE 'O' TO DERNIER-ENREGISTREMENT
END-READ

Ecriture fichier

WRITE SOR-ENR

Apprendre COBOL – LIENS EXTERNES VERS DES RESSOURCES

Ci-dessous quelques liens que j’ai trouvé intéressants qui traitent également de la gestion des fichiers avec COBOL.

Exemple de gestion de fichier du site IBM : Website www.ibm.com

REFM Format : https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.2.0/com.ibm.zos.v2r2.idad400/d4037.htm

Tutorialspoint un article sur la gestion fichier Website www.tutorialspoint.com

COURSERA COBOL with VSCODE : Website www.coursera.org

MEDIUM un article intéressant pour les débutants COBOL : Website medium.com

Egalement sur son blog : http://yvanscher.com/2018-08-01_7-cobol-examples-with-explanations–ae1784b4d576.html

Beaucoup d’exemple COBOL de tutoriaux et sample code gratuits : Website www.csis.ul.ie

GITHUB Awesome-cobol vous Website github.com

Apprendre COBOL – LIENS INTERNES

https://128mots.com/index.php/2020/10/07/ibm-cobol/

IBM COBOL FREE TRAINING

How do I make a career in COBOL?

COBOL (COmmon Business Oriented Language) is a business-oriented language it is very suitable for data processing with high performance and precision, it is offered by IBM.

You can be sure that any purchases or withdrawals you make with your credit card start a COBOL program. Every day COBOL processes millions of transactions. From my point of view learning COBOL is a very interesting set of knowledge.

I have worked with this language for more than 10 years and I share here some notes that will probably allow you to get your hands on it.

The mainframe is modernizing with the ability to program with the latest tools such as the free code editor VsCode and zowe extension as well as Z Open editor, run in the cloud in environments such as Open Shift and integrate devops principles with tools such as Github, Jenkins, Wazi.

COBOL Syntax

The SYNtax of COBOL is quite simple and is similar to the natural language in English.

The code is standardized according to columns that can describe 5 key areas.

Area sequence: specifies a sequence number of the line of code sometimes, sometimes blank

Indicator Area: May contain an indicator for example – to indicate that the line is a comment, D to indicate that the line runs only in debugging mode.

A AREA: Contains divisions, sections, paragraphs and Lift

B AREA: Sentences and statements of the program cobol for example COMPUTE something…

Area Identification: space to ignore and leave blank.

There are also words reserved in COBOL you will find on the link the list of words reserved in COBOL. https://www.ibm.com/support/knowledgecenter/SSZJPZ_9.1.0/com.ibm.swg.im.iis.ds.mfjob.dev.doc/topics/r_dmnjbref_COBOL_Reserved_Words.html

Divisions:

The code is structured by divisions that contain Paragraph-composed Sections themselves made up of Sentences and Statements.

Example of sentences:

ADD 45 TO PRICE.

Note that the point corresponds to an implied scope terminator.

There are 4 Divisions in a COBOL program:

– DATA DIVISION: allows you to set up the data management that will be processed by the program.

– DIVISION IDENTIFICATION: Program name and programmer, program date, program purpose.

– QUARTER ENVIRONEMENT: Type of computer uses and mapping between files used in the program and dataset on the system (link between program and system)

– PROCEDURE DIVISION: This is where the business code composed of the different paragraphs to be executed is contained.

The variables in Cobol:

As in other languages, letters can be used to represent values stored in memory.

The name of a variable is a maximum of 30 characters.

A Picture clause allows you to determine the type of variable.

PIC 9: Digital length is in brackets.

PIC 9(5): digital variable of 5 digits the maximum length for a digital is 18.

PIC A for a character

PIC X(11): an alphanumeric with a maximum length of 255

It is possible to have types edited using symbols:

PIC 9(6)V99 for a 6 digits and 2 decimals separated by comma.

PIC $9,999V99 to represent an amount

Note that COBOL provides constant liters such as ZEROES, SPACE, SPACES, LOW-VALUE …

More information on this link:

https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rllancon.htm

If you are new to IBM COBOL and want to do a serious and not too expensive apprenticeship, I recommend you read this book:

This book covers a lot of topics related to machine language, IBM Cobol training, Open Cobol IDE, DB2 to become a true Cobol programmers.

See also my articles: