Best JavaScript code snippet using backstopjs
test_protocol_chimera_map_subtraction.py
Source:test_protocol_chimera_map_subtraction.py
1# ***************************************************************************2# * Authors: Marta Martinez (mmmtnez@cnb.csic.es)3# * Roberto Marabini (roberto@cnb.csic.es)4# *5# *6# * This program is free software; you can redistribute it and/or modify7# * it under the terms of the GNU General Public License as published by8# * the Free Software Foundation; either version 2 of the License, or9# * (at your option) any later version.10# *11# * This program is distributed in the hope that it will be useful,12# * but WITHOUT ANY WARRANTY; without even the implied warranty of13# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14# * GNU General Public License for more details.15# *16# * You should have received a copy of the GNU General Public License17# * along with this program; if not, write to the Free Software18# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA19# * 02111-1307 USA20# *21# * All comments concerning this program package may be sent to the22# * e-mail address 'scipion@cnb.csic.es'23# ***************************************************************************/24# TODO: Fill in the next line25# protocol to test a chimerax map subtraction starting from two maps or26# a map and an additional map derived from an atomic structure.27from ..protocols import ChimeraProtOperate28from ..protocols import ChimeraSubtractionMaps29from pwem.protocols.protocol_import import (ProtImportPdb,30 ProtImportVolumes)31from ..constants import CHIMERA_CYCLIC32import re33# from pwem import Domain34from pyworkflow.tests import *35import os.path36class TestImportBase(BaseTest):37 @classmethod38 def setUpClass(cls):39 setupTestProject(cls)40 cls.dsModBuild = DataSet.getDataSet('model_building_tutorial')41class TestImportData(TestImportBase):42 """ Import map volumes and atomic structures(PDBx/mmCIF files)43 """44 pdbID = "5ni1" # Haemoglobin atomic structure45 chainID = '{"model": 0, "chain": "A", "residues": 141}'46 FirstResidue = '{"residue": 6, "ASP"}'47 LastResidue = '{"residue": 10, "VAL"}'48 def _importVolume(self):49 args = {'filesPath': self.dsModBuild.getFile('volumes/emd_3488.map'),50 'samplingRate': 1.05,51 'setOrigCoord': False52 }53 protImportVol = self.newProtocol(ProtImportVolumes, **args)54 protImportVol.setObjLabel('import volume haemoglobin\n with default '55 'origin\n')56 self.launchProtocol(protImportVol)57 volume = protImportVol.outputVolume58 return volume59 def _importAtomStruct(self):60 args = {'inputPdbData': ProtImportPdb.IMPORT_FROM_ID,61 'pdbId': self.pdbID62 }63 protImportPDB = self.newProtocol(ProtImportPdb, **args)64 protImportPDB.setObjLabel('import pdb\n 5ni1')65 self.launchProtocol(protImportPDB)66 structure = protImportPDB.outputPdb67 return structure68class TestChimeraSubtractMap(TestImportData):69 """ Test the chimera subtraction map protocol70 """71 def testChimeraSubtract1(self):72 """ This test checks the subtraction in Chimera of a73 model-derived map from an imported map """74 print("Run Chimera subtraction of a model-derived map "75 "from the imported volume\n")76 # Import Volume77 volume = self._importVolume()78 # import PDB79 structure = self._importAtomStruct()80 # create auxiliary CMD file for chimera operate (model fitting)81 extraCommands = ""82 extraCommands += "move -52.50,-52.50,-51.88 model #3 " \83 "coord #2\n"84 extraCommands += "fitmap #3 in #2\n"85 extraCommands += "scipionwrite #3 " \86 "prefix DONOTSAVESESSION_\n"87 extraCommands += "exit\n"88 args = {'extraCommands': extraCommands,89 'inputVolume': volume,90 'pdbFileToBeRefined': structure91 }92 protChimera1 = self.newProtocol(ChimeraProtOperate,93 **args)94 protChimera1.setObjLabel('chimera operate\n volume and pdb\n save '95 'fitted model')96 self.launchProtocol(protChimera1)97 # Dynamically defined name of the variable because it does depend on98 # the protocol ID99 try:100 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d.getFileName()"101 % protChimera1.getObjId())102 except:103 self.assertTrue(False, "There was a problem with the alignment")104 self.assertTrue(os.path.exists(result))105 # TODO: These steps of protChimera2 can not be performed in protChimera1 because106 # when the map is saved keep an inappropriate origin107 extraCommands = ""108 # extraCommands += "molmap #2 2.1 gridSpacing 1.05 modelId 3\n"109 extraCommands += "molmap #2 2.1 gridSpacing 1.05 replace false\n"110 extraCommands += "scipionwrite #3 " \111 "prefix DONOTSAVESESSION_\n"112 extraCommands += "exit\n"113 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d"114 % protChimera1.getObjId())115 args = {'extraCommands': extraCommands,116 'pdbFileToBeRefined': result,117 }118 protChimera2 = self.newProtocol(ChimeraProtOperate,119 **args)120 protChimera2.setObjLabel('chimera operate\n pdb\n save '121 'model-derived map')122 self.launchProtocol(protChimera2)123 try:124 result = eval("protChimera2.DONOTSAVESESSION_Map__3_%06d.getFileName()"125 % protChimera2.getObjId())126 except:127 self.assertTrue(False, "There was a problem with the alignment")128 self.assertTrue(os.path.exists(result))129 # protocol chimera map subtraction130 extraCommands = "run(session, 'select all')\n"131 extraCommands += "run(session, 'exit')\n"132 result = eval("protChimera2.DONOTSAVESESSION_Map__3_%06d"133 % protChimera2.getObjId())134 args = {'extraCommands': extraCommands,135 'inputVolume': volume,136 'mapOrModel': 0,137 'inputVolume2': result,138 }139 protChimera3 = self.newProtocol(ChimeraSubtractionMaps, **args)140 protChimera3.setObjLabel('chimera subtract\n map -\n'141 'model-derived map\n')142 self.launchProtocol(protChimera3)143 # Dynamically defined name of the variable because it does depend on144 # the protocol ID145 try:146 result = eval("protChimera3.difference_Map__8_%06d.getFileName()"147 % protChimera3.getObjId())148 except:149 self.assertTrue(False, "There was a problem with the alignment")150 self.assertTrue(os.path.exists(result))151 try:152 result = eval("protChimera3.filtered_Map__9_%06d.getFileName()"153 % protChimera3.getObjId())154 except:155 self.assertTrue(False, "There was a problem with the alignment")156 self.assertTrue(os.path.exists(result))157 def testChimeraSubtract2(self):158 """ This test checks the subtraction in Chimera of a159 model with control mutations from an imported map """160 print("Run Chimera subtraction of a model with control "161 "mutations from an imported volume\n")162 # Import Volume163 volume = self._importVolume()164 # import PDB165 structure = self._importAtomStruct()166 # create auxiliary CMD file for chimera operate (model fitting)167 extraCommands = ""168 extraCommands += "move -52.50,-52.50,-51.88 model #3 " \169 "coord #2\n"170 extraCommands += "fitmap #3 in #2\n"171 extraCommands += "scipionwrite #3 " \172 "prefix DONOTSAVESESSION_\n"173 extraCommands += "exit\n"174 args = {'extraCommands': extraCommands,175 'inputVolume': volume,176 'pdbFileToBeRefined': structure177 }178 protChimera1 = self.newProtocol(ChimeraProtOperate,179 **args)180 protChimera1.setObjLabel('chimera operate\n volume and pdb\n save '181 'fitted model')182 self.launchProtocol(protChimera1)183 try:184 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d.getFileName()"185 % protChimera1.getObjId())186 except:187 self.assertTrue(False, "There was a problem with the alignment")188 self.assertTrue(os.path.exists(result))189 # protocol chimera map subtraction190 extraCommands = "run(session, 'select all')\n"191 extraCommands += "run(session, 'exit')\n"192 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d"193 % protChimera1.getObjId())194 args = {'extraCommands': extraCommands,195 'inputVolume': volume,196 'mapOrModel': 1,197 'resolution': 3.2,198 'pdbFileToBeRefined': result,199 'selectChain': True,200 'selectStructureChain': self.chainID,201 'removeResidues': True,202 'firstResidueToRemove': self.FirstResidue,203 'lastResidueToRemove': self.LastResidue,204 'applySymmetry': True,205 'symmetryGroup': CHIMERA_CYCLIC,206 'symmetryOrder': 2,207 'rangeDist': 100,208 'selectAreaMap': True,209 'radius': 1210 }211 protChimera2 = self.newProtocol(ChimeraSubtractionMaps, **args)212 protChimera2.setObjLabel('chimera subtract\n chainA-sym-derived map\n '213 'removed residues\nzone')214 self.launchProtocol(protChimera2)215 try:216 result = eval("protChimera2.chain_A_Atom_struct__4_%06d_cif.getFileName()"217 % protChimera2.getObjId())218 except:219 self.assertTrue(False, "There was a problem with the alignment")220 self.assertTrue(os.path.exists(result))221 try:222 result = eval("protChimera2.zone_Map__6_%06d.getFileName()"223 % protChimera2.getObjId())224 except:225 self.assertTrue(False, "There was a problem with the alignment")226 self.assertTrue(os.path.exists(result))227 try:228 result = eval("protChimera2.molmap_chainA_Map__7_%06d.getFileName()"229 % protChimera2.getObjId())230 except:231 self.assertTrue(False, "There was a problem with the alignment")232 self.assertTrue(os.path.exists(result))233 try:234 result = eval("protChimera2.difference_Map__8_%06d.getFileName()"235 % protChimera2.getObjId())236 except:237 self.assertTrue(False, "There was a problem with the alignment")238 self.assertTrue(os.path.exists(result))239 try:240 result = eval("protChimera2.filtered_Map__9_%06d.getFileName()"241 % protChimera2.getObjId())242 except:243 self.assertTrue(False, "There was a problem with the alignment")244 self.assertTrue(os.path.exists(result))245 # protocol chimera map subtraction246 extraCommands = "run(session, 'select all')\n"247 extraCommands += "run(session, 'exit')\n"248 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d"249 % protChimera1.getObjId())250 args = {'extraCommands': extraCommands,251 'inputVolume': volume,252 'mapOrModel': 1,253 'resolution': 3.2,254 'pdbFileToBeRefined': result,255 'selectChain': True,256 'selectStructureChain': self.chainID,257 'removeResidues': True,258 'firstResidueToRemove': self.FirstResidue,259 'lastResidueToRemove': self.LastResidue,260 'applySymmetry': True,261 'symmetryGroup': CHIMERA_CYCLIC,262 'symmetryOrder': 2,263 'rangeDist': 100264 }265 protChimera3 = self.newProtocol(ChimeraSubtractionMaps, **args)266 protChimera3.setObjLabel('chimera subtract\n chainA-sym-derived map\n '267 'removed residues\nno zone')268 self.launchProtocol(protChimera3)269 try:270 result = eval("protChimera3.chain_A_Atom_struct__4_%06d_cif.getFileName()"271 % protChimera3.getObjId())272 except:273 self.assertTrue(False, "There was a problem with the alignment")274 self.assertTrue(os.path.exists(result))275 try:276 result = eval("protChimera3.sym_Atom_struct__5_%06d_cif.getFileName()"277 % protChimera3.getObjId())278 except:279 self.assertTrue(False, "There was a problem with the alignment")280 self.assertTrue(os.path.exists(result))281 try:282 result = eval("protChimera3.molmap_chainA_Map__7_%06d.getFileName()"283 % protChimera3.getObjId())284 except:285 self.assertTrue(False, "There was a problem with the alignment")286 self.assertTrue(os.path.exists(result))287 try:288 result = eval("protChimera3.difference_Map__8_%06d.getFileName()"289 % protChimera3.getObjId())290 except:291 self.assertTrue(False, "There was a problem with the alignment")292 self.assertTrue(os.path.exists(result))293 try:294 result = eval("protChimera3.filtered_Map__9_%06d.getFileName()"295 % protChimera3.getObjId())296 except:297 self.assertTrue(False, "There was a problem with the alignment")298 self.assertTrue(os.path.exists(result))299 # protocol chimera map subtraction300 extraCommands = "run(session, 'select all')\n"301 extraCommands += "run(session, 'exit')\n"302 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d"303 % protChimera1.getObjId())304 args = {'extraCommands': extraCommands,305 'inputVolume': volume,306 'mapOrModel': 1,307 'resolution': 3.2,308 'pdbFileToBeRefined': result,309 'selectChain': True,310 'selectStructureChain': self.chainID,311 'applySymmetry': True,312 'symmetryGroup': CHIMERA_CYCLIC,313 'symmetryOrder': 2,314 'rangeDist': 100,315 'selectAreaMap': True,316 'radius': 1317 }318 protChimera4 = self.newProtocol(ChimeraSubtractionMaps, **args)319 protChimera4.setObjLabel('chimera subtract\n chainA-sym-derived map\n')320 self.launchProtocol(protChimera4)321 try:322 result = eval("protChimera4.chain_A_Atom_struct__4_%06d_cif.getFileName()"323 % protChimera4.getObjId())324 except:325 self.assertTrue(False, "There was a problem with the alignment")326 self.assertTrue(os.path.exists(result))327 try:328 result = eval("protChimera4.sym_Atom_struct__5_%06d_cif.getFileName()"329 % protChimera4.getObjId())330 except:331 self.assertTrue(False, "There was a problem with the alignment")332 self.assertTrue(os.path.exists(result))333 try:334 result = eval("protChimera4.zone_Map__6_%06d.getFileName()"335 % protChimera4.getObjId())336 except:337 self.assertTrue(False, "There was a problem with the alignment")338 self.assertTrue(os.path.exists(result))339 try:340 result = eval("protChimera4.molmap_chainA_Map__7_%06d.getFileName()"341 % protChimera4.getObjId())342 except:343 self.assertTrue(False, "There was a problem with the alignment")344 self.assertTrue(os.path.exists(result))345 try:346 result = eval("protChimera4.difference_Map__8_%06d.getFileName()"347 % protChimera4.getObjId())348 except:349 self.assertTrue(False, "There was a problem with the alignment")350 self.assertTrue(os.path.exists(result))351 try:352 result = eval("protChimera4.filtered_Map__9_%06d.getFileName()"353 % protChimera4.getObjId())354 except:355 self.assertTrue(False, "There was a problem with the alignment")356 self.assertTrue(os.path.exists(result))357 # protocol chimera map subtraction358 extraCommands = "run(session, 'select all')\n"359 extraCommands += "run(session, 'exit')\n"360 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d"361 % protChimera1.getObjId())362 args = {'extraCommands': extraCommands,363 'inputVolume': volume,364 'mapOrModel': 1,365 'resolution': 3.2,366 'pdbFileToBeRefined': result,367 'selectChain': True,368 'selectStructureChain': self.chainID,369 'selectAreaMap': True,370 'radius': 1371 }372 protChimera5 = self.newProtocol(ChimeraSubtractionMaps, **args)373 protChimera5.setObjLabel('chimera subtract\n chainA-derived map\n')374 self.launchProtocol(protChimera5)375 try:376 result = eval("protChimera5.chain_A_Atom_struct__4_%06d_cif.getFileName()"377 % protChimera5.getObjId())378 except:379 self.assertTrue(False, "There was a problem with the alignment")380 self.assertTrue(os.path.exists(result))381 try:382 result = eval("protChimera5.zone_Map__6_%06d.getFileName()"383 % protChimera5.getObjId())384 except:385 self.assertTrue(False, "There was a problem with the alignment")386 self.assertTrue(os.path.exists(result))387 try:388 result = eval("protChimera5.molmap_chainA_Map__7_%06d.getFileName()"389 % protChimera5.getObjId())390 except:391 self.assertTrue(False, "There was a problem with the alignment")392 self.assertTrue(os.path.exists(result))393 try:394 result = eval("protChimera5.difference_Map__8_%06d.getFileName()"395 % protChimera5.getObjId())396 except:397 self.assertTrue(False, "There was a problem with the alignment")398 self.assertTrue(os.path.exists(result))399 try:400 result = eval("protChimera5.filtered_Map__9_%06d.getFileName()"401 % protChimera5.getObjId())402 except:403 self.assertTrue(False, "There was a problem with the alignment")404 self.assertTrue(os.path.exists(result))405 # protocol chimera map subtraction406 extraCommands = "run(session, 'select all')\n"407 extraCommands += "run(session, 'exit')\n"408 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d"409 % protChimera1.getObjId())410 args = {'extraCommands': extraCommands,411 'inputVolume': volume,412 'mapOrModel': 1,413 'resolution': 3.2,414 'pdbFileToBeRefined': result,415 'selectChain': True,416 'selectStructureChain': self.chainID,417 }418 protChimera6 = self.newProtocol(ChimeraSubtractionMaps, **args)419 protChimera6.setObjLabel('chimera subtract\n chainA-derived map\nno zone')420 self.launchProtocol(protChimera6)421 try:422 result = eval("protChimera6.chain_A_Atom_struct__4_%06d_cif.getFileName()"423 % protChimera6.getObjId())424 except:425 self.assertTrue(False, "There was a problem with the alignment")426 self.assertTrue(os.path.exists(result))427 try:428 result = eval("protChimera6.molmap_chainA_Map__7_%06d.getFileName()"429 % protChimera6.getObjId())430 except:431 self.assertTrue(False, "There was a problem with the alignment")432 self.assertTrue(os.path.exists(result))433 try:434 result = eval("protChimera6.difference_Map__8_%06d.getFileName()"435 % protChimera6.getObjId())436 except:437 self.assertTrue(False, "There was a problem with the alignment")438 self.assertTrue(os.path.exists(result))439 try:440 result = eval("protChimera6.filtered_Map__9_%06d.getFileName()"441 % protChimera6.getObjId())442 except:443 self.assertTrue(False, "There was a problem with the alignment")444 self.assertTrue(os.path.exists(result))445 def testChimeraSubtract3(self):446 """ This test checks the subtraction in Chimera of a447 model with control mutations from an imported map """448 print("Run Chimera subtraction of a model with control "449 "mutations from an imported volume\n")450 # Import Volume451 volume = self._importVolume()452 # import PDB453 structure = self._importAtomStruct()454 # create auxiliary CMD file for chimera operate (model fitting)455 extraCommands = ""456 extraCommands += "move -52.50,-52.50,-51.88 model #3 " \457 "coord #2\n"458 extraCommands += "fitmap #3 in #2\n"459 extraCommands += "scipionwrite #3 " \460 "prefix DONOTSAVESESSION_\n"461 extraCommands += "exit\n"462 args = {'extraCommands': extraCommands,463 'inputVolume': volume,464 'pdbFileToBeRefined': structure465 }466 protChimera1 = self.newProtocol(ChimeraProtOperate,467 **args)468 protChimera1.setObjLabel('chimera operate\n volume and pdb\n save '469 'fitted model')470 self.launchProtocol(protChimera1)471 try:472 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d.getFileName()"473 % protChimera1.getObjId())474 except:475 self.assertTrue(False, "There was a problem with the alignment")476 self.assertTrue(os.path.exists(result))477 # protocol chimera map subtraction478 extraCommands = "run(session, 'select all')\n"479 extraCommands += "run(session, 'exit')\n"480 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d"481 % protChimera1.getObjId())482 args = {'extraCommands': extraCommands,483 'inputVolume': volume,484 'mapOrModel': 1,485 'resolution': 3.2,486 'pdbFileToBeRefined': result,487 'removeResidues': True,488 'inputStructureChain': self.chainID,489 'firstResidueToRemove': self.FirstResidue,490 'lastResidueToRemove': self.LastResidue,491 }492 protChimera2 = self.newProtocol(ChimeraSubtractionMaps, **args)493 protChimera2.setObjLabel('chimera subtract\n atomStruct-derived map\n '494 'removed residues\nno zone')495 self.launchProtocol(protChimera2)496 try:497 result = eval("protChimera2.mutated_Atom_struct__3_%06d_cif.getFileName()"498 % protChimera2.getObjId())499 except:500 self.assertTrue(False, "There was a problem with the alignment")501 self.assertTrue(os.path.exists(result))502 try:503 result = eval("protChimera2.molmap_Map__7_%06d.getFileName()"504 % protChimera2.getObjId())505 except:506 self.assertTrue(False, "There was a problem with the alignment")507 self.assertTrue(os.path.exists(result))508 try:509 result = eval("protChimera2.difference_Map__8_%06d.getFileName()"510 % protChimera2.getObjId())511 except:512 self.assertTrue(False, "There was a problem with the alignment")513 self.assertTrue(os.path.exists(result))514 try:515 result = eval("protChimera2.filtered_Map__9_%06d.getFileName()"516 % protChimera2.getObjId())517 except:518 self.assertTrue(False, "There was a problem with the alignment")519 self.assertTrue(os.path.exists(result))520 # protocol chimera map subtraction521 extraCommands = "run(session, 'select all')\n"522 extraCommands += "run(session, 'exit')\n"523 result = eval("protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d"524 % protChimera1.getObjId())525 args = {'extraCommands': extraCommands,526 'inputVolume': volume,527 'mapOrModel': 1,528 'resolution': 3.2,529 'pdbFileToBeRefined': result,530 }531 protChimera3 = self.newProtocol(ChimeraSubtractionMaps, **args)532 protChimera3.setObjLabel('chimera subtract\n atomStruct-derived map\n '533 'no zone')534 self.launchProtocol(protChimera3)535 try:536 result = eval("protChimera3.Atom_struct__3_%06d_cif.getFileName()"537 % protChimera3.getObjId())538 except:539 self.assertTrue(False, "There was a problem with the alignment")540 self.assertTrue(os.path.exists(result))541 try:542 result = eval("protChimera3.molmap_Map__7_%06d.getFileName()"543 % protChimera3.getObjId())544 except:545 self.assertTrue(False, "There was a problem with the alignment")546 self.assertTrue(os.path.exists(result))547 try:548 result = eval("protChimera3.difference_Map__8_%06d.getFileName()"549 % protChimera3.getObjId())550 except:551 self.assertTrue(False, "There was a problem with the alignment")552 self.assertTrue(os.path.exists(result))553 try:554 result = eval("protChimera3.filtered_Map__9_%06d.getFileName()"555 % protChimera3.getObjId())556 except:557 self.assertTrue(False, "There was a problem with the alignment")558 self.assertTrue(os.path.exists(result))559 def testChimeraSubtract4(self):560 """ This test checks the subtraction in Chimera of a561 model with control mutations from an imported map """562 print("Run Chimera subtraction of a model with control "563 "mutations from an imported volume\n")564 # Import Volume565 volume = self._importVolume()566 # import PDB567 structure = self._importAtomStruct()568 # create auxiliary CMD file for chimera operate (model fitting)569 extraCommands = ""570 extraCommands += "move -52.50,-52.50,-51.88 model #3 " \571 "coord #2\n"572 extraCommands += "fitmap #3 in #2\n"573 extraCommands += "scipionwrite #3 " \574 "prefix DONOTSAVESESSION_\n"575 extraCommands += "exit\n"576 args = {'extraCommands': extraCommands,577 'inputVolume': volume,578 'pdbFileToBeRefined': structure579 }580 protChimera1 = self.newProtocol(ChimeraProtOperate,581 **args)582 protChimera1.setObjLabel('chimera operate\n volume and pdb\n save '583 'fitted model')584 self.launchProtocol(protChimera1)585 try:586 result = eval(587 "protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d.getFileName()"588 % protChimera1.getObjId())589 except:590 self.assertTrue(False, "There was a problem with the alignment")591 self.assertTrue(os.path.exists(result))592 # TODO: These steps of protChimera2 can not be performed in protChimera1 because593 # second way of obtaining the starting atom structure (it generates an appropriate594 # cif by applying symmetry)595 extraCommands = ""596 extraCommands += "sel #2/A,B\n"597 extraCommands += "save /tmp/chainA_B.cif format mmcif models #2 relModel #1 selectedOnly true\n"598 extraCommands += "open /tmp/chainA_B.cif\n"599 extraCommands += "scipionwrite #3 " \600 "prefix DONOTSAVESESSION_A_B_\n"601 extraCommands += "exit\n"602 result = eval(603 "protChimera1.DONOTSAVESESSION_Atom_struct__3_%06d"604 % protChimera1.getObjId())605 args = {'extraCommands': extraCommands,606 'pdbFileToBeRefined': result607 }608 protChimera2 = self.newProtocol(ChimeraProtOperate,609 **args)610 protChimera2.setObjLabel('chimera operate\n pdb\n save chain A_B')611 self.launchProtocol(protChimera2)612 try:613 result = eval(614 "protChimera2.DONOTSAVESESSION_A_B_Atom_struct__3_%06d.getFileName()"615 % protChimera2.getObjId())616 except:617 self.assertTrue(False, "There was a problem with the alignment")618 self.assertTrue(os.path.exists(result))619 # protocol chimera map subtraction620 extraCommands = "run(session, 'select all')\n"621 extraCommands += "run(session, 'exit')\n"622 result = eval(623 "protChimera2.DONOTSAVESESSION_A_B_Atom_struct__3_%06d"624 % protChimera2.getObjId())625 args = {'extraCommands': extraCommands,626 'inputVolume': volume,627 'mapOrModel': 1,628 'resolution': 3.2,629 'pdbFileToBeRefined': result,630 # 'selectChain': True,631 # 'selectStructureChain': self.chainID,632 # 'removeResidues': True,633 # 'inputStructureChain': self.chainID,634 # 'firstResidueToRemove': self.FirstResidue,635 # 'lastResidueToRemove': self.LastResidue,636 'applySymmetry': True,637 'symmetryGroup': CHIMERA_CYCLIC,638 'symmetryOrder': 2,639 # 'selectAreaMap': True,640 # 'radius': 1641 }642 protChimera3 = self.newProtocol(ChimeraSubtractionMaps, **args)643 protChimera3.setObjLabel('chimera subtract\n chainAB-sym-derived map\n')644 self.launchProtocol(protChimera3)645 try:646 result = eval(647 "protChimera3.Atom_struct__3_%06d_cif.getFileName()"648 % protChimera3.getObjId())649 except:650 self.assertTrue(False, "There was a problem with the alignment")651 self.assertTrue(os.path.exists(result))652 try:653 result = eval(654 "protChimera3.sym_Atom_struct__5_%06d_cif.getFileName()"655 % protChimera3.getObjId())656 except:657 self.assertTrue(False, "There was a problem with the alignment")658 self.assertTrue(os.path.exists(result))659 try:660 result = eval(661 "protChimera3.molmap_Map__7_%06d.getFileName()"662 % protChimera3.getObjId())663 except:664 self.assertTrue(False, "There was a problem with the alignment")665 self.assertTrue(os.path.exists(result))666 try:667 result = eval(668 "protChimera3.difference_Map__8_%06d.getFileName()"669 % protChimera3.getObjId())670 except:671 self.assertTrue(False, "There was a problem with the alignment")672 self.assertTrue(os.path.exists(result))673 try:674 result = eval(675 "protChimera3.filtered_Map__9_%06d.getFileName()"676 % protChimera3.getObjId())677 except:678 self.assertTrue(False, "There was a problem with the alignment")679 self.assertTrue(os.path.exists(result))680 # protocol chimera map subtraction681 extraCommands = "run(session, 'select all')\n"682 extraCommands += "run(session, 'exit')\n"683 result = eval(684 "protChimera2.DONOTSAVESESSION_A_B_Atom_struct__3_%06d"685 % protChimera2.getObjId())686 args = {'extraCommands': extraCommands,687 'inputVolume': volume,688 'mapOrModel': 1,689 'resolution': 3.2,690 'pdbFileToBeRefined': result,691 # 'selectChain': True,692 # 'selectStructureChain': self.chainID,693 # 'removeResidues': True,694 # 'inputStructureChain': self.chainID,695 # 'firstResidueToRemove': self.FirstResidue,696 # 'lastResidueToRemove': self.LastResidue,697 'applySymmetry': True,698 'symmetryGroup': CHIMERA_CYCLIC,699 'symmetryOrder': 2,700 'selectAreaMap': True,701 'radius': 1702 }703 protChimera4 = self.newProtocol(ChimeraSubtractionMaps, **args)704 protChimera4.setObjLabel('chimera subtract\n chainA-sym-derived map\n'705 'zone')706 self.launchProtocol(protChimera4)707 try:708 result = eval(709 "protChimera4.Atom_struct__3_%06d_cif.getFileName()"710 % protChimera4.getObjId())711 except:712 self.assertTrue(False, "There was a problem with the alignment")713 self.assertTrue(os.path.exists(result))714 try:715 result = eval(716 "protChimera4.sym_Atom_struct__5_%06d_cif.getFileName()"717 % protChimera4.getObjId())718 except:719 self.assertTrue(False, "There was a problem with the alignment")720 self.assertTrue(os.path.exists(result))721 try:722 result = eval(723 "protChimera4.zone_Map__6_%06d.getFileName()"724 % protChimera4.getObjId())725 except:726 self.assertTrue(False, "There was a problem with the alignment")727 self.assertTrue(os.path.exists(result))728 try:729 result = eval(730 "protChimera4.molmap_Map__7_%06d.getFileName()"731 % protChimera4.getObjId())732 except:733 self.assertTrue(False, "There was a problem with the alignment")734 self.assertTrue(os.path.exists(result))735 try:736 result = eval(737 "protChimera4.difference_Map__8_%06d.getFileName()"738 % protChimera4.getObjId())739 except:740 self.assertTrue(False, "There was a problem with the alignment")741 self.assertTrue(os.path.exists(result))742 try:743 result = eval(744 "protChimera4.filtered_Map__9_%06d.getFileName()"745 % protChimera4.getObjId())746 except:747 self.assertTrue(False, "There was a problem with the alignment")748 self.assertTrue(os.path.exists(result))749 # protocol chimera map subtraction750 extraCommands = "run(session, 'select all')\n"751 extraCommands += "run(session, 'exit')\n"752 result = eval(753 "protChimera2.DONOTSAVESESSION_A_B_Atom_struct__3_%06d"754 % protChimera2.getObjId())755 args = {'extraCommands': extraCommands,756 'inputVolume': volume,757 'mapOrModel': 1,758 'resolution': 3.2,759 'pdbFileToBeRefined': result,760 # 'selectChain': True,761 # 'selectStructureChain': self.chainID,762 'removeResidues': True,763 'inputStructureChain': self.chainID,764 'firstResidueToRemove': self.FirstResidue,765 'lastResidueToRemove': self.LastResidue,766 'applySymmetry': True,767 'symmetryGroup': CHIMERA_CYCLIC,768 'symmetryOrder': 2,769 'selectAreaMap': True,770 'radius': 1771 }772 protChimera5 = self.newProtocol(ChimeraSubtractionMaps, **args)773 protChimera5.setObjLabel('chimera subtract\n chainA-sym-derived map\n'774 'remove residues\nzone')775 self.launchProtocol(protChimera5)776 try:777 result = eval(778 "protChimera5.Atom_struct__3_%06d_cif.getFileName()"779 % protChimera5.getObjId())780 except:781 self.assertTrue(False, "There was a problem with the alignment")782 self.assertTrue(os.path.exists(result))783 try:784 result = eval(785 "protChimera5.sym_Atom_struct__5_%06d_cif.getFileName()"786 % protChimera5.getObjId())787 except:788 self.assertTrue(False, "There was a problem with the alignment")789 self.assertTrue(os.path.exists(result))790 try:791 result = eval(792 "protChimera5.zone_Map__6_%06d.getFileName()"793 % protChimera5.getObjId())794 except:795 self.assertTrue(False, "There was a problem with the alignment")796 self.assertTrue(os.path.exists(result))797 try:798 result = eval(799 "protChimera5.molmap_Map__7_%06d.getFileName()"800 % protChimera5.getObjId())801 except:802 self.assertTrue(False, "There was a problem with the alignment")803 self.assertTrue(os.path.exists(result))804 try:805 result = eval(806 "protChimera5.difference_Map__8_%06d.getFileName()"807 % protChimera5.getObjId())808 except:809 self.assertTrue(False, "There was a problem with the alignment")810 self.assertTrue(os.path.exists(result))811 try:812 result = eval(813 "protChimera5.filtered_Map__9_%06d.getFileName()"814 % protChimera5.getObjId())815 except:816 self.assertTrue(False, "There was a problem with the alignment")817 self.assertTrue(os.path.exists(result))818 # protocol chimera map subtraction819 extraCommands = "run(session, 'select all')\n"820 extraCommands += "run(session, 'exit')\n"821 result = eval(822 "protChimera2.DONOTSAVESESSION_A_B_Atom_struct__3_%06d"823 % protChimera2.getObjId())824 args = {'extraCommands': extraCommands,825 'inputVolume': volume,826 'mapOrModel': 1,827 'resolution': 3.2,828 'pdbFileToBeRefined': result,829 # 'selectChain': True,830 # 'selectStructureChain': self.chainID,831 'removeResidues': True,832 'inputStructureChain': self.chainID,833 'firstResidueToRemove': self.FirstResidue,834 'lastResidueToRemove': self.LastResidue,835 'applySymmetry': True,836 'symmetryGroup': CHIMERA_CYCLIC,837 'symmetryOrder': 2838 }839 protChimera6 = self.newProtocol(ChimeraSubtractionMaps, **args)840 protChimera6.setObjLabel('chimera subtract\n chainAB-sym-derived map\n'841 'remove residues\nno zone')842 self.launchProtocol(protChimera6)843 try:844 result = eval(845 "protChimera6.Atom_struct__3_%06d_cif.getFileName()"846 % protChimera6.getObjId())847 except:848 self.assertTrue(False, "There was a problem with the alignment")849 self.assertTrue(os.path.exists(result))850 try:851 result = eval(852 "protChimera6.mutated_Atom_struct__3_%06d_cif.getFileName()"853 % protChimera6.getObjId())854 except:855 self.assertTrue(False, "There was a problem with the alignment")856 self.assertTrue(os.path.exists(result))857 try:858 result = eval(859 "protChimera6.sym_Atom_struct__5_%06d_cif.getFileName()"860 % protChimera6.getObjId())861 except:862 self.assertTrue(False, "There was a problem with the alignment")863 self.assertTrue(os.path.exists(result))864 try:865 result = eval(866 "protChimera6.molmap_Map__7_%06d.getFileName()"867 % protChimera6.getObjId())868 except:869 self.assertTrue(False, "There was a problem with the alignment")870 self.assertTrue(os.path.exists(result))871 try:872 result = eval(873 "protChimera6.difference_Map__8_%06d.getFileName()"874 % protChimera6.getObjId())875 except:876 self.assertTrue(False, "There was a problem with the alignment")877 self.assertTrue(os.path.exists(result))878 try:879 result = eval(880 "protChimera6.filtered_Map__9_%06d.getFileName()"881 % protChimera6.getObjId())882 except:883 self.assertTrue(False, "There was a problem with the alignment")884 self.assertTrue(os.path.exists(result))885 # protocol chimera map subtraction886 extraCommands = "run(session, 'select all')\n"887 extraCommands += "run(session, 'exit')\n"888 result = eval(889 "protChimera2.DONOTSAVESESSION_A_B_Atom_struct__3_%06d"890 % protChimera2.getObjId())891 args = {'extraCommands': extraCommands,892 'inputVolume': volume,893 'mapOrModel': 1,894 'level': 0.217,895 'resolution': 3.2,896 'pdbFileToBeRefined': result,897 # 'selectChain': True,898 # 'selectStructureChain': self.chainID,899 'removeResidues': True,900 'inputStructureChain': self.chainID,901 'firstResidueToRemove': self.FirstResidue,902 'lastResidueToRemove': self.LastResidue,903 'applySymmetry': True,904 'symmetryGroup': CHIMERA_CYCLIC,905 'symmetryOrder': 2906 }907 protChimera7 = self.newProtocol(ChimeraSubtractionMaps, **args)908 protChimera7.setObjLabel('chimera subtract\n chainAB-sym-derived map\n'909 'remove residues\nlevel selected\nno zone')910 self.launchProtocol(protChimera7)911 try:912 result = eval(913 "protChimera7.Atom_struct__3_%06d_cif.getFileName()"914 % protChimera7.getObjId())915 except:916 self.assertTrue(False, "There was a problem with the alignment")917 self.assertTrue(os.path.exists(result))918 try:919 result = eval(920 "protChimera7.mutated_Atom_struct__3_%06d_cif.getFileName()"921 % protChimera7.getObjId())922 except:923 self.assertTrue(False, "There was a problem with the alignment")924 self.assertTrue(os.path.exists(result))925 try:926 result = eval(927 "protChimera7.sym_Atom_struct__5_%06d_cif.getFileName()"928 % protChimera7.getObjId())929 except:930 self.assertTrue(False, "There was a problem with the alignment")931 self.assertTrue(os.path.exists(result))932 try:933 result = eval(934 "protChimera7.molmap_Map__7_%06d.getFileName()"935 % protChimera7.getObjId())936 except:937 self.assertTrue(False, "There was a problem with the alignment")938 self.assertTrue(os.path.exists(result))939 try:940 result = eval(941 "protChimera7.difference_Map__8_%06d.getFileName()"942 % protChimera7.getObjId())943 except:944 self.assertTrue(False, "There was a problem with the alignment")945 self.assertTrue(os.path.exists(result))946 try:947 result = eval(948 "protChimera7.filtered_Map__9_%06d.getFileName()"949 % protChimera7.getObjId())950 except:951 self.assertTrue(False, "There was a problem with the alignment")952 self.assertTrue(os.path.exists(result))953 # protocol chimera mask954 extraCommands = "run(session, 'select all')\n"955 extraCommands += "run(session, 'exit')\n"956 result = eval(957 "protChimera2.DONOTSAVESESSION_A_B_Atom_struct__3_%06d"958 % protChimera2.getObjId())959 args = {'extraCommands': extraCommands,960 'inputVolume': volume,961 'subtractOrMask': 1,962 'level': 0.217,963 'mapOrModel': 1,964 'resolution': 3.2,965 'pdbFileToBeRefined': result,966 # 'selectChain': True,967 # 'selectStructureChain': self.chainID,968 'removeResidues': True,969 'inputStructureChain': self.chainID,970 'firstResidueToRemove': self.FirstResidue,971 'lastResidueToRemove': self.LastResidue,972 'applySymmetry': True,973 'symmetryGroup': CHIMERA_CYCLIC,974 'symmetryOrder': 2975 }976 protChimera8 = self.newProtocol(ChimeraSubtractionMaps, **args)977 protChimera8.setObjLabel('chimera mask\n chainAB-sym-derived map\n'978 'remove residues\nlevel 0.217\nno zone')979 self.launchProtocol(protChimera8)980 try:981 result = eval(982 "protChimera8.Atom_struct__3_%06d_cif.getFileName()"983 % protChimera8.getObjId())984 except:985 self.assertTrue(False, "There was a problem with the alignment")986 self.assertTrue(os.path.exists(result))987 try:988 result = eval(989 "protChimera8.mutated_Atom_struct__3_%06d_cif.getFileName()"990 % protChimera8.getObjId())991 except:992 self.assertTrue(False, "There was a problem with the alignment")993 self.assertTrue(os.path.exists(result))994 try:995 result = eval(996 "protChimera8.sym_Atom_struct__5_%06d_cif.getFileName()"997 % protChimera8.getObjId())998 except:999 self.assertTrue(False, "There was a problem with the alignment")1000 self.assertTrue(os.path.exists(result))1001 try:1002 result = eval(1003 "protChimera8.molmap_Map__7_%06d.getFileName()"1004 % protChimera8.getObjId())1005 except:1006 self.assertTrue(False, "There was a problem with the alignment")1007 self.assertTrue(os.path.exists(result))1008 try:1009 result = eval(1010 "protChimera8.difference_Map__8_%06d.getFileName()"1011 % protChimera8.getObjId())1012 except:1013 self.assertTrue(False, "There was a problem with the alignment")1014 self.assertTrue(os.path.exists(result))1015 try:1016 result = eval(1017 "protChimera8.filtered_Map__9_%06d.getFileName()"1018 % protChimera8.getObjId())1019 except:1020 self.assertTrue(False, "There was a problem with the alignment")1021 self.assertTrue(os.path.exists(result))1022 # protocol chimera mask1023 extraCommands = "run(session, 'select all')\n"1024 extraCommands += "run(session, 'exit')\n"1025 result = eval(1026 "protChimera2.DONOTSAVESESSION_A_B_Atom_struct__3_%06d"1027 % protChimera2.getObjId())1028 args = {'extraCommands': extraCommands,1029 'inputVolume': volume,1030 'subtractOrMask': 1,1031 'level': 2.0,1032 'mapOrModel': 1,1033 'resolution': 3.2,1034 'pdbFileToBeRefined': result,1035 # 'selectChain': True,1036 # 'selectStructureChain': self.chainID,1037 'removeResidues': True,1038 'inputStructureChain': self.chainID,1039 'firstResidueToRemove': self.FirstResidue,1040 'lastResidueToRemove': self.LastResidue,1041 'applySymmetry': True,1042 'symmetryGroup': CHIMERA_CYCLIC,1043 'symmetryOrder': 21044 }1045 protChimera9 = self.newProtocol(ChimeraSubtractionMaps, **args)1046 protChimera9.setObjLabel('chimera mask\n chainAB-sym-derived map\n'1047 'remove residues\nlevel 2.0\nno zone')1048 self.launchProtocol(protChimera9)1049 try:1050 result = eval(1051 "protChimera9.Atom_struct__3_%06d_cif.getFileName()"1052 % protChimera9.getObjId())1053 except:1054 self.assertTrue(False, "There was a problem with the alignment")1055 self.assertTrue(os.path.exists(result))1056 try:1057 result = eval(1058 "protChimera9.mutated_Atom_struct__3_%06d_cif.getFileName()"1059 % protChimera9.getObjId())1060 except:1061 self.assertTrue(False, "There was a problem with the alignment")1062 self.assertTrue(os.path.exists(result))1063 try:1064 result = eval(1065 "protChimera9.sym_Atom_struct__5_%06d_cif.getFileName()"1066 % protChimera9.getObjId())1067 except:1068 self.assertTrue(False, "There was a problem with the alignment")1069 self.assertTrue(os.path.exists(result))1070 try:1071 result = eval(1072 "protChimera9.molmap_Map__7_%06d.getFileName()"1073 % protChimera9.getObjId())1074 except:1075 self.assertTrue(False, "There was a problem with the alignment")1076 self.assertTrue(os.path.exists(result))1077 try:1078 result = eval(1079 "protChimera9.difference_Map__8_%06d.getFileName()"1080 % protChimera9.getObjId())1081 except:1082 self.assertTrue(False, "There was a problem with the alignment")1083 self.assertTrue(os.path.exists(result))1084 try:1085 result = eval(1086 "protChimera9.filtered_Map__9_%06d.getFileName()"1087 % protChimera9.getObjId())1088 except:1089 self.assertTrue(False, "There was a problem with the alignment")...
v2sc.py
Source:v2sc.py
1#-------------------------------------------------------------------------------2# codegen.py3#4# Code Generator from AST to Verilog HDL source code5#6# Copyright (C) 2013, Shinya Takamaeda-Yamazaki7# License: Apache 2.08#-------------------------------------------------------------------------------9from __future__ import absolute_import10from __future__ import print_function11import sys12import os13import math14import re15import functools16from jinja2 import Environment, FileSystemLoader17from optparse import OptionParser18sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))19import pyverilog.utils.version20from pyverilog.vparser.parser import VerilogCodeParser21#from pyverilog.ast_code_generator.codegen import ASTCodeGenerator22from pyverilog.vparser.ast import *23from pyverilog.utils.op2mark import op2mark24from pyverilog.utils.op2mark import op2order25DEFAULT_TEMPLATE_DIR = os.path.dirname(os.path.abspath(__file__)) + '/template/'26#-------------------------------------------------------------------------------27try:28 import textwrap29 indent = textwrap.indent30except:31 def indent(text, prefix, predicate=None):32 if predicate is None: predicate = lambda x: x and not x.isspace()33 ret = []34 for line in text.split('\n'):35 if predicate(line):36 ret.append(prefix)37 ret.append(line)38 ret.append('\n')39 return ''.join(ret[:-1])40def indent_multiline_assign(text):41 ret = []42 texts = text.split('\n')43 if len(texts) <= 1:44 return text45 try:46 p = texts[0].index('=')47 except:48 return text49 ret.append(texts[0])50 ret.append('\n')51 ret.append(indent('\n'.join(texts[1:]), ' ' * (p + 2)))52 return ''.join(ret)53#-------------------------------------------------------------------------------54class ConvertVisitor(object):55 def visit(self, node):56 method = 'visit_' + node.__class__.__name__57 visitor = getattr(self, method, self.visit_default)58 return visitor(node)59 def visit_default(self, node):60 ret = []61 for c in node.children():62 ret.append(self.visit(c))63 return ''.join(ret)64def getfilename(node, suffix=''):65 return node.__class__.__name__.lower() + suffix + '.txt'66def escape(s):67 if s.startswith('\\'):68 return s + ' '69 return s70def del_paren(s):71 if s.startswith('(') and s.endswith(')'):72 return s[1:-1]73 return s74def del_space(s):75 return s.replace(' ', '')76class ASTCodeGenerator(ConvertVisitor):77 def __init__(self, indentsize=4, clock_name='CLK', reset_name='RSTX'):78 self.env = Environment(loader=FileSystemLoader(DEFAULT_TEMPLATE_DIR))79 self.indent = functools.partial(indent, prefix=' '*indentsize)80 self.clock_name = clock_name81 self.reset_name = reset_name82 def visit_process(self, node):83 method = 'visit_' + node.__class__.__name__ + '_process'84 visitor = getattr(self, method, self.visit_none)85 return visitor(node)86 def visit_declaration(self, node):87 method = 'visit_' + node.__class__.__name__ + '_declaration'88 visitor = getattr(self, method, self.visit_none)89 return visitor(node)90 def visit_argument(self, node):91 method = 'visit_' + node.__class__.__name__ + '_argument'92 visitor = getattr(self, method, self.visit_none)93 return visitor(node)94 def visit_parameter(self, node):95 method = 'visit_' + node.__class__.__name__ + '_parameter'96 visitor = getattr(self, method, self.visit_none)97 return visitor(node)98 def visit_none(self, node):99 return ''100 def visit_Source(self, node):101 filename = getfilename(node)102 template = self.env.get_template(filename)103 template_dict = {104 'description' : self.visit(node.description),105 }106 rslt = template.render(template_dict)107 return rslt108 def visit_Description(self, node):109 filename = getfilename(node)110 template = self.env.get_template(filename)111 template_dict = {112 'definitions' : [ self.visit(definition) for definition in node.definitions ],113 }114 rslt = template.render(template_dict)115 return rslt116 def visit_ModuleDef(self, node):117 filename = getfilename(node)118 template = self.env.get_template(filename)119 portlist = self.indent(self.visit(node.portlist)) if node.portlist is not None else ''120 paramlist = [ self.visit(node.paramlist) ] if node.paramlist is not None else ()121 parameters = [ self.visit_parameter(item) for item in node.items ] if node.items else ()122 parameters += paramlist123 template_dict = {124 'modulename' : escape(node.name),125 'portlist' : portlist,126 'parameters' : parameters,127 'declarationlist' : [ self.visit_declaration(item) for item in node.items ] if node.items else (),128 'processlist' : [ self.visit_process(item) for item in node.items ] if node.items else (),129 'items' : [ self.indent(self.visit(item)) for item in node.items ] if node.items else (),130 }131 rslt = template.render(template_dict)132 return rslt133 def visit_Paramlist(self, node):134 filename = getfilename(node)135 template = self.env.get_template(filename)136 params = [ self.visit_parameter(param).replace(';','') for param in node.params ]137 template_dict = {138 'params' : params,139 'len_params' : len(params),140 }141 rslt = template.render(template_dict)142 return rslt143 def visit_Paramlist_parameter(self, node):144 filename = getfilename(node)145 template = self.env.get_template(filename)146 params = [ self.visit_parameter(param).replace(';','') for param in node.params ]147 template_dict = {148 'params' : params,149 'len_params' : len(params),150 }151 rslt = template.render(template_dict)152 return rslt153 def visit_Portlist(self, node):154 filename = getfilename(node)155 template = self.env.get_template(filename)156 ports = [ self.visit(port) for port in node.ports ]157 template_dict = {158 'ports' : ports,159 'len_ports' : len(ports),160 }161 rslt = template.render(template_dict)162 return rslt163 def visit_Port(self, node):164 filename = getfilename(node)165 template = self.env.get_template(filename)166 template_dict = {167 'name' : escape(node.name),168 }169 rslt = template.render(template_dict)170 return rslt171 def visit_Width(self, node):172 filename = getfilename(node)173 template = self.env.get_template(filename)174 msb = del_space(del_paren(self.visit(node.msb)))175 lsb = del_space(del_paren(self.visit(node.lsb)))176 template_dict = {177 'width': eval( msb + '-' + lsb + '+1' ),178 }179 rslt = template.render(template_dict)180 return rslt181 def visit_Length(self, node):182 filename = getfilename(node)183 template = self.env.get_template(filename)184 msb = del_space(del_paren(self.visit(node.msb)))185 lsb = del_space(del_paren(self.visit(node.lsb)))186 template_dict = {187 'width': eval( msb + '-' + lsb + '+1' ),188 }189 rslt = template.render(template_dict)190 return rslt191 def visit_Identifier(self, node):192 filename = getfilename(node)193 template = self.env.get_template(filename)194 template_dict = {195 'name' : escape(node.name),196 'scope' : '' if node.scope is None else self.visit(node.scope).replace('.', '::'),197 }198 rslt = template.render(template_dict)199 return rslt200 def visit_Value(self, node):201 filename = getfilename(node)202 template = self.env.get_template(filename)203 template_dict = {204 'value' : node.value,205 }206 rslt = template.render(template_dict)207 return rslt208 def visit_Constant(self, node):209 filename = getfilename(node)210 template = self.env.get_template(filename)211 template_dict = {212 'value' : node.value,213 }214 rslt = template.render(template_dict)215 return rslt216 def visit_IntConst(self, node):217 filename = getfilename(node)218 template = self.env.get_template(filename)219 template_dict = {220 'value' : node.value,221 }222 rslt = template.render(template_dict)223 return rslt224 def visit_FloatConst(self, node):225 filename = getfilename(node)226 template = self.env.get_template(filename)227 template_dict = {228 'value' : node.value,229 }230 rslt = template.render(template_dict)231 return rslt232 def visit_StringConst(self, node):233 filename = getfilename(node)234 template = self.env.get_template(filename)235 template_dict = {236 'value' : node.value,237 }238 rslt = template.render(template_dict)239 return rslt240 def visit_Variable(self, node):241 filename = getfilename(node)242 template = self.env.get_template(filename)243 if node.width is None:244 width = '1'245 big = False246 else:247 width = self.visit(node.width)248 big = True if int(width) >= 64 else False249 template_dict = {250 'name' : escape(node.name),251 'width' : width,252 'signed' : node.signed,253 'big' : big,254 }255 rslt = template.render(template_dict)256 return rslt257 def visit_Input(self, node):258 filename = getfilename(node)259 template = self.env.get_template(filename)260 if node.width is None:261 width = '1'262 big = False263 else:264 width = self.visit(node.width)265 big = True if int(width) >= 64 else False266 template_dict = {267 'name' : escape(node.name),268 'width' : width,269 'signed' : node.signed,270 'big' : big,271 }272 rslt = template.render(template_dict)273 return rslt274 def visit_Input_argument(self, node):275 filename = getfilename(node, '_argument')276 template = self.env.get_template(filename)277 if node.width is None:278 width = '1'279 big = False280 else:281 width = self.visit(node.width)282 big = True if int(width) >= 64 else False283 template_dict = {284 'name' : escape(node.name),285 'width' : width,286 'signed' : node.signed,287 'big' : big,288 }289 rslt = template.render(template_dict)290 return rslt291 def visit_Output(self, node):292 filename = getfilename(node)293 template = self.env.get_template(filename)294 if node.width is None:295 width = '1'296 big = False297 else:298 width = self.visit(node.width)299 big = True if int(width) >= 64 else False300 template_dict = {301 'name' : escape(node.name),302 'width' : width,303 'signed' : node.signed,304 'big' : big,305 }306 rslt = template.render(template_dict)307 return rslt308 def visit_Output_argument(self, node):309 filename = getfilename(node, '_argument')310 template = self.env.get_template(filename)311 if node.width is None:312 width = '1'313 big = False314 else:315 width = self.visit(node.width)316 big = True if int(width) >= 64 else False317 template_dict = {318 'name' : escape(node.name),319 'width' : width,320 'signed' : node.signed,321 'big' : big,322 }323 rslt = template.render(template_dict)324 return rslt325 def visit_Inout(self, node):326 filename = getfilename(node)327 template = self.env.get_template(filename)328 if node.width is None:329 width = '1'330 big = False331 else:332 width = self.visit(node.width)333 big = True if int(width) >= 64 else False334 template_dict = {335 'name' : escape(node.name),336 'width' : width,337 'signed' : node.signed,338 'big' : big,339 }340 rslt = template.render(template_dict)341 return rslt342 def visit_Inout_argument(self, node):343 filename = getfilename(node, '_argument')344 template = self.env.get_template(filename)345 if node.width is None:346 width = '1'347 big = False348 else:349 width = self.visit(node.width)350 big = True if int(width) >= 64 else False351 template_dict = {352 'name' : escape(node.name),353 'width' : width,354 'signed' : node.signed,355 'big' : big,356 }357 rslt = template.render(template_dict)358 return rslt359 def visit_Tri(self, node):360 filename = getfilename(node)361 template = self.env.get_template(filename)362 if node.width is None:363 width = '1'364 big = False365 else:366 width = self.visit(node.width)367 big = True if int(width) >= 64 else False368 template_dict = {369 'name' : escape(node.name),370 'width' : width,371 'signed' : node.signed,372 'big' : big,373 }374 rslt = template.render(template_dict)375 return rslt376 def visit_Wire(self, node):377 filename = getfilename(node)378 template = self.env.get_template(filename)379 if node.width is None:380 width = '1'381 big = False382 else:383 width = self.visit(node.width)384 big = True if int(width) >= 64 else False385 template_dict = {386 'name' : escape(node.name),387 'width' : width,388 'signed' : node.signed,389 'big' : big,390 }391 rslt = template.render(template_dict)392 return rslt393 def visit_Reg(self, node):394 filename = getfilename(node)395 template = self.env.get_template(filename)396 if node.width is None:397 width = '1'398 big = False399 else:400 width = self.visit(node.width)401 big = True if int(width) >= 64 else False402 template_dict = {403 'name' : escape(node.name),404 'width' : width,405 'signed' : node.signed,406 'big' : big,407 }408 rslt = template.render(template_dict)409 return rslt410 def visit_WireArray(self, node):411 filename = getfilename(node)412 template = self.env.get_template(filename)413 if node.width is None:414 width = '1'415 big = False416 else:417 width = self.visit(node.width)418 big = True if int(width) >= 64 else False419 template_dict = {420 'name' : escape(node.name),421 'width' : width,422 'length' : self.visit(node.length),423 'signed' : node.signed,424 'big' : big,425 }426 rslt = template.render(template_dict)427 return rslt428 def visit_RegArray(self, node):429 filename = getfilename(node)430 template = self.env.get_template(filename)431 if node.width is None:432 width = '1'433 big = False434 else:435 width = self.visit(node.width)436 big = True if int(width) >= 64 else False437 template_dict = {438 'name' : escape(node.name),439 'width' : width,440 'length' : self.visit(node.length),441 'signed' : node.signed,442 'big' : big,443 }444 rslt = template.render(template_dict)445 return rslt446 def visit_Integer(self, node):447 filename = getfilename(node)448 template = self.env.get_template(filename)449 template_dict = {450 'name' : escape(node.name),451 'signed' : node.signed,452 }453 rslt = template.render(template_dict)454 return rslt455 def visit_Real(self, node):456 filename = getfilename(node)457 template = self.env.get_template(filename)458 template_dict = {459 'name' : escape(node.name),460 }461 rslt = template.render(template_dict)462 return rslt463 def visit_Genvar(self, node):464 filename = getfilename(node)465 template = self.env.get_template(filename)466 template_dict = {467 'name' : escape(node.name),468 }469 rslt = template.render(template_dict)470 return rslt471 def visit_Ioport(self, node):472 filename = getfilename(node)473 template = self.env.get_template(filename)474 template_dict = {475 'first' : self.visit(node.first),476 'second' : '' if node.second is None else self.visit(node.second),477 }478 rslt = template.render(template_dict)479 return rslt480 def visit_Parameter(self, node):481 filename = getfilename(node)482 template = self.env.get_template(filename)483 value = self.visit(node.value)484 if node.width is None:485 width = '1'486 big = False487 else:488 width = '' if (value.startswith('"') and value.endswith('"')) else self.visit(node.width)489 big = True if int(width) >= 64 else False490 template_dict = {491 'name' : escape(node.name),492 'width' : width,493 'value' : value,494 'signed' : node.signed,495 'big' : big,496 }497 rslt = template.render(template_dict)498 return rslt499 def visit_Localparam(self, node):500 filename = getfilename(node)501 template = self.env.get_template(filename)502 value = self.visit(node.value)503 template_dict = {504 'name' : escape(node.name),505 'width' : '' if node.width is None or (value.startswith('"') and value.endswith('"')) else self.visit(node.width),506 'value' : value,507 'signed' : node.signed,508 }509 rslt = template.render(template_dict)510 return rslt511 def visit_Decl(self, node):512 filename = getfilename(node)513 template = self.env.get_template(filename)514 template_dict = {515 'items' : [ self.visit(item) for item in node.list if item.__class__.__name__ != 'Parameter'],516 }517 rslt = template.render(template_dict)518 return rslt519 def visit_Decl_argument(self, node):520 filename = getfilename(node, '_argument')521 template = self.env.get_template(filename)522 items = [ self.visit_argument(item) for item in node.list if item.__class__.__name__ == 'Input' or item.__class__.__name__ == 'Output' or item.__class__.__name__ == 'Inout' ]523 template_dict = {524 'items' : items,525 'len_items' : len(items),526 }527 rslt = template.render(template_dict)528 return rslt529 def visit_Decl_parameter(self, node):530 filename = getfilename(node, '_parameter')531 template = self.env.get_template(filename)532 items = [ self.visit(item) for item in node.list if item.__class__.__name__ == 'Parameter' ]533 template_dict = {534 'items' : items,535 'len_items' : len(items),536 }537 rslt = template.render(template_dict)538 return rslt539 def visit_Concat(self, node):540 filename = getfilename(node)541 template = self.env.get_template(filename)542 items = [ del_paren(self.visit(item)) for item in node.list ]543 template_dict = {544 'items' : items,545 'len_items' : len(items),546 }547 rslt = template.render(template_dict)548 return rslt549 def visit_LConcat(self, node):550 filename = getfilename(node)551 template = self.env.get_template(filename)552 items = [ del_paren(self.visit(item)) for item in node.list ]553 template_dict = {554 'items' : items,555 'len_items' : len(items),556 }557 rslt = template.render(template_dict)558 return rslt559 def visit_Repeat(self, node):560 filename = getfilename(node)561 template = self.env.get_template(filename)562 template_dict = {563 'value' : del_paren(self.visit(node.value)),564 'times' : del_paren(self.visit(node.times)),565 }566 rslt = template.render(template_dict)567 return rslt568 def visit_Partselect(self, node):569 filename = getfilename(node)570 template = self.env.get_template(filename)571 template_dict = {572 'var' : self.visit(node.var),573 'msb' : del_space(del_paren(self.visit(node.msb))),574 'lsb' : del_space(del_paren(self.visit(node.lsb))),575 }576 rslt = template.render(template_dict)577 return rslt578 def visit_Pointer(self, node):579 filename = getfilename(node)580 template = self.env.get_template(filename)581 template_dict = {582 'var' : self.visit(node.var),583 'ptr' : del_paren(self.visit(node.ptr)),584 }585 rslt = template.render(template_dict)586 return rslt587 def visit_Lvalue(self, node):588 filename = getfilename(node)589 template = self.env.get_template(filename)590 template_dict = {591 'var' : del_paren(self.visit(node.var)),592 }593 rslt = template.render(template_dict)594 return rslt595 def visit_Rvalue(self, node):596 filename = getfilename(node)597 template = self.env.get_template(filename)598 template_dict = {599 'var' : del_paren(self.visit(node.var)),600 }601 rslt = template.render(template_dict)602 return rslt603 def visit_Operator(self, node):604 filename = getfilename(node)605 template = self.env.get_template(filename)606 order = op2order(node.__class__.__name__)607 lorder = op2order(node.left.__class__.__name__)608 rorder = op2order(node.right.__class__.__name__)609 left = self.visit(node.left)610 right = self.visit(node.right)611 if ((not isinstance(node.left, (Sll, Srl, Sra,612 LessThan, GreaterThan, LessEq, GreaterEq,613 Eq, NotEq, Eql, NotEql))) and614 (lorder is not None and lorder <= order)):615 left = del_paren(left)616 if ((not isinstance(node.right, (Sll, Srl, Sra,617 LessThan, GreaterThan, LessEq, GreaterEq,618 Eq, NotEq, Eql, NotEql))) and619 (rorder is not None and order > rorder)):620 right = del_paren(right)621 template_dict = {622 'left' : left,623 'right' : right,624 'op' : op2mark(node.__class__.__name__),625 }626 rslt = template.render(template_dict)627 return rslt628 def visit_UnaryOperator(self, node):629 filename = getfilename(node)630 template = self.env.get_template(filename)631 right = self.visit(node.right)632 template_dict = {633 'right' : right,634 'op' : op2mark(node.__class__.__name__),635 }636 rslt = template.render(template_dict)637 return rslt638 def visit_Uplus(self, node):639 return self.visit_UnaryOperator(node)640 def visit_Uminus(self, node):641 return self.visit_UnaryOperator(node)642 def visit_Ulnot(self, node):643 return self.visit_UnaryOperator(node)644 def visit_Unot(self, node):645 return self.visit_UnaryOperator(node)646 def visit_Uand(self, node):647 return self.visit_UnaryOperator(node)648 def visit_Unand(self, node):649 return self.visit_UnaryOperator(node)650 def visit_Uor(self, node):651 return self.visit_UnaryOperator(node)652 def visit_Unor(self, node):653 return self.visit_UnaryOperator(node)654 def visit_Uxor(self, node):655 return self.visit_UnaryOperator(node)656 def visit_Uxnor(self, node):657 return self.visit_UnaryOperator(node)658 def visit_Power(self, node):659 return self.visit_Operator(node)660 def visit_Times(self, node):661 return self.visit_Operator(node)662 def visit_Divide(self, node):663 return self.visit_Operator(node)664 def visit_Mod(self, node):665 return self.visit_Operator(node)666 def visit_Plus(self, node):667 return self.visit_Operator(node)668 def visit_Minus(self, node):669 return self.visit_Operator(node)670 def visit_Sll(self, node):671 return self.visit_Operator(node)672 def visit_Srl(self, node):673 return self.visit_Operator(node)674 def visit_Sra(self, node):675 return self.visit_Operator(node)676 def visit_LessThan(self, node):677 return self.visit_Operator(node)678 def visit_GreaterThan(self, node):679 return self.visit_Operator(node)680 def visit_LessEq(self, node):681 return self.visit_Operator(node)682 def visit_GreaterEq(self, node):683 return self.visit_Operator(node)684 def visit_Eq(self, node):685 return self.visit_Operator(node)686 def visit_NotEq(self, node):687 return self.visit_Operator(node)688 def visit_Eql(self, node):689 return self.visit_Operator(node)690 def visit_NotEql(self, node):691 return self.visit_Operator(node)692 def visit_And(self, node):693 return self.visit_Operator(node)694 def visit_Xor(self, node):695 return self.visit_Operator(node)696 def visit_Xnor(self, node):697 return self.visit_Operator(node)698 def visit_Or(self, node):699 return self.visit_Operator(node)700 def visit_Land(self, node):701 return self.visit_Operator(node)702 def visit_Lor(self, node):703 return self.visit_Operator(node)704 def visit_Cond(self, node):705 filename = getfilename(node)706 template = self.env.get_template(filename)707 true_value = del_paren(self.visit(node.true_value))708 false_value = del_paren(self.visit(node.false_value))709 if isinstance(node.false_value, Cond):710 false_value = ''.join( ['\n', false_value] )711 template_dict = {712 'cond' : del_paren(self.visit(node.cond)),713 'true_value' : true_value,714 'false_value' : false_value,715 }716 rslt = template.render(template_dict)717 return rslt718 def visit_Assign(self, node):719 filename = getfilename(node)720 template = self.env.get_template(filename)721 template_dict = {722 'left' : self.visit(node.left),723 'right' : self.visit(node.right),724 }725 rslt = template.render(template_dict)726 rslt = indent_multiline_assign(rslt)727 return rslt728 def visit_Always(self, node):729 filename = getfilename(node)730 template = self.env.get_template(filename)731 template_dict = {732 'lineno' : str(node.lineno),733 'statement' : self.visit(node.statement),734 }735 rslt = template.render(template_dict)736 return rslt737 def visit_Always_process(self, node):738 filename = getfilename(node, '_process')739 template = self.env.get_template(filename)740 clock_sens = ''741 reset_sens = ''742 for sens in node.sens_list.list:743 if sens.sig.name == self.clock_name:744 clock_sens = self.visit(sens)745 if sens.sig.name == self.reset_name:746 reset_sens = self.visit(sens)747 reset_sens = reset_sens.replace('.pos()', ', true')748 reset_sens = reset_sens.replace('.neg()', ', false')749 template_dict = {750 'lineno' : str(node.lineno),751 'clock_sens' : clock_sens,752 'reset_sens' : reset_sens,753 'sens_list' : self.visit(node.sens_list),754 }755 rslt = template.render(template_dict)756 return rslt757 def visit_Always_declaration(self, node):758 filename = getfilename(node, '_declaration')759 template = self.env.get_template(filename)760 template_dict = {761 'lineno' : str(node.lineno),762 }763 rslt = template.render(template_dict)764 return rslt765 def visit_SensList(self, node):766 filename = getfilename(node)767 template = self.env.get_template(filename)768 items = [ self.visit(item) for item in node.list if item.sig.name != self.clock_name and item.sig.name != self.reset_name]769 template_dict = {770 'items' : items,771 'len_items' : len(items),772 }773 rslt = template.render(template_dict)774 return rslt775 def visit_Sens(self, node):776 filename = getfilename(node)777 template = self.env.get_template(filename)778 template_dict = {779 'sig' : '*' if node.type == 'all' else self.visit(node.sig),780 'type' : node.type[0:3] if node.type == 'posedge' or node.type == 'negedge' else ''781 }782 rslt = template.render(template_dict)783 return rslt784 def visit_Substitution(self, node):785 filename = getfilename(node)786 template = self.env.get_template(filename)787 template_dict = {788 'left' : self.visit(node.left),789 'right' : self.visit(node.right),790 'ldelay' : '' if node.ldelay is None else self.visit(node.ldelay),791 'rdelay' : '' if node.rdelay is None else self.visit(node.rdelay),792 }793 rslt = template.render(template_dict)794 rslt = indent_multiline_assign(rslt)795 return rslt796 def visit_BlockingSubstitution(self, node):797 filename = getfilename(node)798 template = self.env.get_template(filename)799 template_dict = {800 'left' : self.visit(node.left),801 'right' : self.visit(node.right),802 'ldelay' : '' if node.ldelay is None else self.visit(node.ldelay),803 'rdelay' : '' if node.rdelay is None else self.visit(node.rdelay),804 }805 rslt = template.render(template_dict)806 rslt = indent_multiline_assign(rslt)807 return rslt808 def visit_NonblockingSubstitution(self, node):809 filename = getfilename(node)810 template = self.env.get_template(filename)811 template_dict = {812 'left' : self.visit(node.left),813 'right' : self.visit(node.right),814 'ldelay' : '' if node.ldelay is None else self.visit(node.ldelay),815 'rdelay' : '' if node.rdelay is None else self.visit(node.rdelay),816 }817 rslt = template.render(template_dict)818 rslt = indent_multiline_assign(rslt)819 return rslt820 def visit_IfStatement(self, node):821 filename = getfilename(node)822 template = self.env.get_template(filename)823 true_statement = '' if node.true_statement is None else self.visit(node.true_statement)824 false_statement = '' if node.false_statement is None else self.visit(node.false_statement)825 template_dict = {826 'cond' : del_paren(self.visit(node.cond)),827 'true_statement' : true_statement,828 'false_statement' : false_statement,829 }830 rslt = template.render(template_dict)831 return rslt832 def visit_ForStatement(self, node):833 filename = getfilename(node)834 template = self.env.get_template(filename)835 template_dict = {836 'pre' : '' if node.pre is None else self.visit(node.pre),837 'cond' : '' if node.cond is None else del_paren(self.visit(node.cond)),838 'post' : '' if node.post is None else self.visit(node.post).replace(';', ''),839 'statement' : '' if node.statement is None else self.visit(node.statement),840 }841 rslt = template.render(template_dict)842 return rslt843 def visit_WhileStatement(self, node):844 filename = getfilename(node)845 template = self.env.get_template(filename)846 template_dict = {847 'cond' : '' if node.cond is None else del_paren(self.visit(node.cond)),848 'statement' : '' if node.statement is None else self.visit(node.statement),849 }850 rslt = template.render(template_dict)851 return rslt852 def visit_CaseStatement(self, node):853 filename = getfilename(node)854 template = self.env.get_template(filename)855 template_dict = {856 'comp' : del_paren(self.visit(node.comp)),857 'caselist' : [ self.indent(self.visit(case)) for case in node.caselist ],858 }859 rslt = template.render(template_dict)860 return rslt861 def visit_CasexStatement(self, node):862 filename = getfilename(node)863 template = self.env.get_template(filename)864 template_dict = {865 'comp' : del_paren(self.visit(node.comp)),866 'caselist' : [ self.indent(self.visit(case)) for case in node.caselist ],867 }868 rslt = template.render(template_dict)869 return rslt870 def visit_Case(self, node):871 filename = getfilename(node)872 template = self.env.get_template(filename)873 condlist = [ 'default' ] if node.cond is None else [ del_paren(self.visit(c)) for c in node.cond ]874 template_dict = {875 'condlist' : condlist,876 'statement' : self.visit(node.statement),877 }878 rslt = template.render(template_dict)879 return rslt880 def visit_Block(self, node):881 filename = getfilename(node)882 template = self.env.get_template(filename)883 template_dict = {884 'scope' : '' if node.scope is None else escape(node.scope),885 'statements' : [ self.indent(self.visit(statement)) for statement in node.statements ],886 }887 rslt = template.render(template_dict)888 return rslt889 def visit_Initial(self, node):890 filename = getfilename(node)891 template = self.env.get_template(filename)892 template_dict = {893 'name' : 'initial_at_line_' + str(node.lineno),894 'statement' : self.visit(node.statement),895 }896 rslt = template.render(template_dict)897 return rslt898 def visit_Initial_process(self, node):899 filename = getfilename(node, '_process')900 template = self.env.get_template(filename)901 template_dict = {902 'name' : 'initial_at_line_' + str(node.lineno),903 }904 rslt = template.render(template_dict)905 return rslt906 def visit_Initial_declaration(self, node):907 filename = getfilename(node, '_declaration')908 template = self.env.get_template(filename)909 template_dict = {910 'name' : 'initial_at_line_' + str(node.lineno),911 }912 rslt = template.render(template_dict)913 return rslt914 def visit_EventStatement(self, node):915 filename = getfilename(node)916 template = self.env.get_template(filename)917 template_dict = {918 'senslist': del_paren(self.visit(node.senslist)),919 }920 rslt = template.render(template_dict)921 return rslt922 def visit_WaitStatement(self, node):923 filename = getfilename(node)924 template = self.env.get_template(filename)925 template_dict = {926 'cond': del_paren(self.visit(node.cond)),927 'statement' : self.visit(node.statement) if node.statement else '',928 }929 rslt = template.render(template_dict)930 return rslt931 def visit_ForeverStatement(self, node):932 filename = getfilename(node)933 template = self.env.get_template(filename)934 template_dict = {935 'statement' : self.visit(node.statement),936 }937 rslt = template.render(template_dict)938 return rslt939 def visit_DelayStatement(self, node):940 filename = getfilename(node)941 template = self.env.get_template(filename)942 template_dict = {943 'delay' : self.visit(node.delay),944 }945 rslt = template.render(template_dict)946 return rslt947 def visit_InstanceList(self, node):948 filename = getfilename(node)949 template = self.env.get_template(filename)950 parameterlist = [ self.indent(self.visit(param)) for param in node.parameterlist ]951 instances = [ self.visit(instance) for instance in node.instances ]952 template_dict = {953 'module' : escape(node.module),954 'parameterlist' : parameterlist,955 'len_parameterlist' : len(parameterlist),956 'instances' : instances,957 'len_instances' : len(instances),958 }959 rslt = template.render(template_dict)960 return rslt961 def visit_Instance(self, node):962 filename = getfilename(node)963 template = self.env.get_template(filename)964 array = '' if node.array is None else self.visit(node.array)965 portlist = [ self.indent(self.visit(port)) for port in node.portlist ]966 template_dict = {967 'name' : escape(node.name),968 'array' : array,969 'portlist' : portlist,970 'len_portlist' : len(portlist),971 }972 rslt = template.render(template_dict)973 return rslt974 def visit_ParamArg(self, node):975 filename = getfilename(node)976 template = self.env.get_template(filename)977 template_dict = {978 'paramname' : '' if node.paramname is None else escape(node.paramname),979 'argname' : '' if node.argname is None else del_paren(self.visit(node.argname)),980 }981 rslt = template.render(template_dict)982 return rslt983 def visit_PortArg(self, node):984 filename = getfilename(node)985 template = self.env.get_template(filename)986 template_dict = {987 'portname' : '' if node.portname is None else escape(node.portname),988 'argname' : '' if node.argname is None else del_paren(self.visit(node.argname)),989 }990 rslt = template.render(template_dict)991 return rslt992 def visit_Function(self, node):993 filename = getfilename(node)994 template = self.env.get_template(filename)995 arguments = [ self.visit_argument(s) for s in node.statement ]996 statements = [ self.visit(s) for s in node.statement ]997 statements = [ statement for statement in statements if not statement.startswith('sc_in<') and not statement.startswith('sc_out<') and not statement.startswith('sc_inout<') ]998 template_dict = {999 'name' : escape(node.name),1000 'lineno' : str(node.lineno),1001 'retwidth' : self.visit(node.retwidth),1002 'arguments' : arguments,1003 'statements' : statements,1004 }1005 rslt = template.render(template_dict)1006 return rslt1007 def visit_Function_declaration(self, node):1008 filename = getfilename(node, '_declaration')1009 template = self.env.get_template(filename)1010 arguments = [ self.visit_argument(s) for s in node.statement ]1011 statements = [ self.indent(self.visit(s)) for s in node.statement ]1012 template_dict = {1013 'name' : escape(node.name),1014 'lineno' : str(node.lineno),1015 'retwidth' : self.visit(node.retwidth),1016 'arguments' : arguments,1017 'statements' : statements,1018 }1019 rslt = template.render(template_dict)1020 return rslt1021 def visit_FunctionCall(self, node):1022 filename = getfilename(node)1023 template = self.env.get_template(filename)1024 args = [ self.visit(arg) for arg in node.args ]1025 template_dict = {1026 'name' : self.visit(node.name),1027 'lineno' : str(node.lineno),1028 'args' : args,1029 'len_args' : len(args),1030 }1031 rslt = template.render(template_dict)1032 return rslt1033 def visit_Task(self, node):1034 filename = getfilename(node)1035 template = self.env.get_template(filename)1036 statement = [ self.indent(self.visit(s)) for s in node.statement ]1037 template_dict = {1038 'name' : escape(node.name),1039 'statement' : statement,1040 }1041 rslt = template.render(template_dict)1042 return rslt1043 #def visit_TaskCall(self, node):1044 # filename = getfilename(node)1045 # template = self.env.get_template(filename)1046 # args = [ self.visit(arg) for arg in node.args ]1047 # template_dict = {1048 # 'name' : self.visit(node.name),1049 # 'args' : args,1050 # 'len_args' : len(args),1051 # }1052 # rslt = template.render(template_dict)1053 # return rslt1054 def visit_GenerateStatement(self, node):1055 filename = getfilename(node)1056 template = self.env.get_template(filename)1057 template_dict = {1058 'items' : [ self.visit(item) for item in node.items ]1059 }1060 rslt = template.render(template_dict)1061 return rslt1062 def visit_SystemCall(self, node):1063 filename = getfilename(node)1064 template = self.env.get_template(filename)1065 args = [ self.visit(arg) for arg in node.args ]1066 template_dict = {1067 'syscall' : escape(node.syscall),1068 'args' : args,1069 'len_args' : len(args),1070 }1071 rslt = template.render(template_dict)1072 return rslt1073 def visit_IdentifierScopeLabel(self, node):1074 filename = getfilename(node)1075 template = self.env.get_template(filename)1076 template_dict = {1077 'name' : escape(node.name),1078 'loop' : '' if node.loop is None else self.visit(node.loop),1079 }1080 rslt = template.render(template_dict)1081 return rslt1082 def visit_IdentifierScope(self, node):1083 filename = getfilename(node)1084 template = self.env.get_template(filename)1085 scopes = [ self.visit(scope) for scope in node.labellist ]1086 template_dict = {1087 'scopes' : scopes,1088 }1089 rslt = template.render(template_dict)1090 return rslt1091 def visit_Pragma(self, node):1092 filename = getfilename(node)1093 template = self.env.get_template(filename)1094 template_dict = {1095 'entry' : self.visit(node.entry),1096 }1097 rslt = template.render(template_dict)1098 return rslt1099 def visit_PragmaEntry(self, node):1100 filename = getfilename(node)1101 template = self.env.get_template(filename)1102 template_dict = {1103 'name' : escape(node.name),1104 'value' : '' if node.value is None else self.visit(node.value),1105 }1106 rslt = template.render(template_dict)1107 return rslt1108 def visit_Disable(self, node):1109 filename = getfilename(node)1110 template = self.env.get_template(filename)1111 template_dict = {1112 'name' : escape(node.dest),1113 }1114 rslt = template.render(template_dict)1115 return rslt1116 def visit_ParallelBlock(self, node):1117 filename = getfilename(node)1118 template = self.env.get_template(filename)1119 template_dict = {1120 'scope' : '' if node.scope is None else escape(node.scope),1121 'statements' : [ self.indent(self.visit(statement)) for statement in node.statements ],1122 }1123 rslt = template.render(template_dict)1124 return rslt1125 def visit_SingleStatement(self, node):1126 filename = getfilename(node)1127 template = self.env.get_template(filename)1128 template_dict = {1129 'statement' : self.visit(node.statement),1130 }1131 rslt = template.render(template_dict)1132 return rslt1133def main():1134 INFO = "Code converter from AST"1135 VERSION = pyverilog.utils.version.VERSION1136 USAGE = "Usage: python example_codegen.py file ..."1137 def showVersion():1138 print(INFO)1139 print(VERSION)1140 print(USAGE)1141 sys.exit()1142 optparser = OptionParser()1143 optparser.add_option("-v","--version",action="store_true",dest="showversion",1144 default=False,help="Show the version")1145 optparser.add_option("-I","--include",dest="include",action="append",1146 default=[],help="Include path")1147 optparser.add_option("-D",dest="define",action="append",1148 default=[],help="Macro Definition")1149 (options, args) = optparser.parse_args()1150 filelist = args1151 if options.showversion:1152 showVersion()1153 for f in filelist:1154 if not os.path.exists(f): raise IOError("file not found: " + f)1155 if len(filelist) == 0:1156 showVersion()1157 codeparser = VerilogCodeParser(filelist,1158 preprocess_include=options.include,1159 preprocess_define=options.define)1160 ast = codeparser.parse()1161 directives = codeparser.get_directives()1162 ast.show();1163 codegen = ASTCodeGenerator()1164 rslt = codegen.visit(ast)1165 print(rslt)1166if __name__ == '__main__':...
codegen.py
Source:codegen.py
1#-------------------------------------------------------------------------------2# codegen.py3# 4# Code Generator from AST to Verilog HDL source code5#6# Copyright (C) 2013, Shinya Takamaeda-Yamazaki7# License: Apache 2.08#-------------------------------------------------------------------------------9import sys10import os11import math12import re13from jinja2 import Environment, FileSystemLoader14sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) )15import pyverilog.utils.version16from pyverilog.vparser.parser import VerilogCodeParser17from pyverilog.vparser.ast import *18from pyverilog.utils.op2mark import op2mark19DEFAULT_TEMPLATE_DIR = os.path.dirname(os.path.abspath(__file__)) + '/template/'20class ConvertVisitor(object):21 def visit(self, node):22 method = 'visit_' + node.__class__.__name__23 visitor = getattr(self, method, self.generic_visit)24 return visitor(node)25 def generic_visit(self, node):26 ret = []27 for c in node.children():28 ret.append(self.visit(c))29 return ''.join(ret)30def getfilename(node):31 return node.__class__.__name__.lower() + '.txt'32class ASTCodeGenerator(ConvertVisitor):33 def __init__(self):34 self.env = Environment(loader=FileSystemLoader(DEFAULT_TEMPLATE_DIR))35 def visit_Source(self, node):36 filename = getfilename(node)37 template = self.env.get_template(filename)38 template_dict = {39 'description' : self.visit(node.description),40 }41 rslt = template.render(template_dict)42 return rslt43 def visit_Description(self, node):44 filename = getfilename(node)45 template = self.env.get_template(filename)46 template_dict = {47 'definitions':[self.visit(definition) for definition in node.definitions],48 }49 rslt = template.render(template_dict)50 return rslt51 def visit_ModuleDef(self, node):52 filename = getfilename(node)53 template = self.env.get_template(filename)54 paramlist = self.visit(node.paramlist)55 template_dict = {56 'modulename' : node.name,57 'paramlist' : '' if len(node.paramlist.params) == 0 else paramlist,58 'portlist' : self.visit(node.portlist),59 'items' : [ self.visit(item) for item in node.items ],60 }61 rslt = template.render(template_dict)62 return rslt63 64 def visit_Paramlist(self, node):65 filename = getfilename(node)66 template = self.env.get_template(filename)67 params = [ self.visit(param).replace(';','') for param in node.params ]68 template_dict = {69 'params' : params,70 'len_params' : len(params),71 }72 rslt = template.render(template_dict)73 return rslt74 def visit_Portlist(self, node):75 filename = getfilename(node)76 template = self.env.get_template(filename)77 ports = [ self.visit(port) for port in node.ports ]78 template_dict = {79 'ports' : ports,80 'len_ports' : len(ports),81 }82 rslt = template.render(template_dict)83 return rslt84 def visit_Port(self, node):85 filename = getfilename(node)86 template = self.env.get_template(filename)87 template_dict = {88 'name' : node.name,89 }90 rslt = template.render(template_dict)91 return rslt92 def visit_Width(self, node):93 filename = getfilename(node)94 template = self.env.get_template(filename)95 template_dict = {96 'msb' : self.visit(node.msb),97 'lsb' : self.visit(node.lsb),98 }99 rslt = template.render(template_dict)100 return rslt101 102 def visit_Length(self, node):103 filename = getfilename(node)104 template = self.env.get_template(filename)105 template_dict = {106 'msb' : self.visit(node.msb),107 'lsb' : self.visit(node.lsb),108 }109 rslt = template.render(template_dict)110 return rslt111 112 def visit_Identifier(self, node):113 filename = getfilename(node)114 template = self.env.get_template(filename)115 template_dict = {116 'name' : node.name,117 'scope' : '' if node.scope is None else self.visit(node.scope),118 }119 rslt = template.render(template_dict)120 return rslt121 122 def visit_Value(self, node):123 filename = getfilename(node)124 template = self.env.get_template(filename)125 template_dict = {126 'value' : node.value,127 }128 rslt = template.render(template_dict)129 return rslt130 def visit_Constant(self, node):131 filename = getfilename(node)132 template = self.env.get_template(filename)133 template_dict = {134 'value' : node.value,135 }136 rslt = template.render(template_dict)137 return rslt138 def visit_IntConst(self, node):139 filename = getfilename(node)140 template = self.env.get_template(filename)141 template_dict = {142 'value' : node.value,143 }144 rslt = template.render(template_dict)145 return rslt146 def visit_FloatConst(self, node):147 filename = getfilename(node)148 template = self.env.get_template(filename)149 template_dict = {150 'value' : node.value,151 }152 rslt = template.render(template_dict)153 return rslt154 def visit_StringConst(self, node):155 filename = getfilename(node)156 template = self.env.get_template(filename)157 template_dict = {158 'value' : node.value,159 }160 rslt = template.render(template_dict)161 return rslt162 def visit_Variable(self, node):163 filename = getfilename(node)164 template = self.env.get_template(filename)165 template_dict = {166 'name' : node.name,167 'width' : '' if node.width is None else self.visit(node.width),168 'signed' : node.signed,169 }170 rslt = template.render(template_dict)171 return rslt172 173 def visit_Input(self, node):174 filename = getfilename(node)175 template = self.env.get_template(filename)176 template_dict = {177 'name' : node.name,178 'width' : '' if node.width is None else self.visit(node.width),179 'signed' : node.signed,180 }181 rslt = template.render(template_dict)182 return rslt183 def visit_Output(self, node):184 filename = getfilename(node)185 template = self.env.get_template(filename)186 template_dict = {187 'name' : node.name,188 'width' : '' if node.width is None else self.visit(node.width),189 'signed' : node.signed,190 }191 rslt = template.render(template_dict)192 return rslt193 def visit_Inout(self, node):194 filename = getfilename(node)195 template = self.env.get_template(filename)196 template_dict = {197 'name' : node.name,198 'width' : '' if node.width is None else self.visit(node.width),199 'signed' : node.signed,200 }201 rslt = template.render(template_dict)202 return rslt203 def visit_Tri(self, node):204 filename = getfilename(node)205 template = self.env.get_template(filename)206 template_dict = {207 'name' : node.name,208 'width' : '' if node.width is None else self.visit(node.width),209 'signed' : node.signed,210 }211 rslt = template.render(template_dict)212 return rslt213 def visit_Wire(self, node):214 filename = getfilename(node)215 template = self.env.get_template(filename)216 template_dict = {217 'name' : node.name,218 'width' : '' if node.width is None else self.visit(node.width),219 'signed' : node.signed,220 }221 rslt = template.render(template_dict)222 return rslt223 def visit_Reg(self, node):224 filename = getfilename(node)225 template = self.env.get_template(filename)226 template_dict = {227 'name' : node.name,228 'width' : '' if node.width is None else self.visit(node.width),229 'signed' : node.signed,230 }231 rslt = template.render(template_dict)232 return rslt233 def visit_WireArray(self, node):234 filename = getfilename(node)235 template = self.env.get_template(filename)236 template_dict = {237 'name' : node.name,238 'width' : '' if node.width is None else self.visit(node.width),239 'length' : self.visit(node.length),240 'signed' : node.signed,241 }242 rslt = template.render(template_dict)243 return rslt244 def visit_RegArray(self, node):245 filename = getfilename(node)246 template = self.env.get_template(filename)247 template_dict = {248 'name' : node.name,249 'width' : '' if node.width is None else self.visit(node.width),250 'length' : self.visit(node.length),251 'signed' : node.signed,252 }253 rslt = template.render(template_dict)254 return rslt255 def visit_Integer(self, node):256 filename = getfilename(node)257 template = self.env.get_template(filename)258 template_dict = {259 'name' : node.name,260 'signed' : node.signed,261 }262 rslt = template.render(template_dict)263 return rslt264 def visit_Real(self, node):265 filename = getfilename(node)266 template = self.env.get_template(filename)267 template_dict = {268 'name' : node.name,269 }270 rslt = template.render(template_dict)271 return rslt272 def visit_Genvar(self, node):273 filename = getfilename(node)274 template = self.env.get_template(filename)275 template_dict = {276 'name' : node.name,277 }278 rslt = template.render(template_dict)279 return rslt280 def visit_Ioport(self, node):281 filename = getfilename(node)282 template = self.env.get_template(filename)283 template_dict = {284 'first' : node.first.__class__.__name__.lower(),285 'second' : '' if node.second is None else node.second.__class__.__name__.lower(),286 'name' : node.first.name,287 'width' : '' if node.first.width is None else self.visit(node.first.width),288 }289 rslt = template.render(template_dict)290 return rslt291 def visit_Parameter(self, node):292 filename = getfilename(node)293 template = self.env.get_template(filename)294 value = self.visit(node.value)295 template_dict = {296 'name' : node.name,297 'width' : '' if node.width is None or (value.startswith('"') and value.endswith('"')) else self.visit(node.width),298 'value' : value,299 'signed' : node.signed,300 }301 rslt = template.render(template_dict)302 return rslt303 304 def visit_Localparam(self, node):305 filename = getfilename(node)306 template = self.env.get_template(filename)307 value = self.visit(node.value)308 template_dict = {309 'name' : node.name,310 'width' : '' if node.width is None or (value.startswith('"') and value.endswith('"')) else self.visit(node.width),311 'value' : value,312 'signed' : node.signed,313 }314 rslt = template.render(template_dict)315 return rslt316 def visit_Decl(self, node):317 filename = getfilename(node)318 template = self.env.get_template(filename)319 template_dict = {320 'items' : [ self.visit(item) for item in node.list ],321 }322 rslt = template.render(template_dict)323 return rslt324 def visit_Concat(self, node):325 filename = getfilename(node)326 template = self.env.get_template(filename)327 items = [ self.visit(item) for item in node.list ]328 template_dict = {329 'items' : items,330 'len_items' : len(items),331 }332 rslt = template.render(template_dict)333 return rslt334 def visit_LConcat(self, node):335 filename = getfilename(node)336 template = self.env.get_template(filename)337 items = [ self.visit(item) for item in node.list ]338 template_dict = {339 'items' : items,340 'len_items' : len(items),341 }342 rslt = template.render(template_dict)343 return rslt344 def visit_Repeat(self, node):345 filename = getfilename(node)346 template = self.env.get_template(filename)347 template_dict = {348 'value' : self.visit(node.value),349 'times' : self.visit(node.times),350 }351 rslt = template.render(template_dict)352 return rslt353 354 def visit_Partselect(self, node):355 filename = getfilename(node)356 template = self.env.get_template(filename)357 template_dict = {358 'var' : self.visit(node.var),359 'msb' : self.visit(node.msb),360 'lsb' : self.visit(node.lsb),361 }362 rslt = template.render(template_dict)363 return rslt364 365 def visit_Pointer(self, node):366 filename = getfilename(node)367 template = self.env.get_template(filename)368 template_dict = {369 'var' : self.visit(node.var),370 'ptr' : self.visit(node.ptr),371 }372 rslt = template.render(template_dict)373 return rslt374 def visit_Lvalue(self, node):375 filename = getfilename(node)376 template = self.env.get_template(filename)377 template_dict = {378 'var' : self.visit(node.var),379 }380 rslt = template.render(template_dict)381 return rslt382 def visit_Rvalue(self, node):383 filename = getfilename(node)384 template = self.env.get_template(filename)385 template_dict = {386 'var' : self.visit(node.var),387 }388 rslt = template.render(template_dict)389 return rslt390 def visit_Operator(self, node):391 filename = getfilename(node)392 template = self.env.get_template(filename)393 template_dict = {394 'left' : self.visit(node.left),395 'right' : self.visit(node.right),396 'op' : op2mark(node.__class__.__name__),397 }398 rslt = template.render(template_dict)399 return rslt400 def visit_UnaryOperator(self, node):401 filename = getfilename(node)402 template = self.env.get_template(filename)403 template_dict = {404 'right' : self.visit(node.right),405 'op' : op2mark(node.__class__.__name__),406 }407 rslt = template.render(template_dict)408 return rslt409 def visit_Uplus(self, node):410 return self.visit_UnaryOperator(node)411 def visit_Uminus(self, node):412 return self.visit_UnaryOperator(node)413 def visit_Ulnot(self, node):414 return self.visit_UnaryOperator(node)415 def visit_Unot(self, node):416 return self.visit_UnaryOperator(node)417 def visit_Uand(self, node):418 return self.visit_UnaryOperator(node)419 420 def visit_Unand(self, node):421 return self.visit_UnaryOperator(node)422 def visit_Uor(self, node):423 return self.visit_UnaryOperator(node)424 425 def visit_Unor(self, node):426 return self.visit_UnaryOperator(node)427 def visit_Uxor(self, node):428 return self.visit_UnaryOperator(node)429 def visit_Uxnor(self, node):430 return self.visit_UnaryOperator(node)431 def visit_Power(self, node):432 return self.visit_Operator(node)433 def visit_Times(self, node):434 return self.visit_Operator(node)435 def visit_Divide(self, node):436 return self.visit_Operator(node)437 def visit_Mod(self, node):438 return self.visit_Operator(node)439 def visit_Plus(self, node):440 return self.visit_Operator(node)441 def visit_Minus(self, node):442 return self.visit_Operator(node)443 def visit_Sll(self, node):444 return self.visit_Operator(node)445 def visit_Srl(self, node):446 return self.visit_Operator(node)447 def visit_Sra(self, node):448 return self.visit_Operator(node)449 def visit_LessThan(self, node):450 return self.visit_Operator(node)451 def visit_GreaterThan(self, node):452 return self.visit_Operator(node)453 def visit_LessEq(self, node):454 return self.visit_Operator(node)455 def visit_GreaterEq(self, node):456 return self.visit_Operator(node)457 def visit_Eq(self, node):458 return self.visit_Operator(node)459 def visit_NotEq(self, node):460 return self.visit_Operator(node)461 def visit_Eql(self, node):462 return self.visit_Operator(node)463 def visit_NotEql(self, node):464 return self.visit_Operator(node)465 def visit_And(self, node):466 return self.visit_Operator(node)467 def visit_Xor(self, node):468 return self.visit_Operator(node)469 def visit_Xnor(self, node):470 return self.visit_Operator(node)471 def visit_Or(self, node):472 return self.visit_Operator(node)473 def visit_Land(self, node):474 return self.visit_Operator(node)475 def visit_Lor(self, node):476 return self.visit_Operator(node)477 def visit_Cond(self, node):478 filename = getfilename(node)479 template = self.env.get_template(filename)480 template_dict = {481 'cond' : self.visit(node.cond),482 'true_value' : self.visit(node.true_value),483 'false_value' : self.visit(node.false_value),484 }485 rslt = template.render(template_dict)486 return rslt487 def visit_Assign(self, node):488 filename = getfilename(node)489 template = self.env.get_template(filename)490 template_dict = {491 'left' : self.visit(node.left),492 'right' : self.visit(node.right),493 }494 rslt = template.render(template_dict)495 return rslt496 def visit_Always(self, node):497 filename = getfilename(node)498 template = self.env.get_template(filename)499 template_dict = {500 'sens_list' : self.visit(node.sens_list),501 'statement' : self.visit(node.statement),502 }503 rslt = template.render(template_dict)504 return rslt505 def visit_SensList(self, node):506 filename = getfilename(node)507 template = self.env.get_template(filename)508 items = [ self.visit(item) for item in node.list ]509 template_dict = {510 'items' : items,511 'len_items' : len(items),512 }513 rslt = template.render(template_dict)514 return rslt515 def visit_Sens(self, node):516 filename = getfilename(node)517 template = self.env.get_template(filename)518 template_dict = {519 'sig' : '*' if node.type == 'all' else self.visit(node.sig),520 'type' : node.type if node.type == 'posedge' or node.type == 'negedge' else ''521 }522 rslt = template.render(template_dict)523 return rslt524 def visit_Substitution(self, node):525 filename = getfilename(node)526 template = self.env.get_template(filename)527 template_dict = {528 'left' : self.visit(node.left),529 'right' : self.visit(node.right),530 'ldelay' : '' if node.ldelay is None else self.visit(node.ldelay),531 'rdelay' : '' if node.rdelay is None else self.visit(node.rdelay),532 }533 rslt = template.render(template_dict)534 return rslt535 def visit_BlockingSubstitution(self, node):536 filename = getfilename(node)537 template = self.env.get_template(filename)538 template_dict = {539 'left' : self.visit(node.left),540 'right' : self.visit(node.right),541 'ldelay' : '' if node.ldelay is None else self.visit(node.ldelay),542 'rdelay' : '' if node.rdelay is None else self.visit(node.rdelay),543 }544 rslt = template.render(template_dict)545 return rslt546 def visit_NonblockingSubstitution(self, node):547 filename = getfilename(node)548 template = self.env.get_template(filename)549 template_dict = {550 'left' : self.visit(node.left),551 'right' : self.visit(node.right),552 'ldelay' : '' if node.ldelay is None else self.visit(node.ldelay),553 'rdelay' : '' if node.rdelay is None else self.visit(node.rdelay),554 }555 rslt = template.render(template_dict)556 return rslt557 def visit_IfStatement(self, node):558 filename = getfilename(node)559 template = self.env.get_template(filename)560 template_dict = {561 'cond' : self.visit(node.cond),562 'true_statement' : '' if node.true_statement is None else self.visit(node.true_statement),563 'false_statement' : '' if node.false_statement is None else self.visit(node.false_statement),564 }565 rslt = template.render(template_dict)566 return rslt567 568 def visit_ForStatement(self, node):569 filename = getfilename(node)570 template = self.env.get_template(filename)571 template_dict = {572 'pre' : '' if node.pre is None else self.visit(node.pre),573 'cond' : '' if node.cond is None else self.visit(node.cond),574 'post' : '' if node.post is None else self.visit(node.post).replace(';', ''),575 'statement' : '' if node.statement is None else self.visit(node.statement),576 }577 rslt = template.render(template_dict)578 return rslt579 580 def visit_WhileStatement(self, node):581 filename = getfilename(node)582 template = self.env.get_template(filename)583 template_dict = {584 'cond' : '' if node.cond is None else self.visit(node.cond),585 'statement' : '' if node.statement is None else self.visit(node.statement),586 }587 rslt = template.render(template_dict)588 return rslt589 def visit_CaseStatement(self, node):590 filename = getfilename(node)591 template = self.env.get_template(filename)592 template_dict = {593 'comp' : self.visit(node.comp),594 'caselist' : [ self.visit(case) for case in node.caselist ],595 }596 rslt = template.render(template_dict)597 return rslt598 def visit_Case(self, node):599 filename = getfilename(node)600 template = self.env.get_template(filename)601 condlist = [ 'default' ] if node.cond is None else [ self.visit(c) for c in node.cond ]602 cond = []603 for c in condlist:604 cond.append(c)605 cond.append(', ')606 template_dict = {607 'cond' : ''.join(cond[:-1]),608 'statement' : self.visit(node.statement),609 }610 rslt = template.render(template_dict)611 return rslt612 def visit_Block(self, node):613 filename = getfilename(node)614 template = self.env.get_template(filename)615 template_dict = {616 'scope' : '' if node.scope is None else node.scope,617 'statements' : [ self.visit(statement) for statement in node.statements ],618 }619 rslt = template.render(template_dict)620 return rslt621 def visit_Initial(self, node):622 filename = getfilename(node)623 template = self.env.get_template(filename)624 template_dict = {625 'statement' : self.visit(node.statement),626 }627 rslt = template.render(template_dict)628 return rslt629 def visit_EventStatement(self, node):630 filename = getfilename(node)631 template = self.env.get_template(filename)632 template_dict = {633 'senslist': self.visit(node.senslist),634 }635 rslt = template.render(template_dict)636 return rslt637 def visit_WaitStatement(self, node):638 filename = getfilename(node)639 template = self.env.get_template(filename)640 template_dict = {641 'cond': self.visit(node.cond),642 'statement' : self.visit(node.statement),643 }644 rslt = template.render(template_dict)645 return rslt646 def visit_ForeverStatement(self, node):647 filename = getfilename(node)648 template = self.env.get_template(filename)649 template_dict = {650 'statement' : self.visit(node.statement),651 }652 rslt = template.render(template_dict)653 return rslt654 def visit_DelayStatement(self, node):655 filename = getfilename(node)656 template = self.env.get_template(filename)657 template_dict = {658 'delay' : self.visit(node.delay),659 }660 rslt = template.render(template_dict)661 return rslt662 663 def visit_Instance(self, node):664 filename = getfilename(node)665 template = self.env.get_template(filename)666 portlist = [ self.visit(port) for port in node.portlist ]667 parameterlist = [ self.visit(param) for param in node.parameterlist ]668 template_dict = {669 'module' : node.module,670 'name' : node.name,671 'portlist' : portlist,672 'len_portlist' : len(portlist),673 'parameterlist' : parameterlist,674 'len_parameterlist' : len(parameterlist),675 }676 rslt = template.render(template_dict)677 return rslt678 def visit_ParamArg(self, node):679 filename = getfilename(node)680 template = self.env.get_template(filename)681 template_dict = {682 'paramname' : '' if node.paramname is None else node.paramname,683 'argname' : '' if node.argname is None else self.visit(node.argname),684 }685 rslt = template.render(template_dict)686 return rslt687 688 def visit_PortArg(self, node):689 filename = getfilename(node)690 template = self.env.get_template(filename)691 template_dict = {692 'portname' : '' if node.portname is None else node.portname,693 'argname' : '' if node.argname is None else self.visit(node.argname),694 }695 rslt = template.render(template_dict)696 return rslt697 698 def visit_Function(self, node):699 filename = getfilename(node)700 template = self.env.get_template(filename)701 statement = [ self.visit(s) for s in node.statement ]702 template_dict = {703 'name' : node.name,704 'retwidth' : self.visit(node.retwidth),705 'statement' : statement,706 }707 rslt = template.render(template_dict)708 return rslt709 def visit_FunctionCall(self, node):710 filename = getfilename(node)711 template = self.env.get_template(filename)712 args = [ self.visit(arg) for arg in node.args ]713 template_dict = {714 'name' : self.visit(node.name),715 'args' : args,716 'len_args' : len(args),717 }718 rslt = template.render(template_dict)719 return rslt720 def visit_Task(self, node):721 filename = getfilename(node)722 template = self.env.get_template(filename)723 template_dict = {724 'name' : node.name,725 'statement' : self.visit(node.statement),726 }727 rslt = template.render(template_dict)728 return rslt729 #def visit_TaskCall(self, node):730 # filename = getfilename(node)731 # template = self.env.get_template(filename)732 # args = [ self.visit(arg) for arg in node.args ]733 # template_dict = {734 # 'name' : self.visit(node.name),735 # 'args' : args,736 # 'len_args' : len(args),737 # }738 # rslt = template.render(template_dict)739 # return rslt740 def visit_GenerateStatement(self, node):741 filename = getfilename(node)742 template = self.env.get_template(filename)743 template_dict = {744 'items' : [ self.visit(item) for item in node.items ]745 }746 rslt = template.render(template_dict)747 return rslt748 def visit_SystemCall(self, node):749 filename = getfilename(node)750 template = self.env.get_template(filename)751 args = [ self.visit(arg) for arg in node.args ]752 template_dict = {753 'syscall' : node.syscall,754 'args' : args,755 'len_args' : len(args),756 }757 rslt = template.render(template_dict)758 return rslt759 def visit_IdentifierScopeLabel(self, node):760 filename = getfilename(node)761 template = self.env.get_template(filename)762 template_dict = {763 'name' : node.name,764 'loop' : '' if node.loop is None else self.visit(node.loop),765 }766 rslt = template.render(template_dict)767 return rslt768 def visit_IdentifierScope(self, node):769 filename = getfilename(node)770 template = self.env.get_template(filename)771 scopes = [ self.visit(scope) for scope in node.labellist ]772 template_dict = {773 'scopes' : scopes,774 }775 rslt = template.render(template_dict)776 return rslt777 def visit_Pragma(self, node):778 filename = getfilename(node)779 template = self.env.get_template(filename)780 template_dict = {781 'entry' : self.visit(node.entry),782 }783 rslt = template.render(template_dict)784 return rslt785 def visit_PragmaEntry(self, node):786 filename = getfilename(node)787 template = self.env.get_template(filename)788 template_dict = {789 'name' : node.name,790 'value' : '' if node.value is None else self.visit(node.value),791 }792 rslt = template.render(template_dict)793 return rslt794 def visit_Disable(self, node):795 filename = getfilename(node)796 template = self.env.get_template(filename)797 template_dict = {798 'name' : node.dest,799 } 800 rslt = template.render(template_dict)801 return rslt802 def visit_ParallelBlock(self, node):803 filename = getfilename(node)804 template = self.env.get_template(filename)805 template_dict = {806 'scope' : '' if node.scope is None else node.scope,807 'statements' : [ self.visit(statement) for statement in node.statements ],808 }809 rslt = template.render(template_dict)810 return rslt811 def visit_SingleStatement(self, node):812 filename = getfilename(node)813 template = self.env.get_template(filename)814 template_dict = {815 'statement' : self.visit(node.statement),816 }817 rslt = template.render(template_dict)818 return rslt819if __name__ == '__main__':820 from optparse import OptionParser821 INFO = "Code converter from AST"822 VERSION = pyverilog.utils.version.VERSION823 USAGE = "Usage: python codegen.py file ..."824 def showVersion():825 print(INFO)826 print(VERSION)827 print(USAGE)828 sys.exit()829 830 optparser = OptionParser()831 optparser.add_option("-v","--version",action="store_true",dest="showversion",832 default=False,help="Show the version")833 optparser.add_option("-I","--include",dest="include",action="append",834 default=[],help="Include path")835 (options, args) = optparser.parse_args()836 filelist = args837 if options.showversion:838 showVersion()839 for f in filelist:840 if not os.path.exists(f): raise IOError("file not found: " + f)841 if len(filelist) == 0:842 showVersion()843 codeparser = VerilogCodeParser(filelist, preprocess_include=options.include)844 ast = codeparser.parse()845 directives = codeparser.get_directives()846 codegen = ASTCodeGenerator()847 rslt = codegen.visit(ast)...
graphicobject.py
Source:graphicobject.py
...28 self.sprites = sDict()29 super(GraphicObject, self).__init__(path, *args, **kwargs)30 @property31 def image_path(self):32 debugMessage("image_path function not defined for " + self.getFilename())33 return 034 @image_path.setter35 def image_path(self, newvalue):36 debugMessage("image_path is read-only")37 @property38 def original_width(self):39 debugMessage("original_width function not defined for " + self.getFilename())40 return 041 @original_width.setter42 def original_width(self, newvalue):43 debugMessage("original_width is read-only")44 @property45 def original_height(self):46 debugMessage("original_height function not defined for " + self.getFilename())47 return 048 @original_height.setter49 def original_height(self, newvalue):50 debugMessage("original_height is read-only")51 @property52 def update_image(self):53 debugMessage("update_image function not defined for " + self.getFilename())54 return False55 @update_image.setter56 def update_image(self, newvalue):57 for sprite in self.sprites.values():58 sprite.update_image = newvalue59 @property60 def layer(self):61 return self._layer62 @layer.setter63 def layer(self, newvalue):64 self._layer = newvalue65 self.update_layer()66 def update_layer(self):67 for sprite in self.sprites.values():68 sprite.layer = self.layer69 @property70 def pos(self):71 return self.getPos()72 @pos.setter73 def pos(self, newvalue):74 if self._pos != newvalue:75 self.setPos(*newvalue)76 @property77 def offset(self):78 debugMessage("offset function not defined for " + self.getFilename())79 return [0,0]80 @offset.setter81 def offset(self, newvalue):82 debugMessage("offset setter function not defined for " + self.getFilename())83 @property84 def other_offsets(self):85 debugMessage("other_offsets function not defined for " + self.getFilename())86 return sDict()87 @other_offsets.setter88 def other_offsets(self, newvalue):89 debugMessage("other_offsets setter function not defined for " + self.getFilename())90 @property91 def width(self):92 debugMessage("width function not defined for " + self.getFilename())93 return 094 @width.setter95 def width(self, newvalue):96 debugMessage("width setter function not defined for " + self.getFilename())97 @property98 def height(self):99 debugMessage("height function not defined for " + self.getFilename())100 return 0101 @height.setter102 def height(self, newvalue):103 debugMessage("height setter function not defined for " + self.getFilename())104 @property105 def tex_widths(self):106 debugMessage("tex_widths function not defined for " + self.getFilename())107 return [0,0]108 @tex_widths.setter109 def tex_widths(self, newvalue):110 debugMessage("tex_widths setter function not defined for " + self.getFilename())111 @property112 def tex_heights(self):113 debugMessage("tex_heights function not defined for " + self.getFilename())114 return [0,0]115 @tex_heights.setter116 def tex_heights(self, newvalue):117 debugMessage("tex_heights setter function not defined for " + self.getFilename())118 @property119 def size(self):120 return self.getSize()121 @size.setter122 def size(self, *args, **kwargs):123 self.setSize(*args, **kwargs)124 def update_size(self):125 for sprite in self.sprites.values():126 sprite.size = self.size127 @property128 def color(self):129 return self._color[:3]130 @color.setter131 def color(self, newvalue):132 self._color = newvalue133 self.update_color()134 def update_color(self):135 for sprite in self.sprites.values():136 sprite.color = self.color137 @property138 def alpha(self):139 return self._alpha140 @alpha.setter141 def alpha(self, newvalue):142 self._alpha = newvalue143 self.update_alpha()144 def update_alpha(self):145 for sprite in self.sprites.values():146 sprite.alpha = self.alpha147 @property148 def show(self):149 return self._show150 @show.setter151 def show(self, newvalue):152 self._show = newvalue153 self.update_show()154 def update_show(self):155 for sprite in self.sprites.values():156 sprite.show = self.show157 @property158 def center(self):159 return self._center160 @center.setter161 def center(self, newvalue):162 if self._center != newvalue:163 self._center = newvalue164 self.update_center()165 def update_center(self):166 for sprite in self.sprites.values():167 sprite.center = self.center168 @property169 def flip(self):170 return self._flip171 @flip.setter172 def flip(self, newvalue):173 if self._flip != newvalue:174 self._flip = newvalue175 self.update_flip()176 def update_flip(self):177 for sprite in self.sprites.values():178 sprite.flip = self.flip179 @property180 def follow_camera(self):181 return self._follow_camera182 @follow_camera.setter183 def follow_camera(self, newvalue):184 self._follow_camera = newvalue185 self.update_follow_camera()186 def update_follow_camera(self):187 for sprite in self.sprites.values():188 sprite.follow_camera = self.follow_camera189 @property190 def bottom_left_corner(self):191 """returns the bottom left corner of the sprite, no matter where that might be"""192 debugMessage("bottom_left_corner not defined for " + self.getFilename())193 return self.pos[:]194 def setPos(self, x = None, y = None):195 try:196 x[0]197 except:198 pass199 else:200 x, y = x201 if x is None:202 x = self.pos[Xi]203 if y is None:204 y = self.pos[Yi]205 self._pos = (x,y)206 def getPos(self):207 return self._pos208 def setOffset(self, x = None, y = None):209 debugMessage("setOffset function not defined for " + self.getFilename())210 def append_offset(self, *args, **kwargs):211 for sprite in self.sprites.values():212 sprite.append_offset(*args, **kwargs)213 def remove_offset(self, *args, **kwargs):214 for sprite in self.sprites.values():215 sprite.remove_offset(*args, **kwargs)216 def change_offset(self, *args, **kwargs):217 for sprite in self.sprites.values():218 sprite.change_offset(*args, **kwargs)219 def setDimensions(self, *args, **kwargs):220 debugMessage("setDimensions function not defined for " + self.getFilename())221 def set_texture_dimensions(self, xLeft = None, xRight = None, yBottom = None, yTop = None):222 debugMessage("set_texture_dimensions function not defined for " + self.getFilename())223 def getSize(self, key = DEFAULT_SIZE_KEY):224 return self._size.get(key, (1.0,1.0))225 def setSize(self, x = None, y = None, key = DEFAULT_SIZE_KEY):226 if x is None:227 x = self.getSize(key)[Xi]228 if y is None:229 y = self.getSize(key)[Yi]230 self._size[key] = (x,y)231 def get_effective_size(self):232 returnval = [1.0,1.0]233 for size in self._size.values():234 returnval[Xi] *= size[Xi]235 returnval[Yi] *= size[Yi]236 return returnval237 def setColor(self, r = None, g = None, b = None, alpha = None):238 #alpha setting is completely ignored239 if r is None:240 r = self.color[RED]241 if g is None:242 g = self.color[GREEN]243 if b is None:244 b = self.color[BLUE]245 self.color = [r,g,b]246 def setCenter(self, x = None, y = None):247 if x is None:248 x = self.center[Xi]249 if y is None:250 y = self.center[Yi]251 self.center = [x,y]252 def setFlip(self, x = None, y = None):253 if x is None:254 x = self.flip[Xi]255 if y is None:256 y = self.flip[Yi]257 self.flip = [x,y]258 def set_image(self, image_path, tex_id = None, keep_dim = True, display = True):259 debugMessage("set_image function not defined for " + self.getFilename())260 def set_image_from_buffer(self, image_name, ix, iy, image_buffer, keep_dim = True, display = True):261 debugMessage("set_image_from_buffer function not defined for " + self.getFilename())262 def remove_image(self, keep_dim = True):263 debugMessage("remove_image function not defined for " + self.getFilename())264 def getDimensions(self):265 try:266 return self.width, self.height267 except:268 debugMessage("width and/or height not defined for " + self.getFilename())269 return (0,0)270 get_dimensions = getDimensions #deprecated function name271 def getWidth(self):272 return self.width273 def getHeight(self):274 return self.height275 def get_effective_dimensions(self):276 try:277 return self.width * self.size[0], self.height * self.size[0]278 except:279 debugMessage("effective width and/or height not defined for " + self.getFilename())280 return [0,0]281 def getExtents(self):282 effective_size = self.get_effective_size()283 width = self.width * effective_size[Xi]284 height = self.height * effective_size[Yi]285 if self.center[Xi]:286 center_xoffset = width / 2287 else:288 center_xoffset = 0289 if self.center[Yi]:290 center_yoffset = height / 2291 else:292 center_yoffset = 0293 xoffset = self.offset[Xi] * effective_size[Xi]...
test_koRemoteFileInfo.py
Source:test_koRemoteFileInfo.py
...44 fileinfo = self._makeKoRemoteFileInfo()45 gm_now = time.gmtime()46 self.failIf(fileinfo.initFromDirectoryListing("testingdir", l) != True,47 "Could not parse directory listing: %r" % (l, ))48 self.failIf(fileinfo.getFilename() != 'Python-2.3.4.tgz',49 "Incorrect filename: %r != 'Python-2.3.4.tgz'" % (fileinfo.getFilename(), ))50 self.failIf(fileinfo.getDirname() != "testingdir",51 "Incorrect directory name: %r != 'testingdir'" % (fileinfo.getDirname(),))52 self.failIf(fileinfo.getFileSize() != '8502738',53 "Incorrect file size: %r != '8502738'" % (fileinfo.getFileSize(),))54 self.failIf(fileinfo.isDirectory() != False,55 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(),))56 self.failIf(fileinfo.isExecutable() != False,57 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(),))58 self.failIf(fileinfo.isFile() != True,59 "Incorrect isFile: '%r'" % (fileinfo.isFile(),))60 self.failIf(not fileinfo.isReadable(),61 "Incorrect isReadable: '%r'" % (fileinfo.isReadable(),))62 self.failIf(fileinfo.isSymlink() != False,63 "Incorrect isSymlink: '%r'" % (fileinfo.isSymlink(),))64 self.failIf(not fileinfo.isWriteable(),65 "Incorrect isWriteable: '%r'" % (fileinfo.isWriteable(),))66 self.failIf(fileinfo.isHidden() != False,67 "Incorrect isHidden: '%r'" % (fileinfo.isHidden(),))68 self.failIf((gm_now[1] <= 11 or gm_now[2] <= 29) and \69 fileinfo.getModifiedTime() > time.time(),70 "The time was parsed as sometime in the future: %s" % (time.ctime(fileinfo.getModifiedTime()), ))71 def test_windows_format(self):72 # Windows file listing73 l = "07-03-06 10:19AM <DIR> home"74 fileinfo = self._makeKoRemoteFileInfo()75 self.failIf(fileinfo.initFromDirectoryListing("testingdir", l) != True,76 "Could not parse directory listing: %r" % (l, ))77 self.failIf(fileinfo.getFilename() != 'home',78 "Incorrect filename: %r != 'home'" % (fileinfo.getFilename(), ))79 self.failIf(fileinfo.getDirname() != "testingdir",80 "Incorrect directory name: %r != testingdir" % (fileinfo.getDirname(), ))81 self.failIf(fileinfo.isDirectory() != True,82 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(), ))83 self.failIf(fileinfo.isExecutable() != True,84 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(), ))85 self.failIf(fileinfo.isFile() != False,86 "Incorrect isFile: '%r'" % (fileinfo.isFile(), ))87 self.failIf(not fileinfo.isReadable(),88 "Incorrect isReadable: '%r'" % (fileinfo.isReadable(), ))89 self.failIf(fileinfo.isSymlink() != False,90 "Incorrect isSymlink: '%r'" % (fileinfo.isSymlink(), ))91 self.failIf(not fileinfo.isWriteable(),92 "Incorrect isWriteable: '%r'" % (fileinfo.isWriteable(), ))93 self.failIf(fileinfo.isHidden() != False,94 "Incorrect isHidden: '%r'" % (fileinfo.isHidden(), ))95 def test_symlink_handling(self):96 # Symlinks97 l = 'lrwxrwxrwx 1 toddw toddw 8 2006-07-25 11:23 link.txt -> todd.txt'98 fileinfo = self._makeKoRemoteFileInfo()99 self.failIf(fileinfo.initFromDirectoryListing("/tmp", l) != True,100 "Could not parse directory listing: %r" % (l, ))101 self.failIf(fileinfo.getFilename() != 'link.txt',102 "Incorrect filename: %r != 'link.txt'" % (fileinfo.getFilename(), ))103 self.failIf(fileinfo.isSymlink() != True,104 "Incorrect symlink info: '%s'" % (fileinfo.isSymlink(), ))105 self.failIf(fileinfo.getLinkTarget() != '/tmp/todd.txt',106 "Incorrect symlink target: %r != '/tmp/todd.txt'" % (fileinfo.getLinkTarget(), ))107 def test_rumpus_format(self):108 # Rumpus file listing109 file_listing = '-rw-r--r-- 0 0 0 Sep 24 16:48 myfile.txt'110 fileinfo = self._makeKoRemoteFileInfo()111 self.failIf(fileinfo.initFromDirectoryListing("testingdir", file_listing) != True,112 "Could not parse directory listing: %r" % (file_listing, ))113 self.failIf(fileinfo.getFilename() != 'myfile.txt',114 "Incorrect filename: %r != 'myfile.txt'" % (fileinfo.getFilename(), ))115 self.failIf(fileinfo.getFileSize() != '0',116 "Incorrect file size: %r != '0'" % (fileinfo.getFileSize(),))117 self.failIf(fileinfo.isDirectory() != False,118 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(),))119 self.failIf(fileinfo.isExecutable() != False,120 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(),))121 self.failIf(fileinfo.isFile() != True,122 "Incorrect isFile: '%r'" % (fileinfo.isFile(),))123 folder_listing = 'drwxr-xr-x folder 0 Sep 24 16:46 foo'124 fileinfo = self._makeKoRemoteFileInfo()125 self.failIf(fileinfo.initFromDirectoryListing("testingdir", folder_listing) != True,126 "Could not parse directory listing: %r" % (folder_listing, ))127 self.failIf(fileinfo.getFilename() != 'foo',128 "Incorrect filename: %r != 'foo'" % (fileinfo.getFilename(), ))129 self.failIf(fileinfo.getFileSize() != '0',130 "Incorrect file size: %r != '0'" % (fileinfo.getFileSize(),))131 self.failIf(fileinfo.isDirectory() != True,132 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(),))133 self.failIf(fileinfo.isExecutable() != True,134 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(),))135 self.failIf(fileinfo.isFile() != False,136 "Incorrect isFile: '%r'" % (fileinfo.isFile(),))137 @tag("bug88866")138 def test_ruski_format(self):139 # Russian file listing140 folder_listing = u'drwxrwxr-x 2 username username 4096 Ðек 5 2009 doxygen'141 fileinfo = self._makeKoRemoteFileInfo()142 self.failIf(fileinfo.initFromDirectoryListing("testingdir", folder_listing) != True,143 "Could not parse directory listing: %r" % (folder_listing, ))144 self.failIf(fileinfo.getFilename() != 'doxygen',145 "Incorrect filename: %r != 'doxygen'" % (fileinfo.getFilename(), ))146 self.failIf(fileinfo.isDirectory() != True,147 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(),))148 self.failIf(fileinfo.isExecutable() != True,149 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(),))150 self.failIf(fileinfo.isFile() != False,151 "Incorrect isFile: '%r'" % (fileinfo.isFile(),))152 file_listing = u'-rw-rw-r-- 1 username username 990 Ðвг 19 2009 failed.gif'153 fileinfo = self._makeKoRemoteFileInfo()154 self.failIf(fileinfo.initFromDirectoryListing("testingdir", file_listing) != True,155 "Could not parse directory listing: %r" % (file_listing, ))156 self.failIf(fileinfo.getFilename() != 'failed.gif',157 "Incorrect filename: %r != 'failed.gif'" % (fileinfo.getFilename(), ))158 self.failIf(fileinfo.getFileSize() != '990',159 "Incorrect file size: %r != '990'" % (fileinfo.getFileSize(),))160 self.failIf(fileinfo.isDirectory() != False,161 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(),))162 self.failIf(fileinfo.isExecutable() != False,163 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(),))164 self.failIf(fileinfo.isFile() != True,165 "Incorrect isFile: '%r'" % (fileinfo.isFile(),))166 file_listing = '-rw-rw-r-- 1 username username 3314 ÐÐ°Ñ 1 2010 icon16x16.png'167 fileinfo = self._makeKoRemoteFileInfo()168 self.failIf(fileinfo.initFromDirectoryListing("testingdir", file_listing) != True,169 "Could not parse directory listing: %r" % (file_listing, ))170 self.failIf(fileinfo.getFilename() != 'icon16x16.png',171 "Incorrect filename: %r != 'icon16x16.png'" % (fileinfo.getFilename(), ))172 self.failIf(fileinfo.getFileSize() != '3314',173 "Incorrect file size: %r != '3314'" % (fileinfo.getFileSize(),))174 self.failIf(fileinfo.isDirectory() != False,175 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(),))176 self.failIf(fileinfo.isExecutable() != False,177 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(),))178 self.failIf(fileinfo.isFile() != True,179 "Incorrect isFile: '%r'" % (fileinfo.isFile(),))180 @tag("bug88866")181 def test_french_format(self):182 # French file listing183 folder_listing = u'drwxr-xr-x 3 root root 4096 26 fév 22:00 boot'184 fileinfo = self._makeKoRemoteFileInfo()185 self.failIf(fileinfo.initFromDirectoryListing("testingdir", folder_listing) != True,186 "Could not parse directory listing: %r" % (folder_listing, ))187 self.failIf(fileinfo.getFilename() != 'boot',188 "Incorrect filename: %r != 'boot'" % (fileinfo.getFilename(), ))189 self.failIf(fileinfo.isDirectory() != True,190 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(),))191 self.failIf(fileinfo.isExecutable() != True,192 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(),))193 self.failIf(fileinfo.isFile() != False,194 "Incorrect isFile: '%r'" % (fileinfo.isFile(),))195 symlink_listing = 'lrwxrwxrwx 1 root root 25 17 sep 2009 vmlinuz.old -> boot/vmlinuz-2.6.26-2-686'196 fileinfo = self._makeKoRemoteFileInfo()197 self.failIf(fileinfo.initFromDirectoryListing("testingdir", symlink_listing) != True,198 "Could not parse symlink listing: %r" % (symlink_listing, ))199 self.failIf(fileinfo.getFilename() != 'vmlinuz.old',200 "Incorrect filename: %r != 'vmlinuz.old'" % (fileinfo.getFilename(), ))201 self.failIf(fileinfo.isDirectory() != False,202 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(),))203 self.failIf(fileinfo.isExecutable() != True,204 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(),))205 self.failIf(fileinfo.isFile() != False,206 "Incorrect isFile: '%r'" % (fileinfo.isFile(),))207 @tag("bug91990")208 def test_space_in_group_name(self):209 file_listing = '-rw------- 1 incognito.guy Domain Users 11420 2011-12-29 18:51 .bash_history'210 fileinfo = self._makeKoRemoteFileInfo()211 self.failIf(fileinfo.initFromDirectoryListing("testingdir", file_listing) != True,212 "Could not parse file listing: %r" % (file_listing, ))213 self.failIf(fileinfo.getFilename() != '.bash_history',214 "Incorrect filename: %r != '.bash_history'" % (fileinfo.getFilename(), ))215 self.failIf(fileinfo.isDirectory() != False,216 "Incorrect isDirectory: '%r'" % (fileinfo.isDirectory(),))217 self.failIf(fileinfo.isExecutable() != False,218 "Incorrect isExecutable: '%r'" % (fileinfo.isExecutable(),))219 self.failIf(fileinfo.isFile() != True,220 "Incorrect isFile: '%r'" % (fileinfo.isFile(),))221 @tag("bug82484")222 def test_remote_file_large_timestamps(self):223 fileinfo = self._makeKoRemoteFileInfo()...
test_filename.py
Source:test_filename.py
...39 self._dummy.initializeArchetype()40 def test_textfieldwithfilename(self):41 obj = self._dummy42 field = obj.getField('atextfield')43 self.assertEqual(field.getFilename(obj), None)44 self.assertEqual(field.getRaw(obj), default_text)45 obj.setAtextfield('Bla', filename='name.rst')46 self.assertEqual(field.getFilename(obj), 'name.rst')47 self.assertEqual(field.getRaw(obj), 'Bla')48 def test_textfieldwithfilename2(self):49 obj = self._dummy50 field = obj.getField('atextfield')51 obj.setAtextfield('Ble', filename='eitadiacho.txt')52 self.assertEqual(field.getRaw(obj), 'Ble')53 self.assertEqual(field.getFilename(obj), 'eitadiacho.txt')54 def test_textfieldwithoutfilename(self):55 obj = self._dummy56 field = obj.getField('atextfield')57 obj.setAtextfield('Bli')58 self.assertEqual(str(field.getRaw(obj)), 'Bli')59 self.assertEqual(field.getFilename(obj), None)60 def test_textfielduploadwithoutfilename(self):61 obj = self._dummy62 file = open(os.path.join(PACKAGE_HOME, 'input', 'rest1.tgz'), 'r')63 field = obj.getField('atextfield')64 obj.setAtextfield(file)65 file.close()66 self.assertEqual(field.getFilename(obj), 'rest1.tgz')67 def test_filefieldwithfilename(self):68 obj = self._dummy69 field = obj.getField('afilefield')70 obj.setAfilefield('Blo', filename='beleza.jpg')71 self.assertEqual(str(obj.getAfilefield()), 'Blo')72 self.assertEqual(field.getFilename(obj), 'beleza.jpg')73 def test_filefieldwithfilename2(self):74 obj = self._dummy75 field = obj.getField('afilefield')76 obj.setAfilefield('Blu', filename='juca.avi')77 self.assertEqual(str(obj.getAfilefield()), 'Blu')78 self.assertEqual(field.getFilename(obj), 'juca.avi')79 def test_filefieldwithoutfilename(self):80 obj = self._dummy81 field = obj.getField('afilefield')82 obj.setAfilefield('Blao')83 self.assertEqual(str(obj.getAfilefield()), 'Blao')84 self.assertEqual(field.getFilename(obj), '')85 def test_filefielduploadwithoutfilename(self):86 obj = self._dummy87 file = open(os.path.join(PACKAGE_HOME, 'input', 'rest1.tgz'), 'r')88 field = obj.getField('afilefield')89 obj.setAfilefield(file)90 file.close()91 self.assertEqual(field.getFilename(obj), 'rest1.tgz')92class SetFilenameTest(ATSiteTestCase):93 def afterSetUp(self):94 gen_dummy()95 self._dummy = dummy = Dummy(oid='dummy')96 self._dummy.initializeArchetype()97 file1 = open(os.path.join(PACKAGE_HOME, 'input', 'rest1.tgz'), 'r')98 file2 = open(os.path.join(PACKAGE_HOME, 'input', 'word.doc'), 'r')99 # afilefield is the primary field100 dummy.setAfilefield(file1)101 dummy.setAnotherfilefield(file2)102 file1.close()103 file2.close()104 def testMutatorSetFilename(self):105 obj = self._dummy106 field1 = obj.getField('afilefield')107 field2 = obj.getField('anotherfilefield')108 filename1 = 'rest1.tgz'109 filename2 = 'word.doc'110 self.assertEqual(field1.getFilename(obj), filename1)111 self.assertEqual(field2.getFilename(obj), filename2)112 def testBaseObjectPrimaryFieldSetFilename(self):113 obj = self._dummy114 filename1 = 'eitadiacho.mid'115 filename2 = 'ehagoraoununca.pdf'116 obj.setFilename(filename1)117 obj.setFilename(filename2, 'anotherfilefield')118 self.assertEqual(obj.getFilename(), filename1)119 self.assertEqual(obj.getFilename('afilefield'), filename1)120 self.assertEqual(obj.getFilename('anotherfilefield'), filename2)121 def testBaseObjectSetFilename(self):122 obj = self._dummy123 filename1 = 'masbahtche.avi'124 filename2 = 'guasco.mpg'125 obj.setFilename(filename1, 'afilefield')126 obj.setFilename(filename2, 'anotherfilefield')127 self.assertEqual(obj.getFilename(), filename1)128 self.assertEqual(obj.getFilename('afilefield'), filename1)129 self.assertEqual(obj.getFilename('anotherfilefield'), filename2)130 def testFieldSetFilename(self):131 obj = self._dummy132 field1 = obj.getField('afilefield')133 field2 = obj.getField('anotherfilefield')134 filename1 = 'muamba.gif'135 filename2 = 'noruega.jpg'136 field1.setFilename(obj, filename1)137 field2.setFilename(obj, filename2)138 self.assertEqual(field1.getFilename(obj), filename1)139 self.assertEqual(field2.getFilename(obj), filename2)140class LargeFileTest(ATSiteTestCase):141 def testSetFilenameOfLargeFile(self):142 """Test for https://dev.plone.org/archetypes/ticket/635143 """144 self.folder.invokeFactory('SimpleFile', 'sf')145 obj = self.folder.sf146 contents = StringIO('largest file, ' * 10000)147 obj.setBody(contents)148 self.assertEqual(obj.getBody().size, 140000)149 obj.getBody().setFilename('Spam.txt')150 self.assertEqual(obj.getBody().size, 140000)151class StrangeIdTest(ATSiteTestCase):152 def test_strangeUnallowedIds(self):153 """ Certain IDs used to give an error and are unusable...
File.py
Source:File.py
...60 def readFile(self, filename, archive_file):61 self.__path = dirname(filename)62 self.__filename = basename(filename)63 self.__extension = self.__filename.split(".")[-1]64 if self.__manifest.isInManifest(self.getFilename()) and self.__manifest.getFormat(self.getFilename()) is not None:65 self.__format = self.__manifest.getFormat(self.getFilename())66 elif self.__extension in self.KNOWN_FORMATS:67 self.__format = self.KNOWN_FORMATS[self.__extension]68 if self.__format == self.XML:69 self.__format = self.guessXML(archive_file.read(filename))70 else:71 self.__format = "http://purl.org/NET/mediatypes/%s" % guess_type(filename)[0]72 if self.__format is None:73 self.__format = self.UNKNOWN74 if not self.__manifest.isInManifest(self.getFilename()):75 self.__manifest.addInManifest(self.getFilename(), self.__format)76 elif self.__manifest.getFormat(self.getFilename()) is None:77 self.__manifest.setFormat(self.getFilename(), self.__format)78 def newFile(self, filename):79 self.__filename = basename(filename)80 self.__extension = self.__filename.split('.')[-1]81 if self.__extension in self.KNOWN_FORMATS:82 self.__format = self.KNOWN_FORMATS[self.__extension]83 if self.__format == self.XML:84 with open(filename, 'rb') as new_file:85 self.__format = self.guessXML(new_file.read())86 else:87 self.__format = "http://purl.org/NET/mediatypes/%s" % guess_type(filename)[0]88 if self.__format is None:89 self.__format = self.UNKNOWN90 self.__manifest.addInManifest(self.__filename, self.__format)91 def isMaster(self):92 return self.__manifest.isInManifest(self.getFilename()) and self.__manifest.isMaster(self.getFilename())93 def setMaster(self):94 if self.__manifest.isInManifest(self.getFilename()):95 self.__manifest.setMaster(self.getFilename())96 def isSedml(self):97 return (self.__manifest.isInManifest(self.getFilename())98 and self.__manifest.getFormat(self.getFilename()).startswith(self.SEDML)99 )100 def isSbml(self):101 return (self.__manifest.isInManifest(self.getFilename())102 and self.__manifest.getFormat(self.getFilename()).startswith(self.SBML)103 )104 def isNuml(self):105 return (106 self.__manifest.isInManifest(self.getFilename())107 and self.__manifest.getFormat(self.getFilename()).startswith(self.NUML)108 )109 def getFilename(self):110 if self.__path is not None:111 return join(self.__path, self.__filename)112 else:113 return self.__filename114 def getFormat(self):115 return self.__format116 def guessXML(self, xml_content):117 root = etree.fromstring(xml_content)118 tag = root.tag.split("}")[1]119 if isinstance(xml_content, bytes):120 xml_content = str("%s" % xml_content.decode('ascii', 'ignore'))121 if tag == "sbml":122 sbmlReader = SBMLReader()123 if sbmlReader is not None:...
data.py
Source:data.py
1#cython: language_level=32import os3import sys4import glob5import json6DATABASE_FILENAME = 'database.json'7def popTextFile(filename: str) -> str:8 with open(getFileName(filename), 'r') as f:9 lines = f.readlines()10 # If we have no lines, then return none11 if len(lines) == 0:12 return None13 popped = lines[0]14 # Save the new file without the first one15 with open(getFileName(filename), 'w') as f:16 # If we have more than one line, then write the rest of them to the file17 if len(lines) > 1:18 for i in lines[1:]:19 f.write(i)20 return popped21def updateJson(path: str, data: dict):22 try:23 d = loadJSON(path)24 except FileNotFoundError:25 d = {}26 d.update(data)27 saveJSON(path, d)28def getLineFromTextFile(filename: str) -> str:29 with open(getFileName(filename), 'r') as f:30 return f.readline().strip()31def deleteLineFromTextFile(line: str, filename: str):32 with open(getFileName(filename), 'r') as f:33 lines = f.readlines()34 with open(getFileName(filename), 'w') as f:35 for i in lines:36 if line in i:37 continue38 f.write(i)39def saveToTextFile(data: str, path: str):40 data = data.strip()41 with open(getFileName(path), 'a') as f:42 if isFileEmpty(path):43 f.write(data)44 else:45 f.write('\n' + data)46def getFileName(path: str):47 directory = ''48 if getattr(sys, 'frozen', False):49 if os.name == 'nt':50 directory = sys.executable[:sys.executable.rfind('\\')]51 else:52 directory = sys.executable[:sys.executable.rfind('/')]53 return os.path.join(directory, path)54def saveListToTextFile(data: list, path: str):55 with open(getFileName(path), 'a') as f:56 fileEmpty = isFileEmpty(path)57 for i in data:58 if fileEmpty:59 f.write(i.strip())60 fileEmpty = False61 else:62 f.write('\n' + i.strip())63def isFileEmpty(fileName: str) -> bool:64 return os.stat(fileName).st_size == 065def loadJSON(fileName: str) -> dict:66 with open(getFileName(fileName), 'r') as f:67 return json.load(f)68def saveJSON(path: str, data: dict):69 path = getFileName(path)70 with open(path, 'w') as f:71 json.dump(data, f, indent=4)...
Using AI Code Generation
1var getFilename = require('backstopjs/core/util/getFilename');2var getFilename = require('backstopjs/core/util/getFilename');3var getFilename = require('backstopjs/core/util/getFilename');4var getFilename = require('backstopjs/core/util/getFilename');5var getFilename = require('backstopjs/core/util/getFilename');6var getFilename = require('backstopjs/core/util/getFilename');7var getFilename = require('backstopjs/core/util/getFilename');8var getFilename = require('backstopjs/core/util/getFilename');9var getFilename = require('backstopjs/core/util/getFilename');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!